Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): unify rate-limit into DO + chat UX fixes (#347)
Gener6ab78969c3cd
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1858f0d89..f26b52d00 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -306,6 +306,9 @@ importers:'@next/third-parties':specifier: ^16.2.10version: 16.2.10([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ '@number-flow/react':+ specifier: ^0.6.1'@opennextjs/cloudflare':specifier: ^1.20.1version: 1.20.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected](@cloudflare/[email protected]))@@ -2376,6 +2379,12 @@ packages:resolution: {integrity: sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA==}engines: {node: '>=12.4.0'}+ '@number-flow/[email protected]':+ resolution: {integrity: sha512-JsvB8FrmtRmn251jbJnFD7Tr6Sv/eQMLUAlbshGo4CfAPk0qgNYTio9HuFoETqtuflcJHQezeGsSTPbUn1oplw==}+ peerDependencies:+ react: ^18 || ^19+ react-dom: ^18 || ^19+'@open-draft/[email protected]':resolution: {integrity: sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA==}@@ -5416,6 +5425,9 @@ packages:jiti:optional: true+ resolution: {integrity: sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==}+resolution: {integrity: sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}@@ -7023,6 +7035,9 @@ packages:resolution: {integrity: sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==}engines: {node: '>=18'}+ resolution: {integrity: sha512-5NUCwZA6J/kZeEzqApOyq7KOf1Wu/oxjpp/95HB0NBNBFlpK/Pp7i4jH8h0LIXyRDKSTewDAUaYHL7IBrk19Ew==}+resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}engines: {node: '>=0.10.0'}@@ -10732,6 +10747,13 @@ snapshots:'@nolyfill/[email protected]': {}+ dependencies:+ esm-env: 1.2.2+ number-flow: 0.6.1+ react: 19.2.7+ react-dom: 19.2.7([email protected])+'@open-draft/[email protected]':optional: true@@ -12337,7 +12359,7 @@ snapshots:obug: 2.1.3std-env: 4.1.0tinyrainbow: 3.1.0- vitest: 4.1.9(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 4.1.9(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@vitest/[email protected]':dependencies:@@ -13662,7 +13684,7 @@ snapshots:'@next/eslint-plugin-next': 16.2.10eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]([email protected])))([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))eslint-plugin-react: 7.37.5([email protected]([email protected]))@@ -13685,7 +13707,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])):dependencies:'@nolyfill/is-core-module': 1.0.39debug: 4.4.3@@ -13700,13 +13722,13 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected]([email protected])([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]([email protected])))([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))transitivePeerDependencies:- supports-color@@ -13721,7 +13743,7 @@ snapshots:doctrine: 2.1.0eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-module-utils: 2.13.0([email protected])([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))+ eslint-module-utils: 2.13.0([email protected])([email protected])([email protected]([email protected]))hasown: 2.0.4is-core-module: 2.16.2is-glob: 4.0.3@@ -13891,6 +13913,8 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]: {}+dependencies:acorn: 8.16.0@@ -16031,6 +16055,10 @@ snapshots:path-key: 4.0.0unicorn-magic: 0.3.0+ dependencies:+ esm-env: 1.2.2+diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 6aecaf475..6837fa128 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -451,6 +451,8 @@ export type { LogLevel, LoggerOptions } from "./logger"// Libexport { isEmptyHtml } from "./lib/html";+export { RATE_LIMITS } from "./lib/rate-limits";+export type { RateLimitName, RateLimitPolicy, RateLimitResult } from "./lib/rate-limits";export { extractThreadId, buildEmailMapKey } from "./lib/context-key";export { parseIcs } from "./lib/ics-parser";export type { MeetingInfo } from "./lib/ics-parser";diff --git a/src/shared/src/lib/rate-limits.ts b/src/shared/src/lib/rate-limits.tsnew file mode 100644index 000000000..4ea0f8d7c--- /dev/null+++ b/src/shared/src/lib/rate-limits.ts@@ -0,0 +1,43 @@+/**+ * Central registry of every rate limit in the system.+ *+ * Every rate-limit call site MUST name a policy that appears in this+ * table. Adding a new limit? Add its entry here first, then reference it+ * from the caller — this keeps every ceiling visible in one place and+ * prevents ad-hoc per-caller magic numbers from proliferating.+ *+ * Naming: `<namespace>:<action>`. Keep the namespace scoped to the+ * subsystem that owns the action, not to the transport that enforces it+ * (they're all backed by the same DO — the transport is an implementation+ * detail).+ *+ * Runtime enforcement lives in `RateLimitDurableObject` (see+ * `src/ws-do/src/rate-limit-do.ts`). Callers reach it via the web-side+ * helper at `src/web/src/lib/rate-limit.ts` (`checkRateLimit`), which+ * fails open on transport error — the DO is a strong-consistency+ * counter, not a security perimeter.+ */+export const RATE_LIMITS = {+ /**+ * Community message send (channel + DM). Prevents scripted flooding of+ * any single channel/DM without throttling normal chat bursts.+ */+ "community:msgSend": { windowMs: 10_000, max: 30 },+ /**+ * OTP send (better-auth `/email-otp/send-verification-otp`). Prevents+ * cost/abuse from someone spamming another user's inbox. Window/max are+ * overridable via `AUTH_OTP_RATE_LIMIT_MAX` / `_WINDOW_SEC`.+ */+ "auth:otpSend": { windowMs: 60_000, max: 5 },+} as const++export type RateLimitName = keyof typeof RATE_LIMITS++export type RateLimitPolicy = {+ windowMs: number+ max: number+}++export type RateLimitResult =+ | { allowed: true }+ | { allowed: false; retryAfterSec: number }diff --git a/src/web/package.json b/src/web/package.jsonindex e0ee52f00..136c729ba 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -35,6 +35,7 @@"@mdx-js/react": "^3.1.1","@next/mdx": "^16.2.10","@next/third-parties": "^16.2.10",+ "@number-flow/react": "^0.6.1","@opennextjs/cloudflare": "^1.20.1","@streamdown/cjk": "^1.0.3","@streamdown/math": "^1.0.2",diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.tsindex e7667281f..1a4e44ded 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts@@ -26,8 +26,8 @@ const mockCheckMessageRateLimit = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-vi.mock("@/lib/community/rate-limit", () => ({- checkMessageRateLimit: (...a: unknown[]) => mockCheckMessageRateLimit(...a),+vi.mock("@/lib/rate-limit", () => ({+ checkRateLimit: (...a: unknown[]) => mockCheckMessageRateLimit(...a),}))vi.mock("@alook/shared", async () => {@@ -78,7 +78,7 @@ vi.mock("@/lib/broadcast", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {}, RATE_LIMIT_KV: {} }, userId: "u1", email: "[email protected]", params })+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })}),}))@@ -156,7 +156,7 @@ describe("POST /api/community/channels/[id]/messages", () => {it("checks the rate limit for the sender's userId, scoped after channel-membership auth", async () => {const res = await POST(postReq({ content: "hello" }), ctx)expect(res.status).toBe(201)- expect(mockCheckMessageRateLimit).toHaveBeenCalledWith(expect.anything(), "u1")+ expect(mockCheckMessageRateLimit).toHaveBeenCalledWith(expect.anything(), "community:msgSend", "u1")// Membership check must run before rate limiting (auth first).expect(mockGetChannelForMember).toHaveBeenCalled()})diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.tsindex fa624f58a..f4f03cdb9 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts@@ -5,7 +5,7 @@ import { getDb } from "@/lib/db"import { queries } from "@alook/shared"import { parseCursor, parsePageSize, buildPaginatedResponse, groupAttachments, groupReactions } from "@/lib/community/messages"import { requireChannelMember } from "@/lib/community/permissions"-import { checkMessageRateLimit } from "@/lib/community/rate-limit"+import { checkRateLimit } from "@/lib/rate-limit"import { createCommunityMessage } from "@/lib/community/message-handler"import { mapMessageForApi } from "@/lib/community/message-payload"@@ -80,7 +80,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {if (!auth.ok) return writeError(auth.error, auth.status)const channel = auth.value- const rateLimit = await checkMessageRateLimit(ctx.env.RATE_LIMIT_KV, ctx.userId)+ const rateLimit = await checkRateLimit(ctx.env, "community:msgSend", ctx.userId)if (!rateLimit.allowed) {return writeError("rate limited", 429, { "Retry-After": String(rateLimit.retryAfterSec) })}diff --git a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts b/src/web/src/app/api/community/dm/[id]/messages/route.test.tsindex 7b4adbaaa..d5a1d784e 100644--- a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/dm/[id]/messages/route.test.ts@@ -24,8 +24,8 @@ const mockCheckMessageRateLimit = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-vi.mock("@/lib/community/rate-limit", () => ({- checkMessageRateLimit: (...a: unknown[]) => mockCheckMessageRateLimit(...a),+vi.mock("@/lib/rate-limit", () => ({+ checkRateLimit: (...a: unknown[]) => mockCheckMessageRateLimit(...a),}))vi.mock("@alook/shared", async () => {@@ -78,7 +78,7 @@ vi.mock("@/lib/broadcast", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {}, RATE_LIMIT_KV: {} }, userId: "u1", email: "[email protected]", params })+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })}),}))diff --git a/src/web/src/app/api/community/dm/[id]/messages/route.ts b/src/web/src/app/api/community/dm/[id]/messages/route.tsindex 8f826a944..661c1c9c4 100644--- a/src/web/src/app/api/community/dm/[id]/messages/route.ts+++ b/src/web/src/app/api/community/dm/[id]/messages/route.ts@@ -5,7 +5,7 @@ import { getDb } from "@/lib/db"import { queries } from "@alook/shared"import { parseCursor, parsePageSize, buildPaginatedResponse, groupAttachments, groupReactions } from "@/lib/community/messages"import { requireDMParticipant } from "@/lib/community/permissions"-import { checkMessageRateLimit } from "@/lib/community/rate-limit"+import { checkRateLimit } from "@/lib/rate-limit"import { createCommunityMessage } from "@/lib/community/message-handler"import { mapMessageForApi } from "@/lib/community/message-payload"@@ -69,7 +69,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const auth = await requireDMParticipant(db, dmId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)- const rateLimit = await checkMessageRateLimit(ctx.env.RATE_LIMIT_KV, ctx.userId)+ const rateLimit = await checkRateLimit(ctx.env, "community:msgSend", ctx.userId)if (!rateLimit.allowed) {return writeError("rate limited", 429, { "Retry-After": String(rateLimit.retryAfterSec) })}diff --git a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsxindex a5a727870..a9789966c 100644--- a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx@@ -121,13 +121,23 @@ function ChannelView() {// `getMessage(lastReadMessageId).createdAt === lastReadAt`, so we only need// the id to find the anchor. `idx === -1` means the last-read message has// scrolled off the top of the fetched window — no divider is shown.+ //+ // Skip past runs of viewer-authored messages. The frozen client snapshot+ // doesn't move mid-mount, but the server DOES advance the sender's own+ // watermark on every send (see `createMessage` in+ // `src/shared/src/db/queries/community/message.ts`) — so without this+ // walk, the divider anchors above the viewer's OWN just-sent message,+ // which is never "unread" from the sender's perspective.const newDividerBefore = useMemo(() => {const lastId = readSnapshot?.lastReadMessageIdif (!lastId) return undefinedconst idx = messages.findIndex((m) => m.id === lastId)if (idx === -1) return undefined- return messages[idx + 1]?.id- }, [messages, readSnapshot])+ for (let i = idx + 1; i < messages.length; i++) {+ if (messages[i].authorId !== currentUser.id) return messages[i].id+ }+ return undefined+ }, [messages, readSnapshot, currentUser.id])// Scroll root of the message list — needed so `useChannelWatermark`'s// IntersectionObserver measures against the correct viewport instead ofdiff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsxindex 5e9b0aee4..f66a35f74 100644--- a/src/web/src/components/community/composer.tsx+++ b/src/web/src/components/community/composer.tsx@@ -8,6 +8,7 @@ import StarterKit from "@tiptap/starter-kit"import Placeholder from "@tiptap/extension-placeholder"import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"import { Skeleton } from "@/components/ui/skeleton"+import { useFileAttachments } from "@/hooks/use-file-attachments"import { Avatar } from "./avatar"import { EmojiPickerPopover } from "./emoji-picker"import type { Member } from "./_types"@@ -43,8 +44,18 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, oreplyingTo?: stringonCancelReply?: () => void}) {- const [pendingFiles, setPendingFiles] = useState<File[]>([])- const fileInputRef = useRef<HTMLInputElement>(null)+ const {+ pendingFiles,+ setPendingFiles,+ fileInputRef,+ handleFileSelect,+ removePendingFile,+ dragging,+ handleDragEnter,+ handleDragLeave,+ handleDragOver,+ handleDrop,+ } = useFileAttachments()const typingTimer = useRef<NodeJS.Timeout | null>(null)const [mentionPopup, setMentionPopup] = useState<MentionPopupState>(EMPTY_MENTION_STATE)@@ -160,26 +171,21 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, oif (!editor || (editor.isEmpty && pendingFiles.length === 0)) returnconst markdown = editor.isEmpty ? "" : editor.getText({ blockSeparator: "\n" }).trim()const mentionType = detectMentionType(markdown)- onSend?.(markdown, pendingFiles.length > 0 ? pendingFiles : undefined, mentionType)+ const files = pendingFiles.length > 0 ? pendingFiles.map((pf) => pf.file) : undefined+ onSend?.(markdown, files, mentionType)editor.commands.clearContent()setPendingFiles([])setMentionPopup(EMPTY_MENTION_STATE)}- const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {- const files = Array.from(e.target.files || [])- if (files.length > 0) {- setPendingFiles((prev) => [...prev, ...files])- }- e.target.value = "" // Reset input to allow same file selection again- }-- const removeFile = (index: number) => {- setPendingFiles((prev) => prev.filter((_, i) => i !== index))- }-return (- <div className="relative px-3 pb-3 pt-0">+ <div+ className="relative px-3 pb-3 pt-0"+ onDragEnter={handleDragEnter}+ onDragLeave={handleDragLeave}+ onDragOver={handleDragOver}+ onDrop={handleDrop}+ ><CommunityMentionList state={mentionPopup} />{/* reply context bar — attached above the input */}@@ -195,14 +201,14 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o{/* pending attachments preview */}{pendingFiles.length > 0 && (<div className={`flex flex-wrap gap-2 border-x border-b border-border/40 bg-muted/40 px-4 py-2 ${replyingTo ? "" : "rounded-t-xl border-t"}`}>- {pendingFiles.map((file, i) => {- const isImage = file.type.startsWith("image/")+ {pendingFiles.map((pf, i) => {+ const isImage = pf.file.type.startsWith("image/")return (<div key={i} className="group relative flex items-center gap-2 rounded border border-border bg-background px-3 py-2 text-xs">{isImage ? <ImageIcon className="size-3.5 text-muted-foreground" /> : <FileIcon className="size-3.5 text-muted-foreground" />}- <span className="max-w-30 truncate text-foreground">{file.name}</span>+ <span className="max-w-30 truncate text-foreground">{pf.file.name}</span><button- onClick={() => removeFile(i)}+ onClick={() => removePendingFile(i)}className="grid size-4 shrink-0 place-items-center rounded-full hover:bg-destructive/10 hover:text-destructive"aria-label="Remove file">@@ -215,6 +221,13 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o)}<div className={`relative bg-muted shadow-(--e1) ring-1 ring-border/40 ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}>+ {dragging && (+ <div+ className={`pointer-events-none absolute inset-0 z-10 grid place-items-center border-2 border-dashed border-ring bg-background/80 ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}+ >+ <p className="text-sm font-medium text-muted-foreground">Drop files here</p>+ </div>+ )}<inputref={fileInputRef}type="file"diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsxindex efdde6efc..bc24d1e70 100644--- a/src/web/src/components/community/message-list.tsx+++ b/src/web/src/components/community/message-list.tsx@@ -1,12 +1,14 @@"use client"-import { useEffect, useMemo, useRef, useState } from "react"+import { useCallback, useEffect, useMemo, useRef, useState } from "react"+import { ArrowDown } from "lucide-react"import { DateDivider, NewDivider } from "./dividers"import { Message } from "./message"import { TypingIndicator } from "./typing-indicator"import { dateKey, formatDateLabel } from "./format-time"import { ChannelIcon } from "./channel-icon"import { Skeleton } from "@/components/ui/skeleton"+import { NumberTicker } from "@/components/ui/number-ticker"import type { Msg, OpenProfile } from "./_types"// Channel message list — welcome hero, date dividers, messages (with the NEW divider),@@ -47,10 +49,9 @@ export function MessageList({}) {const [jumped, setJumped] = useState<string | null>(null)const scrollRef = useRef<HTMLDivElement>(null)- const prevMsgCountRef = useRef(messages.length)// Tracks whether the mount-time initial-scroll has fired yet. On channel// switch (`messages` cleared) we reset it so the new channel gets its own- // initial scroll — mirrors the `prevMsgCountRef` reset below.+ // initial scroll.const didInitialScrollRef = useRef(false)// Publish the scroll root to interested consumers (watermark observer).@@ -62,49 +63,83 @@ export function MessageList({return () => onScrollRoot(null)}, [onScrollRoot])- // When the messages list is cleared on channel switch, the previous count is- // stale — the very first batch that arrives would compare against the old- // length and skip the bottom-anchor scroll. Reset when we hit empty.useEffect(() => {if (messages.length === 0) {- prevMsgCountRef.current = 0didInitialScrollRef.current = false}}, [messages.length])+ // Mount-time initial scroll — exactly two rules, no auto-follow after:+ // 1. NEW divider present → center it vertically in the viewport.+ // 2. No NEW divider → snap to the bottom.+ // Fires once per mount; deliberately no near-bottom heuristic. If the+ // user has scrolled up, incoming messages do NOT pull the view back —+ // the floating "↓ N" button below is how they return.useEffect(() => {const el = scrollRef.currentif (!el) return- const isNewMessage = messages.length > prevMsgCountRef.current- prevMsgCountRef.current = messages.length+ if (didInitialScrollRef.current) return+ if (messages.length === 0) return- // Mount-time initial scroll: target the "New" divider when there's an- // unread pointer, otherwise fall through to the bottom-anchor. Only- // fires once per mount — subsequent renders use the near-bottom heuristic- // below so the list still auto-follows when the user is near the bottom.- if (!didInitialScrollRef.current && messages.length > 0) {- if (newDividerBefore) {- const target = el.querySelector<HTMLElement>(- `[data-msg-id="${cssEscape(newDividerBefore)}"]`,- )- if (target) {- target.scrollIntoView({ block: "start" })- didInitialScrollRef.current = true- return- }+ if (newDividerBefore) {+ const target = el.querySelector<HTMLElement>(+ `[data-msg-id="${cssEscape(newDividerBefore)}"]`,+ )+ if (target) {+ target.scrollIntoView({ block: "center" })+ didInitialScrollRef.current = true+ return}- el.scrollTop = el.scrollHeight- didInitialScrollRef.current = true+ }+ el.scrollTop = el.scrollHeight+ didInitialScrollRef.current = true+ }, [messages, newDividerBefore])++ // Live count of messages sitting below the viewport. Recomputed on scroll,+ // on messages change, and via a ResizeObserver so appended rows update the+ // badge even without a scroll event. `0` means the user is at the bottom+ // (or the list fits entirely in the viewport) — the button hides.+ const [belowCount, setBelowCount] = useState(0)+ const recomputeBelow = useCallback(() => {+ const el = scrollRef.current+ if (!el) {+ setBelowCount(0)+ return+ }+ // Ignore near-bottom noise (a few px off from anti-aliasing / sub-pixel+ // layout counts as "at bottom"). 8px is well below one line's height.+ const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight+ if (distanceFromBottom < 8) {+ setBelowCount(0)return}+ const rows = el.querySelectorAll<HTMLElement>("[data-msg-id]")+ const viewportBottom = el.scrollTop + el.clientHeight+ let count = 0+ for (const row of rows) {+ if (row.offsetTop >= viewportBottom) count+++ }+ setBelowCount(count)+ }, [])- // Only auto-scroll if user is near the bottom (within 150px) or it's- // a new message arriving.- const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 150- if (nearBottom || isNewMessage) {- el.scrollTop = el.scrollHeight+ useEffect(() => {+ const el = scrollRef.current+ if (!el) return+ recomputeBelow()+ el.addEventListener("scroll", recomputeBelow, { passive: true })+ const ro = new ResizeObserver(recomputeBelow)+ ro.observe(el)+ return () => {+ el.removeEventListener("scroll", recomputeBelow)+ ro.disconnect()}- }, [messages, newDividerBefore])+ }, [recomputeBelow, messages.length])++ const scrollToBottom = useCallback(() => {+ const el = scrollRef.current+ if (!el) return+ el.scrollTo({ top: el.scrollHeight, behavior: "smooth" })+ }, [])const jumpTo = (id: string) => {setJumped(id)@@ -143,6 +178,10 @@ export function MessageList({return (<div className="relative flex min-h-0 flex-1 flex-col">+ <ScrollDownButton+ count={belowCount}+ onClick={scrollToBottom}+ /><div ref={scrollRef} className="flex-1 overflow-y-auto thin-scrollbar"><div className="flex min-h-full flex-col justify-end px-4 py-8"><div className="mb-6">@@ -210,6 +249,33 @@ function cssEscape(id: string): string {return id.replace(/[^a-zA-Z0-9_-]/g, "\\$&")}+// Floating "↓ N" pill that appears when the user has scrolled up and there+// are still messages below the viewport. `count === 0` hides the button+// entirely (fade + slide-down, matches the shared scroll-to-bottom pill's+// visual language).+function ScrollDownButton({ count, onClick }: { count: number; onClick: () => void }) {+ const visible = count > 0+ return (+ <div+ className={`pointer-events-none absolute bottom-3 left-1/2 z-10 -translate-x-1/2 transition-all duration-200 ease-out ${+ visible ? "translate-y-0 opacity-100" : "translate-y-2 opacity-0"+ }`}+ >+ <button+ type="button"+ onClick={onClick}+ aria-label={`Scroll to bottom, ${count} more below`}+ className={`pointer-events-auto flex h-8 items-center gap-1.5 rounded-full border border-border bg-background/90 pl-2 pr-3 text-xs font-medium text-foreground shadow-(--e1) backdrop-blur-sm transition-colors hover:bg-accent ${+ visible ? "" : "pointer-events-none"+ }`}+ >+ <ArrowDown className="size-3.5 text-muted-foreground" />+ <NumberTicker value={count} />+ </button>+ </div>+ )+}+// Loading placeholder for the message list. Mirrors the cluster layout used// above (avatar + author line + 1–2 content lines) and sits inside the same// flex-justify-end scroll container so the composer and header stay anchored.diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsxindex eebb90ca5..1a8c135bf 100644--- a/src/web/src/components/community/message.tsx+++ b/src/web/src/components/community/message.tsx@@ -11,6 +11,7 @@ import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent } from "@/componimport { Avatar } from "./avatar"import { MessageBody } from "./message-body"import { EmojiPickerPopover } from "./emoji-picker"+import { NumberTicker } from "@/components/ui/number-ticker"import { MessageContextItems, MessageDropdownItems, hasMessageMenu } from "./message-menu"import { formatMessageTime } from "./format-time"import type { Msg, OpenProfile } from "./_types"@@ -137,7 +138,7 @@ export function Message({)}{m.attachments && (- <div className="mt-2 flex flex-col gap-2">+ <div className="mt-2 flex flex-col gap-2 pb-2">{m.attachments.map((a, i) =>a.kind === "image" ? (<button@@ -166,7 +167,7 @@ export function Message({)}{m.embeds && m.embeds.length > 0 && (- <div className="mt-2 flex flex-col gap-2">+ <div className="mt-2 flex flex-col gap-2 pb-2">{m.embeds.map((embed, ei) => (<articlekey={ei}@@ -240,7 +241,7 @@ export function Message({].join(" ")}><span>{r.emoji}</span>- <span className="text-xs text-muted-foreground">{r.count}</span>+ <NumberTicker value={r.count} className="text-xs text-muted-foreground" /></button>))}<EmojiPickerPopover side="top" align="start" onPick={(e) => onReact?.(e)}>diff --git a/src/web/src/components/community/profile-card.tsx b/src/web/src/components/community/profile-card.tsxindex 4a9be4987..62692387c 100644--- a/src/web/src/components/community/profile-card.tsx+++ b/src/web/src/components/community/profile-card.tsx@@ -76,7 +76,10 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf }: {<inputvalue={msg}onChange={(e) => setMsg(e.target.value)}- onKeyDown={(e) => { if (e.key === "Enter") send() }}+ onKeyDown={(e) => {+ if (e.key !== "Enter" || e.nativeEvent.isComposing) return+ send()+ }}className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"placeholder={`Message @${data.name}`}/>diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxindex c6946f60b..0426c6733 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -40,6 +40,7 @@ import {useDismissForYouEvent,useDeleteMention,useUpdateProfile,+ useSendDmMessage,} from "@/hooks/community/mutations"/**@@ -111,6 +112,7 @@ export function ShellFrame({const updateFolderItems = useUpdateFolderItems()const createFolderWith = useCreateServerFolderWith()const createOrGetDm = useCreateOrGetDm()+ const sendDmMessage = useSendDmMessage()const markAllInboxRead = useMarkAllInboxRead()const dismissForYouEvent = useDismissForYouEvent()const deleteMention = useDeleteMention()@@ -333,7 +335,7 @@ export function ShellFrame({})}, [previewImage, openProfile, goBackMobile])- const profileMessage = async (name: string) => {+ const profileMessage = async (name: string, text: string) => {setProfile(null)const member = members.find((m) => m.name === name)const friend = friends.find((f) => f.name === name)@@ -342,12 +344,37 @@ export function ShellFrame({toast(`Could not find user ${name}`)return}+ let dmId: stringtry {const data = await createOrGetDm.mutateAsync({ userId: targetUserId })- router.push(`/community/me/${data.conversation.id}`)+ dmId = data.conversation.id} catch {toast("Failed to open DM")+ return+ }+ // Await the send BEFORE navigating so the server row exists by the time+ // the DM page mounts and fires its initial `GET /messages`. Otherwise+ // the fresh-mount fetch races the send: it returns [], overwrites the+ // optimistic cache, and the first message silently vanishes. Failure+ // surfaces as a toast + `failed: true` pill; we still navigate so the+ // user has the composer to retry.+ const trimmed = text.trim()+ if (trimmed) {+ try {+ await sendDmMessage.mutateAsync({+ dmId,+ content: trimmed,+ author: {+ id: currentUser.id,+ name: currentUser.name,+ avatar: currentUser.avatar,+ },+ })+ } catch {+ toast("Failed to send message")+ }}+ router.push(`/community/me/${dmId}`)}const openServerChannel = useCallback(diff --git a/src/web/src/components/community/sortable-server.tsx b/src/web/src/components/community/sortable-server.tsxindex 40fab3d45..492b2849e 100644--- a/src/web/src/components/community/sortable-server.tsx+++ b/src/web/src/components/community/sortable-server.tsx@@ -7,6 +7,7 @@ import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, Cimport { RailIndicator } from "./rail-indicator"import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"import { ConfirmDialog } from "@/components/ui/confirm-dialog"+import { NumberTicker } from "@/components/ui/number-ticker"import type { Server } from "./_types"export function SortableServer({ server, active, onClick, onLeave, onOpenSettings, onOpenInvitePopover, onCreateFolder, groupTarget, inFolder, dragging: isDragActive }: { server: Server; active?: boolean; onClick: () => void; onLeave?: () => void; onOpenSettings?: () => void; onOpenInvitePopover?: () => void; onCreateFolder?: () => void; groupTarget?: boolean; inFolder?: boolean; dragging?: boolean }) {@@ -44,10 +45,10 @@ export function SortableServer({ server, active, onClick, onLeave, onOpenSetting</button>{server.mentions > 0 && (<span- className="pointer-events-none absolute -bottom-1 -right-1 grid min-w-5 place-items-center rounded-full border border-(--d-rail) px-1 text-[11px] font-black tracking-tight tabular-nums leading-4.5 text-white"+ className="pointer-events-none absolute -bottom-1 -right-1 grid min-w-5 place-items-center rounded-full border border-(--d-rail) px-1 text-[11px] font-black tracking-tight leading-4.5 text-white"style={{ background: "var(--destructive)", WebkitTextStroke: "0.4px currentColor" }}>- {server.mentions}+ <NumberTicker value={server.mentions} /></span>)}</div>diff --git a/src/web/src/components/community/thread-opener.tsx b/src/web/src/components/community/thread-opener.tsxindex 812b96e43..6f0fc65ad 100644--- a/src/web/src/components/community/thread-opener.tsx+++ b/src/web/src/components/community/thread-opener.tsx@@ -5,6 +5,7 @@ import { Avatar } from "./avatar"import { MessageBody } from "./message-body"import { formatMessageTime } from "./format-time"import { Skeleton } from "@/components/ui/skeleton"+import { NumberTicker } from "@/components/ui/number-ticker"import { avatarInitial } from "@/lib/community/avatar"import { useMessage } from "@/hooks/community/use-message"import type { OpenProfile } from "./_types"@@ -123,7 +124,7 @@ export function ThreadOpener({].join(" ")}><span>{r.emoji}</span>- <span className="text-xs text-muted-foreground">{r.count}</span>+ <NumberTicker value={r.count} className="text-xs text-muted-foreground" /></span>))}</div>diff --git a/src/web/src/components/ui/number-ticker.tsx b/src/web/src/components/ui/number-ticker.tsxnew file mode 100644index 000000000..613765b5b--- /dev/null+++ b/src/web/src/components/ui/number-ticker.tsx@@ -0,0 +1,46 @@+"use client"++import NumberFlow, { type Value } from "@number-flow/react"+import { cn } from "@/lib/utils"++/**+ * Animated numeric ticker. Digits transition with a slot-machine slide when+ * the value changes. Locale-aware formatting (thousands separators, decimals,+ * compact notation) is handed off to Intl.NumberFormat under the hood.+ *+ * Use this anywhere a number can change while it's on screen — reaction+ * counts, unread badges, live totals, the scroll-down indicator, etc.+ * A static number does not need this component; render the value directly.+ *+ * @example+ * <NumberTicker value={12} /> // "12"+ * <NumberTicker value={1234} /> // "1,234"+ * <NumberTicker value={4200} compact /> // "4.2K"+ * <NumberTicker value={0.75} decimals={2} /> // "0.75"+ */+export function NumberTicker({+ value,+ decimals = 0,+ compact = false,+ className,+}: {+ value: Value+ /** Fixed number of fraction digits. Defaults to 0 (integer display). */+ decimals?: number+ /** Compact notation — 1_500 → "1.5K", 1_200_000 → "1.2M". */+ compact?: boolean+ className?: string+}) {+ return (+ <NumberFlow+ value={value}+ format={{+ notation: compact ? "compact" : "standard",+ compactDisplay: "short",+ minimumFractionDigits: decimals,+ maximumFractionDigits: decimals,+ }}+ className={cn("tabular-nums", className)}+ />+ )+}diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.tsindex be5414c8a..a0906c8af 100644--- a/src/web/src/env.d.ts+++ b/src/web/src/env.d.ts@@ -18,7 +18,6 @@ declare namespace Cloudflare {BETTER_AUTH_SECRET: stringBETTER_AUTH_URL: stringENCRYPTION_KEY: string- RATE_LIMIT_KV: KVNamespaceCACHE_KV: KVNamespaceAUTH_OTP_RATE_LIMIT_MAX?: stringAUTH_OTP_RATE_LIMIT_WINDOW_SEC?: stringdiff --git a/src/web/src/hooks/community/use-channel-read-state.ts b/src/web/src/hooks/community/use-channel-read-state.tsindex 0957bec8a..a1a4e3ecf 100644--- a/src/web/src/hooks/community/use-channel-read-state.ts+++ b/src/web/src/hooks/community/use-channel-read-state.ts@@ -27,15 +27,16 @@ export type ChannelReadStateSnapshot = {** Implementation: fire a normal `useQuery`, then latch the first non-null* response in a `useRef`. All subsequent calls return the ref value. The- * `staleTime: Infinity + refetchOnMount: false` combo means TanStack itself- * won't tick the cache during this mount, but the ref makes the invariant- * explicit regardless.+ * `staleTime: Infinity` + `snapshotRef` combo keeps the anchor frozen for+ * the entire mount regardless of what TanStack does mid-mount.*- * Note: this hook does NOT unmount cleanup or invalidate — the next channel- * mount is a fresh useRef, and the next channel's read row is either fresh- * from the server or read via `queries.communityReadState.getReadState`- * afresh. The cache key includes `channelId`, so switching channels reads- * the other channel's snapshot.+ * Cross-mount refresh: `gcTime: 0` evicts the cache entry the instant the+ * consumer unmounts. The next mount finds an empty cache and MUST refetch+ * from the server — otherwise the divider re-anchors to the pre-scroll+ * position even after the IntersectionObserver has advanced the read row.+ * Note: `refetchOnMount: true` is NOT enough here — with `staleTime:+ * Infinity`, TanStack considers cached data fresh and skips the refetch.+ * `gcTime: 0` is the only reliable path to a genuine cross-mount reload.*/export function useChannelReadStateSnapshot(channelId: string | null | undefined): {snapshot: ChannelReadStateSnapshot | null@@ -52,10 +53,13 @@ export function useChannelReadStateSnapshot(channelId: string | null | undefined},enabled: !!channelId,staleTime: Infinity,- // The value is anchored to this mount — no refetch on remount, focus,- // or reconnect. If the user leaves and comes back, a fresh mount fires- // a new query with a new ref.- refetchOnMount: false,+ // Evict the cache entry the moment the last observer unmounts. Combined+ // with the fresh useRef on each mount, this guarantees revisiting a+ // channel fires a real network fetch instead of replaying the stale+ // pre-scroll pointer — otherwise the "New" divider re-appears at the+ // old position because TanStack's `staleTime: Infinity` treats cached+ // data as fresh and refuses to refetch on remount.+ gcTime: 0,refetchOnWindowFocus: false,refetchOnReconnect: false,// Snapshot is one-shot; even if TanStack retries a failed fetch, thediff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.tsindex 7be3ee8dc..b777efd87 100644--- a/src/web/src/lib/auth.test.ts+++ b/src/web/src/lib/auth.test.ts@@ -16,7 +16,7 @@ vi.mock("@alook/shared", async (importOriginal) => {const actual = await importOriginal<typeof import("@alook/shared")>()return {...actual,- createLogger: () => ({ info: vi.fn(), error: vi.fn() }),+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),DEV_EMAIL_WORKER_URL: "http://localhost:0",}})@@ -26,25 +26,24 @@ vi.mock("./email-templates", () => ({renderOtpEmail: () => "<html></html>",}))-type RateLimitValue = { count: number; lastRequest: number } | undefined+// Mock `checkRateLimit` so tests can assert what auth passes to the+// unified rate-limit helper without spinning up the DO.+const mockCheckRateLimit = vi.fn(async () => ({ allowed: true }))+vi.mock("@/lib/rate-limit", () => ({+ checkRateLimit: (...a: unknown[]) => mockCheckRateLimit(...(a as [])),+}))-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 makeEnvBase() {+ return {}}function makeEnv(overrides: Partial<Record<string, unknown>> = {}) {return {+ ...makeEnvBase(),DB: {},EMAIL_BUCKET: {},WS_DO_WORKER: {},- EMAIL_WORKER: { fetch: vi.fn() },+ EMAIL_WORKER: { fetch: vi.fn(async () => new Response("ok", { status: 200 })) },NEXT_INC_CACHE_R2_BUCKET: {},NEXT_TAG_CACHE_D1: {},NEXT_CACHE_DO_QUEUE: {},@@ -54,7 +53,6 @@ function makeEnv(overrides: Partial<Record<string, unknown>> = {}) {GOOGLE_CLIENT_SECRET: "gg-s",BETTER_AUTH_SECRET: "secret",BETTER_AUTH_URL: "http://localhost:3000",- RATE_LIMIT_KV: makeKv(),...overrides,}}@@ -68,12 +66,13 @@ 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>- }}+ plugins?: Array<{+ __plugin?: string+ cfg?: {+ sendVerificationOTP?: (args: { email: string; otp: string; type: string }) => Promise<void>+ }+ }>session?: {cookieCache?: {enabled?: boolean@@ -100,28 +99,41 @@ async function loadCreateAuth() {return mod.createAuth}+// Fetches the OTP-plugin `sendVerificationOTP` callback for a given env+// so tests can drive rate-limit + email-send behavior directly.+function getSendOtp(opts: AuthOptions) {+ const otp = opts.plugins?.find((p) => p?.__plugin === "emailOTP")+ const fn = otp?.cfg?.sendVerificationOTP+ if (!fn) throw new Error("emailOTP plugin not present")+ return fn+}+describe("createAuth rate limiting", () => {- beforeEach(() => vi.clearAllMocks())+ beforeEach(() => {+ vi.clearAllMocks()+ mockCheckRateLimit.mockReset().mockResolvedValue({ allowed: true })+ })- it("enables rate limiting only in production", async () => {+ it("turns off better-auth's built-in rate limiter — we run our own inside sendVerificationOTP", async () => {const createAuth = await loadCreateAuth()- const envProd = makeEnv({ NODE_ENV: "production" })- const optsProd = (createAuth(envProd as never) as { __options: AuthOptions }).__options- expect(optsProd.rateLimit.enabled).toBe(true)+ const optsProd = (createAuth(makeEnv({ NODE_ENV: "production" }) as never) as { __options: AuthOptions }).__options+ expect(optsProd.rateLimit.enabled).toBe(false)- const envDev = makeEnv({ NODE_ENV: "development" })- const optsDev = (createAuth(envDev as never) as { __options: AuthOptions }).__options+ const optsDev = (createAuth(makeEnv({ NODE_ENV: "development" }) as never) as { __options: AuthOptions }).__optionsexpect(optsDev.rateLimit.enabled).toBe(false)})- it("uses default 5/60s for the OTP path when env vars are unset", async () => {+ it("calls checkRateLimit('auth:otpSend', email) with the default 5/60s policy", async () => {const createAuth = await loadCreateAuth()const env = makeEnv({ NODE_ENV: "production" })const opts = (createAuth(env as never) as { __options: AuthOptions }).__options- expect(opts.rateLimit.customRules["/email-otp/send-verification-otp"]).toEqual({- window: 60,- max: 5,- })+ await getSendOtp(opts)({ email: "[email protected]", otp: "1234", type: "sign-in" })+ expect(mockCheckRateLimit).toHaveBeenCalledWith(+ env,+ "auth:otpSend",+ "[email protected]",+ { windowMs: 60_000, max: 5 },+ )})it("honours AUTH_OTP_RATE_LIMIT_MAX / _WINDOW_SEC overrides", async () => {@@ -132,10 +144,13 @@ describe("createAuth rate limiting", () => {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,- })+ await getSendOtp(opts)({ email: "[email protected]", otp: "1234", type: "sign-in" })+ expect(mockCheckRateLimit).toHaveBeenCalledWith(+ env,+ "auth:otpSend",+ "[email protected]",+ { windowMs: 120_000, max: 3 },+ )})it("falls back to defaults when env overrides are non-numeric or zero", async () => {@@ -146,45 +161,25 @@ describe("createAuth rate limiting", () => {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,- })+ await getSendOtp(opts)({ email: "[email protected]", otp: "1234", type: "sign-in" })+ expect(mockCheckRateLimit).toHaveBeenCalledWith(+ env,+ "auth:otpSend",+ "[email protected]",+ { windowMs: 60_000, max: 5 },+ )})- it("customStorage round-trips values through KV with a >=60s TTL", async () => {+ it("throws before sending when the rate limiter blocks", async () => {+ mockCheckRateLimit.mockResolvedValueOnce({ allowed: false, retryAfterSec: 42 })const createAuth = await loadCreateAuth()const env = makeEnv({ NODE_ENV: "production" })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()- const env = makeEnv({ NODE_ENV: "production", 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()- const env = makeEnv({ NODE_ENV: "production", 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)+ const sendOtp = getSendOtp(opts)+ await expect(+ sendOtp({ email: "[email protected]", otp: "1234", type: "sign-in" }),+ ).rejects.toThrow(/retry in 42s/)+ expect(env.EMAIL_WORKER.fetch).not.toHaveBeenCalled()})})diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.tsindex d4ce183de..033761b53 100644--- a/src/web/src/lib/auth.ts+++ b/src/web/src/lib/auth.ts@@ -8,16 +8,18 @@ import {queries,COMMUNITY_BOT_EMAIL_DOMAIN,computeDiscriminator,+ RATE_LIMITS,} from "@alook/shared"import { getDb } from "@/lib/db"+import { checkRateLimit } from "@/lib/rate-limit"import { getOtpSubject, renderOtpEmail } from "./email-templates"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+const DEFAULT_OTP_RATE_LIMIT_MAX = RATE_LIMITS["auth:otpSend"].max+const DEFAULT_OTP_RATE_LIMIT_WINDOW_SEC = Math.round(+ RATE_LIMITS["auth:otpSend"].windowMs / 1000,+)function parsePositiveInt(raw: string | undefined, fallback: number): number {if (!raw) return fallback@@ -33,8 +35,6 @@ export function createAuth(env: Env) {env.AUTH_OTP_RATE_LIMIT_WINDOW_SEC,DEFAULT_OTP_RATE_LIMIT_WINDOW_SEC,)- const kvTtl = Math.max(KV_MIN_TTL_SEC, otpWindow)-const validateClient = (clientId: string) => {const allowed = (env.DEVICE_CLIENT_IDS || "").split(",").map((s) => s.trim()).filter(Boolean)return allowed.includes(clientId)@@ -79,20 +79,14 @@ export function createAuth(env: Env) {clientSecret: env.GOOGLE_CLIENT_SECRET,},},+ // Better-auth's built-in rate limiter is intentionally OFF — we run our+ // own DO-backed limiter inside `sendVerificationOTP` below. That gives+ // the OTP path strong consistency (better-auth's `customStorage`+ // adapter would still be a `get → mutate → put` sequence, race-prone+ // against KV; our DO handles the counter atomically) AND keeps every+ // rate limit going through the shared `RATE_LIMITS` registry.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 })- },- },+ enabled: false,},databaseHooks: {user: {@@ -182,6 +176,21 @@ export function createAuth(env: Env) {bearer(),emailOTP({async sendVerificationOTP({ email, otp, type }) {+ // Rate-limit BEFORE minting/sending the OTP so abuse can't+ // burn a token slot or hit the email worker. Keyed by email+ // (the sender's target); anyone attempting to spam a+ // specific inbox gets throttled per inbox.+ const rate = await checkRateLimit(env, "auth:otpSend", email, {+ windowMs: otpWindow * 1000,+ max: otpMax,+ })+ if (!rate.allowed) {+ log.warn("OTP send rate-limited", {+ to: email,+ retryAfterSec: rate.retryAfterSec,+ })+ throw new Error(`OTP rate limit; retry in ${rate.retryAfterSec}s`)+ }log.info("sending OTP email", { to: email, type })try {const otpPayload = JSON.stringify({diff --git a/src/web/src/lib/cache.ts b/src/web/src/lib/cache.tsindex 661039672..956dbbe7c 100644--- a/src/web/src/lib/cache.ts+++ b/src/web/src/lib/cache.ts@@ -1,3 +1,55 @@+/**+ * ⚠️ READ BEFORE ADDING NEW HELPERS TO THIS MODULE ⚠️+ *+ * This module is backed by **Cloudflare Workers KV**, which is explicitly+ * **eventually consistent** — not "usually consistent," not "consistent+ * within one PoP." Cloudflare's own docs are blunt about this:+ *+ * "Changes are usually immediately visible at the location where they+ * are made. However, this is not guaranteed."+ * — https://developers.cloudflare.com/kv/concepts/how-kv-works/+ *+ * Concretely, KV does not give you:+ * - Atomic read-modify-write / compare-and-swap+ * - Transactions+ * - Any ordering guarantee across writes to the same key+ * - Read-your-writes, even from the same isolate+ *+ * A `get → mutate → put` on the same key from two concurrent Workers can+ * — and will, under load — both read the same value and both write, with+ * one update silently lost (last-write-wins). Reads from another PoP can+ * see a stale value for up to the cache TTL (~60s default).+ *+ * ✅ Use this module for:+ * - Pure TTL memoization / read-through cache (`cached`, `cachedBatch`)+ * - Best-effort throttles where a double-run is safe (`throttled`)+ * - Negative-cache flags with short TTLs, config, feature flags,+ * whitelists, static-content indexes — the classic "write rarely,+ * read a lot" workloads KV is designed for.+ *+ * ❌ DO NOT use this module for:+ * - Rate limiters (community message send, OTP, quota gates)+ * - Locks / mutual exclusion+ * - Counters / tallies where the exact count gates access+ * - Unique-id allocation+ * - Anything that reads-then-writes based on the read value+ *+ * For strongly-consistent state, use a **Durable Object**. A DO instance+ * is single-threaded and `ctx.storage` is strongly consistent — exactly+ * what the workloads above need. Canonical examples in this repo:+ * - `src/shared/src/lib/rate-limits.ts` — every policy (windowMs, max)+ * in one registry; every caller names a policy from here+ * - `src/ws-do/src/rate-limit-do.ts` — the parameterized DO class+ * - `src/web/src/lib/rate-limit.ts` — `checkRateLimit(env, name, key)`,+ * the single entry point used by both community message send and+ * auth OTP send+ *+ * If in doubt: does the correctness of your feature depend on the count+ * being exact, the value being current, or the write being visible on+ * the next read? If yes → DO. If no (a stale value / double-run / lost+ * update is genuinely harmless) → KV via this module is fine.+ */+const log = {warn(msg: string, ctx: Record<string, unknown>) {console.log(JSON.stringify({ level: "warn", service: "cache", msg, ...ctx, ts: new Date().toISOString() }));@@ -95,6 +147,16 @@ export async function cachedBatch<T>(* Timestamp-based throttle — not limited by KV's 60s minimum TTL.* Stores last-run timestamp in KV; skips `fn` if within `intervalSeconds`.* Returns true if `fn` ran, false if throttled.+ *+ * ⚠️ CF KV is NOT strongly consistent. This is a read-then-write against+ * eventual-consistency storage — two concurrent Workers can both read+ * "not set" and both run `fn`. That's acceptable ONLY because every caller+ * of `throttled(...)` in this codebase can tolerate the occasional+ * double-run (sweep jobs, negative-cache flags, last-used bumps —+ * self-healing on the next call).+ *+ * For a counter that MUST NOT overshoot (rate limit, quota), use a+ * Durable Object — see `src/ws-do/src/rate-limit-do.ts`.*/export async function throttled(key: string,diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 1fd32d14c..c7541f9a8 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -84,9 +84,6 @@ export async function createCommunityMessage(params: {const { db, authorId, target, body, source } = paramsconst content = typeof body.content === "string" ? body.content : ""- if (!content || content.trim().length === 0) {- return { ok: false, status: 400, error: "content is required" }- }if (content.length > MAX_MESSAGE_CONTENT_LENGTH) {return {ok: false,@@ -109,6 +106,13 @@ export async function createCommunityMessage(params: {}}+ // A message needs either text content OR at least one attachment. Empty+ // both means the client wired something wrong — but a bare+ // attachments-only send is a legitimate flow (drop an image, hit Enter).+ if (content.trim().length === 0 && (!incomingAttachments || incomingAttachments.length === 0)) {+ return { ok: false, status: 400, error: "content or attachments required" }+ }+const replyToId =typeof body.replyToId === "string" ? body.replyToId : undefinedconst mentionType: MentionType | undefined =diff --git a/src/web/src/lib/community/rate-limit.test.ts b/src/web/src/lib/community/rate-limit.test.tsdeleted file mode 100644index 716c409e2..000000000--- a/src/web/src/lib/community/rate-limit.test.ts+++ /dev/null@@ -1,78 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { checkMessageRateLimit } from "./rate-limit"--function makeKv() {- const store = new Map<string, string>()- return {- get: vi.fn(async (key: string) => store.get(key) ?? null),- put: vi.fn(async (key: string, value: string) => {- store.set(key, value)- }),- _store: store,- }-}--describe("checkMessageRateLimit", () => {- beforeEach(() => {- vi.useRealTimers()- })-- it("allows the first request for a user with no prior state", async () => {- const kv = makeKv()- const result = await checkMessageRateLimit(kv as any, "user-1")- expect(result.allowed).toBe(true)- expect(kv.put).toHaveBeenCalledTimes(1)- })-- it("allows up to the configured max within a window", async () => {- const kv = makeKv()- for (let i = 0; i < 30; i++) {- const result = await checkMessageRateLimit(kv as any, "user-1")- expect(result.allowed).toBe(true)- }- })-- it("rejects the request past the configured max within the same window", async () => {- const kv = makeKv()- for (let i = 0; i < 30; i++) {- await checkMessageRateLimit(kv as any, "user-1")- }- const result = await checkMessageRateLimit(kv as any, "user-1")- expect(result.allowed).toBe(false)- if (!result.allowed) {- expect(result.retryAfterSec).toBeGreaterThan(0)- }- })-- it("does not block a different user sharing the same KV store", async () => {- const kv = makeKv()- for (let i = 0; i < 30; i++) {- await checkMessageRateLimit(kv as any, "user-1")- }- const blocked = await checkMessageRateLimit(kv as any, "user-1")- expect(blocked.allowed).toBe(false)-- const other = await checkMessageRateLimit(kv as any, "user-2")- expect(other.allowed).toBe(true)- })-- it("allows again once the window has elapsed", async () => {- const kv = makeKv()- const nowSpy = vi.spyOn(Date, "now")- let currentTime = 1_000_000- nowSpy.mockImplementation(() => currentTime)-- for (let i = 0; i < 30; i++) {- await checkMessageRateLimit(kv as any, "user-1")- }- const blocked = await checkMessageRateLimit(kv as any, "user-1")- expect(blocked.allowed).toBe(false)-- // Advance past the 10s window.- currentTime += 10_001- const allowedAgain = await checkMessageRateLimit(kv as any, "user-1")- expect(allowedAgain.allowed).toBe(true)-- nowSpy.mockRestore()- })-})diff --git a/src/web/src/lib/community/rate-limit.ts b/src/web/src/lib/community/rate-limit.tsdeleted file mode 100644index 30b90f4a1..000000000--- a/src/web/src/lib/community/rate-limit.ts+++ /dev/null@@ -1,55 +0,0 @@-/**- * Per-user rate limit for community message-send routes, backed by the- * existing `RATE_LIMIT_KV` namespace (already used by better-auth in- * `lib/auth.ts` — separate key prefix so the two never collide).- *- * Fixed-window counter: at most `MAX_MESSAGES_PER_WINDOW` sends per user per- * `WINDOW_MS`. Keyed by userId only (not per-channel/DM) — the goal is to- * stop a single attacker from flooding any channel, regardless of how many- * targets they spread requests across. `expirationTtl` self-cleans the KV- * entry, so there's no sweep/cron needed.- *- * Limits start deliberately generous — the goal is killing scripted- * flooding, not throttling normal chat bursts. Tune down if abuse is- * observed in practice.- */--const WINDOW_MS = 10_000-const MAX_MESSAGES_PER_WINDOW = 30--type RateLimitState = { count: number; windowStart: number }--export type RateLimitResult =- | { allowed: true }- | { allowed: false; retryAfterSec: number }--export async function checkMessageRateLimit(- kv: KVNamespace,- userId: string,-): Promise<RateLimitResult> {- const key = `community:msgrate:${userId}`- const now = Date.now()- const raw = await kv.get(key)- const state: RateLimitState | null = raw ? JSON.parse(raw) : null-- if (!state || now - state.windowStart >= WINDOW_MS) {- await kv.put(- key,- JSON.stringify({ count: 1, windowStart: now } satisfies RateLimitState),- { expirationTtl: Math.ceil(WINDOW_MS / 1000) },- )- return { allowed: true }- }-- if (state.count >= MAX_MESSAGES_PER_WINDOW) {- const retryAfterSec = Math.ceil((state.windowStart + WINDOW_MS - now) / 1000)- return { allowed: false, retryAfterSec: Math.max(retryAfterSec, 1) }- }-- await kv.put(- key,- JSON.stringify({ count: state.count + 1, windowStart: state.windowStart } satisfies RateLimitState),- { expirationTtl: Math.ceil(WINDOW_MS / 1000) },- )- return { allowed: true }-}diff --git a/src/web/src/lib/rate-limit.test.ts b/src/web/src/lib/rate-limit.test.tsnew file mode 100644index 000000000..368009217--- /dev/null+++ b/src/web/src/lib/rate-limit.test.ts@@ -0,0 +1,70 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"+import { checkRateLimit } from "./rate-limit"++const mockWsDoFetch = vi.fn()+vi.mock("@/lib/broadcast", () => ({+ wsDoFetch: (...a: unknown[]) => mockWsDoFetch(...a),+}))++describe("checkRateLimit — unified rate-limit entry", () => {+ beforeEach(() => {+ mockWsDoFetch.mockReset()+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ it("looks up the registered policy and forwards it to the DO", async () => {+ mockWsDoFetch.mockResolvedValue(+ new Response(JSON.stringify({ allowed: true }), { status: 200 }),+ )+ await checkRateLimit({} as Env, "community:msgSend", "u_1")+ const [, path, init] = mockWsDoFetch.mock.calls[0]!+ expect(path).toBe("/rate-limit/check")+ const body = JSON.parse((init as RequestInit).body as string)+ expect(body).toEqual({+ name: "community:msgSend",+ key: "u_1",+ windowMs: 10_000,+ max: 30,+ })+ })++ it("supports per-call overrides for policies whose limits are configurable", async () => {+ mockWsDoFetch.mockResolvedValue(+ new Response(JSON.stringify({ allowed: true }), { status: 200 }),+ )+ await checkRateLimit({} as Env, "auth:otpSend", "[email protected]", {+ windowMs: 120_000,+ max: 3,+ })+ const [, , init] = mockWsDoFetch.mock.calls[0]!+ expect(JSON.parse((init as RequestInit).body as string)).toEqual({+ name: "auth:otpSend",+ key: "[email protected]",+ windowMs: 120_000,+ max: 3,+ })+ })++ it("returns the DO response verbatim on success", async () => {+ mockWsDoFetch.mockResolvedValue(+ new Response(JSON.stringify({ allowed: false, retryAfterSec: 7 }), { status: 200 }),+ )+ const r = await checkRateLimit({} as Env, "community:msgSend", "u_1")+ expect(r).toEqual({ allowed: false, retryAfterSec: 7 })+ })++ it("fails open on non-2xx transport failure", async () => {+ mockWsDoFetch.mockResolvedValue(new Response("boom", { status: 503 }))+ const r = await checkRateLimit({} as Env, "community:msgSend", "u_1")+ expect(r).toEqual({ allowed: true })+ })++ it("fails open when wsDoFetch throws", async () => {+ mockWsDoFetch.mockRejectedValue(new Error("network"))+ const r = await checkRateLimit({} as Env, "community:msgSend", "u_1")+ expect(r).toEqual({ allowed: true })+ })+})diff --git a/src/web/src/lib/rate-limit.ts b/src/web/src/lib/rate-limit.tsnew file mode 100644index 000000000..f5e7d1bfc--- /dev/null+++ b/src/web/src/lib/rate-limit.ts@@ -0,0 +1,60 @@+import { wsDoFetch } from "@/lib/broadcast"+import { RATE_LIMITS, type RateLimitName, type RateLimitPolicy, type RateLimitResult } from "@alook/shared"++// Re-export the shared types from this module so route handlers only need+// one import path (`@/lib/rate-limit`) instead of two.+export type { RateLimitName, RateLimitPolicy, RateLimitResult }++/**+ * Unified rate-limit entry point for every rate-limit-sensitive path in+ * this app. Adds a new rate limit? Register it in+ * `src/shared/src/lib/rate-limits.ts` first, then call this helper.+ *+ * Backed by `RateLimitDurableObject` in the `alook-ws-do` worker via the+ * `WS_DO_WORKER` service binding. The DO's `ctx.storage` is strongly+ * consistent, so concurrent callers can't leak past the cap the way a+ * KV-backed counter could.+ *+ * Sharding: one DO instance per (name, key) pair — different rate-limit+ * names never collide even with a shared key.+ *+ * Fail-open: transport errors return `{ allowed: true }`. The DO is a+ * strong-consistency counter, not a security perimeter; auth/authz above+ * the rate limit is what actually gates access. Locking every user out+ * because we can't reach the DO would be a worse failure mode.+ *+ * @param env Worker env (used to reach `WS_DO_WORKER`).+ * @param name Registered policy name — must exist in `RATE_LIMITS`.+ * @param key Caller-chosen shard key. Typically userId, but any stable+ * string works (email, IP, `${userId}:${channelId}`, …).+ * @param overrides Optional per-call override of `windowMs` / `max`. Use+ * sparingly — the registry is meant to be the source of+ * truth. Currently used only for auth OTP where the+ * window is env-configurable.+ */+export async function checkRateLimit(+ env: Env,+ name: RateLimitName,+ key: string,+ overrides?: Partial<RateLimitPolicy>,+): Promise<RateLimitResult> {+ const policy = RATE_LIMITS[name]+ const windowMs = overrides?.windowMs ?? policy.windowMs+ const max = overrides?.max ?? policy.max+ try {+ const res = await wsDoFetch(+ env,+ "/rate-limit/check",+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name, key, windowMs, max }),+ },+ { label: `${name}:${key}`, type: "rate-limit" },+ )+ if (!res.ok) return { allowed: true }+ return (await res.json()) as RateLimitResult+ } catch {+ return { allowed: true }+ }+}diff --git a/src/web/wrangler.toml b/src/web/wrangler.tomlindex cdbcc9495..f5cdf5a8f 100644--- a/src/web/wrangler.toml+++ b/src/web/wrangler.toml@@ -86,10 +86,6 @@ queue = "alook-wake"binding = "WAKE_WORKER"service = "alook-wake-worker"-[[kv_namespaces]]-binding = "RATE_LIMIT_KV"-id = "a3d035bea7bc49d99377b82ec21ce4c1"-[[kv_namespaces]]binding = "CACHE_KV"id = "3aaa92b4c2c74185b888977e5552e9bf"diff --git a/src/ws-do/src/env.d.ts b/src/ws-do/src/env.d.tsindex 6e8929845..36a179650 100644--- a/src/ws-do/src/env.d.ts+++ b/src/ws-do/src/env.d.ts@@ -1,4 +1,5 @@interface Env {DB: D1DatabaseWS_DO: DurableObjectNamespace+ RATE_LIMIT_DO: DurableObjectNamespace}diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.tsindex 028df0dfb..6f6be5971 100644--- a/src/ws-do/src/index.test.ts+++ b/src/ws-do/src/index.test.ts@@ -1,10 +1,13 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { createMockDONamespace } from "./__mocks__/cf"-// Mock ws-durable so the router import doesn't pull in cloudflare:workers+// Mock ws-durable / rate-limit-do so the router import doesn't pull in cloudflare:workersvi.mock("./ws-durable", () => ({WebSocketDurableObject: class { },}))+vi.mock("./rate-limit-do", () => ({+ RateLimitDurableObject: class { },+}))const mockHashCredential = vi.fn(async (bearer: string) => `sha256:${bearer}`)const mockDoNameFromHash = vi.fn((hash: string) => hash.slice(0, 32))diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.tsindex 12f2ab78f..735260654 100644--- a/src/ws-do/src/index.ts+++ b/src/ws-do/src/index.ts@@ -1,6 +1,7 @@import { createLogger, queries } from "@alook/shared"export { WebSocketDurableObject } from "./ws-durable"+export { RateLimitDurableObject } from "./rate-limit-do"const log = createLogger({ service: "ws-do" })@@ -12,6 +13,44 @@ export default {return Response.json({ status: "ok" })}+ // Strongly-consistent, parameterized rate limiter. Every rate-limit+ // call site (community message send, auth OTP, future policies) hits+ // this single endpoint with a `{ name, key, windowMs, max }` payload+ // — one DO instance per (name, key) pair. Policy values come from the+ // shared `RATE_LIMITS` registry in `src/shared/src/lib/rate-limits.ts`+ // so ceilings live in one place, not scattered across route handlers.+ //+ // See `rate-limit-do.ts` for the counter logic.+ if (url.pathname === "/rate-limit/check" && request.method === "POST") {+ let body: unknown+ try {+ body = await request.json()+ } catch {+ return new Response("invalid json", { status: 400 })+ }+ const { name, key, windowMs, max } = (body ?? {}) as {+ name?: unknown+ key?: unknown+ windowMs?: unknown+ max?: unknown+ }+ if (typeof name !== "string" || name.length === 0) {+ return new Response("name required", { status: 400 })+ }+ if (typeof key !== "string" || key.length === 0) {+ return new Response("key required", { status: 400 })+ }+ const doId = env.RATE_LIMIT_DO.idFromName(name + ":" + key)+ const stub = env.RATE_LIMIT_DO.get(doId)+ return stub.fetch(+ new Request("http://internal/check", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ windowMs, max }),+ }),+ )+ }+const traceId = request.headers.get("X-Trace-Id") ?? undefinedconst daemonBroadcast = url.pathname.match(/^\/broadcast\/daemon\/(.+)$/)diff --git a/src/ws-do/src/rate-limit-do.test.ts b/src/ws-do/src/rate-limit-do.test.tsnew file mode 100644index 000000000..69ebd4c8e--- /dev/null+++ b/src/ws-do/src/rate-limit-do.test.ts@@ -0,0 +1,109 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { createMockCtx } from "./__mocks__/cf"++vi.mock("cloudflare:workers", () => ({+ DurableObject: class {+ ctx: unknown+ env: unknown+ constructor(ctx: unknown, env: unknown) {+ this.ctx = ctx+ this.env = env+ }+ },+}))++import { RateLimitDurableObject } from "./rate-limit-do"++function makeDO() {+ const mock = createMockCtx()+ const doInstance = new RateLimitDurableObject(mock.ctx, {} as Env)+ return { doInstance, ...mock }+}++async function check(+ doInstance: RateLimitDurableObject,+ windowMs: number,+ max: number,+) {+ const res = await doInstance.fetch(+ new Request("http://internal/check", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ windowMs, max }),+ }),+ )+ return (await res.json()) as { allowed: boolean; retryAfterSec?: number }+}++describe("RateLimitDurableObject", () => {+ beforeEach(() => {+ vi.useRealTimers()+ })++ it("allows the first request when no state exists", async () => {+ const { doInstance } = makeDO()+ expect((await check(doInstance, 10_000, 30)).allowed).toBe(true)+ })++ it("allows up to `max` sends within one window", async () => {+ const { doInstance } = makeDO()+ for (let i = 0; i < 30; i++) {+ expect((await check(doInstance, 10_000, 30)).allowed).toBe(true)+ }+ })++ it("blocks the (max+1)th send with a positive retryAfter", async () => {+ const { doInstance } = makeDO()+ for (let i = 0; i < 30; i++) await check(doInstance, 10_000, 30)+ const blocked = await check(doInstance, 10_000, 30)+ expect(blocked.allowed).toBe(false)+ expect(blocked.retryAfterSec).toBeGreaterThan(0)+ })++ it("honours the caller-supplied window+max — the DO is policy-agnostic", async () => {+ const { doInstance } = makeDO()+ // Different caller with a tiny 3/1s policy+ for (let i = 0; i < 3; i++) {+ expect((await check(doInstance, 1_000, 3)).allowed).toBe(true)+ }+ expect((await check(doInstance, 1_000, 3)).allowed).toBe(false)+ })++ it("resets the window once WINDOW has elapsed", async () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date("2026-01-01T00:00:00Z"))+ const { doInstance } = makeDO()+ for (let i = 0; i < 30; i++) await check(doInstance, 10_000, 30)+ expect((await check(doInstance, 10_000, 30)).allowed).toBe(false)+ vi.advanceTimersByTime(10_001)+ expect((await check(doInstance, 10_000, 30)).allowed).toBe(true)+ })++ it("returns 400 when windowMs/max is missing or non-positive", async () => {+ const { doInstance } = makeDO()+ const res = await doInstance.fetch(+ new Request("http://internal/check", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ windowMs: 0, max: -1 }),+ }),+ )+ expect(res.status).toBe(400)+ })++ it("returns 404 for unknown paths", async () => {+ const { doInstance } = makeDO()+ const res = await doInstance.fetch(+ new Request("http://internal/nope", { method: "POST" }),+ )+ expect(res.status).toBe(404)+ })++ it("persists the counter across DO instances (survives eviction)", async () => {+ const mock = createMockCtx()+ const a = new RateLimitDurableObject(mock.ctx, {} as Env)+ for (let i = 0; i < 30; i++) await check(a, 10_000, 30)+ const b = new RateLimitDurableObject(mock.ctx, {} as Env)+ expect((await check(b, 10_000, 30)).allowed).toBe(false)+ })+})diff --git a/src/ws-do/src/rate-limit-do.ts b/src/ws-do/src/rate-limit-do.tsnew file mode 100644index 000000000..3e856bc5a--- /dev/null+++ b/src/ws-do/src/rate-limit-do.ts@@ -0,0 +1,82 @@+import { DurableObject } from "cloudflare:workers"++/**+ * Strongly-consistent, parameterized rate limiter.+ *+ * Cloudflare KV is eventually consistent (see+ * https://developers.cloudflare.com/kv/concepts/how-kv-works/) and has no+ * atomic read-modify-write, so any counter driven by `get → mutate → put`+ * can leak past its cap under concurrent load. A Durable Object instance+ * is single-threaded and its `ctx.storage` is strongly consistent, which+ * is exactly what a rate limiter needs.+ *+ * Every rate-limit call is a fixed-window counter parameterized by+ * `{ windowMs, max }`. The policy is chosen by the CALLER — see the shared+ * `RATE_LIMITS` registry in `src/shared/src/lib/rate-limits.ts` for the+ * canonical list of policies used across the app. This class is+ * intentionally policy-agnostic: adding a new rate limit means adding a+ * row to that registry, not editing this file.+ *+ * Sharding: one DO instance per key via `idFromName(name + ":" + key)`.+ * Different rate-limit names never collide even when they share a key+ * (e.g. same userId for both `community:msgSend` and `auth:otpSend`).+ *+ * Endpoint:+ * POST /check+ * Body: { windowMs: number, max: number }+ * Response: { allowed: true } | { allowed: false, retryAfterSec: number }+ */++type WindowState = { count: number; windowStart: number }++const STATE_KEY = "state"++export type RateLimitResult =+ | { allowed: true }+ | { allowed: false; retryAfterSec: number }++export class RateLimitDurableObject extends DurableObject<Env> {+ async fetch(request: Request): Promise<Response> {+ const url = new URL(request.url)++ if (url.pathname === "/check" && request.method === "POST") {+ let body: unknown+ try {+ body = await request.json()+ } catch {+ return new Response("invalid json", { status: 400 })+ }+ const { windowMs, max } = (body ?? {}) as { windowMs?: unknown; max?: unknown }+ if (+ typeof windowMs !== "number" || !Number.isFinite(windowMs) || windowMs <= 0 ||+ typeof max !== "number" || !Number.isFinite(max) || max <= 0+ ) {+ return new Response("windowMs and max must be positive numbers", { status: 400 })+ }+ return Response.json(await this.check(windowMs, max))+ }++ return new Response("not found", { status: 404 })+ }++ private async check(windowMs: number, max: number): Promise<RateLimitResult> {+ const now = Date.now()+ const state = (await this.ctx.storage.get<WindowState>(STATE_KEY)) ?? null++ if (!state || now - state.windowStart >= windowMs) {+ await this.ctx.storage.put<WindowState>(STATE_KEY, { count: 1, windowStart: now })+ return { allowed: true }+ }++ if (state.count >= max) {+ const retryAfterSec = Math.ceil((state.windowStart + windowMs - now) / 1000)+ return { allowed: false, retryAfterSec: Math.max(retryAfterSec, 1) }+ }++ await this.ctx.storage.put<WindowState>(STATE_KEY, {+ count: state.count + 1,+ windowStart: state.windowStart,+ })+ return { allowed: true }+ }+}diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex d5d664a2e..aa43268e2 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -203,6 +203,7 @@ function createDO() {idFromName: vi.fn().mockReturnValue("mock-do-id"),get: stubGet,} as unknown as DurableObjectNamespace,+ RATE_LIMIT_DO: {} as DurableObjectNamespace,}const durable = new WebSocketDurableObject(ctx, env)return { durable, ctx, getWebSockets, env, stubGet, storage, store }diff --git a/src/ws-do/wrangler.toml b/src/ws-do/wrangler.tomlindex d0016e5a9..879eed286 100644--- a/src/ws-do/wrangler.toml+++ b/src/ws-do/wrangler.toml@@ -32,6 +32,14 @@ database_name = "alook-app"name = "WS_DO"class_name = "WebSocketDurableObject"+[[durable_objects.bindings]]+name = "RATE_LIMIT_DO"+class_name = "RateLimitDurableObject"+[[migrations]]tag = "v1"new_sqlite_classes = ["WebSocketDurableObject"]++[[migrations]]+tag = "v2"+new_sqlite_classes = ["RateLimitDurableObject"]diff --git a/tests/integration/cli/community-rate-limit.test.ts b/tests/integration/cli/community-rate-limit.test.tsnew file mode 100644index 000000000..ad4c1a5a4--- /dev/null+++ b/tests/integration/cli/community-rate-limit.test.ts@@ -0,0 +1,105 @@+/**+ * End-to-end verification of the community message rate limiter.+ *+ * The limiter lives in a Durable Object (`RateLimitDurableObject` in+ * `src/ws-do/`) and is reached from the web worker via the `WS_DO_WORKER`+ * service binding. Since `wsDoFetch` falls open on transport failure, a+ * successful rejection at request 31 also proves the DO round-trip is+ * actually happening — a broken transport would let every request through.+ *+ * Requires both dev servers running (web on :3000, ws-do on :8789).+ */+import { describe, it, expect, beforeAll, afterAll } from "vitest"+import { randomUUID } from "crypto"+import {+ seedTestData,+ cleanupTestData,+ sessionRequest,+ signIn,+ sqlRun,+ type TestSeed,+} from "@alook/test-utils"++let seed: TestSeed+let cookie: string+let serverId: string+let channelId: string++function nanoid() {+ return randomUUID().replace(/-/g, "").slice(0, 21)+}++beforeAll(async () => {+ seed = seedTestData()+ cookie = await signIn(seed.authEmail, seed.authPassword)++ const now = new Date().toISOString()+ serverId = `srv_${nanoid()}`+ channelId = `chn_${nanoid()}`++ sqlRun(+ `INSERT INTO community_server (id, name, description, owner_id, created_at) VALUES (?, ?, ?, ?, ?)`,+ serverId,+ "Rate Limit Test Server",+ "",+ seed.userId,+ now,+ )+ sqlRun(+ `INSERT INTO community_server_member (id, server_id, user_id, role, joined_at) VALUES (?, ?, ?, ?, ?)`,+ `mem_${nanoid()}`,+ serverId,+ seed.userId,+ "owner",+ now,+ )+ sqlRun(+ `INSERT INTO community_channel (id, server_id, name, type, position, created_at) VALUES (?, ?, ?, ?, ?, ?)`,+ channelId,+ serverId,+ "general",+ "text",+ 0,+ now,+ )+})++afterAll(() => {+ try {+ sqlRun(`DELETE FROM community_message WHERE channel_id = ?`, channelId)+ sqlRun(`DELETE FROM community_channel WHERE id = ?`, channelId)+ sqlRun(`DELETE FROM community_server_member WHERE server_id = ?`, serverId)+ sqlRun(`DELETE FROM community_server WHERE id = ?`, serverId)+ } catch { /* ignore */ }+ cleanupTestData(seed)+})++describe("community message rate limit — DO-backed", () => {+ it("allows the first 30 sends inside one window, then returns 429 with Retry-After", async () => {+ const results: number[] = []+ for (let i = 0; i < 31; i++) {+ const res = await sessionRequest(+ `/api/community/channels/${channelId}/messages`,+ cookie,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ content: `rate-limit-e2e ${i}` }),+ },+ )+ results.push(res.status)+ if (i === 30) {+ // The 31st request must be blocked, not fail-open. The Retry-After+ // header is set by writeError() when the DO returns { allowed: false }.+ const retryAfter = res.headers.get("retry-after")+ expect(retryAfter).toBeTruthy()+ expect(Number(retryAfter)).toBeGreaterThan(0)+ }+ }+ // First 30 accepted (201). If any of them 429, the counter started with+ // stale state from a previous run — reset with `pnpm db:reset`.+ const accepted = results.slice(0, 30).filter((s) => s === 201).length+ expect(accepted).toBe(30)+ expect(results[30]).toBe(429)+ }, 30_000)+})