Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): architecture health hardening + dev port cleanup (#346)

Gener8120685330f5
diff --git a/.env.example b/.env.example
index f66f257c7..7b889e14f 100644
--- a/.env.example
+++ b/.env.example
@@ -37,7 +37,7 @@
# DEV_WS_DO_URL=http://localhost:8789
# Email worker URL (must match src/email-worker/wrangler.toml port)
-# DEV_EMAIL_WORKER_URL=http://localhost:8788
+# DEV_EMAIL_WORKER_URL=http://localhost:8787
# Daemon health check server port
# ALOOK_HEALTH_PORT=19514
@@ -128,11 +128,12 @@
# WebSocket Durable Object port (dev only, must match src/ws-do/wrangler.toml)
# NEXT_PUBLIC_WS_DO_PORT=8789
-# Community machine daemon WS endpoint. The pair sheet renders this in the
-# copyable `npx @alook/daemon daemon start --ws-url <...>` command. The daemon
-# appends `?token=<machineKey>` automatically when no --server-url is given.
-# Prod default: wss://community.alook.ai/api/ws/community-daemon
-# NEXT_PUBLIC_COMMUNITY_DAEMON_WS_URL=ws://localhost:8789
+# The community pair sheet's copyable `npx @alook/daemon daemon start
+# --server-url <...> --ws-url <...>` command derives both URLs from the
+# browser's own location.origin (same pattern as use-user-ws.ts) — ws-do routes
+# community-daemon connections by their `Authorization: Bearer cmk_...`
+# header, not by host, so there's no dedicated env var for it. See
+# NEXT_PUBLIC_WS_DO_PORT above for the local dev WS port it falls back to.
# Initial reconnect delay (ms), doubles on each retry
# NEXT_PUBLIC_WS_RECONNECT_DELAY_MS=1000
diff --git a/.gitignore b/.gitignore
index 888355903..65364a715 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
node_modules/
+.pnpm-store/
dist/
bundled/
.turbo/
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index be0e742b9..397e4fb01 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -107,7 +107,7 @@ Tests run on both Ubuntu and Windows in CI.
| `pnpm dev` | Start all dev servers (except CLI) |
| `pnpm dev:web` | Next.js on :3000 |
| `pnpm dev:cli` | CLI daemon |
-| `pnpm dev:email` | Email worker on :8788 |
+| `pnpm dev:email` | Email worker on :8787 |
| `pnpm typecheck` | Typecheck all packages |
| `pnpm lint` | Lint all packages |
| `pnpm test` | Run all tests |
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7e27952b1..1858f0d89 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -530,6 +530,9 @@ importers:
tests/utils:
dependencies:
+ '@alook/shared':
+ specifier: workspace:*
+ version: link:../../src/shared
better-sqlite3:
specifier: ^12.11.1
version: 12.11.1
diff --git a/src/app/src/lib/constants.ts b/src/app/src/lib/constants.ts
index 97e0f6ef2..2c2cdcfa0 100644
--- a/src/app/src/lib/constants.ts
+++ b/src/app/src/lib/constants.ts
@@ -1,5 +1,6 @@
import { homedir } from "os";
import { join } from "path";
+import type { DevPortProfile } from "@alook/shared";
function resolveBaseDir(): string {
if (process.env.ALOOK_PROJECT_ROOT) {
@@ -11,10 +12,14 @@ function resolveBaseDir(): string {
export const SELF_HOSTED_DIR = resolveBaseDir();
export const PID_FILE = join(SELF_HOSTED_DIR, ".pids.json");
-export const DEFAULT_PORTS = {
+// Same shape as @alook/shared's DEV_PORTS (monorepo `pnpm dev`), but a
+// distinct value range — self-hosted instances run alongside a developer's
+// own checkout, so they can't share ports with it.
+export const DEFAULT_PORTS: DevPortProfile = {
web: 15210,
emailWorker: 15211,
wsDo: 15212,
-} as const;
+ wakeWorker: 15213,
+};
export const WEB_URL = (port: number) => `http://localhost:${port}`;
diff --git a/src/app/test/secrets.test.ts b/src/app/test/secrets.test.ts
index d71d05b9b..5eb5637a0 100644
--- a/src/app/test/secrets.test.ts
+++ b/src/app/test/secrets.test.ts
@@ -8,7 +8,7 @@ const testDir = join(tmpdir(), `alook-test-secrets-${process.pid}`);
vi.mock("../src/lib/constants.js", () => ({
SELF_HOSTED_DIR: testDir,
PID_FILE: join(testDir, ".pids.json"),
- DEFAULT_PORTS: { web: 3000, emailWorker: 8787, wsDo: 8789 },
+ DEFAULT_PORTS: { web: 3000, emailWorker: 8787, wsDo: 8789, wakeWorker: 8790 },
WEB_URL: (port: number) => `http://localhost:${port}`,
}));
diff --git a/src/app/test/services.test.ts b/src/app/test/services.test.ts
index 2d959358a..8515926fc 100644
--- a/src/app/test/services.test.ts
+++ b/src/app/test/services.test.ts
@@ -8,7 +8,7 @@ const testDir = join(tmpdir(), `alook-test-services-${process.pid}`);
vi.mock("../src/lib/constants.js", () => ({
SELF_HOSTED_DIR: testDir,
PID_FILE: join(testDir, ".pids.json"),
- DEFAULT_PORTS: { web: 3000, emailWorker: 8787, wsDo: 8789 },
+ DEFAULT_PORTS: { web: 3000, emailWorker: 8787, wsDo: 8789, wakeWorker: 8790 },
WEB_URL: (port: number) => `http://localhost:${port}`,
}));
diff --git a/src/cli/daemon/ws-client.ts b/src/cli/daemon/ws-client.ts
index 390ae496d..e0244ccb7 100644
--- a/src/cli/daemon/ws-client.ts
+++ b/src/cli/daemon/ws-client.ts
@@ -1,5 +1,5 @@
import { createLogger } from "../lib/logger.js";
-import { DaemonPushMessageSchema } from "@alook/shared";
+import { DaemonPushMessageSchema, devWsDoPort } from "@alook/shared";
import type { DaemonPushMessage } from "@alook/shared";
const log = createLogger({ module: "ws-client" });
@@ -8,7 +8,7 @@ const WS_RECONNECT_INIT = 1000;
const WS_RECONNECT_MAX = 30_000;
const WS_PING_INTERVAL = 25_000;
const WS_LIVENESS_TIMEOUT = 50_000;
-const WS_DO_DEV_PORT = Number(process.env.ALOOK_WS_DO_PORT) || 8789;
+const WS_DO_DEV_PORT = Number(process.env.ALOOK_WS_DO_PORT) || devWsDoPort();
export interface DaemonWsClientOptions {
serverURL: string;
diff --git a/src/email-worker/wrangler.toml b/src/email-worker/wrangler.toml
index 7697fab3e..6189dbd43 100644
--- a/src/email-worker/wrangler.toml
+++ b/src/email-worker/wrangler.toml
@@ -18,6 +18,7 @@ enabled = true
head_sampling_rate = 0.05
destinations = ["grafana-traces"]
+# Must match DEV_PORTS.emailWorker in src/shared/src/constants.ts
[dev]
port = 8787
inspector_port = 9231
diff --git a/src/shared/src/constants.ts b/src/shared/src/constants.ts
index 319f880e2..1c8d48323 100644
--- a/src/shared/src/constants.ts
+++ b/src/shared/src/constants.ts
@@ -159,9 +159,40 @@ export function isSelfBotFriendship(id: string): boolean {
// Dev mode auth (shared between web frontend and @alook/app CLI)
export const DEV_PASSWORD = "dev-password-000";
+/**
+ * Shape shared by every "which port does each service run on" profile in the
+ * monorepo — the monorepo-local dev profile below (`DEV_PORTS`) and the
+ * self-hosted `@alook/app` profile (`DEFAULT_PORTS` in
+ * src/app/src/lib/constants.ts, which uses the 1521x range so it doesn't
+ * collide with a developer's own `pnpm dev` checkout). Same format, two
+ * separate value sets on purpose.
+ */
+export interface DevPortProfile {
+ web: number;
+ emailWorker: number;
+ wsDo: number;
+ wakeWorker: number;
+}
+
+// Ports used by `pnpm dev:*` / `wrangler dev` in this monorepo — must match
+// each worker's wrangler.toml `[dev] port` (web via Next, wake-worker via
+// src/wake-worker/wrangler.toml). Single source of truth for the fallback
+// URLs below and every other hardcoded dev-port default across web/cli/daemon.
+export const DEV_PORTS: DevPortProfile = {
+ web: 3000,
+ emailWorker: 8787,
+ wsDo: 8789,
+ wakeWorker: 8790,
+};
+
// Local dev URLs (used for service-binding fallbacks)
-export const DEV_WEB_URL = process.env.ALOOK_SERVER_URL || "http://localhost:3000";
-export const DEV_WS_DO_URL = process.env.DEV_WS_DO_URL || "http://localhost:8789";
-export const DEV_EMAIL_WORKER_URL = process.env.DEV_EMAIL_WORKER_URL || "http://localhost:8787";
-// `src/wake-worker/wrangler.toml`'s `[dev] port` — see wake-transport.ts.
-export const DEV_WAKE_WORKER_URL = process.env.DEV_WAKE_WORKER_URL || "http://localhost:8790";
+export const DEV_WEB_URL = process.env.ALOOK_SERVER_URL || `http://localhost:${DEV_PORTS.web}`;
+export const DEV_WS_DO_URL = process.env.DEV_WS_DO_URL || `http://localhost:${DEV_PORTS.wsDo}`;
+export const DEV_EMAIL_WORKER_URL = process.env.DEV_EMAIL_WORKER_URL || `http://localhost:${DEV_PORTS.emailWorker}`;
+export const DEV_WAKE_WORKER_URL = process.env.DEV_WAKE_WORKER_URL || `http://localhost:${DEV_PORTS.wakeWorker}`;
+
+/** Local ws-do port — derived from `DEV_WS_DO_URL` so env overrides stay in sync. */
+export function devWsDoPort(): number {
+ const port = Number(new URL(DEV_WS_DO_URL).port);
+ return port || DEV_PORTS.wsDo;
+}
diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.ts
index 4c1ec4735..360139b42 100644
--- a/src/shared/src/db/queries/community/member.ts
+++ b/src/shared/src/db/queries/community/member.ts
@@ -362,6 +362,15 @@ export function removeOwnerBotsFromServerStatement(
);
}
+/** Executes `removeOwnerBotsFromServerStatement` — one DELETE for all bots. */
+export async function removeOwnerBotsFromServer(
+ db: Database,
+ serverId: string,
+ botUserIds: string[],
+) {
+ await removeOwnerBotsFromServerStatement(db, serverId, botUserIds);
+}
+
/**
* Wake-dispatch access re-check (unread-wake rebuild path,
* `buildUnreadWakeCommand`) — scoped in SQL before returning, per
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index 359011cb4..97b6b74f5 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -485,3 +485,73 @@ export async function getMessagesByIds(db: Database, ids: string[]) {
.where(inArray(communityMessage.id, ids));
return rows.map((r) => ({ ...r, embeds: safeParseEmbeds(r.embeds, r.id) }));
}
+
+/** Scope a single-id/batched-id lookup to a channel or DM. */
+export type MessageScope = { channelId: string } | { dmConversationId: string };
+
+function scopeCondition(scope: MessageScope) {
+ return "channelId" in scope
+ ? eq(communityMessage.channelId, scope.channelId)
+ : eq(communityMessage.dmConversationId, scope.dmConversationId);
+}
+
+/**
+ * Scope-first single-message lookup — `WHERE id = ? AND (channelId = ? OR
+ * dmConversationId = ?)`. Callers resolving a reply-target preview must use
+ * this instead of `getMessage` + a post-hoc `.filter()`: a message whose id a
+ * client supplies (e.g. `replyToId`) must never resolve outside the current
+ * channel/DM, and folding the check into the WHERE clause makes that
+ * impossible to accidentally drop in a future refactor (see AGENTS.md:
+ * "scope the queries before, not check the ownership after").
+ */
+export async function getMessageInScope(db: Database, messageId: string, scope: MessageScope) {
+ const rows = await db
+ .select({
+ id: communityMessage.id,
+ authorId: communityMessage.authorId,
+ content: communityMessage.content,
+ type: communityMessage.type,
+ mentionType: communityMessage.mentionType,
+ replyToId: communityMessage.replyToId,
+ embeds: communityMessage.embeds,
+ flags: communityMessage.flags,
+ createdAt: communityMessage.createdAt,
+ channelId: communityMessage.channelId,
+ dmConversationId: communityMessage.dmConversationId,
+ authorName: user.name,
+ authorEmail: user.email,
+ authorImage: user.image,
+ })
+ .from(communityMessage)
+ .innerJoin(user, eq(communityMessage.authorId, user.id))
+ .where(and(eq(communityMessage.id, messageId), scopeCondition(scope)));
+ const row = rows[0];
+ if (!row) return null;
+ return { ...row, embeds: safeParseEmbeds(row.embeds, row.id) };
+}
+
+/** Batched form of `getMessageInScope` — see its doc comment for the "why". */
+export async function getMessagesByIdsInScope(db: Database, ids: string[], scope: MessageScope) {
+ if (ids.length === 0) return [];
+ const rows = await db
+ .select({
+ id: communityMessage.id,
+ authorId: communityMessage.authorId,
+ content: communityMessage.content,
+ type: communityMessage.type,
+ mentionType: communityMessage.mentionType,
+ replyToId: communityMessage.replyToId,
+ embeds: communityMessage.embeds,
+ flags: communityMessage.flags,
+ createdAt: communityMessage.createdAt,
+ channelId: communityMessage.channelId,
+ dmConversationId: communityMessage.dmConversationId,
+ authorName: user.name,
+ authorEmail: user.email,
+ authorImage: user.image,
+ })
+ .from(communityMessage)
+ .innerJoin(user, eq(communityMessage.authorId, user.id))
+ .where(and(inArray(communityMessage.id, ids), scopeCondition(scope)));
+ return rows.map((r) => ({ ...r, embeds: safeParseEmbeds(r.embeds, r.id) }));
+}
diff --git a/src/shared/src/db/queries/runtime.ts b/src/shared/src/db/queries/runtime.ts
index 6334c6c4c..f55e7f91b 100644
--- a/src/shared/src/db/queries/runtime.ts
+++ b/src/shared/src/db/queries/runtime.ts
@@ -2,20 +2,19 @@ import { eq, and, asc, sql, inArray } from "drizzle-orm";
import { agentRuntime, agent, machine } from "../schema";
import type { Database } from "../index";
-export async function upsertAgentRuntime(
- db: Database,
- data: {
- workspaceId: string;
- daemonId: string;
- runtimeMode: string;
- provider: string;
- deviceInfo: string;
- metadata?: unknown;
- }
-) {
+export type UpsertAgentRuntimeInput = {
+ workspaceId: string;
+ daemonId: string;
+ runtimeMode: string;
+ provider: string;
+ deviceInfo: string;
+ metadata?: unknown;
+};
+
+export function upsertAgentRuntimeStatement(db: Database, data: UpsertAgentRuntimeInput) {
const now = new Date().toISOString();
const metaJson = JSON.stringify(data.metadata ?? {});
- const rows = await db
+ return db
.insert(agentRuntime)
.values({
workspaceId: data.workspaceId,
@@ -39,9 +38,29 @@ export async function upsertAgentRuntime(
},
})
.returning();
+}
+
+export async function upsertAgentRuntime(
+ db: Database,
+ data: UpsertAgentRuntimeInput,
+) {
+ const rows = await upsertAgentRuntimeStatement(db, data);
return rows[0]!;
}
+export async function batchUpsertAgentRuntimes(
+ db: Database,
+ items: UpsertAgentRuntimeInput[],
+) {
+ if (items.length === 0) return [];
+ if (items.length === 1) {
+ return [await upsertAgentRuntime(db, items[0]!)];
+ }
+ const statements = items.map((item) => upsertAgentRuntimeStatement(db, item));
+ const results = await db.batch(statements as [typeof statements[0], ...typeof statements]);
+ return results.flatMap((rows) => (Array.isArray(rows) ? rows : [rows]));
+}
+
export async function listAgentRuntimes(db: Database, workspaceId: string, userId?: string) {
const conditions = [eq(agentRuntime.workspaceId, workspaceId)];
if (userId) conditions.push(eq(machine.ownerId, userId));
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 51a27070b..6aecaf475 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -89,10 +89,12 @@ export {
AGENT_HANDLE_MIN_LENGTH,
MAX_TASKS_PER_TRACE,
DEV_PASSWORD,
+ DEV_PORTS,
DEV_WEB_URL,
DEV_WS_DO_URL,
DEV_EMAIL_WORKER_URL,
DEV_WAKE_WORKER_URL,
+ devWsDoPort,
MeetingStatus,
TERMINAL_MEETING_STATUSES,
COMMUNITY_BOT_LIMIT_PER_OWNER,
@@ -163,6 +165,7 @@ export type {
IssueStatusType,
MessageRoleType,
MeetingStatusType,
+ DevPortProfile,
} from "./constants";
// Schemas
diff --git a/src/shared/src/mode.ts b/src/shared/src/mode.ts
index 8114d9db4..847c1291f 100644
--- a/src/shared/src/mode.ts
+++ b/src/shared/src/mode.ts
@@ -1,3 +1,5 @@
+import { DEV_WEB_URL } from "./constants";
+
export type AlookMode = "production" | "dev" | "app" | "desktop" | "mobile";
export interface ModeSignals {
@@ -108,11 +110,10 @@ export interface BaseUrlSignals {
}
const DEFAULT_BASE_URL = "https://alook.ai";
-const DEV_BASE_URL = "http://localhost:3000";
export function getBaseUrl(signals: BaseUrlSignals): string {
if (signals.serverUrl) return signals.serverUrl;
if (signals.appUrl) return signals.appUrl;
- if (signals.nodeEnv === "development") return DEV_BASE_URL;
+ if (signals.nodeEnv === "development") return DEV_WEB_URL;
return DEFAULT_BASE_URL;
}
diff --git a/src/shared/test/queries/community-message.test.ts b/src/shared/test/queries/community-message.test.ts
index 9e64ae706..a601526e2 100644
--- a/src/shared/test/queries/community-message.test.ts
+++ b/src/shared/test/queries/community-message.test.ts
@@ -101,6 +101,59 @@ describe("getMessagesByIds", () => {
});
});
+describe("getMessageInScope", () => {
+ it("exports as a function", () => {
+ expect(typeof messageQueries.getMessageInScope).toBe("function");
+ });
+
+ it("returns the row when the db finds an in-scope match", async () => {
+ const db = createSelectMock([messageRow("m_1")]);
+ const result = await messageQueries.getMessageInScope(db, "m_1", { channelId: "ch_1" });
+ expect(result?.id).toBe("m_1");
+ expect(db.where).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns null when the db finds no in-scope match", async () => {
+ const db = createSelectMock([]);
+ const result = await messageQueries.getMessageInScope(db, "m_other", { channelId: "ch_1" });
+ expect(result).toBeNull();
+ });
+
+ it("accepts dmConversationId scope", async () => {
+ const row = { ...messageRow("m_dm"), channelId: null, dmConversationId: "dm_1" };
+ const db = createSelectMock([row]);
+ const result = await messageQueries.getMessageInScope(db, "m_dm", {
+ dmConversationId: "dm_1",
+ });
+ expect(result?.dmConversationId).toBe("dm_1");
+ });
+});
+
+describe("getMessagesByIdsInScope", () => {
+ it("exports as a function", () => {
+ expect(typeof messageQueries.getMessagesByIdsInScope).toBe("function");
+ });
+
+ it("returns [] and does NOT hit db when ids is empty", async () => {
+ const db = createSelectMock([messageRow("m_1")]);
+ const result = await messageQueries.getMessagesByIdsInScope(db, [], { channelId: "ch_1" });
+ expect(result).toEqual([]);
+ expect(db.select).not.toHaveBeenCalled();
+ });
+
+ it("returns only rows the db resolves in-scope", async () => {
+ const db = createSelectMock([messageRow("m_1")]);
+ const result = await messageQueries.getMessagesByIdsInScope(
+ db,
+ ["m_1", "m_leak"],
+ { channelId: "ch_1" },
+ );
+ expect(result).toHaveLength(1);
+ expect(result[0]?.id).toBe("m_1");
+ expect(db.where).toHaveBeenCalledTimes(1);
+ });
+});
+
/**
* Captures each `db.insert(...)` and `db.update(...)` call in order so tests
* can inspect which table was hit with which values/set/onConflict clauses.
diff --git a/src/wake-worker/wrangler.toml b/src/wake-worker/wrangler.toml
index c98dd10c2..b5dd5897e 100644
--- a/src/wake-worker/wrangler.toml
+++ b/src/wake-worker/wrangler.toml
@@ -18,6 +18,7 @@ enabled = true
head_sampling_rate = 0.05
destinations = ["grafana-traces"]
+# Must match DEV_PORTS.wakeWorker in src/shared/src/constants.ts
[dev]
port = 8790
inspector_port = 9232
diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.ts
new file mode 100644
index 000000000..ac6909141
--- /dev/null
+++ b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.ts
@@ -0,0 +1,121 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+
+const mockGetBotOwnedBy = vi.fn()
+const mockGetApprovalRequest = vi.fn()
+const mockGetMember = vi.fn()
+const mockAddMember = vi.fn()
+const mockResolveApprovalRequest = vi.fn()
+const mockLogAudit = vi.fn()
+const mockFanOut = vi.fn()
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityBot: {
+ getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),
+ getApprovalRequest: (...a: unknown[]) => mockGetApprovalRequest(...a),
+ resolveApprovalRequest: (...a: unknown[]) => mockResolveApprovalRequest(...a),
+ },
+ communityMember: {
+ getMember: (...a: unknown[]) => mockGetMember(...a),
+ addMember: (...a: unknown[]) => mockAddMember(...a),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/community/audit", () => ({
+ logAudit: (...a: unknown[]) => mockLogAudit(...a),
+ COMMUNITY_AUDIT_ACTIONS: {
+ BOT_JOIN_APPROVED: "bot_join_approved",
+ BOT_ADDED_TO_SERVER: "bot_added_to_server",
+ BOT_FRIEND_APPROVED: "bot_friend_approved",
+ },
+}))
+
+vi.mock("@/lib/community/fanout", () => ({
+ fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
+ broadcastToUserSafe: vi.fn(),
+}))
+
+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: {} }, userId: "u_owner", email: "[email protected]", params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) =>
+ NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { POST } from "./route"
+
+const ctx = { params: { id: "bot_1", requestId: "req_1" } } as any
+
+describe("POST /api/community/bots/[id]/approval-requests/[requestId]/approve", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetBotOwnedBy.mockResolvedValue({
+ id: "bot_1",
+ name: "Zoe",
+ image: null,
+ })
+ mockGetApprovalRequest.mockResolvedValue({
+ id: "req_1",
+ botId: "bot_1",
+ status: "pending",
+ kind: "join_server",
+ serverId: "srv_1",
+ requestedByUserId: "u_friend",
+ })
+ mockGetMember.mockResolvedValue(null)
+ mockAddMember.mockResolvedValue({
+ id: "mem_bot",
+ role: "member",
+ joinedAt: "2026-07-08T00:00:00.000Z",
+ })
+ mockResolveApprovalRequest.mockResolvedValue(undefined)
+ mockFanOut.mockResolvedValue(undefined)
+ })
+
+ it("returns 404 when the bot is not owned by the caller", async () => {
+ mockGetBotOwnedBy.mockResolvedValue(null)
+ const res = await POST({} as any, ctx)
+ expect(res.status).toBe(404)
+ })
+
+ it("returns 400 when the request is already resolved", async () => {
+ mockGetApprovalRequest.mockResolvedValue({
+ id: "req_1",
+ botId: "bot_1",
+ status: "approved",
+ kind: "join_server",
+ serverId: "srv_1",
+ requestedByUserId: "u_friend",
+ })
+ const res = await POST({} as any, ctx)
+ expect(res.status).toBe(400)
+ })
+
+ it("approves a join_server request and fans out MEMBER_JOIN", async () => {
+ const res = await POST({} as any, ctx)
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body).toEqual({ status: "approved", kind: "join_server" })
+ expect(mockAddMember).toHaveBeenCalled()
+ expect(mockFanOut).toHaveBeenCalledWith(
+ "srv_1",
+ expect.objectContaining({ type: "community:member.join" }),
+ )
+ })
+})
diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.ts
new file mode 100644
index 000000000..1be65ab6b
--- /dev/null
+++ b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.ts
@@ -0,0 +1,81 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+
+const mockGetBotOwnedBy = vi.fn()
+const mockGetApprovalRequest = vi.fn()
+const mockResolveApprovalRequest = vi.fn()
+const mockLogAudit = vi.fn()
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", () => ({
+ queries: {
+ communityBot: {
+ getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),
+ getApprovalRequest: (...a: unknown[]) => mockGetApprovalRequest(...a),
+ resolveApprovalRequest: (...a: unknown[]) => mockResolveApprovalRequest(...a),
+ },
+ },
+}))
+
+vi.mock("@/lib/community/audit", () => ({
+ logAudit: (...a: unknown[]) => mockLogAudit(...a),
+ COMMUNITY_AUDIT_ACTIONS: {
+ BOT_JOIN_DENIED: "bot_join_denied",
+ BOT_FRIEND_DENIED: "bot_friend_denied",
+ },
+}))
+
+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: {} }, userId: "u_owner", email: "[email protected]", params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) =>
+ NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { POST } from "./route"
+
+const ctx = { params: { id: "bot_1", requestId: "req_1" } } as any
+
+describe("POST /api/community/bots/[id]/approval-requests/[requestId]/deny", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetBotOwnedBy.mockResolvedValue({ id: "bot_1", name: "Zoe", image: null })
+ mockGetApprovalRequest.mockResolvedValue({
+ id: "req_1",
+ botId: "bot_1",
+ status: "pending",
+ kind: "friend",
+ serverId: null,
+ requestedByUserId: "u_friend",
+ })
+ mockResolveApprovalRequest.mockResolvedValue(undefined)
+ })
+
+ it("returns 404 when the bot is not owned by the caller", async () => {
+ mockGetBotOwnedBy.mockResolvedValue(null)
+ const res = await POST({} as any, ctx)
+ expect(res.status).toBe(404)
+ })
+
+ it("denies a pending request and writes audit", async () => {
+ const res = await POST({} as any, ctx)
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body).toEqual({ status: "denied", kind: "friend" })
+ expect(mockResolveApprovalRequest).toHaveBeenCalledWith(
+ expect.anything(),
+ "req_1",
+ "denied",
+ )
+ expect(mockLogAudit).toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.ts
index 78a61f5de..e3bfb800e 100644
--- a/src/web/src/app/api/community/bots/route.ts
+++ b/src/web/src/app/api/community/bots/route.ts
@@ -1,4 +1,4 @@
-import { NextRequest, NextResponse } from "next/server"
+import { NextRequest } from "next/server"
import {
queries,
CommunityBotCreateRequestSchema,
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.ts
index 0ddb0a1de..e7667281f 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
@@ -9,7 +9,7 @@ const mockGetChannelForMember = vi.fn()
const mockGetChannel = vi.fn()
const mockCreateMessage = vi.fn()
const mockGetMessage = vi.fn()
-const mockGetMessagesByIds = vi.fn()
+const mockGetMessagesByIdsInScope = vi.fn()
const mockListMembers = vi.fn()
const mockListMemberUserIds = vi.fn()
const mockCreateMentions = vi.fn()
@@ -22,9 +22,14 @@ const mockGetUserInternal = vi.fn()
const mockFanOutToChannel = vi.fn()
const mockBroadcastToUser = vi.fn()
+const mockCheckMessageRateLimit = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/community/rate-limit", () => ({
+ checkMessageRateLimit: (...a: unknown[]) => mockCheckMessageRateLimit(...a),
+}))
+
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
return {
@@ -38,7 +43,7 @@ vi.mock("@alook/shared", async () => {
communityMessage: {
createMessage: (...a: unknown[]) => mockCreateMessage(...a),
getMessage: (...a: unknown[]) => mockGetMessage(...a),
- getMessagesByIds: (...a: unknown[]) => mockGetMessagesByIds(...a),
+ getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIdsInScope(...a),
listMessages: (...a: unknown[]) => mockListMessages(...a),
},
communityMember: {
@@ -73,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: {} }, userId: "u1", email: "[email protected]", params })
+ return handler(req, { env: { DB: {}, RATE_LIMIT_KV: {} }, userId: "u1", email: "[email protected]", params })
}),
}))
@@ -81,7 +86,8 @@ vi.mock("@/lib/middleware/helpers", () => {
const { NextResponse } = require("next/server")
return {
writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ writeError: (message: string, status: number, headers?: Record<string, string>) =>
+ NextResponse.json({ error: message }, { status, ...(headers ? { headers } : {}) }),
}
})
@@ -125,7 +131,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
})
mockListMembers.mockResolvedValue([])
mockListMemberUserIds.mockResolvedValue([])
- mockGetMessagesByIds.mockResolvedValue([])
+ mockGetMessagesByIdsInScope.mockResolvedValue([])
mockCreateMentions.mockResolvedValue(undefined)
mockCreateAttachment.mockImplementation(async (_db: unknown, input: any) => ({
id: "a1",
@@ -133,6 +139,26 @@ describe("POST /api/community/channels/[id]/messages", () => {
}))
mockFanOutToChannel.mockResolvedValue(undefined)
mockBroadcastToUser.mockResolvedValue(undefined)
+ mockCheckMessageRateLimit.mockResolvedValue({ allowed: true })
+ })
+
+ it("returns 429 with Retry-After when the sender is rate limited", async () => {
+ mockCheckMessageRateLimit.mockResolvedValue({ allowed: false, retryAfterSec: 7 })
+
+ const res = await POST(postReq({ content: "hello" }), ctx)
+
+ expect(res.status).toBe(429)
+ expect(res.headers.get("Retry-After")).toBe("7")
+ expect(mockCreateMessage).not.toHaveBeenCalled()
+ expect(mockFanOutToChannel).not.toHaveBeenCalled()
+ })
+
+ 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")
+ // Membership check must run before rate limiting (auth first).
+ expect(mockGetChannelForMember).toHaveBeenCalled()
})
it("rejects content longer than MAX_MESSAGE_CONTENT_LENGTH with 400", async () => {
@@ -282,10 +308,11 @@ describe("GET /api/community/channels/[id]/messages", () => {
mockListReactionsByMessageIds.mockResolvedValue([])
})
- it("resolves reply previews via one getMessagesByIds call (never per-item getMessage)", async () => {
+ it("resolves reply previews via one scoped getMessagesByIdsInScope call (never per-item getMessage)", async () => {
// 5-message page. 3 have replyToId set:
// m-a → target r-in-scope (same channel) → resolves.
- // m-b → target r-out-of-scope (different channel) → filtered → deleted.
+ // m-b → target r-out-of-scope (a different channel) → the scoped query
+ // never returns it (filtered in SQL, not application code) → deleted.
// m-c → target r-missing → deleted.
// m-d → replies to r-in-scope again → resolves.
// m-e → no reply.
@@ -296,9 +323,10 @@ describe("GET /api/community/channels/[id]/messages", () => {
{ id: "m-d", authorId: "u2", authorName: "B", authorEmail: "[email protected]", authorImage: null, content: "again", type: "default", mentionType: null, replyToId: "r-in-scope", channelId: "c1", embeds: null, createdAt: "t4" },
{ id: "m-e", authorId: "u2", authorName: "B", authorEmail: "[email protected]", authorImage: null, content: "no reply", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: null, createdAt: "t5" },
])
- mockGetMessagesByIds.mockResolvedValue([
+ // The (mocked) scoped query only ever returns in-scope rows — "r-out-of-scope"
+ // and "r-missing" are absent, simulating the real WHERE-clause scoping.
+ mockGetMessagesByIdsInScope.mockResolvedValue([
{ id: "r-in-scope", authorName: "Zed", content: "original", channelId: "c1", dmConversationId: null },
- { id: "r-out-of-scope", authorName: "Zed", content: "elsewhere", channelId: "c-other", dmConversationId: null },
])
const res = await GET(getReq(), ctx)
@@ -312,8 +340,10 @@ describe("GET /api/community/channels/[id]/messages", () => {
expect(byId.get("m-d")?.replyTo).toEqual({ id: "r-in-scope", authorName: "Zed", text: "original" })
expect(byId.get("m-e")?.replyTo).toBeUndefined()
- expect(mockGetMessagesByIds).toHaveBeenCalledTimes(1)
+ expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)
expect(mockGetMessage).not.toHaveBeenCalled()
+ const [, , scope] = mockGetMessagesByIdsInScope.mock.calls[0]
+ expect(scope).toEqual({ channelId: "c1" })
})
it("returns author.name verbatim — no 'Unknown' sentinel, no email leak", async () => {
@@ -367,7 +397,7 @@ describe("GET /api/community/channels/[id]/messages", () => {
}
mockListByMessageIds.mockImplementation(() => tracked([]))
mockListReactionsByMessageIds.mockImplementation(() => tracked([]))
- mockGetMessagesByIds.mockImplementation(() => tracked([]))
+ mockGetMessagesByIdsInScope.mockImplementation(() => tracked([]))
mockListChildChannels.mockImplementation(() => tracked([]))
const res = await GET(getReq(), ctx)
@@ -378,7 +408,7 @@ describe("GET /api/community/channels/[id]/messages", () => {
expect(maxInFlight).toBe(4)
expect(mockListByMessageIds).toHaveBeenCalledTimes(1)
expect(mockListReactionsByMessageIds).toHaveBeenCalledTimes(1)
- expect(mockGetMessagesByIds).toHaveBeenCalledTimes(1)
+ expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)
expect(mockListChildChannels).toHaveBeenCalledTimes(1)
})
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.ts
index 47c4d683d..fa624f58a 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,6 +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 { createCommunityMessage } from "@/lib/community/message-handler"
import { mapMessageForApi } from "@/lib/community/message-payload"
@@ -16,7 +17,6 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const auth = await requireChannelMember(db, channelId, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
- const channel = auth.value
const cursor = parseCursor(req.nextUrl.searchParams.get("cursor"))
const pageSize = parsePageSize(req.nextUrl.searchParams.get("limit"))
@@ -43,7 +43,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
? queries.communityReaction.listReactionsByMessageIds(db, messageIds, ctx.userId)
: Promise.resolve([]),
replyToIds.length > 0
- ? queries.communityMessage.getMessagesByIds(db, replyToIds)
+ ? queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { channelId })
: Promise.resolve([]),
queries.communityChannel.listChildChannels(db, channelId),
])
@@ -51,13 +51,10 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const attachmentsByMessage = groupAttachments(allAttachments)
const reactionsByMessage = groupReactions(allReactions, ctx.userId)
- // Scope-check reply targets against this channel so a client can't leak
- // previews of messages from other channels/DMs just by referencing their id.
- const replyMap = new Map(
- replyMessages
- .filter((m) => m.channelId === channelId)
- .map((m) => [m.id, m]),
- )
+ // Reply targets are already scoped to this channel by the query above — a
+ // client can't leak previews of messages from other channels/DMs just by
+ // referencing their id.
+ const replyMap = new Map(replyMessages.map((m) => [m.id, m]))
// Resolve threads (child channels with parentMessageId matching these messages)
const threadByMessageId = new Map(
@@ -83,6 +80,11 @@ 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)
+ if (!rateLimit.allowed) {
+ return writeError("rate limited", 429, { "Retry-After": String(rateLimit.retryAfterSec) })
+ }
+
let body: unknown
try {
body = await req.json()
diff --git a/src/web/src/app/api/community/daemon/activate/route.ts b/src/web/src/app/api/community/daemon/activate/route.ts
index 4170176fd..afbeb40f8 100644
--- a/src/web/src/app/api/community/daemon/activate/route.ts
+++ b/src/web/src/app/api/community/daemon/activate/route.ts
@@ -1,4 +1,4 @@
-import { NextRequest, NextResponse } from "next/server"
+import { NextResponse } from "next/server"
import {
queries,
createLogger,
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.ts
index 582a57cce..7b4adbaaa 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
@@ -9,7 +9,7 @@ const mockGetDM = vi.fn()
const mockIsBlocked = vi.fn()
const mockCreateMessage = vi.fn()
const mockGetMessage = vi.fn()
-const mockGetMessagesByIds = vi.fn()
+const mockGetMessagesByIdsInScope = vi.fn()
const mockListMessages = vi.fn()
const mockListByMessageIds = vi.fn()
const mockListReactionsByMessageIds = vi.fn()
@@ -20,9 +20,14 @@ const mockGetUserInternal = vi.fn()
const mockFanOutToDM = vi.fn()
const mockBroadcastToUser = vi.fn()
+const mockCheckMessageRateLimit = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/community/rate-limit", () => ({
+ checkMessageRateLimit: (...a: unknown[]) => mockCheckMessageRateLimit(...a),
+}))
+
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
return {
@@ -37,7 +42,7 @@ vi.mock("@alook/shared", async () => {
communityMessage: {
createMessage: (...a: unknown[]) => mockCreateMessage(...a),
getMessage: (...a: unknown[]) => mockGetMessage(...a),
- getMessagesByIds: (...a: unknown[]) => mockGetMessagesByIds(...a),
+ getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIdsInScope(...a),
listMessages: (...a: unknown[]) => mockListMessages(...a),
},
communityMember: {
@@ -73,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: {} }, userId: "u1", email: "[email protected]", params })
+ return handler(req, { env: { DB: {}, RATE_LIMIT_KV: {} }, userId: "u1", email: "[email protected]", params })
}),
}))
@@ -81,7 +86,8 @@ vi.mock("@/lib/middleware/helpers", () => {
const { NextResponse } = require("next/server")
return {
writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ writeError: (message: string, status: number, headers?: Record<string, string>) =>
+ NextResponse.json({ error: message }, { status, ...(headers ? { headers } : {}) }),
}
})
@@ -118,6 +124,19 @@ describe("POST /api/community/dm/[id]/messages", () => {
mockGetUserInternal.mockResolvedValue({ isBot: false, deletedAt: null })
mockFanOutToDM.mockResolvedValue(undefined)
mockBroadcastToUser.mockResolvedValue(undefined)
+ mockCheckMessageRateLimit.mockResolvedValue({ allowed: true })
+ })
+
+ it("returns 429 with Retry-After when the sender is rate limited", async () => {
+ mockIsBlocked.mockResolvedValue(false)
+ mockCheckMessageRateLimit.mockResolvedValue({ allowed: false, retryAfterSec: 4 })
+
+ const res = await POST(postReq({ content: "hi" }), ctx)
+
+ expect(res.status).toBe(429)
+ expect(res.headers.get("Retry-After")).toBe("4")
+ expect(mockCreateMessage).not.toHaveBeenCalled()
+ expect(mockFanOutToDM).not.toHaveBeenCalled()
})
it("returns 403 when the DM counterpart is blocked", async () => {
@@ -180,10 +199,11 @@ describe("GET /api/community/dm/[id]/messages", () => {
expect(mockListMessages).not.toHaveBeenCalled()
})
- it("resolves reply previews via one getMessagesByIds call (never per-item getMessage)", async () => {
+ it("resolves reply previews via one scoped getMessagesByIdsInScope call (never per-item getMessage)", async () => {
// 5-message page. 3 have replyToId set:
// m-a → target r-in-scope (same DM) → resolves.
- // m-b → target r-out-of-scope (different DM) → filtered → deleted: true.
+ // m-b → target r-out-of-scope (a different DM) → the scoped query never
+ // returns it (it's filtered in SQL, not in application code) → deleted: true.
// m-c → target r-missing → deleted: true.
// m-d → replies to r-in-scope again → resolves.
// m-e → no reply.
@@ -197,11 +217,10 @@ describe("GET /api/community/dm/[id]/messages", () => {
])
mockListByMessageIds.mockResolvedValue([])
mockListReactionsByMessageIds.mockResolvedValue([])
- mockGetMessagesByIds.mockResolvedValue([
+ // The (mocked) scoped query only ever returns in-scope rows — "r-out-of-scope"
+ // and "r-missing" are absent, simulating the real WHERE-clause scoping.
+ mockGetMessagesByIdsInScope.mockResolvedValue([
{ id: "r-in-scope", authorName: "Zed", content: "original", dmConversationId: "d1", channelId: null },
- // r-out-of-scope belongs to a different DM — filter must drop it.
- { id: "r-out-of-scope", authorName: "Zed", content: "elsewhere", dmConversationId: "d-other", channelId: null },
- // r-missing intentionally not returned.
])
const res = await GET(getReq(), ctx)
@@ -216,11 +235,12 @@ describe("GET /api/community/dm/[id]/messages", () => {
expect(byId.get("m-d")?.replyTo).toEqual({ id: "r-in-scope", authorName: "Zed", text: "original" })
expect(byId.get("m-e")?.replyTo).toBeUndefined()
- // Single batched fetch — no per-item getMessage.
- expect(mockGetMessagesByIds).toHaveBeenCalledTimes(1)
+ // Single batched, scoped fetch — no per-item getMessage.
+ expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)
expect(mockGetMessage).not.toHaveBeenCalled()
- const [, ids] = mockGetMessagesByIds.mock.calls[0]
+ const [, ids, scope] = mockGetMessagesByIdsInScope.mock.calls[0]
expect(ids.sort()).toEqual(["r-in-scope", "r-in-scope", "r-missing", "r-out-of-scope"].sort())
+ expect(scope).toEqual({ dmConversationId: "d1" })
})
it("runs attachment, reaction, and reply-target fetches in parallel", async () => {
@@ -243,7 +263,7 @@ describe("GET /api/community/dm/[id]/messages", () => {
}
mockListByMessageIds.mockImplementation(() => tracked([]))
mockListReactionsByMessageIds.mockImplementation(() => tracked([]))
- mockGetMessagesByIds.mockImplementation(() => tracked([]))
+ mockGetMessagesByIdsInScope.mockImplementation(() => tracked([]))
const res = await GET(getReq(), ctx)
expect(res.status).toBe(200)
@@ -251,6 +271,6 @@ describe("GET /api/community/dm/[id]/messages", () => {
expect(maxInFlight).toBe(3)
expect(mockListByMessageIds).toHaveBeenCalledTimes(1)
expect(mockListReactionsByMessageIds).toHaveBeenCalledTimes(1)
- expect(mockGetMessagesByIds).toHaveBeenCalledTimes(1)
+ expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)
})
})
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.ts
index a8a40cab0..8f826a944 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,6 +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 { createCommunityMessage } from "@/lib/community/message-handler"
import { mapMessageForApi } from "@/lib/community/message-payload"
@@ -41,20 +42,17 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
? queries.communityReaction.listReactionsByMessageIds(db, messageIds, ctx.userId)
: Promise.resolve([]),
replyToIds.length > 0
- ? queries.communityMessage.getMessagesByIds(db, replyToIds)
+ ? queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { dmConversationId: dmId })
: Promise.resolve([]),
])
const attachmentsByMessage = groupAttachments(allAttachments)
const reactionsByMessage = groupReactions(allReactions, ctx.userId)
- // Scope-check reply targets against this DM so a client can't leak previews
- // of messages from other DMs/channels just by referencing their id.
- const replyMap = new Map(
- replyMessages
- .filter((m) => m.dmConversationId === dmId)
- .map((m) => [m.id, m]),
- )
+ // Reply targets are already scoped to this DM by the query above — a
+ // client can't leak previews of messages from other DMs/channels just by
+ // referencing their id.
+ const replyMap = new Map(replyMessages.map((m) => [m.id, m]))
const messages = items.map((r) =>
mapMessageForApi(r, { replyMap, attachmentsByMessage, reactionsByMessage }),
@@ -71,6 +69,11 @@ 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)
+ if (!rateLimit.allowed) {
+ return writeError("rate limited", 429, { "Retry-After": String(rateLimit.retryAfterSec) })
+ }
+
let body: unknown
try {
body = await req.json()
diff --git a/src/web/src/app/api/community/machines/pair/route.test.ts b/src/web/src/app/api/community/machines/pair/route.test.ts
new file mode 100644
index 000000000..eaa2d8957
--- /dev/null
+++ b/src/web/src/app/api/community/machines/pair/route.test.ts
@@ -0,0 +1,46 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+
+const mockCreatePairingToken = vi.fn()
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", () => ({
+ queries: {
+ communityMachine: {
+ createPairingToken: (...a: unknown[]) => mockCreatePairingToken(...a),
+ },
+ },
+}))
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (_req: any, ctx?: any) =>
+ handler(_req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params: ctx?.params }),
+ ),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ }
+})
+
+import { POST } from "./route"
+
+describe("POST /api/community/machines/pair", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockCreatePairingToken.mockResolvedValue({
+ tokenId: "pair_tok_1",
+ expiresAt: "2026-07-09T00:00:00.000Z",
+ })
+ })
+
+ it("creates a pairing token for the authed user", async () => {
+ const res = await POST({} as any, {} as any)
+ expect(res.status).toBe(200)
+ expect(mockCreatePairingToken).toHaveBeenCalledWith(expect.anything(), "u1")
+ const body = await res.json()
+ expect(body).toEqual({ tokenId: "pair_tok_1", expiresAt: "2026-07-09T00:00:00.000Z" })
+ })
+})
diff --git a/src/web/src/app/api/community/messages/[id]/route.test.ts b/src/web/src/app/api/community/messages/[id]/route.test.ts
index 058f75831..526d5d43a 100644
--- a/src/web/src/app/api/community/messages/[id]/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.test.ts
@@ -6,7 +6,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
}))
const mockGetMessage = vi.fn()
-const mockGetMessagesByIds = vi.fn()
+const mockGetMessagesByIdsInScope = vi.fn()
const mockGetChannelForMember = vi.fn()
const mockGetDM = vi.fn()
const mockIsBlocked = vi.fn()
@@ -25,7 +25,7 @@ vi.mock("@alook/shared", async () => {
},
communityMessage: {
getMessage: (...a: unknown[]) => mockGetMessage(...a),
- getMessagesByIds: (...a: unknown[]) => mockGetMessagesByIds(...a),
+ getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIdsInScope(...a),
},
communityAttachment: {
listByMessageIds: (...a: unknown[]) => mockListByMessageIds(...a),
@@ -69,7 +69,7 @@ describe("GET /api/community/messages/[id]", () => {
vi.clearAllMocks()
mockListByMessageIds.mockResolvedValue([])
mockListReactionsByMessageIds.mockResolvedValue([])
- mockGetMessagesByIds.mockResolvedValue([])
+ mockGetMessagesByIdsInScope.mockResolvedValue([])
})
it("returns the hydrated payload for a channel message when caller is a server member", async () => {
@@ -129,16 +129,18 @@ describe("GET /api/community/messages/[id]", () => {
dmConversationId: null,
})
mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetMessagesByIds.mockResolvedValue([
+ mockGetMessagesByIdsInScope.mockResolvedValue([
{ id: "m0", authorName: "Bob", content: "question?", channelId: "c1" },
])
const res = await GET(req(), { params: { id: "m1" } } as any)
const body = await res.json()
expect(body.replyTo).toEqual({ id: "m0", authorName: "Bob", text: "question?" })
+ const [, , scope] = mockGetMessagesByIdsInScope.mock.calls[0]
+ expect(scope).toEqual({ channelId: "c1" })
})
- it("filters out reply preview when target is in a different channel (scope guard)", async () => {
+ it("omits reply preview when target is in a different channel (scope guard)", async () => {
mockGetMessage.mockResolvedValue({
id: "m1",
authorId: "u-author",
@@ -154,13 +156,13 @@ describe("GET /api/community/messages/[id]", () => {
dmConversationId: null,
})
mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetMessagesByIds.mockResolvedValue([
- { id: "m0", authorName: "Bob", content: "leaked?", channelId: "OTHER" },
- ])
+ // The scoped query never returns a message from a different channel — no
+ // application-level `.filter()` involved anymore.
+ mockGetMessagesByIdsInScope.mockResolvedValue([])
const res = await GET(req(), { params: { id: "m1" } } as any)
const body = await res.json()
- // Target filtered out — mapper returns the `deleted` sentinel.
+ // Target not found in scope — mapper returns the `deleted` sentinel.
expect(body.replyTo).toEqual({ id: "m0", authorName: "Unknown", text: "", deleted: true })
})
diff --git a/src/web/src/app/api/community/messages/[id]/route.ts b/src/web/src/app/api/community/messages/[id]/route.ts
index ae00f3d2a..013a4ffd9 100644
--- a/src/web/src/app/api/community/messages/[id]/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.ts
@@ -52,24 +52,21 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {
queries.communityAttachment.listByMessageIds(db, [messageId]),
queries.communityReaction.listReactionsByMessageIds(db, [messageId], ctx.userId),
message.replyToId
- ? queries.communityMessage.getMessagesByIds(db, [message.replyToId])
+ ? queries.communityMessage.getMessagesByIdsInScope(
+ db,
+ [message.replyToId],
+ message.channelId ? { channelId: message.channelId } : { dmConversationId: message.dmConversationId! },
+ )
: Promise.resolve([]),
])
const attachmentsByMessage = groupAttachments(allAttachments)
const reactionsByMessage = groupReactions(allReactions, ctx.userId)
- // Scope-check the reply target against the SAME surface as the parent — a
- // reply preview must not leak content from a different channel/DM.
- const replyMap = new Map(
- replyMessages
- .filter((m) =>
- message.channelId
- ? m.channelId === message.channelId
- : m.dmConversationId === message.dmConversationId,
- )
- .map((m) => [m.id, m]),
- )
+ // Reply target is already scoped to the SAME surface as the parent by the
+ // query above — a reply preview must not leak content from a different
+ // channel/DM.
+ const replyMap = new Map(replyMessages.map((m) => [m.id, m]))
const payload = mapMessageForApi(message, {
replyMap,
diff --git a/src/web/src/app/api/community/servers/[id]/leave/route.test.ts b/src/web/src/app/api/community/servers/[id]/leave/route.test.ts
index 860d828e7..b267d2e84 100644
--- a/src/web/src/app/api/community/servers/[id]/leave/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/leave/route.test.ts
@@ -7,6 +7,8 @@ vi.mock("@opennextjs/cloudflare", () => ({
const mockGetMember = vi.fn()
const mockRemoveMember = vi.fn()
+const mockRemoveOwnerBotsFromServer = vi.fn()
+const mockListOwnerBotsInServer = vi.fn()
const mockLogAudit = vi.fn()
const mockFanOut = vi.fn()
@@ -20,15 +22,20 @@ vi.mock("@alook/shared", async () => {
communityMember: {
getMember: (...a: unknown[]) => mockGetMember(...a),
removeMember: (...a: unknown[]) => mockRemoveMember(...a),
- listOwnerBotsInServer: vi.fn().mockResolvedValue([]),
+ listOwnerBotsInServer: (...a: unknown[]) => mockListOwnerBotsInServer(...a),
+ removeOwnerBotsFromServer: (...a: unknown[]) => mockRemoveOwnerBotsFromServer(...a),
},
},
}
})
-vi.mock("@/lib/community/audit", () => ({
- logAudit: (...a: unknown[]) => mockLogAudit(...a),
-}))
+vi.mock("@/lib/community/audit", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
+ return {
+ ...actual,
+ logAudit: (...a: unknown[]) => mockLogAudit(...a),
+ }
+})
vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
@@ -64,6 +71,8 @@ describe("POST /api/community/servers/[id]/leave", () => {
vi.clearAllMocks()
mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })
mockRemoveMember.mockResolvedValue(true)
+ mockListOwnerBotsInServer.mockResolvedValue([])
+ mockRemoveOwnerBotsFromServer.mockResolvedValue(undefined)
mockFanOut.mockResolvedValue(undefined)
})
@@ -98,4 +107,17 @@ describe("POST /api/community/servers/[id]/leave", () => {
expect(mockLogAudit).not.toHaveBeenCalled()
expect(mockRemoveMember).not.toHaveBeenCalled()
})
+
+ it("bulk-removes owner bots in one call instead of getMember loops", async () => {
+ mockListOwnerBotsInServer.mockResolvedValue(["bot_1", "bot_2"])
+
+ const res = await POST(postReq(), ctx)
+ expect(res.status).toBe(204)
+ expect(mockRemoveOwnerBotsFromServer).toHaveBeenCalledWith(
+ expect.anything(),
+ "s1",
+ ["bot_1", "bot_2"],
+ )
+ expect(mockGetMember).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/src/web/src/app/api/community/servers/[id]/leave/route.ts b/src/web/src/app/api/community/servers/[id]/leave/route.ts
index 28cf02382..5e011899e 100644
--- a/src/web/src/app/api/community/servers/[id]/leave/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/leave/route.ts
@@ -31,15 +31,7 @@ export const POST = withAuth(async (_req, ctx) => {
)
await queries.communityMember.removeMember(db, member.id)
- // Cascade each bot's member row. The bot's member row is unique on
- // (serverId, userId); getMember → removeMember. Loop is O(N) DB calls; the
- // typical case is N=0 or N=1, so no batching needed.
- for (const botId of botIdsToCascade) {
- const bmember = await queries.communityMember.getMember(db, serverId, botId)
- if (bmember) {
- await queries.communityMember.removeMember(db, bmember.id)
- }
- }
+ await queries.communityMember.removeOwnerBotsFromServer(db, serverId, botIdsToCascade)
logAudit(db, {
serverId,
diff --git a/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.test.ts
index bab416604..ad17c2b84 100644
--- a/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.test.ts
@@ -14,6 +14,8 @@ const mockGetMemberById = vi.fn()
const mockListMembers = vi.fn()
const mockUpdateRole = vi.fn()
const mockRemoveMember = vi.fn()
+const mockRemoveOwnerBotsFromServer = vi.fn()
+const mockListOwnerBotsInServer = vi.fn()
const mockLogAudit = vi.fn()
const mockFanOut = vi.fn()
@@ -30,7 +32,8 @@ vi.mock("@alook/shared", async () => {
listMembers: (...a: unknown[]) => mockListMembers(...a),
updateRole: (...a: unknown[]) => mockUpdateRole(...a),
removeMember: (...a: unknown[]) => mockRemoveMember(...a),
- listOwnerBotsInServer: vi.fn().mockResolvedValue([]),
+ removeOwnerBotsFromServer: (...a: unknown[]) => mockRemoveOwnerBotsFromServer(...a),
+ listOwnerBotsInServer: (...a: unknown[]) => mockListOwnerBotsInServer(...a),
},
user: {
getUserInternal: vi.fn().mockResolvedValue({
@@ -44,9 +47,13 @@ vi.mock("@alook/shared", async () => {
}
})
-vi.mock("@/lib/community/audit", () => ({
- logAudit: (...a: unknown[]) => mockLogAudit(...a),
-}))
+vi.mock("@/lib/community/audit", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
+ return {
+ ...actual,
+ logAudit: (...a: unknown[]) => mockLogAudit(...a),
+ }
+})
vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
@@ -184,6 +191,8 @@ describe("DELETE /api/community/servers/[id]/members/[memberId]", () => {
userImage: null,
})
mockRemoveMember.mockResolvedValue({ id: "mem_target" })
+ mockListOwnerBotsInServer.mockResolvedValue([])
+ mockRemoveOwnerBotsFromServer.mockResolvedValue(undefined)
mockFanOut.mockResolvedValue(undefined)
})
@@ -239,4 +248,16 @@ describe("DELETE /api/community/servers/[id]/members/[memberId]", () => {
expect(res.status).toBe(403)
expect(mockRemoveMember).not.toHaveBeenCalled()
})
+
+ it("bulk-removes cascaded owner bots after kicking a human member", async () => {
+ mockListOwnerBotsInServer.mockResolvedValue(["bot_1"])
+
+ const res = await DELETE(deleteReq(), ctx)
+ expect(res.status).toBe(204)
+ expect(mockRemoveOwnerBotsFromServer).toHaveBeenCalledWith(
+ expect.anything(),
+ "srv_1",
+ ["bot_1"],
+ )
+ })
})
diff --git a/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.ts b/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.ts
index 2908fb6e0..e6247917d 100644
--- a/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.ts
@@ -115,12 +115,7 @@ export const DELETE = withAuth(async (_req, ctx) => {
const removed = await queries.communityMember.removeMember(db, memberId)
if (!removed) return writeError("member not found", 404)
- for (const botId of botIdsToCascade) {
- const bmember = await queries.communityMember.getMember(db, serverId, botId)
- if (bmember) {
- await queries.communityMember.removeMember(db, bmember.id)
- }
- }
+ await queries.communityMember.removeOwnerBotsFromServer(db, serverId, botIdsToCascade)
logAudit(db, {
serverId,
diff --git a/src/web/src/app/api/community/threads/[id]/messages/route.test.ts b/src/web/src/app/api/community/threads/[id]/messages/route.test.ts
index e2a501c35..9144b8793 100644
--- a/src/web/src/app/api/community/threads/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/community/threads/[id]/messages/route.test.ts
@@ -6,7 +6,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
}))
const mockGetChannelForMember = vi.fn()
-const mockGetMessagesByIds = vi.fn()
+const mockGetMessagesByIdsInScope = vi.fn()
const mockListMessages = vi.fn()
const mockListByMessageIds = vi.fn()
const mockListReactionsByMessageIds = vi.fn()
@@ -22,7 +22,7 @@ vi.mock("@alook/shared", async () => {
getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),
},
communityMessage: {
- getMessagesByIds: (...a: unknown[]) => mockGetMessagesByIds(...a),
+ getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIdsInScope(...a),
listMessages: (...a: unknown[]) => mockListMessages(...a),
},
communityAttachment: {
@@ -70,7 +70,7 @@ describe("GET /api/community/threads/[id]/messages", () => {
})
mockListByMessageIds.mockResolvedValue([])
mockListReactionsByMessageIds.mockResolvedValue([])
- mockGetMessagesByIds.mockResolvedValue([])
+ mockGetMessagesByIdsInScope.mockResolvedValue([])
})
it("runs attachment, reaction, and reply-target fetches in parallel", async () => {
@@ -92,7 +92,7 @@ describe("GET /api/community/threads/[id]/messages", () => {
}
mockListByMessageIds.mockImplementation(() => tracked([]))
mockListReactionsByMessageIds.mockImplementation(() => tracked([]))
- mockGetMessagesByIds.mockImplementation(() => tracked([]))
+ mockGetMessagesByIdsInScope.mockImplementation(() => tracked([]))
const res = await GET(getReq(), ctx)
expect(res.status).toBe(200)
@@ -100,7 +100,7 @@ describe("GET /api/community/threads/[id]/messages", () => {
expect(maxInFlight).toBe(3)
expect(mockListByMessageIds).toHaveBeenCalledTimes(1)
expect(mockListReactionsByMessageIds).toHaveBeenCalledTimes(1)
- expect(mockGetMessagesByIds).toHaveBeenCalledTimes(1)
+ expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)
})
it("preserves response shape: reply preview scoped to this channel", async () => {
@@ -110,9 +110,8 @@ describe("GET /api/community/threads/[id]/messages", () => {
{ id: "m-a", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "hi", type: "default", mentionType: null, replyToId: "r-in-scope", channelId: "t1", embeds: null, createdAt: "t1" },
{ id: "m-b", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "leak?", type: "default", mentionType: null, replyToId: "r-out-of-scope", channelId: "t1", embeds: null, createdAt: "t2" },
])
- mockGetMessagesByIds.mockResolvedValue([
+ mockGetMessagesByIdsInScope.mockResolvedValue([
{ id: "r-in-scope", authorName: "Zed", content: "original", channelId: "t1", dmConversationId: null },
- { id: "r-out-of-scope", authorName: "Zed", content: "elsewhere", channelId: "c-other", dmConversationId: null },
])
const res = await GET(getReq(), ctx)
diff --git a/src/web/src/app/api/community/threads/[id]/messages/route.ts b/src/web/src/app/api/community/threads/[id]/messages/route.ts
index 4965c23e5..dff4834c1 100644
--- a/src/web/src/app/api/community/threads/[id]/messages/route.ts
+++ b/src/web/src/app/api/community/threads/[id]/messages/route.ts
@@ -15,7 +15,6 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const auth = await requireChannelMember(db, channelId, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
- const channel = auth.value
const cursor = parseCursor(req.nextUrl.searchParams.get("cursor"))
const pageSize = parsePageSize(req.nextUrl.searchParams.get("limit"))
@@ -42,20 +41,17 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
? queries.communityReaction.listReactionsByMessageIds(db, messageIds, ctx.userId)
: Promise.resolve([]),
replyToIds.length > 0
- ? queries.communityMessage.getMessagesByIds(db, replyToIds)
+ ? queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { channelId })
: Promise.resolve([]),
])
const attachmentsByMessage = groupAttachments(allAttachments)
const reactionsByMessage = groupReactions(allReactions, ctx.userId)
- // Scope-check reply targets against this channel so a caller can't leak
- // previews of messages from other channels/DMs just by referencing their id.
- const replyMap = new Map(
- replyMessages
- .filter((m) => m.channelId === channelId)
- .map((m) => [m.id, m]),
- )
+ // Reply targets are already scoped to this channel by the query above — a
+ // caller can't leak previews of messages from other channels/DMs just by
+ // referencing their id.
+ const replyMap = new Map(replyMessages.map((m) => [m.id, m]))
const messages = items.map((r) =>
mapMessageForApi(r, { replyMap, attachmentsByMessage, reactionsByMessage }),
diff --git a/src/web/src/app/api/machine-tokens/activate/route.test.ts b/src/web/src/app/api/machine-tokens/activate/route.test.ts
index 0a6c7ea37..71920e1fb 100644
--- a/src/web/src/app/api/machine-tokens/activate/route.test.ts
+++ b/src/web/src/app/api/machine-tokens/activate/route.test.ts
@@ -4,7 +4,7 @@ import { NextRequest } from "next/server";
const mockGetMachineTokenByToken = vi.fn();
const mockActivateMachineToken = vi.fn();
const mockUpsertMachine = vi.fn();
-const mockUpsertAgentRuntime = vi.fn();
+const mockBatchUpsertAgentRuntimes = vi.fn();
const mockBroadcastToUser = vi.fn();
function sharedMocks() {
@@ -23,7 +23,7 @@ function sharedMocks() {
upsertMachine: (...a: any[]) => mockUpsertMachine(...a),
},
runtime: {
- upsertAgentRuntime: (...a: any[]) => mockUpsertAgentRuntime(...a),
+ batchUpsertAgentRuntimes: (...a: any[]) => mockBatchUpsertAgentRuntimes(...a),
},
},
ActivateTokenRequestSchema: (await import("@alook/shared"))
@@ -95,7 +95,7 @@ describe("POST /api/machine-tokens/activate", () => {
mockGetMachineTokenByToken.mockResolvedValue(pendingToken);
mockUpsertMachine.mockResolvedValue(undefined);
- mockUpsertAgentRuntime.mockResolvedValue({ id: "rt_1", provider: "claude" });
+ mockBatchUpsertAgentRuntimes.mockResolvedValue([{ id: "rt_1", provider: "claude" }]);
mockActivateMachineToken.mockResolvedValue(undefined);
mockBroadcastToUser.mockResolvedValue(undefined);
@@ -115,14 +115,16 @@ describe("POST /api/machine-tokens/activate", () => {
ownerId: "u1",
});
- expect(mockUpsertAgentRuntime).toHaveBeenCalledWith(expect.anything(), {
- workspaceId: "ws_1",
- daemonId: "TestMachine.local",
- runtimeMode: "local",
- provider: "claude",
- deviceInfo: "TestMachine.local",
- metadata: { version: "2.1.0" },
- });
+ expect(mockBatchUpsertAgentRuntimes).toHaveBeenCalledWith(expect.anything(), [
+ {
+ workspaceId: "ws_1",
+ daemonId: "TestMachine.local",
+ runtimeMode: "local",
+ provider: "claude",
+ deviceInfo: "TestMachine.local",
+ metadata: { version: "2.1.0" },
+ },
+ ]);
expect(mockActivateMachineToken).toHaveBeenCalledWith(
expect.anything(),
@@ -136,7 +138,7 @@ describe("POST /api/machine-tokens/activate", () => {
mockGetMachineTokenByToken.mockResolvedValue(pendingToken);
mockUpsertMachine.mockResolvedValue(undefined);
- mockUpsertAgentRuntime.mockResolvedValue({ id: "rt_1", provider: "claude" });
+ mockBatchUpsertAgentRuntimes.mockResolvedValue([{ id: "rt_1", provider: "claude" }]);
mockActivateMachineToken.mockResolvedValue(undefined);
mockBroadcastToUser.mockResolvedValue(undefined);
diff --git a/src/web/src/app/api/machine-tokens/activate/route.ts b/src/web/src/app/api/machine-tokens/activate/route.ts
index bd9a6f4a9..a819c2dfe 100644
--- a/src/web/src/app/api/machine-tokens/activate/route.ts
+++ b/src/web/src/app/api/machine-tokens/activate/route.ts
@@ -49,18 +49,17 @@ export const POST = withEnv(async (req: NextRequest, ctx) => {
ownerId: mt.userId,
});
- const results = [];
- for (const rt of runtimes) {
- const result = await queries.runtime.upsertAgentRuntime(db, {
+ const results = await queries.runtime.batchUpsertAgentRuntimes(
+ db,
+ runtimes.map((rt) => ({
workspaceId,
daemonId,
runtimeMode: "local",
provider: rt.type,
deviceInfo: hostname,
metadata: { version: rt.version || "" },
- });
- results.push({ ...result, machineLastSeenAt: null });
- }
+ })),
+ ).then((rows) => rows.map((result) => ({ ...result, machineLastSeenAt: null })))
await queries.machineToken.activateMachineToken(db, mt.id, hostname);
diff --git a/src/web/src/app/api/ws/token/route.test.ts b/src/web/src/app/api/ws/token/route.test.ts
new file mode 100644
index 000000000..285146a42
--- /dev/null
+++ b/src/web/src/app/api/ws/token/route.test.ts
@@ -0,0 +1,44 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockGetSession = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(async () => ({ env: {} })),
+}))
+
+vi.mock("@/lib/auth", () => ({
+ createAuth: vi.fn(() => ({
+ api: { getSession: (...a: unknown[]) => mockGetSession(...a) },
+ })),
+}))
+
+vi.mock("@/lib/middleware/env", () => ({
+ withEnv: vi.fn((handler: any) => async (req: any, ctx?: any) => handler(req, ctx ?? { env: {} })),
+}))
+
+import { GET } from "./route"
+
+describe("GET /api/ws/token", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it("returns 401 when there is no session", async () => {
+ mockGetSession.mockResolvedValue(null)
+ const res = await GET(new NextRequest("http://localhost/api/ws/token"))
+ expect(res.status).toBe(401)
+ })
+
+ it("returns userId and session token for an authenticated caller", async () => {
+ mockGetSession.mockResolvedValue({
+ user: { id: "u_1" },
+ session: { token: "sess_tok" },
+ })
+ const res = await GET(new NextRequest("http://localhost/api/ws/token"))
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.userId).toBe("u_1")
+ expect(body.token).toBe("sess_tok")
+ })
+})
diff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsx
index e31daab8e..16231102c 100644
--- a/src/web/src/components/community/bots/bot-list.tsx
+++ b/src/web/src/components/community/bots/bot-list.tsx
@@ -77,7 +77,7 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
{backBar}
<div className="flex flex-col gap-3 p-6">
{Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="h-[84px] animate-pulse rounded-lg border bg-muted/30" />
+ <div key={i} className="h-21 animate-pulse rounded-lg border bg-muted/30" />
))}
</div>
</div>
diff --git a/src/web/src/components/community/bots/create-bot-dialog.tsx b/src/web/src/components/community/bots/create-bot-dialog.tsx
index 4c46edcfd..edd6e8558 100644
--- a/src/web/src/components/community/bots/create-bot-dialog.tsx
+++ b/src/web/src/components/community/bots/create-bot-dialog.tsx
@@ -180,7 +180,7 @@ export function CreateBotDialog({
onChange={(e) => setDescription(e.target.value)}
placeholder="What is this bot for?"
rows={3}
- className="min-h-[72px] resize-none"
+ className="min-h-18 resize-none"
/>
</div>
diff --git a/src/web/src/components/community/community-inbox-popover.tsx b/src/web/src/components/community/community-inbox-popover.tsx
index 36c88bb2a..fd33e6fe8 100644
--- a/src/web/src/components/community/community-inbox-popover.tsx
+++ b/src/web/src/components/community/community-inbox-popover.tsx
@@ -170,7 +170,7 @@ export function InboxPopover({
}) {
const hasAnything = forYou.length > 0 || unreads.length > 0 || mentions.length > 0
return (
- <Tabs defaultValue="foryou" className="flex h-[28rem] flex-col">
+ <Tabs defaultValue="foryou" className="flex h-112 flex-col">
<div className="flex items-center gap-2 px-3 pt-4">
<Inbox className="size-5" />
<h2 className="flex-1 text-lg font-semibold">Inbox</h2>
diff --git a/src/web/src/components/community/edit-profile-dialog.tsx b/src/web/src/components/community/edit-profile-dialog.tsx
index 00f8c525a..95ccdf059 100644
--- a/src/web/src/components/community/edit-profile-dialog.tsx
+++ b/src/web/src/components/community/edit-profile-dialog.tsx
@@ -64,7 +64,9 @@ export function UserSettings({ onClose, userName, aboutMe, onSave, onLogout }: {
const [tab, setTab] = useState("profile")
const timerRef = useRef<NodeJS.Timeout | null>(null)
const onSaveRef = useRef(onSave)
- onSaveRef.current = onSave
+ useEffect(() => {
+ onSaveRef.current = onSave
+ }, [onSave])
const debouncedSave = useCallback((data: { name?: string; aboutMe?: string }) => {
if (timerRef.current) clearTimeout(timerRef.current)
diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsx
index 97e6b14e7..b41a6fea8 100644
--- a/src/web/src/components/community/machines/machine-list.tsx
+++ b/src/web/src/components/community/machines/machine-list.tsx
@@ -115,7 +115,7 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
{backBar}
<div className="flex flex-col gap-3 p-6">
{Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="h-[88px] animate-pulse rounded-lg border bg-muted/30" />
+ <div key={i} className="h-22 animate-pulse rounded-lg border bg-muted/30" />
))}
</div>
</div>
diff --git a/src/web/src/components/community/machines/pair-machine-sheet.tsx b/src/web/src/components/community/machines/pair-machine-sheet.tsx
index c3afc00b3..6dd4f34e9 100644
--- a/src/web/src/components/community/machines/pair-machine-sheet.tsx
+++ b/src/web/src/components/community/machines/pair-machine-sheet.tsx
@@ -15,7 +15,24 @@ import {
} from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
import { apiFetch } from "@/lib/api/client"
-import { COMMUNITY_SERVER_URL, COMMUNITY_DAEMON_WS_URL } from "@/lib/community/env"
+import { isLocalMode, WS_DO_PORT_DEFAULT } from "@/lib/utils"
+
+// Community daemon HTTP/WS endpoints live on the same worker + ws-do as the
+// rest of the app — see use-user-ws.ts, which connects to the identical
+// ws-do for the user's live WS channel. ws-do routes community-daemon
+// connections by their `Authorization: Bearer cmk_...` header, not by host
+// or path, so we reuse that exact local/origin split instead of introducing
+// a separate URL concept (or env vars) just for this sheet.
+const isLocal = isLocalMode()
+
+// Only ever called once `pendingTokenId` is set, which happens from a
+// client-only effect — safe to touch `location` here (never runs during SSR).
+function buildPairCommand(machineKey: string): string {
+ const wsUrl = isLocal
+ ? `ws://localhost:${WS_DO_PORT_DEFAULT}`
+ : `${location.origin.replace("http", "ws")}/api/ws/community-daemon`
+ return `npx @alook/daemon daemon start --machine-key ${machineKey} --server-url ${location.origin} --ws-url ${wsUrl}`
+}
export type PairMachineSheetMode =
| { kind: "pair" }
@@ -78,9 +95,7 @@ export function PairMachineSheet({
void generate()
}, [openKey, generate, setPendingTokenId])
- const command = pendingTokenId
- ? `npx @alook/daemon daemon start --machine-key ${pendingTokenId} --server-url ${COMMUNITY_SERVER_URL} --ws-url ${COMMUNITY_DAEMON_WS_URL}`
- : ""
+ const command = pendingTokenId ? buildPairCommand(pendingTokenId) : ""
const copyCommand = useCallback(async () => {
if (!command) return
@@ -228,7 +243,7 @@ function Marker({
].join(" ")}
>
{spinning && (
- <span className="absolute inset-[-3px] rounded-full border-2 border-primary/30 border-t-primary animate-spin" />
+ <span className="absolute -inset-0.75 rounded-full border-2 border-primary/30 border-t-primary animate-spin" />
)}
{n}
</span>
diff --git a/src/web/src/components/community/member-list.tsx b/src/web/src/components/community/member-list.tsx
index 41b551181..945e0bf94 100644
--- a/src/web/src/components/community/member-list.tsx
+++ b/src/web/src/components/community/member-list.tsx
@@ -103,6 +103,8 @@ export function MemberList({
const scrollRef = useRef<HTMLDivElement>(null)
const sentinelRef = useRef<HTMLDivElement>(null)
+ // TanStack Virtual returns unstable function refs — React Compiler skips memoization.
+ // eslint-disable-next-line react-hooks/incompatible-library -- library limitation
const rowVirtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => scrollRef.current,
diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsx
index 3ddbfed87..efdde6efc 100644
--- a/src/web/src/components/community/message-list.tsx
+++ b/src/web/src/components/community/message-list.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useEffect, useRef, useState } from "react"
+import { useEffect, useMemo, useRef, useState } from "react"
import { DateDivider, NewDivider } from "./dividers"
import { Message } from "./message"
import { TypingIndicator } from "./typing-indicator"
@@ -116,6 +116,28 @@ export function MessageList({
if (scrollToMessageId) jumpTo(scrollToMessageId)
}, [scrollToMessageId])
+ // Group consecutive messages from the same author into clusters. Memoized
+ // so a re-render triggered by unrelated state (typing indicator ticks,
+ // presence updates, etc.) doesn't re-walk the full message list every time.
+ const clusters = useMemo(() => {
+ const result: { messages: { m: Msg; grouped: boolean; showDateDivider: boolean; showNewDivider: boolean }[] }[] = []
+ messages.forEach((m, i) => {
+ const prev = i > 0 ? messages[i - 1] : null
+ const prevDate = prev ? dateKey(prev.createdAt) : ""
+ const curDate = dateKey(m.createdAt)
+ const showDateDivider = !!(curDate && curDate !== prevDate)
+ const grouped = !!(prev && !m.type && !m.replyTo && !showDateDivider && prev.authorName === m.authorName
+ && prev.createdAt && m.createdAt && (new Date(m.createdAt).getTime() - new Date(prev.createdAt).getTime()) < 420_000)
+ const entry = { m, grouped, showDateDivider, showNewDivider: m.id === newDividerBefore }
+ if (grouped && result.length > 0) {
+ result[result.length - 1].messages.push(entry)
+ } else {
+ result.push({ messages: [entry] })
+ }
+ })
+ return result
+ }, [messages, newDividerBefore])
+
// All hooks must run before any conditional return — rule-of-hooks.
if (loading && messages.length === 0) return <MessageListSkeleton dm={!!hero} />
@@ -135,56 +157,38 @@ export function MessageList({
)}
</div>
- {(() => {
- // Group consecutive messages from same author into clusters
- const clusters: { messages: { m: Msg; grouped: boolean; showDateDivider: boolean; showNewDivider: boolean }[] }[] = []
- messages.forEach((m, i) => {
- const prev = i > 0 ? messages[i - 1] : null
- const prevDate = prev ? dateKey(prev.createdAt) : ""
- const curDate = dateKey(m.createdAt)
- const showDateDivider = !!(curDate && curDate !== prevDate)
- const grouped = !!(prev && !m.type && !m.replyTo && !showDateDivider && prev.authorName === m.authorName
- && prev.createdAt && m.createdAt && (new Date(m.createdAt).getTime() - new Date(prev.createdAt).getTime()) < 420_000)
- const entry = { m, grouped, showDateDivider, showNewDivider: m.id === newDividerBefore }
- if (grouped && clusters.length > 0) {
- clusters[clusters.length - 1].messages.push(entry)
- } else {
- clusters.push({ messages: [entry] })
- }
- })
- return clusters.map((cluster, ci) => (
- <div key={cluster.messages[0].m.id ?? ci}>
- {cluster.messages.map(({ m, grouped, showDateDivider, showNewDivider }) => (
- // `data-msg-id` anchors the IntersectionObserver in
- // `useChannelWatermark` — every rendered row is a candidate
- // for the read pointer. Also used by the mount-time
- // "scroll to New divider" effect above.
- <div key={m.id} data-msg-id={m.id}>
- {showDateDivider && <DateDivider label={formatDateLabel(m.createdAt!)} />}
- {showNewDivider && <NewDivider />}
- <Message
- m={{ ...m, grouped }}
- pinned={pinnedIds?.has(m.id)}
- onOpenThread={onOpenThread}
- onOpenProfile={onOpenProfile}
- onJumpReply={() => m.replyTo && jumpTo(m.replyTo.id)}
- onToggleReaction={onToggleReaction ? (emoji) => onToggleReaction(m.id, emoji) : undefined}
- onReact={onReact ? (emoji) => onReact(m.id, emoji) : undefined}
- onReply={onReply ? () => onReply(m.id) : undefined}
- onPin={onPin ? () => onPin(m.id) : undefined}
- onCreateThread={onCreateThread ? () => onCreateThread(m.id) : undefined}
- onCopy={onCopy ? () => onCopy(m.id) : undefined}
- onRetry={onRetry ? () => onRetry(m.id) : undefined}
- onPreviewImage={onPreviewImage}
- onDownloadFile={onDownloadFile}
- highlighted={jumped === m.id}
- resolveUserName={resolveUserName}
- />
- </div>
- ))}
- </div>
- ))
- })()}
+ {clusters.map((cluster, ci) => (
+ <div key={cluster.messages[0].m.id ?? ci}>
+ {cluster.messages.map(({ m, grouped, showDateDivider, showNewDivider }) => (
+ // `data-msg-id` anchors the IntersectionObserver in
+ // `useChannelWatermark` — every rendered row is a candidate
+ // for the read pointer. Also used by the mount-time
+ // "scroll to New divider" effect above.
+ <div key={m.id} data-msg-id={m.id}>
+ {showDateDivider && <DateDivider label={formatDateLabel(m.createdAt!)} />}
+ {showNewDivider && <NewDivider />}
+ <Message
+ m={{ ...m, grouped }}
+ pinned={pinnedIds?.has(m.id)}
+ onOpenThread={onOpenThread}
+ onOpenProfile={onOpenProfile}
+ onJumpReply={() => m.replyTo && jumpTo(m.replyTo.id)}
+ onToggleReaction={onToggleReaction ? (emoji) => onToggleReaction(m.id, emoji) : undefined}
+ onReact={onReact ? (emoji) => onReact(m.id, emoji) : undefined}
+ onReply={onReply ? () => onReply(m.id) : undefined}
+ onPin={onPin ? () => onPin(m.id) : undefined}
+ onCreateThread={onCreateThread ? () => onCreateThread(m.id) : undefined}
+ onCopy={onCopy ? () => onCopy(m.id) : undefined}
+ onRetry={onRetry ? () => onRetry(m.id) : undefined}
+ onPreviewImage={onPreviewImage}
+ onDownloadFile={onDownloadFile}
+ highlighted={jumped === m.id}
+ resolveUserName={resolveUserName}
+ />
+ </div>
+ ))}
+ </div>
+ ))}
{typingUsers && typingUsers.length > 0 && <TypingIndicator names={typingUsers} />}
</div>
diff --git a/src/web/src/components/community/server-settings.tsx b/src/web/src/components/community/server-settings.tsx
index 89f55351c..6e9970053 100644
--- a/src/web/src/components/community/server-settings.tsx
+++ b/src/web/src/components/community/server-settings.tsx
@@ -177,6 +177,8 @@ function SettingsMembers({ members, loading, loadingMore, hasMore, total, onLoad
return () => clearTimeout(t)
}, [query, onSearch])
+ // TanStack Virtual returns unstable function refs — React Compiler skips memoization.
+ // eslint-disable-next-line react-hooks/incompatible-library -- library limitation
const rowVirtualizer = useVirtualizer({
count: members.length,
getScrollElement: () => scrollRef.current,
diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsx
index 29df06df4..c6946f60b 100644
--- a/src/web/src/components/community/shell-frame.tsx
+++ b/src/web/src/components/community/shell-frame.tsx
@@ -324,7 +324,7 @@ export function ShellFrame({
)
const previewImage = useCallback((url: string) => setPreview(url), [])
- const goBackMobile = useCallback(() => setMobileZone("nav"), [])
+ const goBackMobile = useCallback(() => setMobileZone("nav"), [setMobileZone])
useEffect(() => {
useCommunityStore.getState().registerUiHandlers({
previewImage,
diff --git a/src/web/src/components/community/thread-opener.tsx b/src/web/src/components/community/thread-opener.tsx
index 22dee1e7e..812b96e43 100644
--- a/src/web/src/components/community/thread-opener.tsx
+++ b/src/web/src/components/community/thread-opener.tsx
@@ -88,15 +88,15 @@ export function ThreadOpener({
<button
key={i}
onClick={() => onPreviewImage?.(a.url)}
- className="block w-fit max-w-[280px] overflow-hidden rounded-md border border-border transition-colors hover:border-primary/40"
+ className="block w-fit max-w-70 overflow-hidden rounded-md border border-border transition-colors hover:border-primary/40"
>
- <img src={a.url} alt={a.name} className="max-h-40 max-w-[280px] rounded-md object-contain" />
+ <img src={a.url} alt={a.name} className="max-h-40 max-w-70 rounded-md object-contain" />
</button>
) : (
<button
key={i}
onClick={() => onDownloadFile?.(a.url)}
- className="flex w-full max-w-[280px] items-center gap-3 rounded-md border border-border bg-card p-2 text-left transition-colors hover:bg-accent"
+ className="flex w-full max-w-70 items-center gap-3 rounded-md border border-border bg-card p-2 text-left transition-colors hover:bg-accent"
>
<FileText className="size-6 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
@@ -142,7 +142,7 @@ function ThreadOpenerSkeleton() {
<Skeleton className="size-8 shrink-0 rounded-full" />
<div className="flex min-w-0 flex-1 flex-col gap-2">
<Skeleton className="h-4 w-32 rounded" />
- <Skeleton className="h-3.5 w-full max-w-[260px] rounded" />
+ <Skeleton className="h-3.5 w-full max-w-65 rounded" />
<Skeleton className="h-3.5 w-40 rounded" />
</div>
</div>
diff --git a/src/web/src/components/community/use-rail-order.ts b/src/web/src/components/community/use-rail-order.ts
index cb4e77ff2..a153d97a4 100644
--- a/src/web/src/components/community/use-rail-order.ts
+++ b/src/web/src/components/community/use-rail-order.ts
@@ -19,6 +19,13 @@ type Callbacks = {
const GROUP_DELAY = 300
+function computeRailOrder(railServerIds: string[], folders: CommunityFolder[]): string[] {
+ const inFolder = new Set(folders.flatMap((f) => f.servers.map((s) => s.id)))
+ const serverItems = railServerIds.filter((id) => !inFolder.has(id))
+ const folderItems = [...folders].sort((a, b) => a.position - b.position).map((f) => folderId(f.id))
+ return [...serverItems, ...folderItems]
+}
+
/**
* Multi-folder rail order hook.
*
@@ -33,17 +40,7 @@ export function useRailOrder(
) {
// Build initial rail order: servers not in any folder + folder keys sorted by position
const folderServerSet = useRef(new Set<string>())
- const buildRailOrder = useCallback(() => {
- const inFolder = new Set(folders.flatMap((f) => f.servers.map((s) => s.id)))
- folderServerSet.current = inFolder
- const serverItems = railServerIds.filter((id) => !inFolder.has(id))
- // Copy before sort — `folders` may be a frozen fallback while the query
- // is loading; mutating it in place would throw.
- const folderItems = [...folders].sort((a, b) => a.position - b.position).map((f) => folderId(f.id))
- return [...serverItems, ...folderItems]
- }, [railServerIds, folders])
-
- const [railOrder, setRailOrder] = useState<string[]>(buildRailOrder)
+ const [railOrder, setRailOrder] = useState<string[]>(() => computeRailOrder(railServerIds, folders))
const [openFolders, setOpenFolders] = useState<Set<string>>(new Set())
const [groupTarget, setGroupTarget] = useState<string | null>(null)
diff --git a/src/web/src/hooks/community/use-channel-read-state.ts b/src/web/src/hooks/community/use-channel-read-state.ts
index 0310e3287..0957bec8a 100644
--- a/src/web/src/hooks/community/use-channel-read-state.ts
+++ b/src/web/src/hooks/community/use-channel-read-state.ts
@@ -65,20 +65,25 @@ export function useChannelReadStateSnapshot(channelId: string | null | undefined
// Latch the first resolved snapshot so subsequent renders return a stable
// reference. Reset on channelId change — a new channel mount is a new
- // snapshot lifecycle.
+ // snapshot lifecycle. Must reset synchronously during render so the
+ // returned snapshot never belongs to the previous channel.
const snapshotRef = useRef<ChannelReadStateSnapshot | null>(null)
const lastChannelIdRef = useRef<string | null | undefined>(channelId)
+ /* eslint-disable react-hooks/refs -- sync channel switch reset; see hook tests */
if (lastChannelIdRef.current !== channelId) {
snapshotRef.current = null
lastChannelIdRef.current = channelId
}
+ /* eslint-enable react-hooks/refs */
useEffect(() => {
if (snapshotRef.current !== null) return
if (query.data) snapshotRef.current = query.data
}, [query.data])
+ /* eslint-disable react-hooks/refs -- latched snapshot read; see hook tests */
return {
snapshot: snapshotRef.current ?? (query.data ?? null),
isFetching: query.isFetching,
}
+ /* eslint-enable react-hooks/refs */
}
diff --git a/src/web/src/hooks/community/use-channel-watermark.ts b/src/web/src/hooks/community/use-channel-watermark.ts
index 9da922442..edde119f6 100644
--- a/src/web/src/hooks/community/use-channel-watermark.ts
+++ b/src/web/src/hooks/community/use-channel-watermark.ts
@@ -53,11 +53,9 @@ export function useChannelWatermark({
// channel changes so a switch between channels doesn't leak the prior
// channel's pointer.
const maxSeenRef = useRef<{ createdAt: string; id: string } | null>(null)
- const lastChannelIdRef = useRef<string | null | undefined>(channelId)
- if (lastChannelIdRef.current !== channelId) {
+ useEffect(() => {
maxSeenRef.current = null
- lastChannelIdRef.current = channelId
- }
+ }, [channelId])
// Keep the freshest `messages` array visible to the IntersectionObserver
// callback via a ref — the callback captures once per observer re-attach
@@ -65,9 +63,11 @@ export function useChannelWatermark({
// observed on the next render pass (see the effect below), so the ref
// avoids stale-closure lookups when a row is measured.
const messagesRef = useRef<Msg[]>(messages)
- messagesRef.current = messages
const advanceRef = useRef(advance)
- advanceRef.current = advance
+ useEffect(() => {
+ messagesRef.current = messages
+ advanceRef.current = advance
+ })
useEffect(() => {
if (!channelId) return
diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.ts
index 8725d5bbc..e2a3d17b1 100644
--- a/src/web/src/hooks/community/use-community-ws.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.test.ts
@@ -213,6 +213,60 @@ describe("useCommunityWs — message.create", () => {
expect(cache?.pages[0].messages).toHaveLength(1)
})
+ it("caps the live page at MAX_LIVE_PAGE_MESSAGES, dropping the oldest entry", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })
+ refCounter = 0
+ stateCounter = 0
+ callbackCounter = 0
+ await mountHook()
+
+ const MAX_LIVE_PAGE_MESSAGES = 500
+ const seeded = Array.from({ length: MAX_LIVE_PAGE_MESSAGES }, (_, i) => ({
+ id: `seed_${i}`,
+ content: "x",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ }))
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{ messages: seeded, hasMore: false }],
+ pageParams: [null],
+ })
+
+ capturedOnMessage!(messageCreate("ch_1", "new_message"))
+
+ const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
+ communityKeys.channelMessages("ch_1"),
+ )
+ const ids = cache?.pages[0].messages.map((m) => m.id) ?? []
+ expect(ids).toHaveLength(MAX_LIVE_PAGE_MESSAGES)
+ // Oldest entry (seed_0) was dropped; the newest inserted message is present.
+ expect(ids).not.toContain("seed_0")
+ expect(ids[ids.length - 1]).toBe("new_message")
+ // Second-oldest survivor shifts to the front.
+ expect(ids[0]).toBe("seed_1")
+ })
+
+ it("does not drop below the cap when the page isn't at capacity yet", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })
+ refCounter = 0
+ stateCounter = 0
+ callbackCounter = 0
+ await mountHook()
+
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{ messages: [{ id: "seed_0", content: "x", createdAt: "t" }], hasMore: false }],
+ pageParams: [null],
+ })
+ capturedOnMessage!(messageCreate("ch_1", "m_new"))
+ const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
+ communityKeys.channelMessages("ch_1"),
+ )
+ expect(cache?.pages[0].messages.map((m) => m.id)).toEqual(["seed_0", "m_new"])
+ })
+
it("does not schedule an inbox invalidate for viewer's own messages", async () => {
vi.useFakeTimers()
try {
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index f5834660e..9312b1ff2 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -84,6 +84,17 @@ import type { ServersResponse, ServerDetail } from "@/hooks/community/use-server
// message burst.
const INBOX_INVALIDATE_DEBOUNCE_MS = 500
+// Cap on the live (newest) page's message count inside `insertMessageIntoCache`.
+// Without this, a channel that stays open for a long session (or a flood of
+// WS message.create events) grows the first page — and the per-render
+// clustering pass in `message-list.tsx` — without bound. Matches
+// `SEEN_MESSAGE_MAX` (stores/community/ws.ts) for consistency; set generous
+// on purpose — tune down later if memory/render cost is still a problem.
+// Only the live-tail page is capped: pagination-loaded older pages
+// (`fetchOlder`) are left uncapped since they only grow from explicit user
+// "load more" clicks, not an attacker-controlled vector.
+const MAX_LIVE_PAGE_MESSAGES = 500
+
// ── Types (kept for backwards compat with any lingering imports) ─────────
export type Subscription = {
@@ -166,9 +177,15 @@ function insertMessageIntoCache(
// on send, see #1).
...(authorId ? { authorId } : {}),
}
+ const merged = [...first.messages, rendered]
+ // Drop from the head (oldest end of this page) once the live tail grows
+ // past the cap — keeps the newest messages, sheds the oldest.
+ const messages = merged.length > MAX_LIVE_PAGE_MESSAGES
+ ? merged.slice(merged.length - MAX_LIVE_PAGE_MESSAGES)
+ : merged
return {
...cache,
- pages: [{ ...first, messages: [...first.messages, rendered] }, ...cache.pages.slice(1)],
+ pages: [{ ...first, messages }, ...cache.pages.slice(1)],
}
}
@@ -285,9 +302,11 @@ export function communityWsSendTyping(target: {
export function useCommunityWs(options?: UseCommunityWsOptions) {
const queryClient = useQueryClient()
const viewerUserIdRef = useRef<string | null>(options?.viewerUserId ?? null)
- viewerUserIdRef.current = options?.viewerUserId ?? null
const callbacksRef = useRef<CommunityWsCallbacks>(options ?? {})
- callbacksRef.current = options ?? {}
+ useEffect(() => {
+ viewerUserIdRef.current = options?.viewerUserId ?? null
+ callbacksRef.current = options ?? {}
+ })
// #3: the previous WS-driven auto-mark-read (a `useMarkChannelRead()` call
// fired on every foreign-authored message in the focused channel) has
@@ -770,7 +789,6 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
// === send` check below). Whoever added the second mount site should
// co-locate them under a single root-level `useCommunityWs()` call.
if (activeSend !== null && activeSend !== send) {
- // eslint-disable-next-line no-console
console.warn(
"[useCommunityWs] Multiple instances detected — mount this hook once at the tree root.",
)
diff --git a/src/web/src/hooks/use-agent-chat.ts b/src/web/src/hooks/use-agent-chat.ts
index 4e6926832..28c7c2d06 100644
--- a/src/web/src/hooks/use-agent-chat.ts
+++ b/src/web/src/hooks/use-agent-chat.ts
@@ -141,7 +141,9 @@ export function useAgentChat(
const [conversation, setConversation] = useState<Conversation | null>(null);
const [messages, setMessages] = useState<Message[]>([]);
const messagesSnapshotRef = useRef<Message[]>([]);
- messagesSnapshotRef.current = messages;
+ useEffect(() => {
+ messagesSnapshotRef.current = messages;
+ });
const [sending, setSending] = useState(false);
const [activeTask, setActiveTask] = useState<Task | null>(null);
const [taskMessages, setTaskMessages] = useState<TaskMessageResponse[]>([]);
@@ -156,7 +158,9 @@ export function useAgentChat(
// `listArtifacts` from creating a new array reference that cascades through
// `agentArtifacts` → `timeline` → every MessageItem re-render.
const artifactsRef = useRef(artifacts);
- artifactsRef.current = artifacts;
+ useEffect(() => {
+ artifactsRef.current = artifacts;
+ });
const setArtifacts = useCallback((next: Artifact[] | ((prev: Artifact[]) => Artifact[])) => {
setArtifactsRaw((prev) => {
const resolved = typeof next === "function" ? next(prev) : next;
@@ -1908,7 +1912,7 @@ export function useAgentChat(
setSending(false);
});
},
- [failedSends, conversation, sending, workspaceId, startPolling],
+ [failedSends, conversation, sending, workspaceId, startPolling, setArtifacts, persistArtifactsToCache, preloadThenCleanPending],
);
const handleRetryTask = useCallback(async () => {
diff --git a/src/web/src/hooks/use-file-attachments.ts b/src/web/src/hooks/use-file-attachments.ts
index 549c9f306..2e009201f 100644
--- a/src/web/src/hooks/use-file-attachments.ts
+++ b/src/web/src/hooks/use-file-attachments.ts
@@ -19,7 +19,9 @@ function revokeThumbnailUrls(files: PendingFile[]) {
export function useFileAttachments() {
const [pendingFiles, _setPendingFiles] = useState<PendingFile[]>([]);
const pendingFilesRef = useRef(pendingFiles);
- pendingFilesRef.current = pendingFiles;
+ useEffect(() => {
+ pendingFilesRef.current = pendingFiles;
+ });
const setPendingFiles = useCallback((next: PendingFile[] | ((prev: PendingFile[]) => PendingFile[])) => {
_setPendingFiles((prev) => {
diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.ts
index c2063fec6..945ea39a8 100644
--- a/src/web/src/lib/api/responses.ts
+++ b/src/web/src/lib/api/responses.ts
@@ -4,7 +4,6 @@ import {
} from "@/lib/middleware/helpers";
import { TaskApiBaseSchema, isOnline, TASK_TYPES, schema, type Message } from "@alook/shared";
-type UserRow = typeof schema.user.$inferSelect;
type WorkspaceRow = typeof schema.workspace.$inferSelect;
type AgentRow = typeof schema.agent.$inferSelect;
type EmailRow = typeof schema.emails.$inferSelect;
diff --git a/src/web/src/lib/community/env.test.ts b/src/web/src/lib/community/env.test.ts
deleted file mode 100644
index 0e7069e49..000000000
--- a/src/web/src/lib/community/env.test.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { describe, it, expect, afterEach, beforeEach, vi } from "vitest"
-
-const originalNodeEnv = process.env.NODE_ENV
-const originalServerUrl = process.env.NEXT_PUBLIC_COMMUNITY_SERVER_URL
-const originalWsUrl = process.env.NEXT_PUBLIC_COMMUNITY_DAEMON_WS_URL
-
-beforeEach(() => {
- vi.resetModules()
- delete process.env.NEXT_PUBLIC_COMMUNITY_SERVER_URL
- delete process.env.NEXT_PUBLIC_COMMUNITY_DAEMON_WS_URL
-})
-
-afterEach(() => {
- process.env.NODE_ENV = originalNodeEnv
- if (originalServerUrl === undefined) delete process.env.NEXT_PUBLIC_COMMUNITY_SERVER_URL
- else process.env.NEXT_PUBLIC_COMMUNITY_SERVER_URL = originalServerUrl
- if (originalWsUrl === undefined) delete process.env.NEXT_PUBLIC_COMMUNITY_DAEMON_WS_URL
- else process.env.NEXT_PUBLIC_COMMUNITY_DAEMON_WS_URL = originalWsUrl
-})
-
-describe("community env constants", () => {
- it("falls back to dev defaults when env vars are unset in dev", async () => {
- process.env.NODE_ENV = "development"
- const mod = await import("./env.js")
- expect(mod.COMMUNITY_SERVER_URL).toBe("http://localhost:3000")
- expect(mod.COMMUNITY_DAEMON_WS_URL).toBe("ws://localhost:8789")
- })
-
- it("uses env var values when set in dev", async () => {
- process.env.NODE_ENV = "development"
- process.env.NEXT_PUBLIC_COMMUNITY_SERVER_URL = "https://alook.example"
- process.env.NEXT_PUBLIC_COMMUNITY_DAEMON_WS_URL = "wss://ws.alook.example"
- const mod = await import("./env.js")
- expect(mod.COMMUNITY_SERVER_URL).toBe("https://alook.example")
- expect(mod.COMMUNITY_DAEMON_WS_URL).toBe("wss://ws.alook.example")
- })
-
- it("throws in production when env vars are unset", async () => {
- process.env.NODE_ENV = "production"
- await expect(import("./env.js")).rejects.toThrow(
- /Missing required env var NEXT_PUBLIC_COMMUNITY_SERVER_URL/,
- )
- })
-
- it("uses env var values when set in production", async () => {
- process.env.NODE_ENV = "production"
- process.env.NEXT_PUBLIC_COMMUNITY_SERVER_URL = "https://alook.example"
- process.env.NEXT_PUBLIC_COMMUNITY_DAEMON_WS_URL = "wss://ws.alook.example"
- const mod = await import("./env.js")
- expect(mod.COMMUNITY_SERVER_URL).toBe("https://alook.example")
- expect(mod.COMMUNITY_DAEMON_WS_URL).toBe("wss://ws.alook.example")
- })
-})
diff --git a/src/web/src/lib/community/env.ts b/src/web/src/lib/community/env.ts
deleted file mode 100644
index 75ca244a8..000000000
--- a/src/web/src/lib/community/env.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-function required(name: string, devFallback: string): string {
- const value = process.env[name]
- if (value && value.length > 0) return value
- if (process.env.NODE_ENV === "production") {
- throw new Error(`Missing required env var ${name}`)
- }
- return devFallback
-}
-
-export const COMMUNITY_SERVER_URL = required(
- "NEXT_PUBLIC_COMMUNITY_SERVER_URL",
- "http://localhost:3000",
-)
-export const COMMUNITY_DAEMON_WS_URL = required(
- "NEXT_PUBLIC_COMMUNITY_DAEMON_WS_URL",
- "ws://localhost:8789",
-)
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index 1aac42e9a..1fd32d14c 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -171,21 +171,18 @@ export async function createCommunityMessage(params: {
})
}
- // Reply target for mention broadcasts. Scope-check against the current
- // target so a caller can't attach a preview of a message from a different
- // DM/channel by passing its id. The payload-side reply preview is built
- // from the same scope-checked map by `mapMessageForWs` below.
+ // Reply target for mention broadcasts. Scoped at the query level (not a
+ // post-hoc `.filter()`) so a caller can't attach a preview of a message
+ // from a different DM/channel by passing its id. The payload-side reply
+ // preview is built from the same scope-checked map by `mapMessageForWs`
+ // below.
const replyMap = new Map<string, { id: string; authorName: string; content: string | null }>()
const replyTargets = new Set<string>()
if (row.replyToId) {
// single-id path — see `dm/[id]/messages/route.ts` / `channels/[id]/messages/route.ts` for the batched N-id path
- const replyMsg = await queries.communityMessage.getMessage(db, row.replyToId)
- const inScope = replyMsg
- ? target.kind === "dm"
- ? replyMsg.dmConversationId === target.dmId
- : replyMsg.channelId === target.channelId
- : false
- if (replyMsg && inScope) {
+ const scope = target.kind === "dm" ? { dmConversationId: target.dmId } : { channelId: target.channelId }
+ const replyMsg = await queries.communityMessage.getMessageInScope(db, row.replyToId, scope)
+ if (replyMsg) {
replyMap.set(replyMsg.id, {
id: replyMsg.id,
authorName: replyMsg.authorName,
diff --git a/src/web/src/lib/community/rate-limit.test.ts b/src/web/src/lib/community/rate-limit.test.ts
new file mode 100644
index 000000000..716c409e2
--- /dev/null
+++ b/src/web/src/lib/community/rate-limit.test.ts
@@ -0,0 +1,78 @@
+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.ts
new file mode 100644
index 000000000..30b90f4a1
--- /dev/null
+++ b/src/web/src/lib/community/rate-limit.ts
@@ -0,0 +1,55 @@
+/**
+ * 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/middleware/helpers.test.ts b/src/web/src/lib/middleware/helpers.test.ts
index 570083ba1..9e145bb9d 100644
--- a/src/web/src/lib/middleware/helpers.test.ts
+++ b/src/web/src/lib/middleware/helpers.test.ts
@@ -3,8 +3,8 @@ import { describe, it, expect, vi } from "vitest";
vi.mock("next/server", () => {
return {
NextResponse: {
- json(data: unknown, init?: { status?: number }) {
- return { body: data, status: init?.status ?? 200 };
+ json(data: unknown, init?: { status?: number; headers?: Record<string, string> }) {
+ return { body: data, status: init?.status ?? 200, headers: init?.headers };
},
},
};
@@ -69,6 +69,18 @@ describe("writeError", () => {
expect(res.status).toBe(500);
expect(res.body).toEqual({ error: "Internal" });
});
+
+ it("omits headers when not provided (no regression for existing 2-arg call sites)", () => {
+ const res = writeError("Not found", 404) as any;
+ expect(res.headers).toBeUndefined();
+ });
+
+ it("sets the provided headers when a third argument is passed", () => {
+ const res = writeError("rate limited", 429, { "Retry-After": "7" }) as any;
+ expect(res.status).toBe(429);
+ expect(res.body).toEqual({ error: "rate limited" });
+ expect(res.headers).toEqual({ "Retry-After": "7" });
+ });
});
// ---------------------------------------------------------------------------
diff --git a/src/web/src/lib/middleware/helpers.ts b/src/web/src/lib/middleware/helpers.ts
index ecb398955..dd8bb95e3 100644
--- a/src/web/src/lib/middleware/helpers.ts
+++ b/src/web/src/lib/middleware/helpers.ts
@@ -4,8 +4,8 @@ export function writeJSON(data: unknown, status = 200): NextResponse {
return NextResponse.json(data, { status });
}
-export function writeError(message: string, status: number): NextResponse {
- return NextResponse.json({ error: message }, { status });
+export function writeError(message: string, status: number, headers?: Record<string, string>): NextResponse {
+ return NextResponse.json({ error: message }, { status, ...(headers ? { headers } : {}) });
}
/** Format a Date or ISO string as RFC 3339 without sub-second precision (matching Go output). */
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index 3852a6b4d..805da1aa7 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -1,10 +1,9 @@
"use client"
import { useEffect, useRef, useCallback } from "react"
import type { WsMessage } from "@alook/shared"
-import { isLocalMode } from "@/lib/utils"
+import { isLocalMode, WS_DO_PORT_DEFAULT } from "@/lib/utils"
const isLocal = isLocalMode()
-const WS_DO_PORT_DEFAULT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789
const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS) || 1000
const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_MS) || 30_000
diff --git a/src/web/src/lib/use-ws.test.ts b/src/web/src/lib/use-ws.test.ts
deleted file mode 100644
index 0946e5c38..000000000
--- a/src/web/src/lib/use-ws.test.ts
+++ /dev/null
@@ -1,253 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
-import type { WsMessage } from "@alook/shared"
-
-// --- Mock WebSocket ---
-class MockWebSocket {
- static instances: MockWebSocket[] = []
- url: string
- onopen: (() => void) | null = null
- onmessage: ((e: { data: string }) => void) | null = null
- onerror: (() => void) | null = null
- onclose: (() => void) | null = null
- closed = false
- sent: string[] = []
-
- constructor(url: string) {
- this.url = url
- MockWebSocket.instances.push(this)
- }
- send(data: string) { this.sent.push(data) }
- close() { this.closed = true; this.onclose?.() }
-
- simulateOpen() { this.onopen?.() }
- simulateMessage(data: unknown) { this.onmessage?.({ data: JSON.stringify(data) }) }
- simulateClose() { this.onclose?.() }
-}
-
-vi.stubGlobal("WebSocket", MockWebSocket)
-
-const mockFetch = vi.fn()
-vi.stubGlobal("fetch", mockFetch)
-
-vi.stubEnv("NODE_ENV", "development")
-vi.stubEnv("NEXT_PUBLIC_WS_DO_PORT", "8789")
-
-// --- Minimal React hooks mock ---
-let effectCleanup: (() => void) | null = null
-let refs: Map<string, { current: unknown }> = new Map()
-let refCounter = 0
-let callbackMemo: Map<string, { fn: Function; deps: unknown[] }> = new Map()
-let callbackCounter = 0
-
-vi.mock("react", () => ({
- useRef: (initial: unknown) => {
- const id = `ref-${refCounter++}`
- if (!refs.has(id)) {
- refs.set(id, { current: initial })
- }
- return refs.get(id)!
- },
- useCallback: (fn: Function, deps: unknown[]) => {
- const id = `cb-${callbackCounter++}`
- const existing = callbackMemo.get(id)
- if (existing && JSON.stringify(existing.deps) === JSON.stringify(deps)) {
- return existing.fn
- }
- callbackMemo.set(id, { fn, deps })
- return fn
- },
- useEffect: (fn: () => (() => void) | void, _deps: unknown[]) => {
- const cleanup = fn()
- if (cleanup) effectCleanup = cleanup
- },
-}))
-
-function setupTokenFetch() {
- mockFetch.mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({ token: "tok-456" }),
- })
-}
-
-function resetMockState() {
- MockWebSocket.instances = []
- mockFetch.mockReset()
- effectCleanup = null
- refs = new Map()
- refCounter = 0
- callbackMemo = new Map()
- callbackCounter = 0
-}
-
-describe("useAgentWs", () => {
- beforeEach(() => {
- resetMockState()
- vi.useFakeTimers()
- })
-
- afterEach(() => {
- vi.useRealTimers()
- })
-
- async function mountHook(agentId: string, onMessage: (msg: WsMessage) => void) {
- const mod = await import("./use-ws")
- mod.useAgentWs(agentId, onMessage)
- await vi.runAllTimersAsync()
- return mod
- }
-
- it("connect depends on [agentId] — changing callback does NOT create new connect", async () => {
- setupTokenFetch()
-
- const mod = await import("./use-ws")
-
- resetMockState()
- setupTokenFetch()
- refCounter = 0
- callbackCounter = 0
-
- mod.useAgentWs("agent-1", vi.fn())
- const firstCallbackId = Array.from(callbackMemo.keys()).find(k => k.startsWith("cb-"))
- const firstConnect = callbackMemo.get(firstCallbackId!)?.fn
-
- // Re-render with different callback, same agentId
- refCounter = 0
- callbackCounter = 0
-
- mod.useAgentWs("agent-1", vi.fn())
- const secondConnect = callbackMemo.get(firstCallbackId!)?.fn
-
- expect(firstConnect).toBe(secondConnect)
- })
-
- it("connect creates new reference when agentId changes", async () => {
- setupTokenFetch()
-
- const mod = await import("./use-ws")
-
- resetMockState()
- setupTokenFetch()
- refCounter = 0
- callbackCounter = 0
-
- mod.useAgentWs("agent-1", vi.fn())
- const firstCallbackId = Array.from(callbackMemo.keys()).find(k => k.startsWith("cb-"))
- const firstConnect = callbackMemo.get(firstCallbackId!)?.fn
-
- // Re-render with different agentId
- refCounter = 0
- callbackCounter = 0
-
- mod.useAgentWs("agent-2", vi.fn())
- const secondConnect = callbackMemo.get(firstCallbackId!)?.fn
-
- // Should be different because agentId changed
- expect(firstConnect).not.toBe(secondConnect)
- })
-
- it("effect cleanup nullifies wsRef and calls close — onclose skips reconnect", async () => {
- setupTokenFetch()
-
- const onMsg = vi.fn()
- await mountHook("agent-1", onMsg)
- await vi.runAllTimersAsync()
-
- const ws = MockWebSocket.instances[0]
- expect(ws).toBeDefined()
-
- effectCleanup?.()
-
- expect(ws.closed).toBe(true)
-
- const instanceCountBefore = MockWebSocket.instances.length
- await vi.advanceTimersByTimeAsync(5000)
- expect(MockWebSocket.instances.length).toBe(instanceCountBefore)
- })
-
- it("onMessageRef dispatches to latest callback", async () => {
- setupTokenFetch()
-
- const cb1 = vi.fn()
- await mountHook("agent-1", cb1)
- await vi.runAllTimersAsync()
-
- const ws = MockWebSocket.instances[0]
- ws.simulateOpen()
-
- ws.simulateMessage({ type: "test", data: "hello" })
- expect(cb1).toHaveBeenCalledWith({ type: "test", data: "hello" })
-
- const onMessageRef = Array.from(refs.values()).find(r =>
- typeof r.current === "function"
- )
- const cb2 = vi.fn()
- if (onMessageRef) onMessageRef.current = cb2
-
- ws.simulateMessage({ type: "test", data: "world" })
- expect(cb2).toHaveBeenCalledWith({ type: "test", data: "world" })
- expect(cb1).toHaveBeenCalledTimes(1)
- })
-
- it("server-initiated close triggers reconnect with backoff", async () => {
- setupTokenFetch()
-
- const onMsg = vi.fn()
- await mountHook("agent-1", onMsg)
- await vi.runAllTimersAsync()
-
- const ws = MockWebSocket.instances[0]
- ws.simulateOpen()
-
- const instancesBefore = MockWebSocket.instances.length
-
- ws.onclose?.()
-
- setupTokenFetch()
- await vi.advanceTimersByTimeAsync(2000)
-
- expect(MockWebSocket.instances.length).toBeGreaterThan(instancesBefore)
- })
-
- it("failed connect does not leave orphaned timers", async () => {
- mockFetch.mockRejectedValue(new Error("network error"))
-
- const onMsg = vi.fn()
- await mountHook("agent-1", onMsg)
- await vi.runAllTimersAsync()
-
- expect(MockWebSocket.instances.length).toBe(0)
- expect(() => effectCleanup?.()).not.toThrow()
- })
-
- it("effect cleanup clears pending reconnect timer", async () => {
- setupTokenFetch()
-
- const onMsg = vi.fn()
- await mountHook("agent-1", onMsg)
- await vi.runAllTimersAsync()
-
- const ws = MockWebSocket.instances[0]
- ws.simulateOpen()
-
- const instancesBefore = MockWebSocket.instances.length
- ws.onclose?.()
-
- effectCleanup?.()
-
- setupTokenFetch()
- await vi.advanceTimersByTimeAsync(60_000)
-
- expect(MockWebSocket.instances.length).toBe(instancesBefore)
- })
-
- it("connects to correct URL with agentId", async () => {
- setupTokenFetch()
-
- await mountHook("my-agent-id", vi.fn())
- await vi.runAllTimersAsync()
-
- const ws = MockWebSocket.instances[0]
- expect(ws).toBeDefined()
- expect(ws.url).toContain("agentId=my-agent-id")
- })
-})
diff --git a/src/web/src/lib/use-ws.ts b/src/web/src/lib/use-ws.ts
deleted file mode 100644
index 246f51516..000000000
--- a/src/web/src/lib/use-ws.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-"use client"
-import { useEffect, useRef, useCallback } from "react"
-import type { WsMessage } from "@alook/shared"
-import { isLocalMode } from "@/lib/utils"
-
-const isLocal = isLocalMode()
-const WS_DO_PORT_DEFAULT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789
-const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS) || 1000
-const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_MS) || 30_000
-
-export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void) {
- const wsRef = useRef<WebSocket | null>(null)
- const reconnectDelay = useRef(WS_RECONNECT_INIT)
- const onMessageRef = useRef(onMessage)
- const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
-
- useEffect(() => {
- onMessageRef.current = onMessage
- }, [onMessage])
-
- const connectRef = useRef<(() => Promise<void>) | null>(null)
-
- const connect = useCallback(async () => {
- let userId: string
- let authToken: string
- let wsPort: number = WS_DO_PORT_DEFAULT
- try {
- const res = await fetch("/api/ws/token")
- if (!res.ok) return
- const body = await res.json() as { userId: string; token: string; wsPort?: number }
- userId = body.userId
- authToken = body.token
- if (body.wsPort) wsPort = body.wsPort
- } catch {
- return
- }
-
- const url = isLocal
- ? `ws://localhost:${wsPort}/?userId=${userId}&agentId=${agentId}`
- : `${location.origin.replace("http", "ws")}/api/ws?userId=${userId}&agentId=${agentId}`
-
- let ws: WebSocket
- try {
- ws = new WebSocket(url)
- } catch {
- return
- }
- wsRef.current = ws
-
- ws.onopen = () => {
- reconnectDelay.current = WS_RECONNECT_INIT
- ws.send(JSON.stringify({ type: "auth", token: authToken }))
- }
-
- ws.onmessage = (e) => {
- try {
- const msg = JSON.parse(e.data)
- if (msg.type === "auth.ok") return
- onMessageRef.current(msg as WsMessage)
- } catch {}
- }
-
- ws.onerror = () => {}
-
- ws.onclose = () => {
- if (ws !== wsRef.current) return
-
- const delay = Math.min(reconnectDelay.current, WS_RECONNECT_MAX)
- reconnectDelay.current = Math.min(delay * 2, WS_RECONNECT_MAX)
- reconnectTimerRef.current = setTimeout(() => {
- void connectRef.current?.()
- }, delay + Math.random() * 500)
- }
- }, [agentId])
-
- useEffect(() => {
- connectRef.current = connect
- }, [connect])
-
- useEffect(() => {
- connect()
- return () => {
- if (reconnectTimerRef.current !== null) {
- clearTimeout(reconnectTimerRef.current)
- reconnectTimerRef.current = null
- }
- const ws = wsRef.current
- wsRef.current = null
- ws?.close()
- }
- }, [connect])
-}
diff --git a/src/web/src/lib/utils-getmode.test.ts b/src/web/src/lib/utils-getmode.test.ts
index d248f3ba5..e2d3b8ae0 100644
--- a/src/web/src/lib/utils-getmode.test.ts
+++ b/src/web/src/lib/utils-getmode.test.ts
@@ -10,6 +10,8 @@ vi.mock("@alook/shared", () => ({
daemonCommand: vi.fn(() => "npx @alook/cli daemon start"),
isTauri: (...args: any[]) => mockIsTauri(...args),
isMobile: (...args: any[]) => mockIsMobile(...args),
+ DEV_PORTS: { web: 3000, emailWorker: 8787, wsDo: 8789, wakeWorker: 8790 },
+ devWsDoPort: () => 8789,
}));
import { getAppMode } from "./utils";
diff --git a/src/web/src/lib/utils.ts b/src/web/src/lib/utils.ts
index aefc241ee..3c34663f4 100644
--- a/src/web/src/lib/utils.ts
+++ b/src/web/src/lib/utils.ts
@@ -1,6 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
-import { resolveMode, cliCommand, updateCommand, daemonCommand, isTauri, isMobile, type AlookMode } from "@alook/shared"
+import { resolveMode, cliCommand, updateCommand, daemonCommand, isTauri, isMobile, devWsDoPort, type AlookMode } from "@alook/shared"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
@@ -24,6 +24,12 @@ export function isLocalMode(): boolean {
return getMode() !== "production"
}
+// The local dev WS Durable Object port (see DEV_WS_DO_URL in @alook/shared).
+// Browser-side constant shared by every hook/component that dials ws-do
+// directly in local dev — keep this the single definition instead of
+// re-reading NEXT_PUBLIC_WS_DO_PORT in each call site.
+export const WS_DO_PORT_DEFAULT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || devWsDoPort()
+
export function cliCmd(): string {
return cliCommand(getMode())
}
diff --git a/src/web/src/test/e2e-setup.ts b/src/web/src/test/e2e-setup.ts
index 9b5517ed0..fb16de4d9 100644
--- a/src/web/src/test/e2e-setup.ts
+++ b/src/web/src/test/e2e-setup.ts
@@ -1,8 +1,9 @@
import { afterAll } from "vitest"
import { closeDb } from "@alook/test-utils"
+import { DEV_WEB_URL } from "@alook/shared"
if (!process.env.APP_URL) {
- process.env.APP_URL = "http://localhost:3000"
+ process.env.APP_URL = DEV_WEB_URL
}
afterAll(() => {
diff --git a/src/web/src/test/e2e/dm-to-broadcast.test.ts b/src/web/src/test/e2e/dm-to-broadcast.test.ts
index 9c22b3c42..ca57feb95 100644
--- a/src/web/src/test/e2e/dm-to-broadcast.test.ts
+++ b/src/web/src/test/e2e/dm-to-broadcast.test.ts
@@ -5,17 +5,15 @@
*/
import { describe, it, expect, beforeAll, afterAll } from "vitest"
import { randomUUID } from "crypto"
+import { DEV_WS_DO_URL } from "@alook/shared"
import { seedTestData, cleanupTestData, type TestSeed, tokenRequest } from "@alook/test-utils"
-const WS_DO_PORT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789
-const WS_DO_HTTP = `http://localhost:${WS_DO_PORT}`
-
let seed: TestSeed
let wsAvailable = false
async function checkWsAvailable(): Promise<boolean> {
try {
- const res = await fetch(WS_DO_HTTP, { method: "GET" })
+ const res = await fetch(DEV_WS_DO_URL, { method: "GET" })
return res.status < 500
} catch {
return false
@@ -109,7 +107,7 @@ describe("cross-service: DM → task lifecycle → WS broadcast", () => {
if (!wsAvailable) return
const payload = { type: "task.completed", taskId: `test_${randomUUID().slice(0, 8)}`, conversationId }
- const broadcastRes = await fetch(`${WS_DO_HTTP}/broadcast/user/${seed.userId}`, {
+ const broadcastRes = await fetch(`${DEV_WS_DO_URL}/broadcast/user/${seed.userId}`, {
method: "POST",
body: JSON.stringify(payload),
})
diff --git a/src/web/src/test/e2e/ws-broadcast-on-task-event.test.ts b/src/web/src/test/e2e/ws-broadcast-on-task-event.test.ts
index d2fbaea8d..eddaee3fe 100644
--- a/src/web/src/test/e2e/ws-broadcast-on-task-event.test.ts
+++ b/src/web/src/test/e2e/ws-broadcast-on-task-event.test.ts
@@ -8,17 +8,15 @@
*/
import { describe, it, expect, beforeAll, afterAll } from "vitest"
import { randomUUID } from "crypto"
+import { DEV_WS_DO_URL } from "@alook/shared"
import { seedTestData, cleanupTestData, type TestSeed } from "@alook/test-utils"
-const WS_DO_PORT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789
-const WS_DO_HTTP = `http://localhost:${WS_DO_PORT}`
-
let seed: TestSeed
let wsAvailable = false
async function checkWsAvailable(): Promise<boolean> {
try {
- const res = await fetch(WS_DO_HTTP, { method: "GET" })
+ const res = await fetch(DEV_WS_DO_URL, { method: "GET" })
return res.status < 500
} catch {
return false
@@ -40,7 +38,7 @@ describe("regression: WS broadcast HTTP endpoint on task events", () => {
taskId: `task_${randomUUID().slice(0, 8)}`,
conversationId: `conv_${randomUUID().slice(0, 8)}`,
}
- const broadcastRes = await fetch(`${WS_DO_HTTP}/broadcast/user/${seed.userId}`, {
+ const broadcastRes = await fetch(`${DEV_WS_DO_URL}/broadcast/user/${seed.userId}`, {
method: "POST",
body: JSON.stringify(eventPayload),
})
@@ -53,7 +51,7 @@ describe("regression: WS broadcast HTTP endpoint on task events", () => {
if (!wsAvailable) return
const fakeUserId = `u_nonexistent_${randomUUID().slice(0, 8)}`
- const res = await fetch(`${WS_DO_HTTP}/broadcast/user/${fakeUserId}`, {
+ const res = await fetch(`${DEV_WS_DO_URL}/broadcast/user/${fakeUserId}`, {
method: "POST",
body: JSON.stringify({ type: "test.ping" }),
})
@@ -65,7 +63,7 @@ describe("regression: WS broadcast HTTP endpoint on task events", () => {
it("daemon broadcast endpoint delivers to daemon WS clients", async () => {
if (!wsAvailable) return
- const res = await fetch(`${WS_DO_HTTP}/broadcast/daemon/${seed.daemonId}`, {
+ const res = await fetch(`${DEV_WS_DO_URL}/broadcast/daemon/${seed.daemonId}`, {
method: "POST",
body: JSON.stringify({ type: "daemon.tasks", tasks: [] }),
})
diff --git a/src/web/src/test/e2e/ws.test.ts b/src/web/src/test/e2e/ws.test.ts
index 511ab4ec8..29b3a430a 100644
--- a/src/web/src/test/e2e/ws.test.ts
+++ b/src/web/src/test/e2e/ws.test.ts
@@ -1,10 +1,9 @@
import { describe, it, expect, beforeAll, afterAll } from "vitest"
import { randomUUID } from "crypto"
+import { DEV_WS_DO_URL } from "@alook/shared"
import { signUp, signIn, sessionRequest, sqlRun } from "@alook/test-utils"
-const WS_DO_PORT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789
-const WS_DO_HTTP = `http://localhost:${WS_DO_PORT}`
-const WS_DO_WS = `ws://localhost:${WS_DO_PORT}`
+const WS_DO_WS = DEV_WS_DO_URL.replace(/^http/, "ws")
const testEmail = `e2e_ws_${randomUUID().slice(0, 8)}@test.local`
const testPassword = "TestPassword123!"
@@ -13,7 +12,7 @@ const testName = "E2E WS User"
async function wsReachable(): Promise<boolean> {
try {
// Any non-WS GET returns 400 ("userId required") — we just want a TCP RST-free response.
- const res = await fetch(WS_DO_HTTP, { method: "GET" })
+ const res = await fetch(DEV_WS_DO_URL, { method: "GET" })
return res.status < 500
} catch {
return false
@@ -106,7 +105,7 @@ describe("ws (dev direct to ws-do)", () => {
const payload = { type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" }
const recv = waitForMessage<typeof payload>(ws, (m) => m.type === "runtime.status")
- const broadcastRes = await fetch(`${WS_DO_HTTP}/broadcast/user/${userId}`, {
+ const broadcastRes = await fetch(`${DEV_WS_DO_URL}/broadcast/user/${userId}`, {
method: "POST",
body: JSON.stringify(payload),
})
diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.ts
index 722846f46..d5d664a2e 100644
--- a/src/ws-do/src/ws-durable.test.ts
+++ b/src/ws-do/src/ws-durable.test.ts
@@ -76,6 +76,9 @@ const mockMarkMachineOffline = vi.fn()
const mockMarkMachineOnlineIfOffline = vi.fn()
const mockGetCoMemberUserIds = vi.fn<(db: unknown, userId: string) => Promise<string[]>>().mockResolvedValue([])
const mockGetFriendUserIds = vi.fn<(db: unknown, userId: string) => Promise<string[]>>().mockResolvedValue([])
+const mockGetChannelForMember = vi.fn()
+const mockGetDM = vi.fn()
+const mockListMembers = vi.fn()
// mockToSummary now returns row.status verbatim — status is the source of
// truth on the column, not a derivation from lastSeenAt. See
// plans/community-machine-presence-fix.md.
@@ -170,10 +173,17 @@ vi.mock("@alook/shared", () => {
},
communityMember: {
getCoMemberUserIds: (...a: [unknown, string]) => mockGetCoMemberUserIds(...a),
+ listMembers: (...a: any[]) => mockListMembers(...a),
},
communityFriendship: {
getFriendUserIds: (...a: [unknown, string]) => mockGetFriendUserIds(...a),
},
+ communityChannel: {
+ getChannelForMember: (...a: any[]) => mockGetChannelForMember(...a),
+ },
+ communityDm: {
+ getDM: (...a: any[]) => mockGetDM(...a),
+ },
},
}
})
@@ -1105,4 +1115,107 @@ describe("WebSocketDurableObject", () => {
expect(ctx.storage.setAlarm).toHaveBeenCalled()
})
})
+
+ describe("webSocketMessage — community:typing.start authz (fanOutTyping)", () => {
+ // fanOutTyping runs fire-and-forget (`.catch()`, not awaited) inside
+ // webSocketMessage, so `await durable.webSocketMessage(...)` alone
+ // doesn't guarantee its internal DB-then-broadcast chain has settled.
+ // Flush a macrotask so all pending microtasks (getDM/getChannelForMember
+ // → listMembers → Promise.all(fetch)) drain before asserting.
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0))
+
+ it("does not fan out or broadcast when sender is not a member of the target channel", async () => {
+ const { durable, env } = createDO()
+ mockGetChannelForMember.mockResolvedValueOnce(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "chan-private" }),
+ )
+ await flush()
+
+ expect(mockGetChannelForMember).toHaveBeenCalledWith(expect.anything(), "chan-private", "attacker")
+ expect(mockListMembers).not.toHaveBeenCalled()
+ expect((env.WS_DO as any).get).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("fans out to other server members when sender IS a channel member", async () => {
+ const { durable, env } = createDO()
+ mockGetChannelForMember.mockResolvedValueOnce({ id: "chan-1", serverId: "server-1" })
+ mockListMembers.mockResolvedValueOnce([
+ { userId: "member-1" },
+ { userId: "member-2" },
+ { userId: "sender-1" },
+ ])
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "chan-1" }),
+ )
+ await flush()
+
+ expect(mockGetChannelForMember).toHaveBeenCalledWith(expect.anything(), "chan-1", "sender-1")
+ expect(mockListMembers).toHaveBeenCalledWith(expect.anything(), "server-1")
+ // Sender is excluded from recipients — only the other 2 members get a broadcast POST.
+ expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:member-1")
+ expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:member-2")
+ expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:sender-1")
+ expect(mockStubFetch).toHaveBeenCalledTimes(2)
+ })
+
+ it("does not fan out when sender is not a participant of the target DM", async () => {
+ const { durable, env } = createDO()
+ mockGetDM.mockResolvedValueOnce({
+ id: "dm-1",
+ user1Id: "alice",
+ user2Id: "bob",
+ lastMessageAt: null,
+ createdAt: "",
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", dmConversationId: "dm-1" }),
+ )
+ await flush()
+
+ expect(mockGetDM).toHaveBeenCalledWith(expect.anything(), "dm-1")
+ expect((env.WS_DO as any).get).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("fans out to the other participant when sender IS a DM participant", async () => {
+ const { durable, env } = createDO()
+ mockGetDM.mockResolvedValueOnce({
+ id: "dm-1",
+ user1Id: "alice",
+ user2Id: "bob",
+ lastMessageAt: null,
+ createdAt: "",
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", dmConversationId: "dm-1" }),
+ )
+ await flush()
+
+ expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:bob")
+ expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:alice")
+ expect(mockStubFetch).toHaveBeenCalledTimes(1)
+ })
+ })
})
diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.ts
index 86ef7f287..a4cfb0fa8 100644
--- a/src/ws-do/src/ws-durable.ts
+++ b/src/ws-do/src/ws-durable.ts
@@ -824,6 +824,13 @@ export class WebSocketDurableObject extends DurableObject<Env> {
* For channel/thread: resolve channel -> server -> members.
* For DM: resolve the 2 participants.
* Excludes the sender.
+ *
+ * Authorization: the sender must actually be a member of the target
+ * channel's server (or a participant of the target DM) before we resolve
+ * recipients — otherwise anyone who merely knows a channel/DM id could
+ * make their client "type" into a scope they have no access to. Both
+ * branches fold the check into the same query that already resolves the
+ * fan-out target, so this adds no extra DB round-trip versus before.
*/
private async fanOutTyping(
senderUserId: string,
@@ -838,18 +845,25 @@ export class WebSocketDurableObject extends DurableObject<Env> {
if (dmConversationId) {
const dm = await queries.communityDm.getDM(db, dmConversationId)
- if (dm) {
- recipientUserIds = [dm.user1Id, dm.user2Id].filter(Boolean) as string[]
+ if (!dm || (dm.user1Id !== senderUserId && dm.user2Id !== senderUserId)) {
+ log.warn("fanOutTyping: sender not a DM participant", { senderUserId, dmConversationId })
+ return
}
+ recipientUserIds = [dm.user1Id, dm.user2Id].filter(Boolean) as string[]
} else {
// Both threadId and channelId resolve to a channel after thread→channel unification
const targetId = threadId || channelId
if (targetId) {
- const channel = await queries.communityChannel.getChannel(db, targetId)
- if (channel) {
- const members = await queries.communityMember.listMembers(db, channel.serverId)
- recipientUserIds = members.map((m) => m.userId)
+ // getChannelForMember returns null when senderUserId isn't a member
+ // of the channel's server — same authz the HTTP layer enforces via
+ // requireChannelMember (src/web/src/lib/community/permissions.ts).
+ const membership = await queries.communityChannel.getChannelForMember(db, targetId, senderUserId)
+ if (!membership) {
+ log.warn("fanOutTyping: sender not a channel member", { senderUserId, channelId: targetId })
+ return
}
+ const members = await queries.communityMember.listMembers(db, membership.serverId)
+ recipientUserIds = members.map((m) => m.userId)
}
}
diff --git a/src/ws-do/wrangler.toml b/src/ws-do/wrangler.toml
index ece7bde41..d0016e5a9 100644
--- a/src/ws-do/wrangler.toml
+++ b/src/ws-do/wrangler.toml
@@ -18,6 +18,7 @@ enabled = true
head_sampling_rate = 0.05
destinations = ["grafana-traces"]
+# Must match DEV_PORTS.wsDo in src/shared/src/constants.ts
[dev]
port = 8789
inspector_port = 9230
diff --git a/tests/integration/cli/ws-push-poll.test.ts b/tests/integration/cli/ws-push-poll.test.ts
index 03be4a08a..47802f6d7 100644
--- a/tests/integration/cli/ws-push-poll.test.ts
+++ b/tests/integration/cli/ws-push-poll.test.ts
@@ -7,10 +7,10 @@ import {
sqlRun,
} from "@alook/test-utils"
import { DaemonClient } from "../../../src/cli/daemon/client"
-import { DaemonPushMessageSchema } from "@alook/shared"
+import { DaemonPushMessageSchema, DEV_WEB_URL, DEV_WS_DO_URL } from "@alook/shared"
-const APP_URL = process.env.APP_URL ?? "http://localhost:3000"
-const WS_DO_URL = process.env.WS_DO_URL ?? "http://localhost:8789"
+const APP_URL = process.env.APP_URL ?? DEV_WEB_URL
+const WS_DO_URL = process.env.WS_DO_URL ?? DEV_WS_DO_URL
const client = new DaemonClient(APP_URL)
let seed: TestSeed
diff --git a/tests/utils/package.json b/tests/utils/package.json
index 465e84899..6f1b0e683 100644
--- a/tests/utils/package.json
+++ b/tests/utils/package.json
@@ -11,6 +11,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
+ "@alook/shared": "workspace:*",
"better-sqlite3": "^12.11.1"
},
"devDependencies": {
diff --git a/tests/utils/src/auth.ts b/tests/utils/src/auth.ts
index fabad5d8f..51cafa56e 100644
--- a/tests/utils/src/auth.ts
+++ b/tests/utils/src/auth.ts
@@ -1,6 +1,7 @@
+import { DEV_WEB_URL } from "@alook/shared"
import { fetchWithRetry } from "./fetch"
-const APP_URL = process.env.APP_URL ?? "http://localhost:3000"
+const APP_URL = process.env.APP_URL ?? DEV_WEB_URL
export async function signUp(email: string, password: string, name: string) {
return fetch(`${APP_URL}/api/auth/sign-up/email`, {
diff --git a/tests/utils/src/email.ts b/tests/utils/src/email.ts
index 5a485ee21..71c454dc5 100644
--- a/tests/utils/src/email.ts
+++ b/tests/utils/src/email.ts
@@ -1,7 +1,8 @@
import { randomUUID } from "crypto"
+import { DEV_EMAIL_WORKER_URL } from "@alook/shared"
import { fetchWithRetry } from "./fetch"
-const EMAIL_WORKER_URL = process.env.EMAIL_WORKER_URL ?? "http://localhost:8787"
+const EMAIL_WORKER_URL = process.env.EMAIL_WORKER_URL ?? DEV_EMAIL_WORKER_URL
export function rawEmail(from: string, to: string, subject: string, body: string): string {
const msgId = `<${randomUUID()}@e2e.test>`