Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

Unify routes under one auth entry and retire old CLI connections (#1113)

Gustavo Ye37255abff0b6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e650b230b..be3a846dd 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -563,7 +563,7 @@ jobs:
run: node scripts/ci/validate-execution-plan.mjs
- name: Create local bindings
run: |
- printf 'BETTER_AUTH_SECRET=ci-e2e-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\n' > src/web/.dev.vars
+ printf 'BETTER_AUTH_SECRET=ci-e2e-secret\nBETTER_AUTH_URL=http://localhost:3000\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\n' > src/web/.dev.vars
cp src/queue-worker/.dev.vars.example src/queue-worker/.dev.vars
sed -i 's|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!|' src/queue-worker/.dev.vars
- run: pnpm run db:migrate
@@ -666,7 +666,7 @@ jobs:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
- - run: printf 'BETTER_AUTH_SECRET=ci-lighthouse-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\n' > src/web/.dev.vars
+ - run: printf 'BETTER_AUTH_SECRET=ci-lighthouse-secret\nBETTER_AUTH_URL=http://localhost:3000\n' > src/web/.dev.vars
- run: pnpm run db:migrate
- working-directory: src/web
run: npx @lhci/cli autorun --config=lighthouserc.json && node scripts/print-lighthouse-scores.mjs
@@ -706,7 +706,7 @@ jobs:
run: |
printf 'artifact_name=ui-e2e-build-%s-%s\n' "${{ github.run_id }}" "${{ github.run_attempt }}" >> "$GITHUB_OUTPUT"
printf 'artifact_attempt=%s\n' "${{ github.run_attempt }}" >> "$GITHUB_OUTPUT"
- - run: printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\nDEV_WS_DO_URL=http://localhost:3000\nNODE_ENV=development\n' > src/web/.dev.vars
+ - run: printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\nBETTER_AUTH_URL=http://localhost:3000\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\nDEV_WS_DO_URL=http://localhost:3000\nNODE_ENV=development\n' > src/web/.dev.vars
- name: Build Web and Blog OpenNext workers
env:
NEXT_PUBLIC_WS_DO_PORT: "3000"
@@ -773,7 +773,7 @@ jobs:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
- - run: printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\nDEV_WS_DO_URL=http://localhost:3000\nNODE_ENV=development\n' > src/web/.dev.vars
+ - run: printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\nBETTER_AUTH_URL=http://localhost:3000\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\nDEV_WS_DO_URL=http://localhost:3000\nNODE_ENV=development\n' > src/web/.dev.vars
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8
with:
name: ${{ needs.ui-e2e-build.outputs.artifact_name }}
@@ -842,7 +842,7 @@ jobs:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
- - run: printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\nDEV_WS_DO_URL=http://localhost:3000\nNODE_ENV=development\n' > src/web/.dev.vars
+ - run: printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\nBETTER_AUTH_URL=http://localhost:3000\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\nDEV_WS_DO_URL=http://localhost:3000\nNODE_ENV=development\n' > src/web/.dev.vars
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8
with:
name: ${{ needs.ui-e2e-build.outputs.artifact_name }}
diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
index 5aefaf0c6..74d98322f 100644
--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json
+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
@@ -173,18 +173,6 @@
{
"key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:30"
},
- {
- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:31"
- },
- {
- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:32"
- },
- {
- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:33"
- },
- {
- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:34"
- },
{
"key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:4"
},
diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.ts
index 17685d0e0..854191621 100644
--- a/scripts/ci/workflow-contract.test.ts
+++ b/scripts/ci/workflow-contract.test.ts
@@ -325,7 +325,7 @@ describe("E2E UI workflow", () => {
const producer = ciJob("ui-e2e-build")
const shard = ciJob("e2e-ui")
const gate = ciJob("ui-e2e-gate")
- const devVars = "printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\\nBETTER_AUTH_URL=http://localhost:3000\\nDEVICE_CLIENT_IDS=e2e-test-client\\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\\nDEV_WS_DO_URL=http://localhost:3000\\nNODE_ENV=development\\n' > src/web/.dev.vars"
+ const devVars = "printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\\nBETTER_AUTH_URL=http://localhost:3000\\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\\nDEV_WS_DO_URL=http://localhost:3000\\nNODE_ENV=development\\n' > src/web/.dev.vars"
expect(producer).toContain("image: ${{ fromJSON(needs.scope.outputs.e2e_matrix).include[0].image }}")
expect(producer).toContain("options: --init --ipc=host --user 1001")
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index 75e6b62ba..ed66096e0 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -9,7 +9,6 @@ export * as conversation from "./queries/conversation";
export * as message from "./queries/message";
export * as task from "./queries/task";
export * as machine from "./queries/machine";
-export * as machineToken from "./queries/machine-token";
export * as whitelist from "./queries/whitelist";
export * as email from "./queries/email";
export * as session from "./queries/session";
diff --git a/src/shared/src/db/queries/account-deletion.test.ts b/src/shared/src/db/queries/account-deletion.test.ts
index b94a50713..14406662e 100644
--- a/src/shared/src/db/queries/account-deletion.test.ts
+++ b/src/shared/src/db/queries/account-deletion.test.ts
@@ -308,8 +308,6 @@ describe("account deletion snapshot and delete queries", () => {
expect(snapshot!.providers).toHaveLength(1)
expect(snapshot!.ownedWorkspaceIds).toEqual([ownedWorkspace])
expect(snapshot!.ownedAgentIds.sort()).toEqual([ownedAgent, sharedOwnedAgent].sort())
- expect(snapshot!.legacyDaemons).toEqual([{ workspaceId: sharedWorkspace, daemonId: daemon }])
- expect(snapshot!.machineTokens.sort()).toEqual(["al_owner_token", "al_workspace_token"])
expect(snapshot!.machineDoNames).toEqual(["b".repeat(32)])
expect(snapshot!.botBindings).toEqual([{ botId: bot, machineId: "community_machine_1" }])
expect(snapshot!.ownedServers).toEqual(expect.arrayContaining([
diff --git a/src/shared/src/db/queries/account-deletion.ts b/src/shared/src/db/queries/account-deletion.ts
index bd1a454ce..a773969ee 100644
--- a/src/shared/src/db/queries/account-deletion.ts
+++ b/src/shared/src/db/queries/account-deletion.ts
@@ -9,7 +9,6 @@ import {
emails,
issueComment,
machine,
- machineToken,
meetingSession,
member,
session,
@@ -126,8 +125,6 @@ export type AccountDeletionSnapshot = {
}>
ownedWorkspaceIds: string[]
ownedAgentIds: string[]
- legacyDaemons: Array<{ workspaceId: string; daemonId: string }>
- machineTokens: string[]
machineDoNames: string[]
botBindings: Array<{ botId: string; machineId: string }>
ownedServers: Array<{ id: string; icon: string | null; memberIds: string[] }>
@@ -224,8 +221,6 @@ export async function getAccountDeletionSnapshot(
providers,
ownedWorkspaceRows,
ownedAgentRows,
- legacyDaemons,
- machineTokens,
machineCredentials,
botBindings,
serverRows,
@@ -254,18 +249,6 @@ export async function getAccountDeletionSnapshot(
}).from(account).where(inArray(account.userId, identitiesQuery)),
ownedWorkspaceIdsQuery,
ownedAgentRowsQuery,
- db.select({ workspaceId: machine.workspaceId, daemonId: machine.daemonId })
- .from(machine)
- .where(or(
- inArray(machine.workspaceId, ownedWorkspaceIdsQuery),
- inArray(machine.ownerId, identitiesQuery),
- )),
- db.select({ token: machineToken.token })
- .from(machineToken)
- .where(or(
- inArray(machineToken.userId, identitiesQuery),
- inArray(machineToken.workspaceId, ownedWorkspaceIdsQuery),
- )),
db.select({ doName: communityMachineCredential.doName })
.from(communityMachineCredential)
.where(inArray(communityMachineCredential.userId, identitiesQuery)),
@@ -353,8 +336,6 @@ export async function getAccountDeletionSnapshot(
providers,
ownedWorkspaceIds: ownedWorkspaceRows.map((row) => row.id),
ownedAgentIds: ownedAgentRows.map((row) => row.id),
- legacyDaemons,
- machineTokens: unique(machineTokens.map((row) => row.token)),
machineDoNames: unique(machineCredentials.map((row) => row.doName)),
botBindings,
ownedServers: serverRows.map((row) => ({
diff --git a/src/shared/src/db/queries/machine-token.ts b/src/shared/src/db/queries/machine-token.ts
deleted file mode 100644
index ce9967190..000000000
--- a/src/shared/src/db/queries/machine-token.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { eq, and, desc, isNull } from "drizzle-orm";
-import { machineToken, user } from "../schema";
-import type { Database } from "../index";
-
-export async function createMachineToken(
- db: Database,
- data: {
- userId: string;
- workspaceId?: string | null;
- token: string;
- name: string;
- status?: string;
- }
-) {
- const rows = await db
- .insert(machineToken)
- .values({
- userId: data.userId,
- workspaceId: data.workspaceId ?? null,
- token: data.token,
- name: data.name,
- status: data.status ?? "active",
- })
- .returning();
- return rows[0]!;
-}
-
-export async function getMachineTokenByToken(db: Database, token: string) {
- const rows = await db
- .select({
- id: machineToken.id,
- userId: machineToken.userId,
- workspaceId: machineToken.workspaceId,
- token: machineToken.token,
- name: machineToken.name,
- status: machineToken.status,
- lastUsedAt: machineToken.lastUsedAt,
- createdAt: machineToken.createdAt,
- userEmail: user.email,
- })
- .from(machineToken)
- .innerJoin(user, eq(user.id, machineToken.userId))
- .where(and(eq(machineToken.token, token), isNull(user.deletedAt)));
- return rows[0] ?? null;
-}
-
-export async function getPendingMachineToken(
- db: Database,
- userId: string,
- workspaceId?: string | null
-) {
- const conditions = [
- eq(machineToken.userId, userId),
- eq(machineToken.status, "pending"),
- ];
- if (workspaceId) {
- conditions.push(eq(machineToken.workspaceId, workspaceId));
- } else {
- conditions.push(isNull(machineToken.workspaceId));
- }
- const rows = await db
- .select()
- .from(machineToken)
- .where(and(...conditions))
- .limit(1);
- return rows[0] ?? null;
-}
-
-export async function activateMachineToken(
- db: Database,
- id: string,
- hostname: string,
-) {
- await db
- .update(machineToken)
- .set({ status: "active", hostname })
- .where(eq(machineToken.id, id));
-}
-
-export async function getLatestTokenForUser(db: Database, userId: string) {
- const rows = await db
- .select({
- id: machineToken.id,
- token: machineToken.token,
- status: machineToken.status,
- workspaceId: machineToken.workspaceId,
- hostname: machineToken.hostname,
- lastUsedAt: machineToken.lastUsedAt,
- })
- .from(machineToken)
- .where(eq(machineToken.userId, userId))
- .orderBy(desc(machineToken.createdAt))
- .limit(1);
- return rows[0] ?? null;
-}
-
-export async function listMachineTokens(
- db: Database,
- userId: string,
- workspaceId: string
-) {
- return db
- .select()
- .from(machineToken)
- .where(
- and(
- eq(machineToken.userId, userId),
- eq(machineToken.workspaceId, workspaceId)
- )
- )
- .orderBy(desc(machineToken.createdAt));
-}
-
-export async function deleteMachineToken(
- db: Database,
- id: string,
- userId: string
-) {
- await db
- .delete(machineToken)
- .where(and(eq(machineToken.id, id), eq(machineToken.userId, userId)));
-}
-
-export async function updateMachineTokenLastUsed(db: Database, id: string) {
- await db
- .update(machineToken)
- .set({ lastUsedAt: new Date().toISOString() })
- .where(eq(machineToken.id, id));
-}
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 3a6ec946a..a1cb0644f 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -27,7 +27,6 @@ export type {
Channel,
WsMessage,
WorkspaceFileResult,
- DaemonPushMessage,
} from "./types";
// API types
@@ -251,7 +250,6 @@ export {
UpdateAgentRequestSchema,
CreateConversationRequestSchema,
CreateMessageRequestSchema,
- AgentDmRequestSchema,
EmailAttachmentSchema,
SendEmailRequestSchema,
UpdateEmailStatusRequestSchema,
@@ -273,7 +271,6 @@ export {
CreateStudioRequestSchema,
RecruitAgentRequestSchema,
CreateThreadRequestSchema,
- DaemonPushMessageSchema,
CommunityMachineRuntimeSchema,
CommunityMachineRuntimeListSchema,
ReasoningEffortSchema,
@@ -359,7 +356,6 @@ export type {
DeregisterRequest,
CompleteTaskRequest,
FailTaskRequest,
- AgentDmRequest,
MessageItem,
ReportMessagesRequest,
CreateCalendarEventRequestInput,
@@ -388,7 +384,6 @@ export type {
CreateStudioRequest,
RecruitAgentRequest,
CreateThreadRequest,
- DaemonPushMessageType,
CommunityDaemonReady,
CommunityPairTokenResponse,
CommunityDaemonActivateRequest,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index f065f78de..ee947dd2e 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -179,21 +179,6 @@ export const PollResponseSchema = z.object({
});
export type PollResponse = z.infer<typeof PollResponseSchema>;
-// ---------------------------------------------------------------------------
-// Daemon push messages (server -> daemon WebSocket)
-// ---------------------------------------------------------------------------
-
-export const DaemonPushMessageSchema = z.discriminatedUnion("type", [
- z.object({ type: z.literal("daemon.tasks"), tasks: z.array(TaskApiSchema) }),
- z.object({ type: z.literal("daemon.file_requests"), workspaceId: z.string(), requests: z.array(FileRequestItemSchema) }),
- z.object({ type: z.literal("daemon.meetings"), meetings: z.array(PollMeetingItemSchema) }),
- z.object({ type: z.literal("daemon.evict"), workspaceId: z.string() }),
- z.object({ type: z.literal("daemon.update"), version: z.string() }),
- z.object({ type: z.literal("daemon.rescan") }),
- z.object({ type: z.literal("daemon.kill"), workspaceId: z.string(), agentId: z.string().min(1), taskId: z.string(), targetTaskId: z.string() }),
-]);
-export type DaemonPushMessageType = z.infer<typeof DaemonPushMessageSchema>;
-
// ---------------------------------------------------------------------------
// Register response
// ---------------------------------------------------------------------------
@@ -561,15 +546,6 @@ export const CreateMessageRequestSchema = z.object({
});
export type CreateMessageRequest = z.infer<typeof CreateMessageRequestSchema>;
-// Agent-authored DM: the agent's own `role:"assistant"` reply, posted via the
-// machine-token daemon route (`alook sync send-dm`). Unlike CreateMessageRequest
-// (a user send) this does NOT enqueue a task — it only delivers the message.
-export const AgentDmRequestSchema = z.object({
- content: z.string().min(1, "content is required"),
- task_id: z.string().min(1).optional(),
-});
-export type AgentDmRequest = z.infer<typeof AgentDmRequestSchema>;
-
// ---------------------------------------------------------------------------
// Email request schemas
// ---------------------------------------------------------------------------
diff --git a/src/shared/src/types.ts b/src/shared/src/types.ts
index 693d10845..c7234b8d6 100644
--- a/src/shared/src/types.ts
+++ b/src/shared/src/types.ts
@@ -1,4 +1,4 @@
-import type { TaskApi, WorkspaceFileEntry, FileRequestItem, PollMeetingItem } from "./schemas";
+import type { TaskApi, WorkspaceFileEntry } from "./schemas";
import type { CommunityWsEvent } from "./community-ws-events";
export type EmailDirection = "inbound" | "outbound";
@@ -308,13 +308,3 @@ export interface WorkspaceFileResult {
error?: string;
path: string;
}
-
-/** Messages pushed from server to daemon via WebSocket. */
-export type DaemonPushMessage =
- | { type: "daemon.tasks"; tasks: TaskApi[] }
- | { type: "daemon.file_requests"; workspaceId: string; requests: FileRequestItem[] }
- | { type: "daemon.meetings"; meetings: PollMeetingItem[] }
- | { type: "daemon.evict"; workspaceId: string }
- | { type: "daemon.update"; version: string }
- | { type: "daemon.rescan" }
- | { type: "daemon.kill"; workspaceId: string; agentId: string; taskId: string; targetTaskId: string }
diff --git a/src/shared/test/queries/machine-token.test.ts b/src/shared/test/queries/machine-token.test.ts
deleted file mode 100644
index f35af1d07..000000000
--- a/src/shared/test/queries/machine-token.test.ts
+++ /dev/null
@@ -1,146 +0,0 @@
-import { describe, it, expect, vi } from "vitest";
-import * as mt from "../../src/db/queries/machine-token";
-
-function createSelectMock(rows: any[]) {
- const chain: any = {};
- chain.select = vi.fn(() => chain);
- chain.from = vi.fn(() => chain);
- chain.where = vi.fn(() => Promise.resolve(rows));
- chain.innerJoin = vi.fn(() => chain);
- chain.insert = vi.fn(() => chain);
- chain.values = vi.fn(() => chain);
- chain.returning = vi.fn(() => Promise.resolve(rows));
- chain.orderBy = vi.fn(() => chain);
- return chain;
-}
-
-describe("machine-token exports", () => {
- it("exports createMachineToken", () => { expect(typeof mt.createMachineToken).toBe("function"); });
- it("exports getMachineTokenByToken", () => { expect(typeof mt.getMachineTokenByToken).toBe("function"); });
- it("exports getPendingMachineToken", () => { expect(typeof mt.getPendingMachineToken).toBe("function"); });
- it("exports activateMachineToken", () => { expect(typeof mt.activateMachineToken).toBe("function"); });
- it("exports getLatestTokenForUser", () => { expect(typeof mt.getLatestTokenForUser).toBe("function"); });
- it("exports listMachineTokens", () => { expect(typeof mt.listMachineTokens).toBe("function"); });
- it("exports deleteMachineToken", () => { expect(typeof mt.deleteMachineToken).toBe("function"); });
- it("exports updateMachineTokenLastUsed", () => { expect(typeof mt.updateMachineTokenLastUsed).toBe("function"); });
-});
-
-describe("createMachineToken", () => {
- it("creates token with defaults", async () => {
- const t = { id: "mt_1" };
- const mockDb = createSelectMock([t]);
- const result = await mt.createMachineToken(mockDb, { userId: "u", token: "tok", name: "T" });
- expect(mockDb.values).toHaveBeenCalledWith(expect.objectContaining({ status: "active", workspaceId: null }));
- expect(result).toEqual(t);
- });
- it("uses custom status", async () => {
- const mockDb = createSelectMock([{ id: "mt_1" }]);
- await mt.createMachineToken(mockDb, { userId: "u", token: "tok", name: "T", status: "pending" });
- expect(mockDb.values).toHaveBeenCalledWith(expect.objectContaining({ status: "pending" }));
- });
-});
-
-function referencesColumn(node: unknown, columnName: string, seen = new Set<unknown>()): boolean {
- if (node === null || typeof node !== "object") return false;
- if (seen.has(node)) return false;
- seen.add(node);
- if ((node as { name?: unknown }).name === columnName) return true;
- for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
- if (key === "table") continue;
- if (Array.isArray(value)) {
- if (value.some((v) => referencesColumn(v, columnName, seen))) return true;
- } else if (referencesColumn(value, columnName, seen)) {
- return true;
- }
- }
- return false;
-}
-
-describe("getMachineTokenByToken", () => {
- it("returns null when not found", async () => { expect(await mt.getMachineTokenByToken(createSelectMock([]), "x")).toBeNull(); });
- it("returns token with join", async () => {
- const t = { id: "mt_1" };
- const mockDb = createSelectMock([t]);
- expect(await mt.getMachineTokenByToken(mockDb, "tok")).toEqual(t);
- expect(mockDb.innerJoin).toHaveBeenCalled();
- });
- it("filters on `user.deletedAt` in the WHERE so a soft-deleted owner's token stops authenticating", async () => {
- const mockDb = createSelectMock([{ id: "mt_1" }]);
- await mt.getMachineTokenByToken(mockDb, "tok");
- expect(referencesColumn(mockDb.where.mock.calls[0][0], "deletedAt")).toBe(true);
- });
-});
-
-describe("getPendingMachineToken", () => {
- it("returns null when none", async () => {
- const chain: any = {};
- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);
- chain.where = vi.fn(() => chain); chain.limit = vi.fn(() => Promise.resolve([]));
- expect(await mt.getPendingMachineToken(chain, "u")).toBeNull();
- });
- it("returns pending token", async () => {
- const t = { id: "mt_1" };
- const chain: any = {};
- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);
- chain.where = vi.fn(() => chain); chain.limit = vi.fn(() => Promise.resolve([t]));
- expect(await mt.getPendingMachineToken(chain, "u")).toEqual(t);
- });
- it("handles workspaceId", async () => {
- const t = { id: "mt_1" };
- const chain: any = {};
- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);
- chain.where = vi.fn(() => chain); chain.limit = vi.fn(() => Promise.resolve([t]));
- expect(await mt.getPendingMachineToken(chain, "u", "ws_1")).toEqual(t);
- });
-});
-
-describe("activateMachineToken", () => {
- it("sets active status with hostname", async () => {
- const chain: any = {};
- chain.update = vi.fn(() => chain); chain.set = vi.fn(() => chain);
- chain.where = vi.fn(() => Promise.resolve());
- await mt.activateMachineToken(chain, "mt_1", "host.local");
- expect(chain.set).toHaveBeenCalledWith(expect.objectContaining({
- status: "active",
- hostname: "host.local",
- }));
- });
-});
-
-describe("getLatestTokenForUser", () => {
- it("returns null when no tokens exist", async () => {
- const chain: any = {};
- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);
- chain.where = vi.fn(() => chain); chain.orderBy = vi.fn(() => chain);
- chain.limit = vi.fn(() => Promise.resolve([]));
- expect(await mt.getLatestTokenForUser(chain, "u")).toBeNull();
- });
- it("returns latest token with status", async () => {
- const t = { id: "mt_1", status: "active" };
- const chain: any = {};
- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);
- chain.where = vi.fn(() => chain); chain.orderBy = vi.fn(() => chain);
- chain.limit = vi.fn(() => Promise.resolve([t]));
- expect(await mt.getLatestTokenForUser(chain, "u")).toEqual(t);
- });
-});
-
-describe("deleteMachineToken", () => {
- it("deletes by id and userId", async () => {
- const chain: any = {};
- chain.delete = vi.fn(() => chain);
- chain.where = vi.fn(() => Promise.resolve());
- await mt.deleteMachineToken(chain, "mt_1", "u");
- expect(chain.delete).toHaveBeenCalled();
- });
-});
-
-describe("updateMachineTokenLastUsed", () => {
- it("updates lastUsedAt", async () => {
- const chain: any = {};
- chain.update = vi.fn(() => chain); chain.set = vi.fn(() => chain);
- chain.where = vi.fn(() => Promise.resolve());
- await mt.updateMachineTokenLastUsed(chain, "mt_1");
- expect(chain.set).toHaveBeenCalledWith(expect.objectContaining({ lastUsedAt: expect.any(String) }));
- });
-});
diff --git a/src/shared/test/schemas/daemon-push-message.test.ts b/src/shared/test/schemas/daemon-push-message.test.ts
deleted file mode 100644
index b1d5c2efa..000000000
--- a/src/shared/test/schemas/daemon-push-message.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { DaemonPushMessageSchema } from "../../src/schemas";
-
-describe("DaemonPushMessageSchema — daemon.kill", () => {
- it("accepts valid daemon.kill message with agentId", () => {
- const msg = {
- type: "daemon.kill",
- workspaceId: "ws1",
- agentId: "ag_abc123",
- taskId: "kt1",
- targetTaskId: "t1",
- };
- const result = DaemonPushMessageSchema.safeParse(msg);
- expect(result.success).toBe(true);
- });
-
- it("rejects daemon.kill message without agentId", () => {
- const msg = {
- type: "daemon.kill",
- workspaceId: "ws1",
- taskId: "kt1",
- targetTaskId: "t1",
- };
- const result = DaemonPushMessageSchema.safeParse(msg);
- expect(result.success).toBe(false);
- });
-
- it("rejects daemon.kill message with non-string agentId", () => {
- const msg = {
- type: "daemon.kill",
- workspaceId: "ws1",
- agentId: 123,
- taskId: "kt1",
- targetTaskId: "t1",
- };
- const result = DaemonPushMessageSchema.safeParse(msg);
- expect(result.success).toBe(false);
- });
-
- it("rejects daemon.kill message with empty string agentId", () => {
- const msg = {
- type: "daemon.kill",
- workspaceId: "ws1",
- agentId: "",
- taskId: "kt1",
- targetTaskId: "t1",
- };
- const result = DaemonPushMessageSchema.safeParse(msg);
- expect(result.success).toBe(false);
- });
-});
diff --git a/src/web/.dev.vars.example b/src/web/.dev.vars.example
index f093f765d..598c2f4ce 100644
--- a/src/web/.dev.vars.example
+++ b/src/web/.dev.vars.example
@@ -29,9 +29,6 @@ APPLE_TEAM_ID=
APPLE_KEY_ID=
APPLE_PRIVATE_KEY=
-# Device Code Flow — comma-separated allowed client IDs
-DEVICE_CLIENT_IDS=alook-cli
-
# JEV wake relevance providers. Configure the key for the selected JEV_PROVIDER.
OPENROUTER_API_KEY=
TYPESAFE_API_KEY=
diff --git a/src/web/cloudflare-env.d.ts b/src/web/cloudflare-env.d.ts
index b9fba80b8..ccb318704 100644
--- a/src/web/cloudflare-env.d.ts
+++ b/src/web/cloudflare-env.d.ts
@@ -33,7 +33,6 @@ interface __BaseEnv_CloudflareEnv {
APPLE_TEAM_ID: string;
APPLE_KEY_ID: string;
APPLE_PRIVATE_KEY: string;
- DEVICE_CLIENT_IDS: string;
OPENROUTER_API_KEY: string;
TYPESAFE_API_KEY: string;
NEXT_CACHE_DO_QUEUE: DurableObjectNamespace<import("./custom-worker").DOQueueHandler>;
@@ -55,7 +54,7 @@ type StringifyValues<EnvType extends Record<string, unknown>> = {
[Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;
};
declare namespace NodeJS {
- interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "RUNTIME_MODEL_OPTIONS" | "MIN_CLI_VERSION" | "BLOG_DISCOVERY_REQUIRED" | "JEV_PROVIDER" | "JEV_WAKE_THRESHOLD" | "OPENROUTER_JEV_BASE_URL" | "OPENROUTER_JEV_MODEL" | "TYPESAFE_JEV_BASE_URL" | "TYPESAFE_JEV_MODEL" | "BETTER_AUTH_SECRET" | "RESEND_API_KEY" | "BETTER_AUTH_URL" | "ENCRYPTION_KEY" | "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET" | "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET" | "APPLE_CLIENT_ID" | "APPLE_TEAM_ID" | "APPLE_KEY_ID" | "APPLE_PRIVATE_KEY" | "DEVICE_CLIENT_IDS" | "OPENROUTER_API_KEY" | "TYPESAFE_API_KEY">> {}
+ interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "RUNTIME_MODEL_OPTIONS" | "MIN_CLI_VERSION" | "BLOG_DISCOVERY_REQUIRED" | "JEV_PROVIDER" | "JEV_WAKE_THRESHOLD" | "OPENROUTER_JEV_BASE_URL" | "OPENROUTER_JEV_MODEL" | "TYPESAFE_JEV_BASE_URL" | "TYPESAFE_JEV_MODEL" | "BETTER_AUTH_SECRET" | "RESEND_API_KEY" | "BETTER_AUTH_URL" | "ENCRYPTION_KEY" | "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET" | "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET" | "APPLE_CLIENT_ID" | "APPLE_TEAM_ID" | "APPLE_KEY_ID" | "APPLE_PRIVATE_KEY" | "OPENROUTER_API_KEY" | "TYPESAFE_API_KEY">> {}
}
declare module "*.txt" {
const value: string;
diff --git a/src/web/next.config.ts b/src/web/next.config.ts
index a590160e5..4a0090703 100644
--- a/src/web/next.config.ts
+++ b/src/web/next.config.ts
@@ -9,6 +9,7 @@ const daemonPkg = JSON.parse(readFileSync(path.resolve(__dirname, "../daemon/pac
const observation = resolveObservationBuild(process.env);
const nextConfig: NextConfig = {
+ experimental: { turbopackFileSystemCacheForDev: false },
async headers() {
return [{ source: "/community-shell/:hash", headers: [
{ key: "Cache-Control", value: "public, max-age=31536000, immutable" },
diff --git a/src/web/src/app/api/community/analytics/funnel-events/route.test.ts b/src/web/src/app/api/community/analytics/funnel-events/route.test.ts
index 7bb9501b4..da8b0cd07 100644
--- a/src/web/src/app/api/community/analytics/funnel-events/route.test.ts
+++ b/src/web/src/app/api/community/analytics/funnel-events/route.test.ts
@@ -4,13 +4,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
const mocks = vi.hoisted(() => ({
db: { primary: true },
claimPendingEvents: vi.fn(),
- withCookieHumanAuth: vi.fn(
- (handler: (req: NextRequest, ctx: Record<string, any>) => Promise<Response>) =>
- async (req: NextRequest) => handler(req, {
+ cookieHumanAuthPolicy: { resolve: async (req: NextRequest) => ({ context: {
env: { DB: {} },
userId: "session-user",
- }),
- ),
+ } }) },
}))
vi.mock("@/lib/db", () => ({ getPrimaryDb: () => mocks.db }))
@@ -22,7 +19,7 @@ vi.mock("@alook/shared", () => ({
},
}))
vi.mock("@/lib/middleware/auth", () => ({
- withCookieHumanAuth: mocks.withCookieHumanAuth,
+ cookieHumanAuthPolicy: mocks.cookieHumanAuthPolicy,
}))
import { POST } from "./route"
diff --git a/src/web/src/app/api/community/analytics/funnel-events/route.ts b/src/web/src/app/api/community/analytics/funnel-events/route.ts
index df4d95d95..cdc2f6580 100644
--- a/src/web/src/app/api/community/analytics/funnel-events/route.ts
+++ b/src/web/src/app/api/community/analytics/funnel-events/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withCookieHumanAuth } from "@/lib/middleware/auth"
+import { cookieHumanAuthPolicy } from "@/lib/middleware/auth"
import { readAnalyticsConsent } from "@/lib/analytics-consent"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
-export const POST = withCookieHumanAuth(async (req, ctx) => {
+export const POST = withAuth(cookieHumanAuthPolicy, async (req, ctx) => {
const scope = req.nextUrl.searchParams.get("event") ?? "legacy"
if (scope !== "legacy" && scope !== "invited_human_joined") return writeError("invalid event scope", 400)
const events = scope === "invited_human_joined" && readAnalyticsConsent(req.headers.get("cookie") ?? "") === "denied" ? [] : await queries.communityFunnelAnalytics.claimPendingEvents(
diff --git a/src/web/src/app/api/community/automation/access-codes/[codeId]/route.ts b/src/web/src/app/api/community/automation/access-codes/[codeId]/route.ts
index 621780b2c..1d44ab335 100644
--- a/src/web/src/app/api/community/automation/access-codes/[codeId]/route.ts
+++ b/src/web/src/app/api/community/automation/access-codes/[codeId]/route.ts
@@ -1,16 +1,17 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { AutomationAccessCodeUpdateSchema, queries } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withAutomationManagement } from "@/lib/automation"
+import { automationManagementPolicy } from "@/lib/automation"
import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers"
-export const PATCH = withAutomationManagement(async (req, ctx) => {
+export const PATCH = withAuth(automationManagementPolicy, async (req, ctx) => {
const [body, error] = await parseBody(req, AutomationAccessCodeUpdateSchema)
if (error) return error
const accessCode = await queries.automation.updateAccessCode(getPrimaryDb(ctx.env.DB), ctx.userId, ctx.params?.codeId ?? "", body)
return accessCode ? writeJSON({ accessCode }) : writeError("Access code not found", 404)
})
-export const DELETE = withAutomationManagement(async (_req, ctx) => {
+export const DELETE = withAuth(automationManagementPolicy, async (_req, ctx) => {
const deleted = await queries.automation.deleteAccessCode(getPrimaryDb(ctx.env.DB), ctx.userId, ctx.params?.codeId ?? "")
return deleted ? writeJSON({ deleted: true }) : writeError("Access code not found", 404)
})
diff --git a/src/web/src/app/api/community/automation/access-codes/route.test.ts b/src/web/src/app/api/community/automation/access-codes/route.test.ts
index e2a70a025..c08029da8 100644
--- a/src/web/src/app/api/community/automation/access-codes/route.test.ts
+++ b/src/web/src/app/api/community/automation/access-codes/route.test.ts
@@ -2,9 +2,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
const mocks = vi.hoisted(() => ({ list: vi.fn(), create: vi.fn(), update: vi.fn(), remove: vi.fn() }))
vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))
-vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: (req: NextRequest, ctx: unknown) => Promise<Response>) => async (req: NextRequest, context?: { params?: Promise<Record<string, string>> }) => {
- if (req.headers.get("Cookie") !== "synthetic-human") return Response.json({}, { status: 401 })
- return handler(req, { env: { DB: {} }, userId: "owner", params: await context?.params })
+vi.mock("@/lib/middleware/auth", () => ({ humanAuthPolicy: {
+ resolve: async (req: NextRequest) => req.headers.get("Cookie") !== "synthetic-human"
+ ? Response.json({}, { status: 401 })
+ : { context: { env: { DB: {} }, userId: "owner" } },
+ respond: (_req: NextRequest, response: Response) => response,
} }))
vi.mock("@alook/shared", async (importOriginal) => ({ ...await importOriginal<typeof import("@alook/shared")>(), queries: { automation: { listAccessCodes: mocks.list, createAccessCode: mocks.create, updateAccessCode: mocks.update, deleteAccessCode: mocks.remove } } }))
import { GET, POST } from "./route"
diff --git a/src/web/src/app/api/community/automation/access-codes/route.ts b/src/web/src/app/api/community/automation/access-codes/route.ts
index 8ad1bc43d..ae04e1934 100644
--- a/src/web/src/app/api/community/automation/access-codes/route.ts
+++ b/src/web/src/app/api/community/automation/access-codes/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { AutomationAccessCodeCreateSchema, queries } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { hashAutomationSecret, newAutomationSecret, withAutomationManagement } from "@/lib/automation"
+import { hashAutomationSecret, newAutomationSecret, automationManagementPolicy } from "@/lib/automation"
import { parseBody, writeJSON } from "@/lib/middleware/helpers"
-export const GET = withAutomationManagement(async (_req, ctx) => writeJSON({ accessCodes: await queries.automation.listAccessCodes(getPrimaryDb(ctx.env.DB), ctx.userId) }))
+export const GET = withAuth(automationManagementPolicy, async (_req, ctx) => writeJSON({ accessCodes: await queries.automation.listAccessCodes(getPrimaryDb(ctx.env.DB), ctx.userId) }))
-export const POST = withAutomationManagement(async (req, ctx) => {
+export const POST = withAuth(automationManagementPolicy, async (req, ctx) => {
const [body, error] = await parseBody(req, AutomationAccessCodeCreateSchema)
if (error) return error
const secret = newAutomationSecret()
diff --git a/src/web/src/app/api/community/automation/bots/route.ts b/src/web/src/app/api/community/automation/bots/route.ts
index f431478c0..f00f0bc0a 100644
--- a/src/web/src/app/api/community/automation/bots/route.ts
+++ b/src/web/src/app/api/community/automation/bots/route.ts
@@ -1,3 +1,4 @@
-import { withAutomation } from "@/lib/automation"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { automationPolicy } from "@/lib/automation"
import { createBotForUser } from "@/lib/community/create-bot.server"
-export const POST = withAutomation("bot.create", createBotForUser)
+export const POST = withAuth(automationPolicy("bot.create"), createBotForUser)
diff --git a/src/web/src/app/api/community/automation/friends/route.ts b/src/web/src/app/api/community/automation/friends/route.ts
index 812ab3b4f..45d2d61aa 100644
--- a/src/web/src/app/api/community/automation/friends/route.ts
+++ b/src/web/src/app/api/community/automation/friends/route.ts
@@ -1,3 +1,4 @@
-import { withAutomation } from "@/lib/automation"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { automationPolicy } from "@/lib/automation"
import { readAutomationFriends } from "@/lib/community/automation-read.server"
-export const GET = withAutomation("friend.read", readAutomationFriends)
+export const GET = withAuth(automationPolicy("friend.read"), readAutomationFriends)
diff --git a/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.test.ts b/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.test.ts
index 9880208eb..2fcecd938 100644
--- a/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.test.ts
+++ b/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.test.ts
@@ -5,10 +5,10 @@ const mocks = vi.hoisted(() => ({ machine: vi.fn(), dispatch: vi.fn(), admit: vi
vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))
vi.mock("@/lib/broadcast", () => ({ wsDoFetch: mocks.dispatch }))
vi.mock("@alook/shared", async (importOriginal) => { const actual = await importOriginal<typeof import("@alook/shared")>(); return { ...actual, queries: { ...actual.queries, communityMachine: { getMachineByIdForUser: mocks.machine } } } })
-vi.mock("@/lib/middleware/community-actor", () => ({ withCommunityActor: (handler: unknown) => handler }))
-vi.mock("@/lib/automation", () => ({ withAutomation: (permission: string, handler: (...args: any[]) => unknown) => {
+vi.mock("@/lib/middleware/community-actor", () => ({ communityActorPolicy: () => ({ resolve: async () => ({ context: {} }) }) }))
+vi.mock("@/lib/automation", () => ({ automationPolicy: (permission: string) => {
expect(permission).toBe("machine.read")
- return (req: NextRequest) => handler(req, { env: { DB: {} }, userId: "code-owner", params: { id: "m1" }, beforeCreate: mocks.admit })
+ return { resolve: async () => ({ context: { env: { DB: {} }, userId: "code-owner", beforeCreate: mocks.admit } }) }
} }))
import { POST } from "./route"
const catalog = { catalogOrigin: "native_report", updateMode: "unsupported", defaultModelId: "fresh/model", models: [{ id: "fresh/model", supportedReasoningEfforts: [{ value: "high" }], defaultReasoningEffort: "high" }] }
@@ -20,7 +20,7 @@ beforeEach(() => {
mocks.dispatch.mockResolvedValue(Response.json({ sent: 1, unsupported: 0, observedAt: "2026-10-29T00:00:00Z", result: { status: "complete", catalog } }))
})
it("admits once, refreshes the owner target and projects the matching fresh result", async () => {
- const response = await POST(request())
+ const response = await POST(request(), { params: { id: "m1" } })
expect(response.status).toBe(200)
expect(mocks.machine).toHaveBeenCalledWith({ primary: true }, "code-owner", "m1")
expect(mocks.admit).toHaveBeenCalledOnce()
@@ -30,7 +30,7 @@ it("admits once, refreshes the owner target and projects the matching fresh resu
it("returns fresh missing and empty catalogs without the two removed metadata fields", async () => {
for (const value of [null, { updateMode: "unsupported", models: [] }]) {
mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 1, unsupported: 0, observedAt: "2026-10-29T00:00:00Z", result: { status: "complete", catalog: value } }))
- const body = await (await POST(request())).json()
+ const body = await (await POST(request(), { params: { id: "m1" } })).json()
expect(body.models).toEqual(value ? [] : null)
expect(body).not.toHaveProperty("catalogState")
expect(body).not.toHaveProperty("catalogOrigin")
@@ -38,46 +38,46 @@ it("returns fresh missing and empty catalogs without the two removed metadata fi
})
it("does not dispatch on denied quota, malformed request, foreign/offline machine or unknown runtime", async () => {
mocks.admit.mockResolvedValueOnce(Response.json({ error: "limited" }, { status: 429 }))
- expect((await POST(request())).status).toBe(429)
- expect((await POST(request({}))).status).toBe(400)
+ expect((await POST(request(), { params: { id: "m1" } })).status).toBe(429)
+ expect((await POST(request({}), { params: { id: "m1" } })).status).toBe(400)
mocks.machine.mockResolvedValueOnce(null)
- expect((await POST(request())).status).toBe(404)
+ expect((await POST(request(), { params: { id: "m1" } })).status).toBe(404)
mocks.machine.mockResolvedValueOnce({ status: "offline" })
- expect((await POST(request())).status).toBe(409)
- expect((await POST(request({ requestId: "request", runtimeId: "missing" }))).status).toBe(400)
+ expect((await POST(request(), { params: { id: "m1" } })).status).toBe(409)
+ expect((await POST(request({ requestId: "request", runtimeId: "missing" }), { params: { id: "m1" } })).status).toBe(400)
expect(mocks.dispatch).not.toHaveBeenCalled()
})
it("returns discovery errors and refuses missing/corrupt results instead of using old models", async () => {
mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 1, unsupported: 0, result: { status: "error", code: "AUTH_REQUIRED", message: "Sign in" } }))
- const response = await POST(request())
+ const response = await POST(request(), { params: { id: "m1" } })
expect(response.status).toBe(502)
expect(await response.json()).toEqual({ error: "Sign in", code: "AUTH_REQUIRED", machineId: "m1", backendId: "codex", requestId: "request" })
for (const result of [undefined, {}, { status: "complete", catalog: "bad" }]) {
mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 1, unsupported: 0, result }))
- expect((await POST(request())).status).toBe(503)
+ expect((await POST(request(), { params: { id: "m1" } })).status).toBe(503)
}
})
it("returns a timestamped server cache hit and allows an explicit refresh without forwarding refresh to the daemon", async () => {
mocks.machine.mockResolvedValueOnce({ status: "online", availableRuntimes: [{ id: "codex", status: "healthy", reasoning: catalog }] })
mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 0, unsupported: 0, cached: true, observedAt: "2026-10-29T00:00:00Z", catalogFingerprint: await fingerprintRuntimeModelCatalog(catalog as never) }))
- expect(await (await POST(request())).json()).toMatchObject({ source: "cached_report", observedAt: "2026-10-29T00:00:00Z" })
- await POST(request({ requestId: "force", runtimeId: "codex", refresh: true }))
+ expect(await (await POST(request(), { params: { id: "m1" } })).json()).toMatchObject({ source: "cached_report", observedAt: "2026-10-29T00:00:00Z" })
+ await POST(request({ requestId: "force", runtimeId: "codex", refresh: true }), { params: { id: "m1" } })
expect(mocks.dispatch.mock.lastCall?.[1]).toBe("/community-machine/by-id/m1/discover-models?wait=1")
expect(JSON.parse(mocks.dispatch.mock.lastCall?.[2].body)).toEqual({ requestId: "force", runtimeId: "codex" })
- expect((await POST(request({ requestId: "force", runtimeId: "codex", refresh: "yes" }))).status).toBe(400)
+ expect((await POST(request({ requestId: "force", runtimeId: "codex", refresh: "yes" }), { params: { id: "m1" } })).status).toBe(400)
})
it("rejects mismatched cache metadata instead of pairing it with an unrelated D1 snapshot", async () => {
mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 0, unsupported: 0, cached: true, observedAt: "2026-10-29T00:00:00Z", catalogFingerprint: "b".repeat(64) }))
- expect((await POST(request())).status).toBe(503)
+ expect((await POST(request(), { params: { id: "m1" } })).status).toBe(503)
})
it("fails closed on HTTP transport failure and invalid observation timestamps", async () => {
mocks.dispatch.mockResolvedValueOnce(new Response("down", { status: 503 }))
- expect((await POST(request())).status).toBe(503)
+ expect((await POST(request(), { params: { id: "m1" } })).status).toBe(503)
for (const observedAt of [undefined, "invalid"]) {
mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 1, observedAt, result: { status: "complete", catalog } }))
- expect((await POST(request())).status).toBe(503)
+ expect((await POST(request(), { params: { id: "m1" } })).status).toBe(503)
}
})
diff --git a/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.ts b/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.ts
index c78e00715..be31dc7b8 100644
--- a/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.ts
+++ b/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.ts
@@ -1,9 +1,10 @@
-import { withAutomation } from "@/lib/automation"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { automationPolicy } from "@/lib/automation"
import { discoverRuntimeModels, discoveryFailure } from "@/lib/community/discover-models.server"
import { projectModelOptions } from "@/lib/community/machine-options.server"
import { writeJSON } from "@/lib/middleware/helpers"
-export const POST = withAutomation("machine.read", async (req, ctx) => {
+export const POST = withAuth(automationPolicy("machine.read"), async (req, ctx) => {
const id = ctx.params?.id as string
const response = await discoverRuntimeModels(req, ctx, true, (message, status) => discoveryFailure(message, status, id))
if (response instanceof Response) return response
diff --git a/src/web/src/app/api/community/automation/machines/route.ts b/src/web/src/app/api/community/automation/machines/route.ts
index 9f58060ea..cb84d5956 100644
--- a/src/web/src/app/api/community/automation/machines/route.ts
+++ b/src/web/src/app/api/community/automation/machines/route.ts
@@ -1,3 +1,4 @@
-import { withAutomation } from "@/lib/automation"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { automationPolicy } from "@/lib/automation"
import { readAutomationMachines } from "@/lib/community/automation-read.server"
-export const GET = withAutomation("machine.read", readAutomationMachines)
+export const GET = withAuth(automationPolicy("machine.read"), readAutomationMachines)
diff --git a/src/web/src/app/api/community/automation/messages/route.ts b/src/web/src/app/api/community/automation/messages/route.ts
index 3a4dbc5ab..eca33b44e 100644
--- a/src/web/src/app/api/community/automation/messages/route.ts
+++ b/src/web/src/app/api/community/automation/messages/route.ts
@@ -1,3 +1,4 @@
-import { withAutomation } from "@/lib/automation"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { automationPolicy } from "@/lib/automation"
import { sendAutomationMessage } from "@/lib/community/automation-message.server"
-export const POST = withAutomation("message.send", sendAutomationMessage)
+export const POST = withAuth(automationPolicy("message.send"), sendAutomationMessage)
diff --git a/src/web/src/app/api/community/automation/servers/[id]/invites/route.ts b/src/web/src/app/api/community/automation/servers/[id]/invites/route.ts
index d71cec398..c943a3e1f 100644
--- a/src/web/src/app/api/community/automation/servers/[id]/invites/route.ts
+++ b/src/web/src/app/api/community/automation/servers/[id]/invites/route.ts
@@ -1,3 +1,4 @@
-import { withAutomation } from "@/lib/automation"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { automationPolicy } from "@/lib/automation"
import { inviteAutomationFriend } from "@/lib/community/automation-invite.server"
-export const POST = withAutomation("server.invite", inviteAutomationFriend)
+export const POST = withAuth(automationPolicy("server.invite"), inviteAutomationFriend)
diff --git a/src/web/src/app/api/community/automation/servers/route.ts b/src/web/src/app/api/community/automation/servers/route.ts
index 4945eeac0..de69fec39 100644
--- a/src/web/src/app/api/community/automation/servers/route.ts
+++ b/src/web/src/app/api/community/automation/servers/route.ts
@@ -1,5 +1,6 @@
-import { withAutomation } from "@/lib/automation"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { automationPolicy } from "@/lib/automation"
import { createServerForUser } from "@/lib/community/create-server.server"
import { readAutomationServers } from "@/lib/community/automation-read.server"
-export const GET = withAutomation("server.read", readAutomationServers)
-export const POST = withAutomation("server.create", createServerForUser)
+export const GET = withAuth(automationPolicy("server.read"), readAutomationServers)
+export const POST = withAuth(automationPolicy("server.create"), createServerForUser)
diff --git a/src/web/src/app/api/community/billing/cancel-change/route.ts b/src/web/src/app/api/community/billing/cancel-change/route.ts
index 6e8bd9201..ead044a3a 100644
--- a/src/web/src/app/api/community/billing/cancel-change/route.ts
+++ b/src/web/src/app/api/community/billing/cancel-change/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { BillingSummarySchema } from "@alook/shared"
-import { withCookieHumanAuth } from "@/lib/middleware/auth"
+import { cookieHumanAuthPolicy } from "@/lib/middleware/auth"
import { getPrimaryDb } from "@/lib/db"
import { billingClient, billingFailure, billingResponse } from "@/lib/billing/client"
import { cancelScheduledChange } from "@/lib/billing/service"
-export const POST = withCookieHumanAuth(async (req, ctx) => {
+export const POST = withAuth(cookieHumanAuthPolicy, async (req, ctx) => {
const text = await req.text()
if (text.trim()) {
try {
diff --git a/src/web/src/app/api/community/billing/checkout/route.ts b/src/web/src/app/api/community/billing/checkout/route.ts
index 434b2e2ee..61b5c6497 100644
--- a/src/web/src/app/api/community/billing/checkout/route.ts
+++ b/src/web/src/app/api/community/billing/checkout/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { BillingCheckoutRequestSchema, BillingRedirectResponseSchema, queries } from "@alook/shared"
-import { withCookieHumanAuth } from "@/lib/middleware/auth"
+import { cookieHumanAuthPolicy } from "@/lib/middleware/auth"
import { getPrimaryDb } from "@/lib/db"
import { billingClient, billingFailure, billingResponse } from "@/lib/billing/client"
import { createCheckout } from "@/lib/billing/service"
import { readCheckoutAnalyticsConsent } from "@/lib/analytics-consent-server"
-export const POST = withCookieHumanAuth(async (req, ctx) => {
+export const POST = withAuth(cookieHumanAuthPolicy, async (req, ctx) => {
const parsed = BillingCheckoutRequestSchema.safeParse(await req.json().catch(() => null))
if (!parsed.success) return billingResponse({ error: "BILLING_REQUEST_INVALID" }, 400)
try {
diff --git a/src/web/src/app/api/community/billing/portal/route.ts b/src/web/src/app/api/community/billing/portal/route.ts
index 85929160e..9e68a1dbe 100644
--- a/src/web/src/app/api/community/billing/portal/route.ts
+++ b/src/web/src/app/api/community/billing/portal/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { BillingPortalRequestSchema, BillingRedirectResponseSchema } from "@alook/shared"
-import { withCookieHumanAuth } from "@/lib/middleware/auth"
+import { cookieHumanAuthPolicy } from "@/lib/middleware/auth"
import { getPrimaryDb } from "@/lib/db"
import { billingClient, billingFailure, billingResponse } from "@/lib/billing/client"
import { createPortal } from "@/lib/billing/service"
-export const POST = withCookieHumanAuth(async (req, ctx) => {
+export const POST = withAuth(cookieHumanAuthPolicy, async (req, ctx) => {
const text = await req.text()
let body: unknown = {}
try { if (text.trim()) body = JSON.parse(text) } catch { body = null }
diff --git a/src/web/src/app/api/community/billing/route.ts b/src/web/src/app/api/community/billing/route.ts
index c510c7e47..63fce3ca6 100644
--- a/src/web/src/app/api/community/billing/route.ts
+++ b/src/web/src/app/api/community/billing/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { BillingSummarySchema, queries } from "@alook/shared"
-import { withOptionalAuth } from "@/lib/middleware/auth"
+import { optionalAuthPolicy } from "@/lib/middleware/auth"
import { getPrimaryDb } from "@/lib/db"
import { billingClient, billingFailure, billingResponse } from "@/lib/billing/client"
import { getBillingSummary } from "@/lib/billing/service"
-export const GET = withOptionalAuth(async (req, ctx) => {
+export const GET = withAuth(optionalAuthPolicy, async (req, ctx) => {
if (req.headers.has("Authorization") || !ctx.userId || ctx.user?.isBot) return billingResponse({ error: "UNAUTHORIZED" }, 401)
try {
const db = getPrimaryDb(ctx.env.DB)
diff --git a/src/web/src/app/api/community/bots/[id]/active/route.test.ts b/src/web/src/app/api/community/bots/[id]/active/route.test.ts
index beb6042b2..50d7e0401 100644
--- a/src/web/src/app/api/community/bots/[id]/active/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/active/route.test.ts
@@ -31,12 +31,7 @@ vi.mock("@/lib/community/fanout", () => ({
}))
vi.mock("@/lib/logger", () => ({ log: { warn: (...args: unknown[]) => mockLogWarn(...args) } }))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any, ctx?: any) => handler(req, {
- env: { DB: {} },
- userId: "owner_1",
- email: "[email protected]",
- params: ctx?.params,
- }),
+ humanAuthPolicy: { resolve: async (req: any) => ({ context: { env: { DB: {} }, userId: "owner_1", email: "[email protected]" } }) },
}))
vi.mock("@/lib/middleware/helpers", async () => {
const { NextResponse } = require("next/server")
diff --git a/src/web/src/app/api/community/bots/[id]/active/route.ts b/src/web/src/app/api/community/bots/[id]/active/route.ts
index 651742c21..3e3653518 100644
--- a/src/web/src/app/api/community/bots/[id]/active/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/active/route.ts
@@ -1,13 +1,14 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { CommunityBotActivationRequestSchema, queries } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers"
import { pushBotEventToMachine } from "@/lib/community/bot-push"
import { fanOutPresenceUpdate } from "@/lib/community/fanout"
import { log } from "@/lib/logger"
-export const PATCH = withAuth(async (req: NextRequest, ctx) => {
+export const PATCH = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const id = ctx.params?.id as string
const [body, error] = await parseBody(req, CommunityBotActivationRequestSchema)
if (error) return error
diff --git a/src/web/src/app/api/community/bots/[id]/audit-log/route.test.ts b/src/web/src/app/api/community/bots/[id]/audit-log/route.test.ts
index b8e3f6862..8f783136e 100644
--- a/src/web/src/app/api/community/bots/[id]/audit-log/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/audit-log/route.test.ts
@@ -24,19 +24,19 @@ vi.mock("@alook/shared", async () => {
let isAuthed = true
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ humanAuthPolicy: { resolve: async (req: any) => {
if (!isAuthed) {
const { NextResponse } = require("next/server")
return NextResponse.json({ error: "unauthorized" }, { status: 401 })
}
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, {
+
+ return ({ context: {
env: { DB: {} },
userId: "u1",
- params,
- })
- },
+
+ } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/bots/[id]/audit-log/route.ts b/src/web/src/app/api/community/bots/[id]/audit-log/route.ts
index d521e798e..4e6f62efc 100644
--- a/src/web/src/app/api/community/bots/[id]/audit-log/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/audit-log/route.ts
@@ -1,7 +1,8 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import type { NextRequest } from "next/server"
import { queries } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { parseAuditLogPayload } from "@/lib/community/audit-log-payload"
@@ -20,7 +21,7 @@ const MAX_LIMIT = 100
* (per plan §API — the ownership + deletedAt filter is scoped up-front, never
* fetch-then-check).
*/
-export const GET = withAuth(async (req: NextRequest, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const id = ctx.params?.id as string
const db = getDb(ctx.env.DB)
diff --git a/src/web/src/app/api/community/bots/[id]/avatar/route.test.ts b/src/web/src/app/api/community/bots/[id]/avatar/route.test.ts
index 39f899d45..74f8eae9a 100644
--- a/src/web/src/app/api/community/bots/[id]/avatar/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/avatar/route.test.ts
@@ -49,19 +49,19 @@ vi.mock("@/lib/community/fanout", () => ({
let isAuthed = true
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ humanAuthPolicy: { resolve: async (req: any) => {
if (!isAuthed) {
const { NextResponse } = require("next/server")
return NextResponse.json({ error: "unauthorized" }, { status: 401 })
}
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, {
+
+ return ({ context: {
env: { DB: {}, COMMUNITY_MEDIA: { get: (...a: unknown[]) => mediaGet(...a) } },
userId: "u1",
- params,
- })
- },
+
+ } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/bots/[id]/avatar/route.ts b/src/web/src/app/api/community/bots/[id]/avatar/route.ts
index b9d4e9e1c..7fb923d98 100644
--- a/src/web/src/app/api/community/bots/[id]/avatar/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/avatar/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { CACHE_REVALIDATE, createLogger, queries } from "@alook/shared"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
@@ -21,7 +22,7 @@ import { fanOutIdentityUpdate } from "@/lib/community/fanout"
const log = createLogger({ service: "community-bot-avatar-route" })
const PRIVATE_NO_STORE = "private, no-store"
-export const GET = withPrivateMediaCache(withAuth(async (req: NextRequest, ctx) => {
+export const GET = withPrivateMediaCache(withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const botId = ctx.params?.id
if (!botId) return writeError("missing bot id", 400)
@@ -74,7 +75,7 @@ export const GET = withPrivateMediaCache(withAuth(async (req: NextRequest, ctx)
})
}))
-export const POST = withAuth(async (req: NextRequest, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const botId = ctx.params?.id
if (!botId) return writeError("missing bot id", 400)
diff --git a/src/web/src/app/api/community/bots/[id]/diagnostics/route.test.ts b/src/web/src/app/api/community/bots/[id]/diagnostics/route.test.ts
index fad35e341..f86127eab 100644
--- a/src/web/src/app/api/community/bots/[id]/diagnostics/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/diagnostics/route.test.ts
@@ -11,15 +11,15 @@ vi.mock("@/lib/community/diagnostic-report-push", () => ({
pushDiagnosticReportToMachine: (...args: unknown[]) => pushDiagnostic(...args),
}));
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: NextRequest, context?: any) => {
- const params = context?.params instanceof Promise ? await context.params : context?.params;
- return handler(req, {
+ humanAuthPolicy: { resolve: async (req: NextRequest) => {
+
+ return ({ context: {
env: { DB: {} },
userId: "owner_1",
- params,
- });
- },
+
+ } });
+ } },
}));
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
diff --git a/src/web/src/app/api/community/bots/[id]/diagnostics/route.ts b/src/web/src/app/api/community/bots/[id]/diagnostics/route.ts
index d2c49fe3b..74dece23b 100644
--- a/src/web/src/app/api/community/bots/[id]/diagnostics/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/diagnostics/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server";
import {
DiagnosticReportCreateRequestSchema,
@@ -9,7 +10,7 @@ import {
projectOwnerDiagnosticReport,
type OwnerDiagnosticReportSource,
} from "@/lib/community/diagnostic-report";
-import { withAuth } from "@/lib/middleware/auth";
+import { humanAuthPolicy } from "@/lib/middleware/auth";
import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers";
function reportEnvelope(
@@ -24,7 +25,7 @@ function reportEnvelope(
}, status);
}
-export const POST = withAuth(async (req: NextRequest, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const [body, bodyError] = await parseBody(req, DiagnosticReportCreateRequestSchema);
if (bodyError) return bodyError;
const agentId = ctx.params?.id as string;
diff --git a/src/web/src/app/api/community/bots/[id]/marks/route.test.ts b/src/web/src/app/api/community/bots/[id]/marks/route.test.ts
index a927a1b77..cc717d989 100644
--- a/src/web/src/app/api/community/bots/[id]/marks/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/marks/route.test.ts
@@ -28,17 +28,13 @@ vi.mock("@alook/shared", async () => {
let isAuthed = true
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ humanAuthPolicy: { resolve: async (req: any) => {
if (!isAuthed) {
const { NextResponse } = require("next/server")
return NextResponse.json({ error: "unauthorized" }, { status: 401 })
}
- return handler(req, {
- env: { DB: {} },
- userId: "owner_1",
- params: await ctx?.params,
- })
- },
+ return ({ context: { env: { DB: {} }, userId: "owner_1" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
const { NextResponse } = require("next/server")
diff --git a/src/web/src/app/api/community/bots/[id]/marks/route.ts b/src/web/src/app/api/community/bots/[id]/marks/route.ts
index 5dc26a13f..4b1d901dc 100644
--- a/src/web/src/app/api/community/bots/[id]/marks/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/marks/route.ts
@@ -1,14 +1,15 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import type { NextRequest } from "next/server"
import { queries } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
import { avatarInitial } from "@/lib/community/avatar"
import { canonicalUserImage } from "@/lib/community/storage"
const PREVIEW_LIMIT = 4
-export const GET = withAuth(async (_req: NextRequest, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req: NextRequest, ctx) => {
const botId = ctx.params?.id as string
const db = getDb(ctx.env.DB)
const bot = await queries.communityBot.getBotOwnedBy(db, botId, ctx.userId)
diff --git a/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.test.ts b/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.test.ts
index f5bfd6d0e..4dfb9c408 100644
--- a/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.test.ts
@@ -26,9 +26,7 @@ vi.mock("@/lib/community/permissions", () => ({
requireMessageSurfaceAccess: (...args: unknown[]) => requireMessageSurfaceAccess(...args),
}))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => (req: NextRequest, ctx: any) => handler(req, {
- env: { DB: {} }, userId: ctx.actor ?? "owner", email: "owner@test", params: ctx.params,
- }),
+ humanAuthPolicy: { resolve: async (req: NextRequest) => ({ context: { env: { DB: {} }, userId: ctx.actor ?? "owner", email: "owner@test" } }) },
}))
import { DELETE, PUT } from "./route"
diff --git a/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.ts b/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.ts
index 92b87b497..2e6c9b299 100644
--- a/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.ts
@@ -1,8 +1,9 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { NOTIFICATION_LEVEL_VALUES, queries } from "@alook/shared"
import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
import { getDb } from "@/lib/db"
-import { withAuth, type AuthContext } from "@/lib/middleware/auth"
+import { humanAuthPolicy, type AuthContext } from "@/lib/middleware/auth"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
async function authorize(ctx: AuthContext & { params?: Record<string, string> }) {
@@ -17,7 +18,7 @@ async function authorize(ctx: AuthContext & { params?: Record<string, string> })
return { ok: true as const, db, botId: bot.id, channelId }
}
-export const GET = withAuth(async (_req, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
const auth = await authorize(ctx)
if (!auth.ok) return auth.response
const setting = await queries.communityNotificationSetting.getChannelSetting(
@@ -26,7 +27,7 @@ export const GET = withAuth(async (_req, ctx) => {
return writeJSON({ level: setting?.level ?? null })
})
-export const PUT = withAuth(async (req: NextRequest, ctx) => {
+export const PUT = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const auth = await authorize(ctx)
if (!auth.ok) return auth.response
let body: { level?: string }
@@ -43,7 +44,7 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
return writeJSON(result.setting)
})
-export const DELETE = withAuth(async (_req, ctx) => {
+export const DELETE = withAuth(humanAuthPolicy, async (_req, ctx) => {
const auth = await authorize(ctx)
if (!auth.ok) return auth.response
await queries.communityNotificationSetting.removeChannelOverride(auth.db, {
diff --git a/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.test.ts b/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.test.ts
index b3b7404c9..5aae0f7c2 100644
--- a/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.test.ts
@@ -23,9 +23,7 @@ vi.mock("@/lib/community/permissions", () => ({
requireServerMember: (...args: unknown[]) => requireServerMember(...args),
}))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => (req: NextRequest, ctx: any) => handler(req, {
- env: { DB: {} }, userId: ctx.actor ?? "owner", email: "owner@test", params: ctx.params,
- }),
+ humanAuthPolicy: { resolve: async (req: NextRequest) => ({ context: { env: { DB: {} }, userId: ctx.actor ?? "owner", email: "owner@test" } }) },
}))
import { PUT } from "./route"
diff --git a/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.ts b/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.ts
index b4865254f..721ff66b5 100644
--- a/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.ts
@@ -1,8 +1,9 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { NOTIFICATION_LEVEL_VALUES, queries } from "@alook/shared"
import { requireServerMember } from "@/lib/community/permissions"
import { getDb } from "@/lib/db"
-import { withAuth, type AuthContext } from "@/lib/middleware/auth"
+import { humanAuthPolicy, type AuthContext } from "@/lib/middleware/auth"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
async function authorize(ctx: AuthContext & { params?: Record<string, string> }) {
@@ -17,7 +18,7 @@ async function authorize(ctx: AuthContext & { params?: Record<string, string> })
return { ok: true as const, db, botId: bot.id, serverId }
}
-export const GET = withAuth(async (_req, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
const auth = await authorize(ctx)
if (!auth.ok) return auth.response
const setting = await queries.communityNotificationSetting.getServerSetting(
@@ -26,7 +27,7 @@ export const GET = withAuth(async (_req, ctx) => {
return writeJSON({ level: setting?.level ?? null })
})
-export const PUT = withAuth(async (req: NextRequest, ctx) => {
+export const PUT = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const auth = await authorize(ctx)
if (!auth.ok) return auth.response
let body: { level?: string }
diff --git a/src/web/src/app/api/community/bots/[id]/pii/route.ts b/src/web/src/app/api/community/bots/[id]/pii/route.ts
index 897f905db..d6946b0b0 100644
--- a/src/web/src/app/api/community/bots/[id]/pii/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/pii/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { PII_REQUEST_MAX_BYTES, PiiRequestSchema, queries, readBoundedJsonRequest } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withCookieHumanAuth } from "@/lib/middleware/auth"
+import { cookieHumanAuthPolicy } from "@/lib/middleware/auth"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
import { wsDoFetch } from "@/lib/broadcast"
-export const POST = withCookieHumanAuth(async (request, context) => {
+export const POST = withAuth(cookieHumanAuthPolicy, async (request, context) => {
const input = await readBoundedJsonRequest(request, PII_REQUEST_MAX_BYTES)
const payload = PiiRequestSchema.safeParse(input.ok ? input.value : null)
if (!payload.success) return writeError("INVALID_PII_REQUEST", 400)
diff --git a/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts b/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts
index ffc8bcfb4..13b9b6cd2 100644
--- a/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts
@@ -40,10 +40,10 @@ vi.mock("@/lib/community/bot-push", () => ({
}))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, { env: { DB: {} }, userId: ctx?.actor ?? "owner_1", email: "[email protected]", params })
- },
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: ctx?.actor ?? "owner_1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts b/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
index 629a0aadf..c82058beb 100644
--- a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
@@ -1,7 +1,8 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { nanoid } from "nanoid"
import { queries, makeRuntimeConfig, resolveModelConfig, formatHandle } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { pushAgentResetToMachine } from "@/lib/community/bot-push"
@@ -17,7 +18,7 @@ import { pushAgentResetToMachine } from "@/lib/community/bot-push"
* frame at reborn-ready), so the record reflects "the reset actually completed"
* rather than "the command was dispatched."
*/
-export const POST = withAuth(async (_req, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (_req, ctx) => {
const id = ctx.params?.id as string
const db = getDb(ctx.env.DB)
diff --git a/src/web/src/app/api/community/bots/[id]/route.test.ts b/src/web/src/app/api/community/bots/[id]/route.test.ts
index a8e6bd6e2..c4a1ed222 100644
--- a/src/web/src/app/api/community/bots/[id]/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/route.test.ts
@@ -81,15 +81,15 @@ vi.mock("@/lib/community/fanout", () => ({
}))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, {
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: {
env: { DB: {}, COMMUNITY_MEDIA: { delete: (...a: unknown[]) => mockMediaDelete(...a) } },
userId: "u1",
- params,
- })
- },
+
+ } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.ts
index 54fff8b67..270b1c862 100644
--- a/src/web/src/app/api/community/bots/[id]/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { NextResponse } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
@@ -19,7 +20,7 @@ import {
requiresExplicitModel,
} from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"
import {
pushBotEventToMachine,
@@ -32,7 +33,7 @@ import { scheduleCommunityMediaCleanup } from "@/lib/community/community-media-c
const log = createLogger({ service: "community-bot-update" })
-export const PATCH = withAuth(async (req: NextRequest, ctx) => {
+export const PATCH = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const id = ctx.params?.id as string
const [body, err] = await parseBody(req, CommunityBotPatchRequestSchema)
if (err) return err
@@ -286,7 +287,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
})
})
-export const DELETE = withAuth(async (_req, ctx) => {
+export const DELETE = withAuth(humanAuthPolicy, async (_req, ctx) => {
const id = ctx.params?.id as string
const db = getDb(ctx.env.DB)
@@ -335,7 +336,6 @@ export const DELETE = withAuth(async (_req, ctx) => {
})
}
-
if (before.machineId) {
await pushBotEventToMachine(ctx.env, before.machineId, {
type: "bot:removed",
diff --git a/src/web/src/app/api/community/bots/creation-requests/[id]/route.ts b/src/web/src/app/api/community/bots/creation-requests/[id]/route.ts
index 9f9a745e6..42c942e73 100644
--- a/src/web/src/app/api/community/bots/creation-requests/[id]/route.ts
+++ b/src/web/src/app/api/community/bots/creation-requests/[id]/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries, BotCreationDecisionSchema, WS_EVENTS } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"
import { botCreationFailure, completeBotCreation } from "@/lib/community/bot-creation.server"
import { broadcastToUserSafe } from "@/lib/community/fanout"
-export const PATCH = withCommunityActor(async (req, ctx) => {
+export const PATCH = withAuth(communityActorPolicy(), async (req, ctx) => {
if (ctx.actor.kind !== "human" || ctx.actor.isBot) return writeError("Only the human owner can decide", 403)
const [body, error] = await parseBody(req, BotCreationDecisionSchema)
if (error) return error
diff --git a/src/web/src/app/api/community/bots/creation-requests/route.test.ts b/src/web/src/app/api/community/bots/creation-requests/route.test.ts
index 0e9df039e..9010f4ba9 100644
--- a/src/web/src/app/api/community/bots/creation-requests/route.test.ts
+++ b/src/web/src/app/api/community/bots/creation-requests/route.test.ts
@@ -5,7 +5,7 @@ const mocks = vi.hoisted(() => ({ actor: { kind: "bot", userId: "requester", own
vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({}) }))
vi.mock("@/lib/middleware/community-actor", async () => {
const actual = await vi.importActual<typeof import("@/lib/middleware/community-actor")>("@/lib/middleware/community-actor")
- return { ...actual, withCommunityActor: (handler: (req: NextRequest, context: any) => unknown) => (req: NextRequest) => handler(req, { env: { DB: {} }, actor: mocks.actor, params: { id: "request" } }) }
+ return { ...actual, communityActorPolicy: () => ({ resolve: async (req: NextRequest) => ({ context: { env: { DB: {} }, actor: mocks.actor } }) }) }
})
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -39,7 +39,7 @@ describe("bot creation request API authorization and envelopes", () => {
it("propagates unexpected decision failures without publishing an approval", async () => {
mocks.actor = { kind: "human", userId: "owner", isBot: false }
mocks.decide.mockRejectedValueOnce(new Error("decision storage unavailable"))
- await expect(PATCH(request({ decision: "approve" }, "PATCH"))).rejects.toThrow("decision storage unavailable")
+ await expect(PATCH(request({ decision: "approve" }, "PATCH"), { params: { id: "request" } })).rejects.toThrow("decision storage unavailable")
expect(mocks.complete).not.toHaveBeenCalled()
expect(mocks.broadcast).not.toHaveBeenCalled()
})
@@ -64,7 +64,7 @@ describe("bot creation request API authorization and envelopes", () => {
mocks.actor = { kind: "human", userId: "owner", isBot: false }
expect((await POST(request({ requestId: "request", bots: [proposal] }))).status).toBe(403)
mocks.actor = { kind: "bot", userId: "requester", ownerUserId: "owner" }
- expect((await PATCH(request({ decision: "approve" }, "PATCH"))).status).toBe(403)
+ expect((await PATCH(request({ decision: "approve" }, "PATCH"), { params: { id: "request" } })).status).toBe(403)
expect(mocks.submit).not.toHaveBeenCalled()
expect(mocks.decide).not.toHaveBeenCalled()
})
@@ -72,20 +72,20 @@ describe("bot creation request API authorization and envelopes", () => {
mocks.actor = { kind: "human", userId: "owner", isBot: false }
const approved = { ...row, status: "approved", resolvedAt: row.createdAt, bots: [{ ...item, createdBot: { id: "newbot", name: item.name, discriminator: "0002", image: null, avatarVersion: 0 } }] }
mocks.decide.mockResolvedValue({ row: approved, changed: true })
- const response = await PATCH(request({ decision: "approve" }, "PATCH"))
+ const response = await PATCH(request({ decision: "approve" }, "PATCH"), { params: { id: "request" } })
expect(response.status).toBe(200)
expect(mocks.decide).toHaveBeenCalledWith(expect.anything(), "owner", "request", "approve")
expect(mocks.complete).toHaveBeenCalledOnce()
expect(mocks.broadcast).toHaveBeenCalledWith("owner", expect.objectContaining({ type: "community:message.updated", channelId: "dm", messageId: "card", botCreation: expect.objectContaining({ status: "approved" }) }))
mocks.decide.mockResolvedValue({ row: approved, changed: false })
- await PATCH(request({ decision: "approve" }, "PATCH"))
+ await PATCH(request({ decision: "approve" }, "PATCH"), { params: { id: "request" } })
expect(mocks.complete).toHaveBeenCalledTimes(1)
expect(mocks.broadcast).toHaveBeenCalledTimes(1)
})
it("keeps useful capacity errors and does not claim approval or dispatch effects", async () => {
mocks.actor = { kind: "human", userId: "owner", isBot: false }
mocks.decide.mockRejectedValue(new BotCreationError("BOT_LIMIT_REACHED", "Not enough bot slots", 409, { required: 2, available: 1 }))
- const response = await PATCH(request({ decision: "approve" }, "PATCH"))
+ const response = await PATCH(request({ decision: "approve" }, "PATCH"), { params: { id: "request" } })
expect(response.status).toBe(409)
expect(await response.json()).toMatchObject({ code: "BOT_LIMIT_REACHED", required: 2, available: 1 })
expect(mocks.complete).not.toHaveBeenCalled()
diff --git a/src/web/src/app/api/community/bots/creation-requests/route.ts b/src/web/src/app/api/community/bots/creation-requests/route.ts
index cec4b54b2..f01b33513 100644
--- a/src/web/src/app/api/community/bots/creation-requests/route.ts
+++ b/src/web/src/app/api/community/bots/creation-requests/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries, BotCreationSubmitSchema, BOT_CREATION_BODY_MAX_BYTES, readBoundedJsonRequest, formatHandle } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"
+import { communityActorPolicy, requireBot } from "@/lib/middleware/community-actor"
import { writeJSON } from "@/lib/middleware/helpers"
import { botCreationFailure } from "@/lib/community/bot-creation.server"
import { dispatchCommittedMessage } from "@/lib/community/message-dispatcher"
-export const POST = withCommunityActor(async (req, ctx) => {
+export const POST = withAuth(communityActorPolicy(), async (req, ctx) => {
const gate = requireBot(ctx.actor)
if (!gate.ok) return gate.response
const raw = await readBoundedJsonRequest(req, BOT_CREATION_BODY_MAX_BYTES)
diff --git a/src/web/src/app/api/community/bots/me/nap/route.test.ts b/src/web/src/app/api/community/bots/me/nap/route.test.ts
index ed2788114..0dc07b647 100644
--- a/src/web/src/app/api/community/bots/me/nap/route.test.ts
+++ b/src/web/src/app/api/community/bots/me/nap/route.test.ts
@@ -33,17 +33,16 @@ vi.mock("@/lib/community/bot-push", () => ({
}))
// Unified actor: nap is a bot-only verb moved from /agent/nap to /community/nap.
-// withCommunityActor injects the resolved actor; the bot acts on
+// communityActorPolicy injects the resolved actor; the bot acts on
// ITSELF — botUserId/machineId come from the authenticated runner, not the body.
// requireBot is a passthrough for a bot actor (human → 403, covered by the
// community-actor unit test). This test mocks the wrapper directly (as the
// incoming /agent/nap test did) so it stays focused on the nap handler logic.
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: any) => async (req: any) =>
- handler(req, {
+ communityActorPolicy: () => ({ resolve: async (req: any) => ({ context: {
env: { DB: {} },
actor: { kind: "bot", userId: "b1", ownerUserId: "owner_1", machineId: "mac_1" },
- }),
+ } }) }),
requireBot: (actor: any) =>
actor.kind === "bot"
? { ok: true, bot: actor }
diff --git a/src/web/src/app/api/community/bots/me/nap/route.ts b/src/web/src/app/api/community/bots/me/nap/route.ts
index c784187c5..245e66657 100644
--- a/src/web/src/app/api/community/bots/me/nap/route.ts
+++ b/src/web/src/app/api/community/bots/me/nap/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { flattenError } from "zod"
import { NextResponse, type NextRequest } from "next/server"
import { nanoid } from "nanoid"
@@ -9,7 +10,7 @@ import {
CommunityAgentNapRequestSchema,
} from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"
+import { communityActorPolicy, requireBot } from "@/lib/middleware/community-actor"
import { pushAgentNapToMachine } from "@/lib/community/bot-push"
/**
@@ -38,7 +39,7 @@ import { pushAgentNapToMachine } from "@/lib/community/bot-push"
* deleting it on the daemon being confirmed on this new target.
*
*/
-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
+export const POST = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const gate = requireBot(ctx.actor)
if (!gate.ok) return gate.response
const { userId: botUserId, machineId } = gate.bot
@@ -87,7 +88,5 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
)
}
-
-
return NextResponse.json({ napped: true })
})
diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.ts
index e2158c05e..d8d5d462e 100644
--- a/src/web/src/app/api/community/bots/route.test.ts
+++ b/src/web/src/app/api/community/bots/route.test.ts
@@ -54,10 +54,11 @@ vi.mock("@/lib/community/bot-push", () => ({
}))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (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 })
- },
+ resolveHumanAuth: async () => ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.ts
index 8f3148156..b1a2ba06e 100644
--- a/src/web/src/app/api/community/bots/route.ts
+++ b/src/web/src/app/api/community/bots/route.ts
@@ -1,18 +1,19 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { getDb } from "@/lib/db"
import { queries } from "@alook/shared"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
-import { withAuth } from "@/lib/middleware/auth"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
import { createBotForUser } from "@/lib/community/create-bot.server"
import { readCommunityBots } from "@/lib/community/bots.server"
export { tokenUsageDayWindow } from "@/lib/community/bots.server"
-export const GET = withCommunityActor(async (_req, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (_req, ctx) => {
if (ctx.actor.kind === "human") return writeJSON(await readCommunityBots(getDb(ctx.env.DB), ctx.actor.userId))
const bots = await queries.communityBot.listBotsForOwner(getDb(ctx.env.DB), ctx.actor.ownerUserId)
return writeJSON({ bots: bots.map((bot) => ({ id: bot.id, handle: `${bot.name}#${bot.discriminator}`, name: bot.name,
machineId: bot.machineId, backendId: bot.runtime, model: bot.modelName, reasoningEffort: bot.reasoningEffort, isActive: bot.isActive, presence: bot.presence })) })
})
-export const POST = withAuth(createBotForUser)
+export const POST = withAuth(humanAuthPolicy, createBotForUser)
diff --git a/src/web/src/app/api/community/channel-ref/route.test.ts b/src/web/src/app/api/community/channel-ref/route.test.ts
index d1224af43..fc74adde2 100644
--- a/src/web/src/app/api/community/channel-ref/route.test.ts
+++ b/src/web/src/app/api/community/channel-ref/route.test.ts
@@ -4,7 +4,7 @@ import type { AuthenticatedHandler } from "@/lib/middleware/auth"
const m = vi.hoisted(() => ({ db: {}, resolve: vi.fn() }))
vi.mock("@/lib/db", () => ({ getPrimaryDb: () => m.db }))
vi.mock("@/lib/community/channel-ref-target", () => ({ resolveChannelRefTarget: m.resolve }))
-vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: AuthenticatedHandler) => (request: NextRequest) => handler(request, { env: { DB: {} } as Env, userId: "viewer", email: "[email protected]" }) }))
+vi.mock("@/lib/middleware/auth", () => ({ humanAuthPolicy: { resolve: async (request: NextRequest) => ({ context: { env: { DB: {} } as Env, userId: "viewer", email: "[email protected]" } }) } }))
import { GET } from "./route"
beforeEach(() => { m.resolve.mockReset() })
describe("human readonly channel ref route", () => {
diff --git a/src/web/src/app/api/community/channel-ref/route.ts b/src/web/src/app/api/community/channel-ref/route.ts
index 4f08efc26..8f1603068 100644
--- a/src/web/src/app/api/community/channel-ref/route.ts
+++ b/src/web/src/app/api/community/channel-ref/route.ts
@@ -1,9 +1,10 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { getPrimaryDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
import { resolveChannelRefTarget } from "@/lib/community/channel-ref-target"
-export const GET = withAuth(async (req, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (req, ctx) => {
const result = await resolveChannelRefTarget(getPrimaryDb(ctx.env.DB), ctx.userId, req.nextUrl.searchParams.get("ref") ?? "")
if ("error" in result) return writeError(result.error === 400 ? "invalid channel ref" : result.error === 403 ? "forbidden" : "not found", result.error)
return writeJSON(result)
diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts
index 557a1dd37..e13b63a31 100644
--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts
@@ -29,15 +29,15 @@ vi.mock("@/lib/middleware/community-actor", async () => {
)
return {
...actual,
- withCommunityActor: (handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
+
const authz = req?.headers?.get?.("Authorization") ?? ""
const actor =
ctx?.actor ??
(authz.startsWith("Bearer crk_")
? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }
: { kind: "human", userId: "u1", email: "[email protected]", isBot: false })
- return handler(req, {
+ return ({ context: {
env: {
COMMUNITY_MEDIA: {
get: (...a: unknown[]) => mockR2Get(...a),
@@ -45,9 +45,9 @@ vi.mock("@/lib/middleware/community-actor", async () => {
},
},
actor,
- params,
- })
- },
+
+ } })
+ } }),
}
})
diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts
index 06ea39d57..177fd1c63 100644
--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts
@@ -1,8 +1,9 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { contentDisposition, encodeRfc5987 } from "@/lib/content-disposition"
import { NextResponse, type NextRequest } from "next/server"
import { createLogger } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"
import { authorizeAttachment } from "@/lib/community/attachment-authorization"
import { ATTACHMENT_PRIVATE_IMMUTABLE_CACHE } from "@/lib/community/storage"
@@ -36,7 +37,6 @@ function parseByteRange(value: string, size: number): ParsedByteRange | null {
return { offset, length: end - offset + 1, end }
}
-
/**
* GET /api/community/channels/[id]/attachments/[attachmentId] — the canonical
* attachment-download door. Dual-actor (route/disc trunk — folds the bot
@@ -53,7 +53,7 @@ function parseByteRange(value: string, size: number): ParsedByteRange | null {
* when the DB row exists but R2 has drifted (infra fault, not a user-facing
* gate). Response FORM forks by actor; the authz core is identical.
*/
-export const GET = withPrivateMediaCache(withCommunityActor(async (req: NextRequest, ctx) => {
+export const GET = withPrivateMediaCache(withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const attachmentId = ctx.params?.attachmentId
if (!attachmentId) {
return NextResponse.json({ error: "attachment not found" }, { status: 404 })
diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.test.ts
index 6f553c492..c2bfe40a2 100644
--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.test.ts
@@ -9,11 +9,7 @@ vi.mock("@/lib/community/attachment-authorization", () => ({
authorizeAttachment: (...args: unknown[]) => mockAuthorizeAttachment(...args),
}))
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: any) => async (req: NextRequest, ctx: any) => handler(req, {
- params: ctx.params,
- actor: { kind: "human", userId: "u1", email: "[email protected]", isBot: false },
- env: { DB: {}, COMMUNITY_MEDIA: { get: (...args: unknown[]) => mockR2Get(...args) } },
- }),
+ communityActorPolicy: () => ({ resolve: async (req: NextRequest) => ({ context: { actor: { kind: "human", userId: "u1", email: "[email protected]", isBot: false }, env: { DB: {}, COMMUNITY_MEDIA: { get: (...args: unknown[]) => mockR2Get(...args) } } } }) }),
}))
import { GET } from "./route"
diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.ts
index 3878b2f92..d4c4cce87 100644
--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.ts
@@ -1,14 +1,15 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse, type NextRequest } from "next/server"
import { createLogger } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"
import { authorizeAttachment } from "@/lib/community/attachment-authorization"
import { ATTACHMENT_PRIVATE_IMMUTABLE_CACHE } from "@/lib/community/storage"
const log = createLogger({ service: "community-attachment-thumbnail-download" })
-export const GET = withPrivateMediaCache(withCommunityActor(async (_req: NextRequest, ctx) => {
+export const GET = withPrivateMediaCache(withAuth(communityActorPolicy(), async (_req: NextRequest, ctx) => {
const attachmentId = ctx.params?.attachmentId
if (!attachmentId) {
return NextResponse.json({ error: "attachment not found" }, { status: 404 })
diff --git a/src/web/src/app/api/community/channels/[id]/attachments/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.ts
index 5bcc26f03..a253d2f6b 100644
--- a/src/web/src/app/api/community/channels/[id]/attachments/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.ts
@@ -1,7 +1,8 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse, type NextRequest } from "next/server"
import { queries, createLogger } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withCommunityActor, requireBot, type CommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy, requireBot, type CommunityActor } from "@/lib/middleware/community-actor"
import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"
import {
requireChannelMember,
@@ -17,7 +18,7 @@ const log = createLogger({ service: "community-attachments-upload" })
// which the bot arm ignores — it resolves the ref itself. A human/web caller
// puts the real channelId in the path. Mirrors the channels/[id]/members
// dual-actor door.
-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
+export const POST = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const ownerId = ctx.actor.kind === "bot" ? ctx.actor.ownerUserId : ctx.actor.userId
const rate = await checkRateLimit(ctx.env, "community:upload", ownerId)
if (!rate.allowed) return NextResponse.json({ error: "Upload limit reached. Try again shortly." }, {
@@ -33,7 +34,6 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
env: ctx.env,
userId: ctx.actor.userId,
email: ctx.actor.email,
- workspaceId: ctx.actor.workspaceId,
params: ctx.params,
})
})
diff --git a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts
index 5e01c86dd..e2dec0dcb 100644
--- a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts
@@ -40,17 +40,17 @@ vi.mock("@/lib/community/resolve-ref", () => ({
}))
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
+
const bot = req.headers.get("authorization")?.startsWith("Bearer crk_")
- return handler(req, {
+ return ({ context: {
env: { DB: {} },
actor: bot
? { kind: "bot", userId: "bot1", ownerUserId: "u1", machineId: "m1" }
: { kind: "human", userId: "u1", email: "[email protected]" },
- params,
- })
- }),
+
+ } })
+ } }),
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts
index b9a0909e7..e7c27c370 100644
--- a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts
@@ -1,5 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries, WS_EVENTS, isThread, DM_SERVER, parseRef } from "@alook/shared"
@@ -17,7 +18,7 @@ const REF_PLACEHOLDER_ID = "resolve"
* - A creator may self-leave after deterministic creator handoff. Removing
* another current creator remains out of scope.
*/
-export const DELETE = withCommunityActor(async (req: NextRequest, ctx) => {
+export const DELETE = withAuth(communityActorPolicy({ allowInactiveBot: true }), async (req: NextRequest, ctx) => {
const pathChannelId = ctx.params?.id
const pathTargetUserId = ctx.params?.userId
if (!pathChannelId || !pathTargetUserId) return writeError("missing params", 400)
@@ -88,6 +89,5 @@ export const DELETE = withCommunityActor(async (req: NextRequest, ctx) => {
[...new Set([...recipients, targetUserId])].map((uid) => broadcastToUserSafe(uid, event))
)
-
return new Response(null, { status: 204 })
-}, { allowInactiveBot: true })
+})
diff --git a/src/web/src/app/api/community/channels/[id]/members/route.test.ts b/src/web/src/app/api/community/channels/[id]/members/route.test.ts
index 627a6ea10..3c1cc5ebc 100644
--- a/src/web/src/app/api/community/channels/[id]/members/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/members/route.test.ts
@@ -80,14 +80,14 @@ vi.mock("@/lib/community/fanout", () => ({
// Dual-actor: crk_ bearer → bot (folded channelMember), else human.
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
+
const authz = req?.headers?.get?.("Authorization") ?? ""
const actor = authz.startsWith("Bearer crk_")
? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }
: { kind: "human", userId: "u1", email: "[email protected]" }
- return handler(req, { env: { DB: {} }, actor, params })
- },
+ return ({ context: { env: { DB: {} }, actor } })
+ } }),
rejectBot: (actor: { kind: string }) => {
const { NextResponse } = require("next/server")
return actor.kind === "bot"
diff --git a/src/web/src/app/api/community/channels/[id]/members/route.ts b/src/web/src/app/api/community/channels/[id]/members/route.ts
index 4a9b78ebe..11ddca7fd 100644
--- a/src/web/src/app/api/community/channels/[id]/members/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/members/route.ts
@@ -1,5 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"
+import { communityActorPolicy, rejectBot } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries, WS_EVENTS, isThread, DM_SERVER, formatHandle, parseRef, withD1Retry } from "@alook/shared"
@@ -31,7 +32,7 @@ import { resolveMessageTarget } from "@/lib/community/message-door"
* any enumeration; human id → requireChannelAccess 403/404). Any caller with
* access may read.
*/
-export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
if (ctx.actor.kind === "bot" && !requestsCommunityContract(req.headers)) {
@@ -53,7 +54,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
* are rejected — they're the NOTIFY dimension, inherit the parent's roster,
* and take PARTICIPANTS (via the participants route), not access members.
*/
-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
+export const POST = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
// Human-only management op (add a member to a private access unit). There is
// NO bot add-member verb, and this is a capability boundary (not an
// existence-mask concern), so a bot is a plain 403, not an opaque 404.
@@ -113,7 +114,6 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
const recipients = await queries.communityChannel.getPrivateChannelAudienceUserIds(db, channelId)
await Promise.all([...new Set([...recipients, targetUserId])].map((uid) => broadcastToUserSafe(uid, event)))
-
return writeJSON({ ok: true }, 201)
})
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts
index 82e6d0036..81931e112 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts
@@ -15,9 +15,7 @@ let beforeUnread: (() => Promise<boolean>) | undefined
vi.mock("@/lib/db", () => ({ getDb: () => fixture.db, getPrimaryDb: () => fixture.db }))
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: any) => (request: any) => handler(request, {
- env: { DB: {} }, actor: { kind: actorKind, userId: "author" }, params: { id: "channel" },
- }),
+ communityActorPolicy: () => ({ resolve: async (request: any) => ({ context: { env: { DB: {} }, actor: { kind: actorKind, userId: "author" } } }) }),
}))
vi.mock("@/lib/community/message-door", () => ({
resolveMessageTarget: async () => ({ ok: true, value: { target: { kind: targetKind, channelId: "channel", serverId: "server" } } }),
@@ -94,7 +92,7 @@ describe("message HTTP route — concurrent nonce with real SQL writes", () => {
it.each(["human", "bot"] as const)("%s concurrent first sends both acknowledge the same complete attached message", async (kind) => {
actorKind = kind
- const responses = await Promise.all([POST(request()), POST(request())])
+ const responses = await Promise.all([POST(request(), { params: { id: "channel" } }), POST(request(), { params: { id: "channel" } })])
const bodies = await Promise.all(responses.map((response) => response.json()))
expect(responses.map((response) => response.status)).toEqual(kind === "human" ? [201, 201] : [200, 200])
expect(bodies[0].message.id).toBe(bodies[1].message.id)
@@ -108,7 +106,7 @@ describe("message HTTP route — concurrent nonce with real SQL writes", () => {
it("concurrent bot forum titles return the same complete thread and count sent once", async () => {
targetKind = "forum"
- const responses = await Promise.all([POST(request()), POST(request())])
+ const responses = await Promise.all([POST(request(), { params: { id: "channel" } }), POST(request(), { params: { id: "channel" } })])
const bodies = await Promise.all(responses.map((response) => response.json()))
expect(responses.map((response) => response.status)).toEqual([200, 200])
expect(bodies[0].message.id).toBe(bodies[1].message.id)
@@ -128,7 +126,7 @@ describe("message HTTP route — concurrent nonce with real SQL writes", () => {
})
return true
}
- const response = await POST(request())
+ const response = await POST(request(), { params: { id: "channel" } })
const body = await response.json()
expect(response.status).toBe(200)
expect(body).toMatchObject({ state: "sent", deduped: true })
@@ -138,12 +136,12 @@ describe("message HTTP route — concurrent nonce with real SQL writes", () => {
targetKind = "forum"
nonceReads = 2
vi.mocked(dispatchCommittedMessage).mockRejectedValueOnce(new Error("notification offline"))
- expect((await POST(request())).status).toBe(200)
+ expect((await POST(request(), { params: { id: "channel" } })).status).toBe(200)
await Promise.all(background)
const committed = fixture.sqlite.prepare("SELECT id FROM community_message").get() as { id: string }
expect(committed.id).toBeTruthy()
expect(fixture.sqlite.prepare("SELECT count(*) AS count FROM community_channel WHERE type='thread'").get()).toEqual({ count: 1 })
- const response = await POST(request())
+ const response = await POST(request(), { params: { id: "channel" } })
expect(await response.json()).toMatchObject({ state: "sent", message: { id: committed.id }, deduped: true })
expect(fixture.sqlite.prepare("SELECT sent_count FROM community_bot_daily_activity").get()).toEqual({ sent_count: 1 })
expect(dispatchCommittedMessage).toHaveBeenCalledOnce()
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts
index c7fd4de4b..c8a63d594 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts
@@ -53,11 +53,7 @@ vi.mock("@/lib/community/message-handler", () => ({
}))
vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn(async () => ({ allowed: true })) }))
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: any) => async (req: any, ctx?: any) => handler(req, {
- env: { DB: {} },
- actor: { kind: actorKind, userId: "bot_1", ownerUserId: "owner_1", machineId: "m_1" },
- params: ctx?.params instanceof Promise ? await ctx.params : ctx?.params,
- }),
+ communityActorPolicy: () => ({ resolve: async (req: any) => ({ context: { env: { DB: {} }, actor: { kind: actorKind, userId: "bot_1", ownerUserId: "owner_1", machineId: "m_1" } } }) }),
}))
vi.mock("@/lib/middleware/helpers", () => {
const { NextResponse } = require("next/server")
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 efabad24b..683e2b692 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
@@ -193,26 +193,26 @@ 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 })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
-// POST is now the dual-actor door (withCommunityActor). These POST tests
+// POST is now the dual-actor door (communityActorPolicy). These POST tests
// exercise the HUMAN arm — mock the wrapper to yield a human actor + the real
// channelId from the path. The bot arm is covered in the send-fold tests.
vi.mock("@/lib/middleware/community-actor", () => ({
// Credential-based actor dispatch (mirrors the real wrapper): a crk_ bearer →
// bot actor, else → human. Lets the bot-read arm be exercised via header.
- withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
+
const authz = req?.headers?.get?.("Authorization") ?? ""
const actor = authz.startsWith("Bearer crk_")
? { kind: "bot", userId: "bot_1", ownerUserId: "owner_1", machineId: "m_1" }
: { kind: "human", userId: "u1", email: "[email protected]" }
- return handler(req, { env: { DB: {} }, actor, params })
- }),
+ return ({ context: { env: { DB: {} }, actor } })
+ } }),
}))
vi.mock("@/lib/middleware/helpers", () => {
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 001af32ce..f232a43a0 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
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { COMMUNITY_RESOURCE_CONTRACT_VERSION, MAX_FORUM_TAG_LENGTH, queries, requestsCommunityContract, requestedCommunityContract } from "@alook/shared"
import { NextRequest, NextResponse } from "next/server"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeError } from "@/lib/middleware/helpers"
import { getDb, getPrimaryDb } from "@/lib/db"
import { parseCommunityMessageWindow } from "@/lib/community/messages"
@@ -41,7 +42,7 @@ function parseIntParam(raw: string | null): number | undefined {
* create-if-missing (structurally, not just create=false — Aigneis #246 ⑤); a
* ref to a nonexistent target is a 404, not a read-then-create.
*/
-export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const params = req.nextUrl.searchParams
@@ -127,7 +128,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
* carries `/`, can't sit in a path segment).
*
* Authorization is credential-defined, addressing is body/path only. First
- * segment = `withCommunityActor` credential dispatch (crk_ → bot arm; session →
+ * segment = `communityActorPolicy` credential dispatch (crk_ → bot arm; session →
* human arm) BEFORE any field is read, so a body field can't flip the actor arm.
*
* §3 (Ingaborg #219): the former standalone `requireChannelMember` is REPLACED
@@ -137,7 +138,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
* would be a bypass of the single mask). A bot hitting this id route passes the
* SAME mask (never skipped because machine-token — ASSERT 1 ①-C).
*/
-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
+export const POST = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
// A send is read-before-write: authorization, alignment, retries, and the
// blocked response all depend on the latest committed channel state. Start
// this request on primary so a lagging replica cannot supply a stale CAS
diff --git a/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.test.ts
index 5d94cbffc..c184a85e9 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.test.ts
@@ -30,14 +30,14 @@ vi.mock("@alook/shared", async () => {
// Dual-actor: crk_ bearer → bot, else human (mirrors the real wrapper).
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
+
const authz = req?.headers?.get?.("Authorization") ?? ""
const actor = authz.startsWith("Bearer crk_")
? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }
: { kind: "human", userId: "u1", email: "[email protected]" }
- return handler(req, { env: { DB: {} }, actor, params })
- },
+ return ({ context: { env: { DB: {} }, actor } })
+ } }),
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.ts b/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.ts
index bea69ac02..54c021076 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.ts
@@ -1,5 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries } from "@alook/shared"
@@ -20,7 +21,7 @@ const REF_PLACEHOLDER_ID = "resolve"
* need its ID to trigger an anchor fetch. Also the folded `resolve` bot verb's
* seq→id lookup.
*
- * Dual-actor door (route/disc trunk — message-keyed faces). withCommunityActor
+ * Dual-actor door (route/disc trunk — message-keyed faces). communityActorPolicy
* serves human (session, id-in-path) + bot (crk_, ref-in-query). Two steps,
* both arms:
* 1. arrive at a channelId — human: path id; bot: `resolveTargetForMember`
@@ -39,7 +40,7 @@ const REF_PLACEHOLDER_ID = "resolve"
*
* Returns: { id: string } | { error: "not_found" }
*/
-export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const seqStr = ctx.params?.seq
if (typeof seqStr !== "string") {
return writeJSON({ error: "invalid_params" }, 400)
diff --git a/src/web/src/app/api/community/channels/[id]/messages/tags/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/tags/route.test.ts
index 780d68e24..e180fe3d5 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/tags/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/tags/route.test.ts
@@ -23,11 +23,7 @@ vi.mock("@alook/shared", async () => {
}
})
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any, ctx: any) => handler(req, {
- env: { DB: {} },
- userId: "user_1",
- params: await ctx.params,
- }),
+ humanAuthPolicy: { resolve: async (req: any) => ({ context: { env: { DB: {} }, userId: "user_1" } }) },
}))
import { GET } from "./route"
diff --git a/src/web/src/app/api/community/channels/[id]/messages/tags/route.ts b/src/web/src/app/api/community/channels/[id]/messages/tags/route.ts
index 8a30e4ef9..9f686cea2 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/tags/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/tags/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries } from "@alook/shared"
import { getDb } from "@/lib/db"
import { requireChannelAccess } from "@/lib/community/permissions"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
-export const GET = withAuth(async (_req, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
const db = getDb(ctx.env.DB)
diff --git a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
index 90ec93946..9b639ee3f 100644
--- a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
@@ -43,17 +43,17 @@ vi.mock("@alook/shared", async () => {
})
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
+
const bot = req.headers.get("authorization")?.startsWith("Bearer crk_")
- return handler(req, {
+ return ({ context: {
env: { DB: {} },
actor: bot
? { kind: "bot", userId: "bot1", ownerUserId: "u1", machineId: "m1" }
: { kind: "human", userId: "u1", email: "[email protected]" },
- params,
- })
- }),
+
+ } })
+ } }),
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts
index a33fb43f8..46440cf0f 100644
--- a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts
@@ -1,5 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries, WS_EVENTS, isThread, DM_SERVER, parseRef } from "@alook/shared"
@@ -17,7 +18,7 @@ const REF_PLACEHOLDER_ID = "resolve"
* (Muting is NOT here — that's the outer channel-header notification level,
* per-layer, same control a channel uses. Participation is add/leave only.)
*/
-export const DELETE = withCommunityActor(async (req: NextRequest, ctx) => {
+export const DELETE = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const pathChannelId = ctx.params?.id
const pathTargetUserId = ctx.params?.userId
if (!pathChannelId || !pathTargetUserId) return writeError("missing params", 400)
diff --git a/src/web/src/app/api/community/channels/[id]/participants/route.test.ts b/src/web/src/app/api/community/channels/[id]/participants/route.test.ts
index 40cc59e21..45271baee 100644
--- a/src/web/src/app/api/community/channels/[id]/participants/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/participants/route.test.ts
@@ -41,10 +41,10 @@ vi.mock("@/lib/community/fanout", () => ({
}))
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 })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/channels/[id]/participants/route.ts b/src/web/src/app/api/community/channels/[id]/participants/route.ts
index ba1341ba7..8e52d5c50 100644
--- a/src/web/src/app/api/community/channels/[id]/participants/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/participants/route.ts
@@ -1,5 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries, WS_EVENTS, isThread, PARTICIPANT_SOURCE } from "@alook/shared"
@@ -19,7 +20,7 @@ import { requireChannelAccess } from "@/lib/community/permissions"
* member of the PARENT's access audience (you can only pull in people who can
* already see the channel/forum the unit lives in).
*/
-export const POST = withAuth(async (req: NextRequest, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
diff --git a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.ts
index bcf8aafd2..56d3eb853 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.ts
@@ -28,16 +28,15 @@ vi.mock("@alook/shared", async () => {
};
});
-
vi.mock("@/lib/community/fanout", () => ({
fanOutToChannel: (...a: unknown[]) => mockFanOut(...a),
}));
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: {}, userId: "u1", email: "[email protected]", params });
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: {}, userId: "u1", email: "[email protected]" } });
+ } },
}));
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts
index f4997d2eb..6d536e6f0 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts
@@ -1,5 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeError } from "@/lib/middleware/helpers"
import { getPrimaryDb } from "@/lib/db"
import { queries, WS_EVENTS } from "@alook/shared"
@@ -7,7 +8,7 @@ import { fanOutToChannel } from "@/lib/community/fanout"
import { requireChannelMember, requireServerAdmin } from "@/lib/community/permissions"
import { requirePinnableSurface } from "@/lib/community/channel-write-guard"
-export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
+export const DELETE = withAuth(humanAuthPolicy, async (_req: NextRequest, ctx) => {
const channelId = ctx.params?.id
const messageId = ctx.params?.messageId
if (!channelId || !messageId) return writeError("missing params", 400)
@@ -35,6 +36,5 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
messageId,
})
-
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/app/api/community/channels/[id]/pins/access.test.ts b/src/web/src/app/api/community/channels/[id]/pins/access.test.ts
index e19045fcc..d10b35b61 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/access.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/access.test.ts
@@ -28,15 +28,7 @@ const { state, fanOut } = vi.hoisted(() => ({
}))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: AuthenticatedHandler) => async (
- request: NextRequest,
- context?: { params?: Record<string, string> | Promise<Record<string, string>> },
- ) => handler(request, {
- userId: state.userId,
- email: "[email protected]",
- env: { DB: state.binding } as Env,
- params: await context?.params,
- }),
+ humanAuthPolicy: { resolve: async (request: NextRequest) => ({ context: { userId: state.userId, email: "[email protected]", env: { DB: state.binding } as Env } }) },
}))
vi.mock("@/lib/community/fanout", () => ({ fanOutToChannel: fanOut }))
diff --git a/src/web/src/app/api/community/channels/[id]/pins/route.test.ts b/src/web/src/app/api/community/channels/[id]/pins/route.test.ts
index b4c9a6e96..59c8cfaf8 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/route.test.ts
@@ -38,16 +38,15 @@ vi.mock("@alook/shared", async () => {
};
});
-
vi.mock("@/lib/community/fanout", () => ({
fanOutToChannel: (...a: unknown[]) => mockFanOut(...a),
}));
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: {}, userId: "u1", email: "[email protected]", params });
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: {}, userId: "u1", email: "[email protected]" } });
+ } },
}));
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/channels/[id]/pins/route.ts b/src/web/src/app/api/community/channels/[id]/pins/route.ts
index a826e3c59..aa313024f 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb, getPrimaryDb } from "@/lib/db"
import { queries, isUniqueConstraintError, WS_EVENTS } from "@alook/shared"
@@ -8,9 +9,7 @@ import { fanOutToChannel } from "@/lib/community/fanout"
import { requireChannelMember, requireServerAdmin } from "@/lib/community/permissions"
import { requirePinnableSurface } from "@/lib/community/channel-write-guard"
-
-
-export const GET = withAuth(async (_req: NextRequest, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req: NextRequest, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
@@ -24,7 +23,7 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {
return writeJSON({ pins, resources })
})
-export const POST = withAuth(async (req: NextRequest, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
@@ -75,6 +74,5 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
messageId: body.messageId,
})
-
return writeJSON(pin, 201)
})
diff --git a/src/web/src/app/api/community/channels/[id]/read/route.test.ts b/src/web/src/app/api/community/channels/[id]/read/route.test.ts
index b84b84065..fcfafb1d4 100644
--- a/src/web/src/app/api/community/channels/[id]/read/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/read/route.test.ts
@@ -68,10 +68,10 @@ vi.mock("@alook/shared", async () => {
})
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 })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/community/fanout", () => ({
diff --git a/src/web/src/app/api/community/channels/[id]/read/route.ts b/src/web/src/app/api/community/channels/[id]/read/route.ts
index e0a977eaf..d97041f50 100644
--- a/src/web/src/app/api/community/channels/[id]/read/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/read/route.ts
@@ -1,7 +1,8 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { COMMUNITY_RESOURCE_CONTRACT_VERSION, communityReadSchemas } from "@alook/shared"
import { writeCommunityContractJSON } from "@/lib/community/read-contract"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeError } from "@/lib/middleware/helpers"
import { getPrimaryDb } from "@/lib/db"
import { queries, WS_EVENTS, withD1Retry } from "@alook/shared"
@@ -16,7 +17,7 @@ import { broadcastToUserSafe } from "@/lib/community/fanout"
* The server re-reads the canonical target row, rejects an unknown id (404)
* or a row from another channel (400), and never falls back to the latest row.
*/
-export const PUT = withAuth(async (req: NextRequest, ctx) => {
+export const PUT = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
diff --git a/src/web/src/app/api/community/channels/[id]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.ts
index 6f7021ee2..bc3e7ecc6 100644
--- a/src/web/src/app/api/community/channels/[id]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.test.ts
@@ -67,15 +67,15 @@ vi.mock("@/lib/community/community-media-cleanup", async () => {
})
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, {
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: {
env: { DB: {}, COMMUNITY_MEDIA: { delete: vi.fn() } },
userId: "u1",
- params,
- })
- }),
+
+ } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.ts
index 3740a2b57..76dc290e1 100644
--- a/src/web/src/app/api/community/channels/[id]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb, getPrimaryDb } from "@/lib/db"
import {
@@ -19,7 +20,7 @@ import { requireChannelAccess, requireMessageSurfaceAccess } from "@/lib/communi
import { writeCommunityChannelRead } from "@/lib/community/read-contract"
import { scheduleCommunityMediaCleanup } from "@/lib/community/community-media-cleanup"
-export const GET = withAuth(async (req: NextRequest, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
@@ -36,7 +37,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
canCreateDiscussion: readable && !channel.parentChannelId && (channel.type === "text" || channel.type === "forum") })
})
-export const PATCH = withAuth(async (req: NextRequest, ctx) => {
+export const PATCH = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
@@ -144,11 +145,10 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
})
}
-
return writeJSON(updated)
})
-export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
+export const DELETE = withAuth(humanAuthPolicy, async (_req: NextRequest, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
@@ -216,6 +216,5 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
await fanOutToServerMembers(channel.serverId, event)
}
-
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts b/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
index efcd5d92f..c5c0e3459 100644
--- a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
@@ -68,10 +68,10 @@ vi.mock("@alook/shared", async () => {
})
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 })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.ts b/src/web/src/app/api/community/channels/[id]/threads/route.ts
index 2586f1737..8896e9974 100644
--- a/src/web/src/app/api/community/channels/[id]/threads/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/threads/route.ts
@@ -1,5 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { FORUM_ARCHIVE_TAG, isForum, queries, MAX_FORUM_TAG_LENGTH, COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
@@ -9,7 +10,7 @@ import { parseBoundedInt } from "@/lib/community/messages"
import { parseForumCreatedAtCursor } from "@/lib/community/forum-feed-cursor"
import { readCommunityForumRows } from "@/lib/community/forum-feed.server"
-export const GET = withAuth(async (req: NextRequest, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
diff --git a/src/web/src/app/api/community/channels/participants/batch/route.test.ts b/src/web/src/app/api/community/channels/participants/batch/route.test.ts
index 0f55521aa..d09376990 100644
--- a/src/web/src/app/api/community/channels/participants/batch/route.test.ts
+++ b/src/web/src/app/api/community/channels/participants/batch/route.test.ts
@@ -27,7 +27,7 @@ vi.mock("@alook/shared", async () => {
})
vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireMessageSurfaceAccess(...args) }))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any) => handler(req, { env: { DB: {} }, userId: "user_1" }),
+ humanAuthPolicy: { resolve: async (req: any) => ({ context: { env: { DB: {} }, userId: "user_1" } }) },
}))
import { POST } from "./route"
diff --git a/src/web/src/app/api/community/channels/participants/batch/route.ts b/src/web/src/app/api/community/channels/participants/batch/route.ts
index ae374a7cd..90b95defe 100644
--- a/src/web/src/app/api/community/channels/participants/batch/route.ts
+++ b/src/web/src/app/api/community/channels/participants/batch/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries } from "@alook/shared"
import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
-export const POST = withAuth(async (req: NextRequest, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
let body: { parentChannelId?: unknown; channelIds?: unknown; limitPerChannel?: unknown }
try { body = await req.json() } catch { return writeError("invalid request body", 400) }
const ids = Array.isArray(body.channelIds) ? [...new Set(body.channelIds.filter((id): id is string => typeof id === "string"))] : []
diff --git a/src/web/src/app/api/community/channels/route.test.ts b/src/web/src/app/api/community/channels/route.test.ts
index 769bff3cb..ee35a9bbb 100644
--- a/src/web/src/app/api/community/channels/route.test.ts
+++ b/src/web/src/app/api/community/channels/route.test.ts
@@ -25,13 +25,13 @@ vi.mock("@/lib/db", () => ({
// reject; dm/thread defensive, no bot verb today) → bot → 403 before any target
// touch. The human arm dispatches to the creation cores.
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: any) => async (req: any) => {
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
const authz = req?.headers?.get?.("Authorization") ?? ""
const actor = authz.startsWith("Bearer crk_")
? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }
: { kind: "human", userId: "u1", email: "[email protected]" }
- return handler(req, { env: { DB: {} }, actor })
- },
+ return ({ context: { env: { DB: {} }, actor } })
+ } }),
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/channels/route.ts b/src/web/src/app/api/community/channels/route.ts
index 1d74fd9b8..427701ec4 100644
--- a/src/web/src/app/api/community/channels/route.ts
+++ b/src/web/src/app/api/community/channels/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { communityChannelResourceFromStorage } from "@alook/shared"
import { NextRequest } from "next/server"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb, getPrimaryDb } from "@/lib/db"
import {
@@ -21,7 +22,7 @@ import {
* create-channels.ts and stay alive transitionally (deleted at the flat-delete
* step after the deploy window closes).
*
- * Dual-actor (`withCommunityActor`), but bot CAPABILITY is minimal and ORTHOGONAL
+ * Dual-actor (`communityActorPolicy`), but bot CAPABILITY is minimal and ORTHOGONAL
* to the 4-type dispatch — supporting a type ≠ opening it to bots. The bot arm is
* two DIFFERENT rejections, kept distinct on purpose (Melly #486 / Aigneis #475):
*
@@ -50,7 +51,7 @@ import {
* on `type`; the parent is addressed by the id each kind needs (serverId / peer
* userId / root messageId).
*/
-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
+export const POST = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
let body: {
type?: unknown
serverId?: unknown
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 ee560ed62..6148236a0 100644
--- a/src/web/src/app/api/community/daemon/activate/route.ts
+++ b/src/web/src/app/api/community/daemon/activate/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { flattenError } from "zod"
import { NextResponse } from "next/server"
import {
@@ -11,7 +12,7 @@ import {
import { getPrimaryDb } from "@/lib/db"
import { broadcastToUser } from "@/lib/broadcast"
import { forceCloseCommunityMachinesByDoNames } from "@/lib/community/machine-disconnect"
-import { withCommunityPairingToken } from "@/lib/middleware/community-pairing-token"
+import { pairingTokenPolicy } from "@/lib/middleware/community-pairing-token"
const log = createLogger({ service: "community/daemon/activate" })
@@ -22,7 +23,7 @@ const log = createLogger({ service: "community/daemon/activate" })
* daemon credential (`cmk_...`). Server atomically revokes the pairing
* token so it can't be re-used.
*/
-export const POST = withCommunityPairingToken(async (req, ctx) => {
+export const POST = withAuth(pairingTokenPolicy, async (req, ctx) => {
const tokenId = ctx.rawTokenId
let raw: unknown
diff --git a/src/web/src/app/api/community/daemon/bots/route.test.ts b/src/web/src/app/api/community/daemon/bots/route.test.ts
index 05acd1f97..244e127bf 100644
--- a/src/web/src/app/api/community/daemon/bots/route.test.ts
+++ b/src/web/src/app/api/community/daemon/bots/route.test.ts
@@ -3,7 +3,7 @@ import { NextRequest } from "next/server"
const mocks = vi.hoisted(() => ({ list: vi.fn(async () => []) }))
vi.mock("@/lib/db", () => ({ getDb: () => "normal-db", getPrimaryDb: () => "primary-db" }))
vi.mock("@alook/shared", () => ({ queries: { communityBot: { listBotsForMachine: mocks.list } } }))
-vi.mock("@/lib/middleware/community-daemon-auth", () => ({ withCommunityDaemonAuth: (handler: (req: NextRequest, ctx: unknown) => Promise<Response>) => (req: NextRequest) => handler(req, { env: { DB: {} }, machineId: "bound-machine" }) }))
+vi.mock("@/lib/middleware/community-daemon-auth", () => ({ machineAuthPolicy: { resolve: async (req: NextRequest) => ({ context: { env: { DB: {} }, machineId: "bound-machine" } }) } }))
import { GET } from "./route"
describe("daemon bound bot inventory", () => {
it("keeps normal warmup active-only and scopes both modes to the authenticated machine", async () => {
diff --git a/src/web/src/app/api/community/daemon/bots/route.ts b/src/web/src/app/api/community/daemon/bots/route.ts
index a2ba2eda4..45c0053ca 100644
--- a/src/web/src/app/api/community/daemon/bots/route.ts
+++ b/src/web/src/app/api/community/daemon/bots/route.ts
@@ -1,7 +1,8 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse } from "next/server"
import { queries } from "@alook/shared"
import { getDb, getPrimaryDb } from "@/lib/db"
-import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"
+import { machineAuthPolicy } from "@/lib/middleware/community-daemon-auth"
/**
* GET /api/community/daemon/bots
@@ -14,7 +15,7 @@ import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"
* into the bot's global handle; `ownerName`+`ownerDiscriminator` into the
* owner's). No avatar (display-only, server does that).
*/
-export const GET = withCommunityDaemonAuth(async (req, ctx) => {
+export const GET = withAuth(machineAuthPolicy, async (req, ctx) => {
const includeInactive = req.nextUrl.searchParams.get("includeInactive") === "true"
const db = includeInactive ? getPrimaryDb(ctx.env.DB) : getDb(ctx.env.DB)
const bots = await queries.communityBot.listBotsForMachine(db, ctx.machineId, { includeInactive })
diff --git a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.test.ts b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.test.ts
index 6b71b1e99..d62c8e692 100644
--- a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.test.ts
+++ b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.test.ts
@@ -14,19 +14,12 @@ vi.mock("@/lib/community/diagnostic-upload", () => ({
vi.mock("@/lib/db", () => ({ getDb: () => ({ diagnosticDb: true }) }));
vi.mock("@/lib/middleware/community-daemon-auth", () => ({
- withCommunityDaemonAuth: (handler: (...args: unknown[]) => Promise<Response>) =>
- async (request: NextRequest, context?: { params?: Promise<Record<string, string>> }) => {
+ machineAuthPolicy: { resolve: async (request: NextRequest) => {
if (request.headers.get("authorization") !== "Bearer cmk_valid") {
return NextResponse.json({ error: "unauthorized" }, { status: 401 });
}
- return handler(request, {
- env: { DB: {}, BUG_REPORTS: { privateBucket: true } },
- machineId: "cm_original",
- userId: "owner_1",
- credentialId: "cred_1",
- params: await context?.params,
- });
- },
+ return ({ context: { env: { DB: {}, BUG_REPORTS: { privateBucket: true } }, machineId: "cm_original", userId: "owner_1", credentialId: "cred_1" } });
+ } },
}));
interface BundleRouteModule {
diff --git a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.ts b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.ts
index ef502300a..b16c73983 100644
--- a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.ts
+++ b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.ts
@@ -1,7 +1,8 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse } from "next/server";
import { DiagnosticReportIdSchema } from "@alook/shared";
import { getDb } from "@/lib/db";
-import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth";
+import { machineAuthPolicy } from "@/lib/middleware/community-daemon-auth";
import {
createDiagnosticUploadQueryPort,
createDiagnosticUploadService,
@@ -16,7 +17,7 @@ function responseStatus(result: DiagnosticUploadResult): number {
return result.status === "uploaded" ? 200 : 409;
}
-export const PUT = withCommunityDaemonAuth(async (request, ctx) => {
+export const PUT = withAuth(machineAuthPolicy, async (request, ctx) => {
const parsedReportId = DiagnosticReportIdSchema.safeParse(ctx.params?.reportId);
if (!parsedReportId.success) {
return NextResponse.json({ error: "invalid diagnostic report id" }, { status: 400 });
diff --git a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.test.ts b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.test.ts
index a576875a8..6cc5450d4 100644
--- a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.test.ts
+++ b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.test.ts
@@ -14,19 +14,12 @@ vi.mock("@/lib/community/diagnostic-upload", () => ({
vi.mock("@/lib/db", () => ({ getDb: () => ({ diagnosticDb: true }) }));
vi.mock("@/lib/middleware/community-daemon-auth", () => ({
- withCommunityDaemonAuth: (handler: (...args: unknown[]) => Promise<Response>) =>
- async (request: NextRequest, context?: { params?: Promise<Record<string, string>> }) => {
+ machineAuthPolicy: { resolve: async (request: NextRequest) => {
if (request.headers.get("authorization") !== "Bearer cmk_valid") {
return NextResponse.json({ error: "unauthorized" }, { status: 401 });
}
- return handler(request, {
- env: { DB: {}, BUG_REPORTS: { privateBucket: true } },
- machineId: "cm_original",
- userId: "owner_1",
- credentialId: "cred_1",
- params: await context?.params,
- });
- },
+ return ({ context: { env: { DB: {}, BUG_REPORTS: { privateBucket: true } }, machineId: "cm_original", userId: "owner_1", credentialId: "cred_1" } });
+ } },
}));
interface FailureRouteModule {
diff --git a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.ts b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.ts
index 796e47795..a0b60f521 100644
--- a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.ts
+++ b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse } from "next/server";
import {
DiagnosticReportIdSchema,
type DiagnosticReportFailureCode,
} from "@alook/shared";
import { getDb } from "@/lib/db";
-import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth";
+import { machineAuthPolicy } from "@/lib/middleware/community-daemon-auth";
import {
createDiagnosticUploadQueryPort,
createDiagnosticUploadService,
@@ -38,7 +39,7 @@ function parseFailure(value: unknown): DiagnosticReportFailureCode | null {
: null;
}
-export const PATCH = withCommunityDaemonAuth(async (request, ctx) => {
+export const PATCH = withAuth(machineAuthPolicy, async (request, ctx) => {
const parsedReportId = DiagnosticReportIdSchema.safeParse(ctx.params?.reportId);
if (!parsedReportId.success) {
return NextResponse.json({ error: "invalid diagnostic report id" }, { status: 400 });
diff --git a/src/web/src/app/api/community/daemon/enroll-agent/route.ts b/src/web/src/app/api/community/daemon/enroll-agent/route.ts
index 8185abc37..fbb0a5672 100644
--- a/src/web/src/app/api/community/daemon/enroll-agent/route.ts
+++ b/src/web/src/app/api/community/daemon/enroll-agent/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { flattenError } from "zod"
import { NextResponse } from "next/server"
import {
@@ -7,7 +8,7 @@ import {
withD1Retry,
} from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"
+import { machineAuthPolicy } from "@/lib/middleware/community-daemon-auth"
/**
* POST /api/community/daemon/enroll-agent
@@ -19,7 +20,7 @@ import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"
* directly — they only reach canonical `/api/community/*` REST doors through
* that proxy.
*/
-export const POST = withCommunityDaemonAuth(async (req, ctx) => {
+export const POST = withAuth(machineAuthPolicy, async (req, ctx) => {
let raw: unknown
try {
raw = await req.json()
diff --git a/src/web/src/app/api/community/daemon/identity/route.ts b/src/web/src/app/api/community/daemon/identity/route.ts
index 5a474b417..d46d5ce03 100644
--- a/src/web/src/app/api/community/daemon/identity/route.ts
+++ b/src/web/src/app/api/community/daemon/identity/route.ts
@@ -1,6 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse } from "next/server"
-import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"
+import { machineAuthPolicy } from "@/lib/middleware/community-daemon-auth"
-export const GET = withCommunityDaemonAuth(async (_req, ctx) =>
- NextResponse.json({ machineId: ctx.machineId })
-)
+export const GET = withAuth(machineAuthPolicy, async (_req, ctx) =>
+ NextResponse.json({ machineId: ctx.machineId }))
diff --git a/src/web/src/app/api/community/daemon/resync-diagnostics/route.ts b/src/web/src/app/api/community/daemon/resync-diagnostics/route.ts
index c81de75f9..3dd35887d 100644
--- a/src/web/src/app/api/community/daemon/resync-diagnostics/route.ts
+++ b/src/web/src/app/api/community/daemon/resync-diagnostics/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse } from "next/server";
import { queries } from "@alook/shared";
import { getDb } from "@/lib/db";
import { pushDiagnosticReportToMachine } from "@/lib/community/diagnostic-report-push";
-import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth";
+import { machineAuthPolicy } from "@/lib/middleware/community-daemon-auth";
-export const POST = withCommunityDaemonAuth(async (_request, ctx) => {
+export const POST = withAuth(machineAuthPolicy, async (_request, ctx) => {
const db = getDb(ctx.env.DB);
const nowMs = Date.now();
await queries.communityDiagnosticReport.timeoutPendingDiagnosticReportsForMachine(db, {
diff --git a/src/web/src/app/api/community/daemon/resync-wakes/route.ts b/src/web/src/app/api/community/daemon/resync-wakes/route.ts
index 935b7e02b..47e836327 100644
--- a/src/web/src/app/api/community/daemon/resync-wakes/route.ts
+++ b/src/web/src/app/api/community/daemon/resync-wakes/route.ts
@@ -1,8 +1,9 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse } from "next/server"
import { queries, dispatchOneUnreadWake, withD1Retry } from "@alook/shared"
import { getDb } from "@/lib/db"
import { wsDoFetch } from "@/lib/broadcast"
-import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"
+import { machineAuthPolicy } from "@/lib/middleware/community-daemon-auth"
/**
* POST /api/community/daemon/resync-wakes
@@ -23,7 +24,7 @@ import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"
* Because the daemon's WS just connected, `sendWakeToMachine` finds a live
* socket this time and delivers immediately.
*/
-export const POST = withCommunityDaemonAuth(async (_req, ctx) => {
+export const POST = withAuth(machineAuthPolicy, async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const wakeEnv = {
WS_DO_WORKER: {
diff --git a/src/web/src/app/api/community/diagnostics/[reportId]/route.test.ts b/src/web/src/app/api/community/diagnostics/[reportId]/route.test.ts
index 594da94ba..87e4da9b7 100644
--- a/src/web/src/app/api/community/diagnostics/[reportId]/route.test.ts
+++ b/src/web/src/app/api/community/diagnostics/[reportId]/route.test.ts
@@ -6,15 +6,15 @@ const timeoutPending = vi.fn();
vi.mock("@/lib/db", () => ({ getDb: () => ({}) }));
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: NextRequest, context?: any) => {
- const params = context?.params instanceof Promise ? await context.params : context?.params;
- return handler(req, {
+ humanAuthPolicy: { resolve: async (req: NextRequest) => {
+
+ return ({ context: {
env: { DB: {} },
userId: "owner_1",
- params,
- });
- },
+
+ } });
+ } },
}));
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
diff --git a/src/web/src/app/api/community/diagnostics/[reportId]/route.ts b/src/web/src/app/api/community/diagnostics/[reportId]/route.ts
index 08187f39d..a04a33a12 100644
--- a/src/web/src/app/api/community/diagnostics/[reportId]/route.ts
+++ b/src/web/src/app/api/community/diagnostics/[reportId]/route.ts
@@ -1,13 +1,14 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import {
DiagnosticReportIdSchema,
queries,
} from "@alook/shared";
import { getDb } from "@/lib/db";
import { projectOwnerDiagnosticReport } from "@/lib/community/diagnostic-report";
-import { withAuth } from "@/lib/middleware/auth";
+import { humanAuthPolicy } from "@/lib/middleware/auth";
import { writeError, writeJSON } from "@/lib/middleware/helpers";
-export const GET = withAuth(async (_req, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
const parsedId = DiagnosticReportIdSchema.safeParse(ctx.params?.reportId);
if (!parsedId.success) return writeError("invalid diagnostic report id", 400);
diff --git a/src/web/src/app/api/community/friends/[id]/accept/route.ts b/src/web/src/app/api/community/friends/[id]/accept/route.ts
index 5bece0d5b..af4e9f70a 100644
--- a/src/web/src/app/api/community/friends/[id]/accept/route.ts
+++ b/src/web/src/app/api/community/friends/[id]/accept/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
-export const POST = withAuth(async (_req, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const id = ctx.params?.id as string
diff --git a/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts b/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts
index abc24f202..fc3c6f509 100644
--- a/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts
+++ b/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts
@@ -33,14 +33,13 @@ vi.mock("@alook/shared", async () => {
}
})
-
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
+ humanAuthPolicy: { resolve: async (req: any) => {
+
// caller id supplied per test via a header, defaults to alice
const uid = req.headers?.get?.("x-test-uid") ?? "u_alice"
- return handler(req, { env: {}, userId: uid, email: "[email protected]", user: { isBot: false }, params })
- }),
+ return ({ context: { env: {}, userId: uid, email: "[email protected]", user: { isBot: false } } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/friends/[id]/owner-decision/route.test.ts b/src/web/src/app/api/community/friends/[id]/owner-decision/route.test.ts
index ecc2e78aa..326054e6d 100644
--- a/src/web/src/app/api/community/friends/[id]/owner-decision/route.test.ts
+++ b/src/web/src/app/api/community/friends/[id]/owner-decision/route.test.ts
@@ -21,10 +21,10 @@ 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: {}, userId: "owner_bob", email: "[email protected]", user: { isBot: false }, params })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: {}, userId: "owner_bob", email: "[email protected]", user: { isBot: false } } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts b/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts
index ce7cfd09f..5a6293192 100644
--- a/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts
+++ b/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts
@@ -1,7 +1,8 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { queries } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
@@ -10,7 +11,7 @@ import { broadcastToUserSafe } from "@/lib/community/fanout"
* bot owner approves or denies a gated friend row via their DM card.
* Dispatches to `ownerDecideOnRow`, which encapsulates all four cases.
*/
-export const POST = withAuth(async (req: NextRequest, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const id = ctx.params?.id as string
@@ -43,6 +44,5 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
await broadcastToUserSafe(b.userId, b.event)
}
-
return writeJSON({ status: result.friendship.status, friendshipId: id })
})
diff --git a/src/web/src/app/api/community/friends/[id]/reject/route.ts b/src/web/src/app/api/community/friends/[id]/reject/route.ts
index ce83a9f25..f50e5ebb5 100644
--- a/src/web/src/app/api/community/friends/[id]/reject/route.ts
+++ b/src/web/src/app/api/community/friends/[id]/reject/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries, WS_EVENTS } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
-export const POST = withAuth(async (_req, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const id = ctx.params?.id as string
diff --git a/src/web/src/app/api/community/friends/[id]/route.ts b/src/web/src/app/api/community/friends/[id]/route.ts
index 5d7e69595..3b882257d 100644
--- a/src/web/src/app/api/community/friends/[id]/route.ts
+++ b/src/web/src/app/api/community/friends/[id]/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse } from "next/server"
import { queries, WS_EVENTS } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeError } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
-export const DELETE = withAuth(async (_req, ctx) => {
+export const DELETE = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const id = ctx.params?.id as string
diff --git a/src/web/src/app/api/community/friends/accepted/route.test.ts b/src/web/src/app/api/community/friends/accepted/route.test.ts
index bd7ee7f0b..719f6919d 100644
--- a/src/web/src/app/api/community/friends/accepted/route.test.ts
+++ b/src/web/src/app/api/community/friends/accepted/route.test.ts
@@ -21,14 +21,11 @@ vi.mock("@alook/shared", async () => {
}
})
-// Human arm delegates through the real withCommunityActor → withAuth; mock
+// Human arm delegates through the real communityActorPolicy → withAuth; mock
// withAuth to inject a human ctx (this route's accepted human arm is the
// inheritor of the retired aggregate GET /friends' friends[] projection).
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: {}, userId: "u1", email: "[email protected]", params })
- }),
+ resolveHumanAuth: async () => ({ context: { env: {}, userId: "u1", email: "[email protected]" } }),
}))
import { GET } from "./route"
diff --git a/src/web/src/app/api/community/friends/accepted/route.ts b/src/web/src/app/api/community/friends/accepted/route.ts
index 2d3d41771..fba4269f5 100644
--- a/src/web/src/app/api/community/friends/accepted/route.ts
+++ b/src/web/src/app/api/community/friends/accepted/route.ts
@@ -1,12 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
import { NextResponse, type NextRequest } from "next/server"
import { BUSINESS_SCHEMA_VERSION, CommunityAcceptedFriendsReadSchema, type CommunityAcceptedFriendsRead, queries, readOrStale } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { resolvePresence, toFriendCard } from "@/lib/community/friend-cards"
-
-export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (_req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const userId = ctx.actor.userId
diff --git a/src/web/src/app/api/community/friends/blocked/route.test.ts b/src/web/src/app/api/community/friends/blocked/route.test.ts
index 0afe4e172..c45b224be 100644
--- a/src/web/src/app/api/community/friends/blocked/route.test.ts
+++ b/src/web/src/app/api/community/friends/blocked/route.test.ts
@@ -37,13 +37,8 @@ vi.mock("@alook/shared", async () => {
}
})
-// The human arm delegates through the real withAuth; mock it so a human ctx is
-// injected without exercising Better-Auth.
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 })
- }),
+ resolveHumanAuth: async () => ({ context: { env: { DB: {} }, userId: "u_owner", email: "[email protected]" } }),
}))
import { GET } from "./route"
diff --git a/src/web/src/app/api/community/friends/blocked/route.ts b/src/web/src/app/api/community/friends/blocked/route.ts
index 60314217b..14b09a3f4 100644
--- a/src/web/src/app/api/community/friends/blocked/route.ts
+++ b/src/web/src/app/api/community/friends/blocked/route.ts
@@ -1,8 +1,9 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
import { NextResponse, type NextRequest } from "next/server"
import { BUSINESS_SCHEMA_VERSION, CommunityBlockedFriendsReadSchema, type CommunityBlockedFriendsRead, queries, readOrStale } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"
+import { communityActorPolicy, rejectBot } from "@/lib/middleware/community-actor"
/**
* GET /api/community/friends/blocked — the blocked bucket (route/disc trunk,
@@ -15,9 +16,10 @@ import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"
* `listFriends` verb never exposed blocked to bots; this keeps that invariant
* while giving human a clean per-bucket read.
*/
-export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
- const denied = rejectBot(ctx.actor)
- if (denied) return denied
+export const GET = withAuth({
+ ...communityActorPolicy(),
+ authorize: (_req, ctx) => rejectBot(ctx.actor),
+}, async (_req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const { value } = await readOrStale<CommunityBlockedFriendsRead>(
diff --git a/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts b/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts
index 6740c065d..e1682b4fd 100644
--- a/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts
+++ b/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts
@@ -37,10 +37,11 @@ vi.mock("@alook/shared", async () => {
// Inject a BOT ctx to trip the local assertion.
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: {}, userId: "u_bot", email: "[email protected]", user: { isBot: true }, params })
- }),
+ resolveHumanAuth: async () => ({ context: { env: {}, userId: "u_bot", email: "[email protected]", user: { isBot: true } } }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: {}, userId: "u_bot", email: "[email protected]", user: { isBot: true } } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/friends/pending/route.test.ts b/src/web/src/app/api/community/friends/pending/route.test.ts
index e99310730..75239155f 100644
--- a/src/web/src/app/api/community/friends/pending/route.test.ts
+++ b/src/web/src/app/api/community/friends/pending/route.test.ts
@@ -22,10 +22,7 @@ vi.mock("@alook/shared", async () => {
})
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: {}, userId: "u1", email: "[email protected]", params })
- }),
+ resolveHumanAuth: async () => ({ context: { env: {}, userId: "u1", email: "[email protected]" } }),
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/friends/pending/route.ts b/src/web/src/app/api/community/friends/pending/route.ts
index f58e556e8..e3bf07356 100644
--- a/src/web/src/app/api/community/friends/pending/route.ts
+++ b/src/web/src/app/api/community/friends/pending/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
import { NextResponse, type NextRequest } from "next/server"
import { BUSINESS_SCHEMA_VERSION, CommunityPendingFriendsReadSchema, type CommunityPendingFriendsRead, queries, readOrStale } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { resolvePresence, toFriendCard } from "@/lib/community/friend-cards"
-export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (_req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const userId = ctx.actor.userId
diff --git a/src/web/src/app/api/community/friends/presence/route.test.ts b/src/web/src/app/api/community/friends/presence/route.test.ts
index d1659e997..a15a8dc3a 100644
--- a/src/web/src/app/api/community/friends/presence/route.test.ts
+++ b/src/web/src/app/api/community/friends/presence/route.test.ts
@@ -21,13 +21,13 @@ vi.mock("@alook/shared", async () => {
})
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ humanAuthPolicy: { resolve: async (req: any) => {
const env = {
DB: {},
WS_DO_WORKER: { fetch: (...a: unknown[]) => mockWsDoWorkerFetch(...a) },
}
- return handler(req, { env, userId: "u1", email: "[email protected]", params: ctx?.params })
- }),
+ return ({ context: { env, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/friends/presence/route.ts b/src/web/src/app/api/community/friends/presence/route.ts
index 1856943de..07fdf4c44 100644
--- a/src/web/src/app/api/community/friends/presence/route.ts
+++ b/src/web/src/app/api/community/friends/presence/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries, PRESENCE_MEMBER_CAP, readOrStale } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
import { wsDoFetch } from "@/lib/broadcast"
@@ -14,7 +15,7 @@ import { wsDoFetch } from "@/lib/broadcast"
* list is looked up server-side from `ctx.userId` — callers can never pass
* in arbitrary ids to probe someone else's presence.
*/
-export const GET = withAuth(async (_req, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getDb(ctx.env.DB)
// D1 read is fail-closed via `readOrStale`; a transient outage yields
// `{ online: [] }` with `stale: true` rather than a 500.
diff --git a/src/web/src/app/api/community/friends/request/route.test.ts b/src/web/src/app/api/community/friends/request/route.test.ts
index 898793a2b..9c8511555 100644
--- a/src/web/src/app/api/community/friends/request/route.test.ts
+++ b/src/web/src/app/api/community/friends/request/route.test.ts
@@ -1,6 +1,8 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
+const authFixture = vi.hoisted(() => ({ humanIsBot: false }))
+
const getUserInternal = vi.fn()
const getUserByNameAndDiscriminator = vi.fn()
const getUserByNameCaseInsensitive = vi.fn()
@@ -35,19 +37,15 @@ vi.mock("@alook/shared", async () => {
// Dual-actor: crk_ bearer → bot arm, else human. The route dispatches by
// actor.kind to two independent handlers.
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- // A test may inject a specific actor via ctx.actor (used to drive the
- // isBot→403 backstop); otherwise derive it from the Authorization header
- // (crk_ → bot arm, else human).
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
+
const authz = req?.headers?.get?.("Authorization") ?? ""
const actor =
- ctx?.actor ??
(authz.startsWith("Bearer crk_")
? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }
- : { kind: "human", userId: "u1", email: "[email protected]", isBot: false })
- return handler(req, { env: {}, actor, params })
- },
+ : { kind: "human", userId: "u1", email: "[email protected]", isBot: authFixture.humanIsBot })
+ return ({ context: { env: {}, actor } })
+ } }),
}))
vi.mock("@/lib/middleware/helpers", async () => {
@@ -62,7 +60,6 @@ vi.mock("@/lib/broadcast", () => ({
broadcastToUser: (...a: unknown[]) => broadcastToUser(...a),
}))
-
import { POST } from "./route"
function postReq(body: unknown) {
@@ -75,6 +72,7 @@ function postReq(body: unknown) {
describe("POST /api/community/friends/request", () => {
beforeEach(() => {
+ authFixture.humanIsBot = false
vi.clearAllMocks()
getUserInternal.mockResolvedValue({
id: "u2",
@@ -276,11 +274,10 @@ describe("POST /api/community/friends/request", () => {
// Backstop (Aigneis #541): the human arm auto-accepts with no owner gate, so a
// bot must NEVER reach it. Dispatch is the main door; isBot→403 is the last
// line if a future auth regression puts isBot=true on a human actor. The mock
- // honors ctx.actor so we can inject the crafted (production-impossible) case.
+ // supplies a crafted actor to exercise this defensive business boundary.
it("human arm rejects an isBot=true human actor with 403 (backstop survives the fold)", async () => {
- const res = await POST(postReq({ username: "alex" }), {
- actor: { kind: "human", userId: "u1", email: "[email protected]", isBot: true },
- } as never)
+ authFixture.humanIsBot = true
+ const res = await POST(postReq({ username: "alex" }))
expect(res.status).toBe(403)
// Never reaches the friend-graph write.
expect(sendRequest).not.toHaveBeenCalled()
diff --git a/src/web/src/app/api/community/friends/request/route.ts b/src/web/src/app/api/community/friends/request/route.ts
index ed888a673..c7edbc555 100644
--- a/src/web/src/app/api/community/friends/request/route.ts
+++ b/src/web/src/app/api/community/friends/request/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest, NextResponse } from "next/server"
import {
queries,
@@ -6,7 +7,7 @@ import {
CommunityAgentFriendRequestSchema,
} from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import type { BotActor, CommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
@@ -14,7 +15,7 @@ import { requireNotBlocked } from "@/lib/community/permissions"
/**
* POST /api/community/friends/request — the friend-request door (route/disc
- * 接口树统一, friendRequest fold; Melly #540). Dual-actor via withCommunityActor,
+ * 接口树统一, friendRequest fold; Melly #540). Dual-actor via communityActorPolicy,
* dispatched by actor.kind to TWO INDEPENDENT handlers that share ONLY the URL +
* the gate — NOT one handler with shared-middle if-branches (that would flatten
* the two distinct semantics; Ingaborg #539/#542 reds cross-contamination):
@@ -32,7 +33,7 @@ import { requireNotBlocked } from "@/lib/community/permissions"
* the flat-delete step). Self-scoped: requesterId = the credential's
* botUserId, never a body field.
*/
-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
+export const POST = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
if (ctx.actor.kind === "bot") {
return handleBotFriendRequest(req, ctx.env, ctx.actor)
}
diff --git a/src/web/src/app/api/community/invites/[token]/info/route.test.ts b/src/web/src/app/api/community/invites/[token]/info/route.test.ts
index 59cde54e0..4fe822e9d 100644
--- a/src/web/src/app/api/community/invites/[token]/info/route.test.ts
+++ b/src/web/src/app/api/community/invites/[token]/info/route.test.ts
@@ -35,7 +35,7 @@ vi.mock("@alook/shared", async () => {
}
})
-// The route is `withOptionalAuth` (preview-first): it NEVER 401s on a missing
+// The route is `optionalAuthPolicy` (preview-first): it NEVER 401s on a missing
// session — the handler runs either way, only `userId` differs. Two shapes:
// * `authed` — the default: handler runs with a userId, as if signed in.
// * `anonymous` — handler still runs, with userId undefined (no 401).
@@ -44,12 +44,12 @@ vi.mock("@alook/shared", async () => {
let isAuthed = true
vi.mock("@/lib/middleware/auth", () => ({
- withOptionalAuth: (handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ optionalAuthPolicy: { resolve: async (req: any) => {
+
return isAuthed
- ? handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
- : handler(req, { env: { DB: {} }, params })
- },
+ ? ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ : ({ context: { env: { DB: {} } } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/invites/[token]/info/route.ts b/src/web/src/app/api/community/invites/[token]/info/route.ts
index 95846c05f..12e76c613 100644
--- a/src/web/src/app/api/community/invites/[token]/info/route.ts
+++ b/src/web/src/app/api/community/invites/[token]/info/route.ts
@@ -1,4 +1,5 @@
-import { withOptionalAuth } from "@/lib/middleware/auth"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { optionalAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries } from "@alook/shared"
@@ -11,11 +12,11 @@ import { avatarInitial } from "@/lib/community/avatar"
const MEMBER_PREVIEW_LIMIT = 5
// Viewable logged-in OR anonymous — the invite landing page loads before any
-// login (preview-first journey), so `withOptionalAuth` never 401s on a missing
+// login (preview-first journey), so `optionalAuthPolicy` never 401s on a missing
// session. The invite token stays the sole capability: an invalid/expired token
// is still rejected below (404/410). Every field returned is the same for any
// caller (no per-viewer projection), so the handler ignores `ctx.userId`.
-export const GET = withOptionalAuth(async (_req, ctx) => {
+export const GET = withAuth(optionalAuthPolicy, async (_req, ctx) => {
const token = ctx.params?.token
if (!token) return writeError("missing token", 400)
diff --git a/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts b/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
index 35541eba9..33eb3d0a7 100644
--- a/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
+++ b/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
@@ -58,7 +58,7 @@ import { isUniqueConstraintError } from "@alook/shared"
// Bot-path coverage for the UNIFIED join route (folded from /agent/joinServer,
// plan §9 phase 4/5). The token is a ROUTE PARAM now (`[token]`), not a body
// field — the invite body carried it on the old flat /agent route; here it
-// rides `ctx.params.token`. A `crk_` bearer drives withCommunityActor's bot
+// rides `ctx.params.token`. A `crk_` bearer drives communityActorPolicy's bot
// path (same resolveBotActor query mocks as before). The human path is covered
// by the sibling route.test.ts.
const TOKEN = "tok_abc"
diff --git a/src/web/src/app/api/community/invites/[token]/join/route.test.ts b/src/web/src/app/api/community/invites/[token]/join/route.test.ts
index cebb87dbd..1e8c72df7 100644
--- a/src/web/src/app/api/community/invites/[token]/join/route.test.ts
+++ b/src/web/src/app/api/community/invites/[token]/join/route.test.ts
@@ -11,24 +11,16 @@ vi.mock("@/lib/community/fanout", () => ({
vi.mock("@/lib/middleware/auth", async () => {
return {
- withAuth: (
- handler: (req: NextRequest, ctx: {
- userId: string
- email: string
- env: { DB: unknown }
- params: Record<string, string>
- }) => Promise<Response>,
- ) => {
- return async (req: NextRequest, ctx: { params?: Promise<Record<string, string>> }) => {
- const params = (await ctx.params) ?? {}
- return handler(req, {
+ resolveHumanAuth: async () => ({ context: { userId: "u_caller", email: "[email protected]", env: { DB: {} } } }),
+ humanAuthPolicy: { resolve: async (req: NextRequest) => {
+ const params = (await undefined) ?? {}
+ return ({ context: {
userId: "u_caller",
env: { DB: {} },
- params,
- })
- }
- },
+
+ } })
+ } },
}
})
diff --git a/src/web/src/app/api/community/invites/[token]/join/route.ts b/src/web/src/app/api/community/invites/[token]/join/route.ts
index 0b6a12cca..0fd1c89d6 100644
--- a/src/web/src/app/api/community/invites/[token]/join/route.ts
+++ b/src/web/src/app/api/community/invites/[token]/join/route.ts
@@ -1,15 +1,16 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries, ROLES, WS_EVENTS, isUniqueConstraintError } from "@alook/shared"
import type { CommunityMemberJoin } from "@alook/shared"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { fanOutToServerMembers, broadcastToUserSafe } from "@/lib/community/fanout"
import { canonicalUserImage } from "@/lib/community/storage"
/**
* POST /api/community/invites/[token]/join — the unified join route (plan §4
- * FOLD, §9 phase 4). Serves both a human (session/al_) and a bot (crk_) via
- * `withCommunityActor`; the old /agent/joinServer folds in here (batch1
+ * FOLD, §9 phase 4). Serves both a human (session) and a bot (crk_) via
+ * `communityActorPolicy`; the old /agent/joinServer folds in here (batch1
* cab6c3e7 did the same fold). Two things branch on `actor.kind`:
* 1. owner-gate — a bot may only consume an invite created by ITS OWN owner
* (checked BEFORE useInvite, so a foreign/dead-creator invite is never
@@ -22,7 +23,7 @@ import { canonicalUserImage } from "@/lib/community/storage"
* ({id,name}). `invite.createdBy === null` (creator account gone) is the
* generic "invalid/expired" case, distinct from an owner mismatch.
*/
-export const POST = withCommunityActor(async (_req, ctx) => {
+export const POST = withAuth(communityActorPolicy(), async (_req, ctx) => {
const token = ctx.params?.token
if (!token) return writeError("invite token is required", 400)
@@ -62,7 +63,6 @@ export const POST = withCommunityActor(async (_req, ctx) => {
return writeError("Invalid or expired invite", 400)
}
-
const memberEvent: CommunityMemberJoin = {
type: WS_EVENTS.MEMBER_JOIN,
serverId: result.invite.serverId,
diff --git a/src/web/src/app/api/community/invites/[token]/route.test.ts b/src/web/src/app/api/community/invites/[token]/route.test.ts
new file mode 100644
index 000000000..682a30912
--- /dev/null
+++ b/src/web/src/app/api/community/invites/[token]/route.test.ts
@@ -0,0 +1,68 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const mocks = vi.hoisted(() => ({
+ resolve: vi.fn(), db: {}, getInvite: vi.fn(), admin: vi.fn(), revoke: vi.fn(),
+}))
+vi.mock("@/lib/middleware/auth", () => ({ humanAuthPolicy: { resolve: mocks.resolve } }))
+vi.mock("@/lib/db", () => ({ getDb: () => mocks.db }))
+vi.mock("@/lib/community/permissions", () => ({ requireServerAdmin: mocks.admin }))
+vi.mock("@alook/shared", () => ({
+ queries: { communityInvite: { getInviteByToken: mocks.getInvite, revokeInvite: mocks.revoke } },
+}))
+
+import { DELETE } from "./route"
+
+const request = () => new NextRequest("http://localhost/api/community/invites/token-a", { method: "DELETE" })
+const route = () => ({ params: Promise.resolve({ token: "token-a" }) })
+
+describe("invite revocation through the common auth entry", () => {
+ beforeEach(() => {
+ vi.resetAllMocks()
+ mocks.resolve.mockResolvedValue({ context: { env: { DB: {} }, userId: "owner-a" } })
+ mocks.getInvite.mockResolvedValue({ id: "invite-a", serverId: "server-a" })
+ mocks.admin.mockResolvedValue({ ok: true })
+ })
+
+ it("stops rejected credentials before looking up an invite", async () => {
+ mocks.resolve.mockResolvedValue(new Response(null, { status: 401 }))
+ expect((await DELETE(request(), route())).status).toBe(401)
+ expect(mocks.getInvite).not.toHaveBeenCalled()
+ expect(mocks.revoke).not.toHaveBeenCalled()
+ })
+
+ it("requires a token before querying", async () => {
+ const response = await DELETE(request())
+ expect(response.status).toBe(400)
+ expect(await response.json()).toEqual({ error: "invite token is required" })
+ expect(mocks.getInvite).not.toHaveBeenCalled()
+ })
+
+ it("returns 404 for a missing invite without a permission check or write", async () => {
+ mocks.getInvite.mockResolvedValue(null)
+ const response = await DELETE(request(), route())
+ expect(response.status).toBe(404)
+ expect(await response.json()).toEqual({ error: "invite not found" })
+ expect(mocks.admin).not.toHaveBeenCalled()
+ expect(mocks.revoke).not.toHaveBeenCalled()
+ })
+
+ it("preserves the permission failure and does not revoke", async () => {
+ mocks.admin.mockResolvedValue({ ok: false, error: "forbidden", status: 403 })
+ const response = await DELETE(request(), route())
+ expect(response.status).toBe(403)
+ expect(await response.json()).toEqual({ error: "forbidden" })
+ expect(mocks.admin).toHaveBeenCalledWith(mocks.db, "server-a", "owner-a")
+ expect(mocks.revoke).not.toHaveBeenCalled()
+ })
+
+ it("revokes the resolved invite after checking its server and authenticated owner", async () => {
+ const response = await DELETE(request(), route())
+ expect(response.status).toBe(204)
+ expect(await response.text()).toBe("")
+ expect(mocks.getInvite).toHaveBeenCalledWith(mocks.db, "token-a")
+ expect(mocks.admin).toHaveBeenCalledWith(mocks.db, "server-a", "owner-a")
+ expect(mocks.revoke).toHaveBeenCalledExactlyOnceWith(mocks.db, "invite-a")
+ expect(mocks.admin.mock.invocationCallOrder[0]).toBeLessThan(mocks.revoke.mock.invocationCallOrder[0]!)
+ })
+})
diff --git a/src/web/src/app/api/community/invites/[token]/route.ts b/src/web/src/app/api/community/invites/[token]/route.ts
index 31241a44b..f226ba23f 100644
--- a/src/web/src/app/api/community/invites/[token]/route.ts
+++ b/src/web/src/app/api/community/invites/[token]/route.ts
@@ -1,10 +1,11 @@
-import { withAuth } from "@/lib/middleware/auth"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries } from "@alook/shared"
import { requireServerAdmin } from "@/lib/community/permissions"
-export const DELETE = withAuth(async (_req, ctx) => {
+export const DELETE = withAuth(humanAuthPolicy, async (_req, ctx) => {
const token = ctx.params?.token
if (!token) return writeError("invite token is required", 400)
@@ -18,6 +19,5 @@ export const DELETE = withAuth(async (_req, ctx) => {
await queries.communityInvite.revokeInvite(db, invite.id)
-
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/app/api/community/machines/[id]/discover-models/route.test.ts b/src/web/src/app/api/community/machines/[id]/discover-models/route.test.ts
index fbdbc857f..9aff7cd0a 100644
--- a/src/web/src/app/api/community/machines/[id]/discover-models/route.test.ts
+++ b/src/web/src/app/api/community/machines/[id]/discover-models/route.test.ts
@@ -8,10 +8,13 @@ vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
return { ...actual, queries: { ...actual.queries, communityMachine: { getMachineByIdForUser: mocks.machine } } }
})
-vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: any) => (req: any) => handler(req, { env: { DB: {} }, userId: "owner", params: { id: "machine" } }) }))
+vi.mock("@/lib/middleware/auth", () => ({
+ resolveHumanAuth: async () => ({ context: { env: { DB: {} }, userId: "owner" } }),
+}))
vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: async () => ({ env: { DB: {} } }) }))
vi.mock("@/lib/middleware/community-agent-runner-auth", () => ({ resolveBotActor: mocks.bot }))
-import { POST } from "./route"
+import { POST as routePost } from "./route"
+const POST = (request: NextRequest, context = { params: { id: "machine" } }) => routePost(request, context)
const payload = { runtimeId: "codex", requestId: "request" }
const request = (body: unknown = payload) => new NextRequest("http://localhost/api/community/machines/machine/discover-models", { method: "POST", body: JSON.stringify(body) })
describe("model discovery owner route", () => {
diff --git a/src/web/src/app/api/community/machines/[id]/discover-models/route.ts b/src/web/src/app/api/community/machines/[id]/discover-models/route.ts
index 0fb940c48..8f047e5bc 100644
--- a/src/web/src/app/api/community/machines/[id]/discover-models/route.ts
+++ b/src/web/src/app/api/community/machines/[id]/discover-models/route.ts
@@ -1,4 +1,5 @@
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { discoverModels } from "@/lib/community/discover-models.server"
-export const POST = withCommunityActor((req, ctx) => discoverModels(req, { ...ctx, kind: ctx.actor.kind, userId: ctx.actor.kind === "bot" ? ctx.actor.ownerUserId : ctx.actor.userId }))
+export const POST = withAuth(communityActorPolicy(), (req, ctx) => discoverModels(req, { ...ctx, kind: ctx.actor.kind, userId: ctx.actor.kind === "bot" ? ctx.actor.ownerUserId : ctx.actor.userId }))
diff --git a/src/web/src/app/api/community/machines/[id]/models/route.test.ts b/src/web/src/app/api/community/machines/[id]/models/route.test.ts
index 23f7bae5c..16e869850 100644
--- a/src/web/src/app/api/community/machines/[id]/models/route.test.ts
+++ b/src/web/src/app/api/community/machines/[id]/models/route.test.ts
@@ -6,28 +6,28 @@ vi.mock("@alook/shared", async (importOriginal) => {
const actual = await importOriginal<typeof import("@alook/shared")>()
return { ...actual, queries: { ...actual.queries, communityBot: { ...actual.queries.communityBot, getMachineForOwner: mocks.machine } } }
})
-vi.mock("@/lib/middleware/community-actor", () => ({ withCommunityActor: (handler: (...args: any[]) => unknown) => (req: NextRequest) => handler(req, { env: { DB: {} }, actor: mocks.actor, params: { id: "m1" } }) }))
+vi.mock("@/lib/middleware/community-actor", () => ({ communityActorPolicy: () => ({ resolve: async (req: NextRequest) => ({ context: { env: { DB: {} }, actor: mocks.actor } }) }) }))
import { GET } from "./route"
const request = (backend = "codex") => new NextRequest(`http://localhost/api/community/machines/m1/models?backend=${backend}`)
beforeEach(() => { vi.clearAllMocks(); mocks.actor = { kind: "human", userId: "owner", ownerUserId: "owner" }; mocks.machine.mockResolvedValue({ id: "m1", status: "online", availableRuntimes: [{ id: "codex", status: "healthy" }] }) })
it.each(["human", "bot"])("scopes the existing %s model read to the human owner", async (kind) => {
mocks.actor = { kind, userId: kind === "bot" ? "bot" : "owner", ownerUserId: "owner" }
- const response = await GET(request())
+ const response = await GET(request(), { params: { id: "m1" } })
expect(mocks.machine).toHaveBeenCalledExactlyOnceWith({ primary: true }, "m1", "owner")
expect(await response.json()).toMatchObject({ machineId: "m1", backendId: "codex", source: "stored_report", models: null })
})
it("retains owner, online and installed-backend guards", async () => {
mocks.machine.mockResolvedValueOnce(null)
- expect((await GET(request())).status).toBe(404)
+ expect((await GET(request(), { params: { id: "m1" } })).status).toBe(404)
mocks.machine.mockResolvedValueOnce({ id: "m1", status: "offline", availableRuntimes: [] })
- expect((await GET(request())).status).toBe(409)
- const response = await GET(request("missing"))
+ expect((await GET(request(), { params: { id: "m1" } })).status).toBe(409)
+ const response = await GET(request("missing"), { params: { id: "m1" } })
expect(response.status).toBe(404)
expect(await response.json()).toMatchObject({ code: "BACKEND_NOT_FOUND" })
})
it("returns model defaults and effort options without runtime diagnostics", async () => {
mocks.machine.mockResolvedValueOnce({ id: "m1", status: "online", availableRuntimes: [{ id: "codex", status: "healthy", lastError: "private", reasoning: { updateMode: "live_next_turn", defaultModelId: "provider/model", catalogOrigin: "native_report", models: [{ id: "provider/model", supportedReasoningEfforts: [{ value: "high" }], defaultReasoningEffort: "high" }] } }] })
- const body = await (await GET(request())).json()
+ const body = await (await GET(request(), { params: { id: "m1" } })).json()
expect(body).toMatchObject({ defaultModelId: "provider/model", models: [{ id: "provider/model", reasoningEfforts: [{ value: "high" }], defaultReasoningEffort: "high" }] })
expect(JSON.stringify(body)).not.toContain("private")
expect(body.catalogState).toBe("reported")
diff --git a/src/web/src/app/api/community/machines/[id]/models/route.ts b/src/web/src/app/api/community/machines/[id]/models/route.ts
index bcb6f1696..b8d5e9e3c 100644
--- a/src/web/src/app/api/community/machines/[id]/models/route.ts
+++ b/src/web/src/app/api/community/machines/[id]/models/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeJSON } from "@/lib/middleware/helpers"
import { projectModelOptions } from "@/lib/community/machine-options.server"
-export const GET = withCommunityActor(async (req, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (req, ctx) => {
const ownerId = ctx.actor.kind === "bot" ? ctx.actor.ownerUserId : ctx.actor.userId
const machine = await queries.communityBot.getMachineForOwner(getPrimaryDb(ctx.env.DB), ctx.params?.id as string, ownerId)
if (!machine) return writeJSON({ error: "machine not found", code: "MACHINE_NOT_FOUND", machineId: ctx.params?.id }, 404)
diff --git a/src/web/src/app/api/community/machines/[id]/reconnect/route.test.ts b/src/web/src/app/api/community/machines/[id]/reconnect/route.test.ts
index f29b4e97d..2fd48a223 100644
--- a/src/web/src/app/api/community/machines/[id]/reconnect/route.test.ts
+++ b/src/web/src/app/api/community/machines/[id]/reconnect/route.test.ts
@@ -20,13 +20,7 @@ vi.mock("@alook/shared", async () => {
}})
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any, ctx?: any) =>
- handler(req, {
- env: { DB: {} },
- userId: "u_1",
- email: "[email protected]",
- params: ctx?.params,
- }),
+ humanAuthPolicy: { resolve: async (req: any) => ({ context: { env: { DB: {} }, userId: "u_1", email: "[email protected]" } }) },
}))
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/machines/[id]/reconnect/route.ts b/src/web/src/app/api/community/machines/[id]/reconnect/route.ts
index f7570c386..20d9c5ea0 100644
--- a/src/web/src/app/api/community/machines/[id]/reconnect/route.ts
+++ b/src/web/src/app/api/community/machines/[id]/reconnect/route.ts
@@ -1,13 +1,14 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
// Reconnect: mint a new pending pairing token bound to the existing
// machineId. Minting is deliberately non-disruptive: credential and runner
// rotation happens only when the exact-machine reconnect command activates
// this token.
-export const POST = withAuth(async (_req, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
const id = ctx.params?.id as string
if (!id) return writeError("machine id is required", 400)
diff --git a/src/web/src/app/api/community/machines/[id]/reset-agents/route.test.ts b/src/web/src/app/api/community/machines/[id]/reset-agents/route.test.ts
index 2fac318e1..d8f1e83e8 100644
--- a/src/web/src/app/api/community/machines/[id]/reset-agents/route.test.ts
+++ b/src/web/src/app/api/community/machines/[id]/reset-agents/route.test.ts
@@ -31,10 +31,10 @@ vi.mock("@/lib/community/bot-push", () => ({
}))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, { env: { DB: {} }, userId: ctx?.actor ?? "owner_1", email: "[email protected]", params })
- },
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: ctx?.actor ?? "owner_1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts b/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts
index 8f92f22c1..7ae3a7cd6 100644
--- a/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts
+++ b/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts
@@ -1,7 +1,8 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { nanoid } from "nanoid"
import { queries, makeRuntimeConfig, resolveModelConfig, formatHandle } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { pushBatchResetToMachine } from "@/lib/community/bot-push"
@@ -22,7 +23,7 @@ import { pushBatchResetToMachine } from "@/lib/community/bot-push"
* delivery honesty. No per-agent success tracking (that'd be a v2 correlated-ack
* path the control channel doesn't have).
*/
-export const POST = withAuth(async (_req, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (_req, ctx) => {
const machineId = ctx.params?.id as string
if (!machineId) return writeError("machine id is required", 400)
const db = getDb(ctx.env.DB)
diff --git a/src/web/src/app/api/community/machines/[id]/route.test.ts b/src/web/src/app/api/community/machines/[id]/route.test.ts
index 974860b08..6eae84f30 100644
--- a/src/web/src/app/api/community/machines/[id]/route.test.ts
+++ b/src/web/src/app/api/community/machines/[id]/route.test.ts
@@ -56,15 +56,16 @@ vi.mock("@/lib/community/fanout", () => ({
}))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, {
+ resolveHumanAuth: async () => ({ context: { env: { DB: {}, COMMUNITY_MEDIA: { delete: (...args: unknown[]) => mockMediaDelete(...args) } }, userId: "u1", email: "[email protected]" } }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: {
env: { DB: {}, COMMUNITY_MEDIA: { delete: (...args: unknown[]) => mockMediaDelete(...args) } },
userId: "u1",
- params,
- })
- },
+
+ } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
@@ -222,7 +223,6 @@ describe("DELETE /api/community/machines/[id]", () => {
})
})
-
describe("platform target machine queries", () => {
it("returns a scoped 404 when the target does not belong to the caller", async () => {
mockGetMachineForOwner.mockResolvedValueOnce(null)
diff --git a/src/web/src/app/api/community/machines/[id]/route.ts b/src/web/src/app/api/community/machines/[id]/route.ts
index 20910f84b..f1455cfea 100644
--- a/src/web/src/app/api/community/machines/[id]/route.ts
+++ b/src/web/src/app/api/community/machines/[id]/route.ts
@@ -1,4 +1,5 @@
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { getPrimaryDb } from "@/lib/db"
import { projectMachineBackends } from "@/lib/community/machine-options.server"
import { NextRequest, NextResponse } from "next/server"
@@ -6,14 +7,14 @@ import { getCloudflareContext } from "@opennextjs/cloudflare"
import { queries, WS_EVENTS } from "@alook/shared"
import type { CommunityWsEvent } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
import { broadcastToUserSafe, fanOutToServerMembers } from "@/lib/community/fanout"
import { forceCloseCommunityMachinesByDoNames } from "@/lib/community/machine-disconnect"
import { scheduleCommunityMediaCleanup } from "@/lib/community/community-media-cleanup"
import { buildBotAvatarKey, isOwnedBotAvatarObjectKey } from "@/lib/community/storage"
-export const DELETE = withAuth(async (req: NextRequest, ctx) => {
+export const DELETE = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const id = ctx.params?.id as string
if (!id) return writeError("machine id is required", 400)
@@ -113,7 +114,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {
return new NextResponse(null, { status: 204 })
})
-export const GET = withCommunityActor(async (_req, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (_req, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
const ownerId = ctx.actor.kind === "bot" ? ctx.actor.ownerUserId : ctx.actor.userId
const machine = await queries.communityBot.getMachineForOwner(db, ctx.params?.id as string, ownerId)
diff --git a/src/web/src/app/api/community/machines/[id]/stop/route.test.ts b/src/web/src/app/api/community/machines/[id]/stop/route.test.ts
index 547cc7d5d..4be5ccf5e 100644
--- a/src/web/src/app/api/community/machines/[id]/stop/route.test.ts
+++ b/src/web/src/app/api/community/machines/[id]/stop/route.test.ts
@@ -7,8 +7,7 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
vi.mock("@alook/shared", () => ({ queries: { communityMachine: { getMachineByIdForUser: (...args: unknown[]) => getMachine(...args) } } }))
vi.mock("@/lib/community/bot-push", () => ({ pushMachineStop: (...args: unknown[]) => pushStop(...args) }))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: (request: NextRequest, context: unknown) => Promise<Response>) => async (request: NextRequest, context: { params?: Promise<Record<string, string>> }) =>
- handler(request, { env: { DB: {} }, userId: "owner", email: "[email protected]", params: await context.params }),
+ humanAuthPolicy: { resolve: async (request: NextRequest) => ({ context: { env: { DB: {} }, userId: "owner", email: "[email protected]" } }) },
}))
import { POST } from "./route"
diff --git a/src/web/src/app/api/community/machines/[id]/stop/route.ts b/src/web/src/app/api/community/machines/[id]/stop/route.ts
index 65493a538..8007ecedb 100644
--- a/src/web/src/app/api/community/machines/[id]/stop/route.ts
+++ b/src/web/src/app/api/community/machines/[id]/stop/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries } from "@alook/shared"
import { getDb } from "@/lib/db"
import { pushMachineStop } from "@/lib/community/bot-push"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
-export const POST = withAuth(async (_request, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (_request, ctx) => {
const machineId = ctx.params?.id as string
if (!machineId) return writeError("machine id is required", 400)
const machine = await queries.communityMachine.getMachineByIdForUser(getDb(ctx.env.DB), ctx.userId, machineId)
diff --git a/src/web/src/app/api/community/machines/[id]/update/route.test.ts b/src/web/src/app/api/community/machines/[id]/update/route.test.ts
index 1a7cce4ac..2f8401182 100644
--- a/src/web/src/app/api/community/machines/[id]/update/route.test.ts
+++ b/src/web/src/app/api/community/machines/[id]/update/route.test.ts
@@ -25,15 +25,15 @@ vi.mock("@/lib/community/bot-push", () => ({
pushMachineUpdate: (...args: unknown[]) => mockPushMachineUpdate(...args),
}))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (request: any, context?: any) => {
- const params = context?.params instanceof Promise ? await context.params : context?.params
- return handler(request, {
+ humanAuthPolicy: { resolve: async (request: any) => {
+
+ return ({ context: {
env: { DB: {} },
userId: context?.actor ?? "owner_1",
- params,
- })
- },
+
+ } })
+ } },
}))
import { POST } from "./route"
diff --git a/src/web/src/app/api/community/machines/[id]/update/route.ts b/src/web/src/app/api/community/machines/[id]/update/route.ts
index 974052bd1..bcf4c17c7 100644
--- a/src/web/src/app/api/community/machines/[id]/update/route.ts
+++ b/src/web/src/app/api/community/machines/[id]/update/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import {
SELF_UPDATE_MIN_DAEMON_VERSION,
queries,
@@ -5,10 +6,10 @@ import {
} from "@alook/shared"
import { getDb } from "@/lib/db"
import { pushMachineUpdate } from "@/lib/community/bot-push"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
-export const POST = withAuth(async (_request, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (_request, ctx) => {
const machineId = ctx.params?.id as string
if (!machineId) return writeError("machine id is required", 400)
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
index 91f2e0f17..e42e97960 100644
--- a/src/web/src/app/api/community/machines/pair/route.test.ts
+++ b/src/web/src/app/api/community/machines/pair/route.test.ts
@@ -16,9 +16,7 @@ vi.mock("@alook/shared", async () => {
}})
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 }),
- ),
+ humanAuthPolicy: { resolve: async (_req: any) => ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } }) },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/machines/pair/route.ts b/src/web/src/app/api/community/machines/pair/route.ts
index 14a266c51..e3975d9d7 100644
--- a/src/web/src/app/api/community/machines/pair/route.ts
+++ b/src/web/src/app/api/community/machines/pair/route.ts
@@ -1,9 +1,10 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
-export const POST = withAuth(async (_req, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
try {
const { tokenId, expiresAt } = await queries.communityMachine.createPairingToken(db, ctx.userId)
diff --git a/src/web/src/app/api/community/machines/route.test.ts b/src/web/src/app/api/community/machines/route.test.ts
index 76bc95cd0..be21332e8 100644
--- a/src/web/src/app/api/community/machines/route.test.ts
+++ b/src/web/src/app/api/community/machines/route.test.ts
@@ -23,8 +23,7 @@ vi.mock("@alook/shared", async () => {
})
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (request: any) =>
- handler(request, { env: { DB: {} }, userId: "u1", email: "[email protected]" }),
+ resolveHumanAuth: async () => ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } }),
}))
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/machines/route.ts b/src/web/src/app/api/community/machines/route.ts
index 9db218e52..0854b792b 100644
--- a/src/web/src/app/api/community/machines/route.ts
+++ b/src/web/src/app/api/community/machines/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { readCommunityMachines, readCommunityMachineList, readCommunityMachineObservations } from "@/lib/community/machines.server"
import { queries } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { readPlatformMachines } from "@/lib/community/machine-options.server"
import { writeJSON } from "@/lib/middleware/helpers"
-export const GET = withCommunityActor(async (req, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (req, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
if (ctx.actor.kind === "bot") return writeJSON(await readPlatformMachines(db, ctx.actor.ownerUserId, ctx.actor.machineId))
try {
diff --git a/src/web/src/app/api/community/messages/[id]/marks/route.test.ts b/src/web/src/app/api/community/messages/[id]/marks/route.test.ts
index 21b871b97..d3d81d975 100644
--- a/src/web/src/app/api/community/messages/[id]/marks/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/marks/route.test.ts
@@ -35,14 +35,14 @@ vi.mock("@/lib/community/permissions", () => ({
}))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ humanAuthPolicy: { resolve: async (req: any) => {
if (req.headers.get("authorization")?.startsWith("Bearer crk_")) {
const { NextResponse } = require("next/server")
return NextResponse.json({ error: "unauthorized" }, { status: 401 })
}
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
- }),
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/messages/[id]/marks/route.ts b/src/web/src/app/api/community/messages/[id]/marks/route.ts
index b3df5aa5c..5df98d78e 100644
--- a/src/web/src/app/api/community/messages/[id]/marks/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/marks/route.ts
@@ -1,5 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries } from "@alook/shared"
@@ -21,7 +22,7 @@ import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
// Toggle-on: mark a message for the current user. Idempotent — a re-mark hits
// UNIQUE(userId, messageId) and no-ops (markMessage uses onConflictDoNothing),
// so the client can call it without a 409 dance.
-export const PUT = withAuth(async (req: NextRequest, ctx) => {
+export const PUT = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
let body: { channelId?: string }
try {
@@ -58,7 +59,7 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
// Toggle-off: unmark a message for the current user. Self-scoped — deletes only
// ctx.userId's own row; another user's mark on the same message is untouched
// (0-row no-op). Returns ok whether or not a row existed (idempotent).
-export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
+export const DELETE = withAuth(humanAuthPolicy, async (_req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const messageId = ctx.params?.id
if (!messageId) return writeError("missing message id", 400)
@@ -74,7 +75,7 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
// Menu-open check: is THIS message marked by the current user? Self-scoped
// (WHERE userId=ctx.userId) — answers "did *I* mark it", never "did anyone",
// so it can't leak another user's private mark state. One-row index lookup.
-export const GET = withAuth(async (_req: NextRequest, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req: NextRequest, ctx) => {
const messageId = ctx.params?.id
if (!messageId) return writeError("missing message id", 400)
diff --git a/src/web/src/app/api/community/messages/[id]/properties/route.test.ts b/src/web/src/app/api/community/messages/[id]/properties/route.test.ts
index 93c0840e5..b1531aa39 100644
--- a/src/web/src/app/api/community/messages/[id]/properties/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/properties/route.test.ts
@@ -52,12 +52,12 @@ vi.mock("@/lib/community/reaction-operations", () => ({
removeReactionForActor: (...args: unknown[]) => mockRemoveReaction(...args),
}))
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: any) => async (req: NextRequest, routeCtx?: any) => {
+ communityActorPolicy: () => ({ resolve: async (req: NextRequest) => {
const actor = req.headers.get("Authorization") === "human"
? { kind: "human", userId: "u1" }
: { kind: "bot", userId: "bot1", ownerUserId: "owner1", machineId: "machine1" }
- return handler(req, { env: { DB: {} }, actor, params: routeCtx?.params })
- },
+ return ({ context: { env: { DB: {} }, actor } })
+ } }),
requireBot: (actor: any) => actor.kind === "bot"
? { ok: true, bot: actor }
: { ok: false, response: NextResponse.json({ error: "forbidden: bot-only endpoint" }, { status: 403 }) },
diff --git a/src/web/src/app/api/community/messages/[id]/properties/route.ts b/src/web/src/app/api/community/messages/[id]/properties/route.ts
index 11ddbc272..cb970968b 100644
--- a/src/web/src/app/api/community/messages/[id]/properties/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/properties/route.ts
@@ -1,3 +1,5 @@
+import type { CommunityActorHandler } from "@/lib/middleware/community-actor"
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import {
isStoredChannelType,
@@ -8,7 +10,7 @@ import { getDb, getPrimaryDb } from "@/lib/db"
import { listForumTagsForActor, mutateForumTagsForActor } from "@/lib/community/forum-tag-operations"
import { listReactionsForActor, removeReactionForActor, setReactionForActor } from "@/lib/community/reaction-operations"
import { resolveMessageRefForBot } from "@/lib/community/resolve-message-ref"
-import { requireBot, withCommunityActor } from "@/lib/middleware/community-actor"
+import { requireBot, communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
import { queries } from "@alook/shared"
@@ -68,7 +70,7 @@ function unsupportedProperty(type: PropertyType, channelType: string, capabiliti
}, 400)
}
-export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const gate = requireBot(ctx.actor)
if (!gate.ok) return gate.response
if (ctx.params?.id !== "resolve") return writeError("not found", 404)
@@ -109,7 +111,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
return writeJSON({ capabilities, properties })
})
-async function mutate(req: NextRequest, ctx: Parameters<Parameters<typeof withCommunityActor>[0]>[1], action: "set" | "remove") {
+async function mutate(req: NextRequest, ctx: Parameters<CommunityActorHandler>[1], action: "set" | "remove") {
const gate = requireBot(ctx.actor)
if (!gate.ok) return gate.response
if (ctx.params?.id !== "resolve") return writeError("not found", 404)
@@ -186,5 +188,5 @@ async function mutate(req: NextRequest, ctx: Parameters<Parameters<typeof withCo
return writeJSON({ type: "emoji", value: result.value.emoji, changed: result.value.changed })
}
-export const PUT = withCommunityActor((req, ctx) => mutate(req, ctx, "set"))
-export const DELETE = withCommunityActor((req, ctx) => mutate(req, ctx, "remove"))
+export const PUT = withAuth(communityActorPolicy(), (req, ctx) => mutate(req, ctx, "set"))
+export const DELETE = withAuth(communityActorPolicy(), (req, ctx) => mutate(req, ctx, "remove"))
diff --git a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.ts b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.ts
index 0c6033a2c..353b96421 100644
--- a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.ts
@@ -62,14 +62,14 @@ vi.mock("@/lib/community/resolve-ref", () => ({
// arm reaches resolveTargetForMember + the identity-only seq lookup; the human arm
// carries the messageId in the path.
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
+
const authz = req?.headers?.get?.("Authorization") ?? "";
const actor = authz.startsWith("Bearer crk_")
? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }
: { kind: "human", userId: "u1", email: "[email protected]" };
- return handler(req, { env: { DB: {} }, actor, params });
- },
+ return ({ context: { env: { DB: {} }, actor } });
+ } }),
}));
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts
index d38a4d513..6aa6e868d 100644
--- a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts
@@ -1,5 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb, getPrimaryDb } from "@/lib/db"
import { resolveMessageRefForBot } from "@/lib/community/resolve-message-ref"
@@ -14,7 +15,7 @@ import {
// in the path.
/**
* Message-keyed reaction door (route/disc trunk — message-keyed faces dual-actor).
- * withCommunityActor: both human (session) and bot (crk_, the folded `reactAdd`
+ * communityActorPolicy: both human (session) and bot (crk_, the folded `reactAdd`
* verb) hit this one route. Authorization is credential-scoped — `authorizeReaction`
* resolves the message → its channel → the communication surface gate (DM
* participant + block + accepted friendship, channel member otherwise) keyed
@@ -23,7 +24,7 @@ import {
* messageId resolution happens upstream at the flat-verb→door retarget (proxy); this
* route is message-keyed (messageId in path) for both actors.
*/
-export const PUT = withCommunityActor(async (req: NextRequest, ctx) => {
+export const PUT = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const rawEmoji = ctx.params?.emoji
if (!rawEmoji) return writeError("missing params", 400)
@@ -66,7 +67,7 @@ export const PUT = withCommunityActor(async (req: NextRequest, ctx) => {
return writeJSON(result.value.reaction)
})
-export const DELETE = withCommunityActor(async (_req: NextRequest, ctx) => {
+export const DELETE = withAuth(communityActorPolicy(), async (_req: NextRequest, ctx) => {
// Defensive bot→404 (①-C): there is NO bot react-REMOVE verb in the ServerApi
// contract (only `reactAdd`), so no bot caller reaches this arm today and the
// retarget wires none. 5c opened bot credentials on the route; collapse the
diff --git a/src/web/src/app/api/community/messages/[id]/reactions/route.test.ts b/src/web/src/app/api/community/messages/[id]/reactions/route.test.ts
index 72916aaaf..ae34891ba 100644
--- a/src/web/src/app/api/community/messages/[id]/reactions/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/reactions/route.test.ts
@@ -24,16 +24,12 @@ vi.mock("@alook/shared", async () => {
}
})
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: Function) => async (req: NextRequest, ctx: { params: { id: string } }) => {
+ communityActorPolicy: () => ({ resolve: async (req: NextRequest) => {
const bot = req.headers.get("authorization")?.startsWith("Bearer crk_")
- return handler(req, {
- env: { DB: {} },
- params: ctx.params,
- actor: bot
+ return ({ context: { env: { DB: {} }, actor: bot
? { kind: "bot", userId: "bot_1", ownerUserId: "u1", machineId: "machine_1" }
- : { kind: "human", userId: "viewer_1", email: "[email protected]" },
- })
- },
+ : { kind: "human", userId: "viewer_1", email: "[email protected]" } } })
+ } }),
}))
import { GET } from "./route"
diff --git a/src/web/src/app/api/community/messages/[id]/reactions/route.ts b/src/web/src/app/api/community/messages/[id]/reactions/route.ts
index 1dd7d92cb..a0570801e 100644
--- a/src/web/src/app/api/community/messages/[id]/reactions/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/reactions/route.ts
@@ -1,11 +1,12 @@
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { parseCommunityReactionDetailsRead, queries } from "@alook/shared"
import { authorizeReaction } from "@/lib/community/reaction-access"
import { canonicalUserImage } from "@/lib/community/storage"
-export const GET = withCommunityActor(async (_req, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (_req, ctx) => {
if (ctx.actor.kind !== "human") return writeError("human session required", 401)
const messageId = ctx.params?.id
if (!messageId) return writeError("missing message id", 400)
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 54c007b45..1b3c5e340 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
@@ -102,21 +102,21 @@ vi.mock("@alook/shared", async () => {
// Dual-actor: crk_ bearer → bot (folded resolve), else human. Human arm carries
// messageId in the path; bot arm carries ref+seq on the query.
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
+
const authz = req?.headers?.get?.("Authorization") ?? ""
const actor = authz.startsWith("Bearer crk_")
? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }
: { kind: "human", userId: "u1", email: "[email protected]" }
- return handler(req, {
+ return ({ context: {
env: {
DB: {},
COMMUNITY_MEDIA: { delete: (...a: unknown[]) => cloudflareMocks.mediaDelete(...a) },
},
actor,
- params,
- })
- },
+
+ } })
+ } }),
}))
vi.mock("@/lib/middleware/helpers", () => {
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 72405be06..ae0229b84 100644
--- a/src/web/src/app/api/community/messages/[id]/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb, getPrimaryDb } from "@/lib/db"
import { canManageServer, queries, WS_EVENTS } from "@alook/shared"
@@ -31,7 +32,7 @@ const REF_PLACEHOLDER_ID = "resolve"
* GET /api/community/messages/[id] — single fully-hydrated message.
*
* Dual-actor hydrate door (route/disc trunk — folds the `resolve` bot verb).
- * withCommunityActor serves human (session, id-in-path) + bot (crk_, ref+seq).
+ * communityActorPolicy serves human (session, id-in-path) + bot (crk_, ref+seq).
* The response FORM forks by the credential actor (Aigneis ②, never a field):
* - human/web → `mapMessageForApi` (attachments + reactions + reply preview),
* the thread-opener block shape. Addressing: messageId in the path.
@@ -50,7 +51,7 @@ const REF_PLACEHOLDER_ID = "resolve"
* Both arms hydrate the SAME row (attachments + reply scoped to the message's
* own surface); only the projection differs.
*/
-export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
if (ctx.actor.kind === "bot") {
@@ -68,7 +69,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
* text-channel thread openers deliberately remain unsupported in this first
* version.
*/
-export const DELETE = withCommunityActor(async (_req: NextRequest, ctx) => {
+export const DELETE = withAuth(communityActorPolicy(), async (_req: NextRequest, ctx) => {
if (ctx.actor.kind !== "human") return writeError("human session required", 401)
const openerId = ctx.params?.id
if (!openerId || openerId === REF_PLACEHOLDER_ID) return writeError("missing message id", 400)
diff --git a/src/web/src/app/api/community/messages/[id]/tags/route.test.ts b/src/web/src/app/api/community/messages/[id]/tags/route.test.ts
index e1f7d4845..843b9286d 100644
--- a/src/web/src/app/api/community/messages/[id]/tags/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/tags/route.test.ts
@@ -32,11 +32,7 @@ vi.mock("@/lib/community/fanout", () => ({
fanOutToChannel: (...args: unknown[]) => mockFanOutToChannel(...args),
}))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => (req: any, routeCtx: any) => handler(req, {
- env: { DB: {} },
- userId: "u1",
- params: routeCtx.params,
- }),
+ humanAuthPolicy: { resolve: async (req: any) => ({ context: { env: { DB: {} }, userId: "u1" } }) },
}))
vi.mock("@/lib/middleware/helpers", () => {
const { NextResponse } = require("next/server")
diff --git a/src/web/src/app/api/community/messages/[id]/tags/route.ts b/src/web/src/app/api/community/messages/[id]/tags/route.ts
index def9a6d41..4fbcdc24a 100644
--- a/src/web/src/app/api/community/messages/[id]/tags/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/tags/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { replaceForumTagsForActor } from "@/lib/community/forum-tag-operations"
/** Replace the tag set on a forum opener message. */
-export const PUT = withAuth(async (req: NextRequest, ctx) => {
+export const PUT = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const messageId = ctx.params?.id
if (!messageId) return writeError("missing message id", 400)
diff --git a/src/web/src/app/api/community/messages/batch/route.test.ts b/src/web/src/app/api/community/messages/batch/route.test.ts
index 617a855f9..1cb206085 100644
--- a/src/web/src/app/api/community/messages/batch/route.test.ts
+++ b/src/web/src/app/api/community/messages/batch/route.test.ts
@@ -29,7 +29,7 @@ vi.mock("@alook/shared", async () => {
})
vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireMessageSurfaceAccess(...args) }))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any) => handler(req, { env: { DB: {} }, userId: "user_1" }),
+ humanAuthPolicy: { resolve: async (req: any) => ({ context: { env: { DB: {} }, userId: "user_1" } }) },
}))
vi.mock("@/lib/middleware/helpers", () => {
const { NextResponse } = require("next/server")
diff --git a/src/web/src/app/api/community/messages/batch/route.ts b/src/web/src/app/api/community/messages/batch/route.ts
index acc9bb959..bc177d5af 100644
--- a/src/web/src/app/api/community/messages/batch/route.ts
+++ b/src/web/src/app/api/community/messages/batch/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries } from "@alook/shared"
import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
-export const POST = withAuth(async (req: NextRequest, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
let body: { channelId?: unknown; ids?: unknown; firstInChannelIds?: unknown }
try { body = await req.json() } catch { return writeError("invalid request body", 400) }
const ids = Array.isArray(body.ids) ? body.ids.filter((id): id is string => typeof id === "string") : []
diff --git a/src/web/src/app/api/community/messages/tags/batch/route.test.ts b/src/web/src/app/api/community/messages/tags/batch/route.test.ts
index 1863c14b9..7baa2da24 100644
--- a/src/web/src/app/api/community/messages/tags/batch/route.test.ts
+++ b/src/web/src/app/api/community/messages/tags/batch/route.test.ts
@@ -20,7 +20,7 @@ vi.mock("@alook/shared", async () => {
}
})
vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireMessageSurfaceAccess(...args) }))
-vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: any) => async (req: any) => handler(req, { env: { DB: {} }, userId: "user_1" }) }))
+vi.mock("@/lib/middleware/auth", () => ({ humanAuthPolicy: { resolve: async (req: any) => ({ context: { env: { DB: {} }, userId: "user_1" } }) } }))
vi.mock("@/lib/middleware/helpers", () => {
const { NextResponse } = require("next/server")
return {
diff --git a/src/web/src/app/api/community/messages/tags/batch/route.ts b/src/web/src/app/api/community/messages/tags/batch/route.ts
index fcf4bc707..aa25d8908 100644
--- a/src/web/src/app/api/community/messages/tags/batch/route.ts
+++ b/src/web/src/app/api/community/messages/tags/batch/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries } from "@alook/shared"
import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
-export const POST = withAuth(async (req: NextRequest, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
let body: { channelId?: unknown; messageIds?: unknown }
try { body = await req.json() } catch { return writeError("invalid request body", 400) }
const ids = Array.isArray(body.messageIds) ? body.messageIds.filter((id): id is string => typeof id === "string") : []
diff --git a/src/web/src/app/api/community/notifications/devices/[installationId]/route.test.ts b/src/web/src/app/api/community/notifications/devices/[installationId]/route.test.ts
index 6c52332da..181679256 100644
--- a/src/web/src/app/api/community/notifications/devices/[installationId]/route.test.ts
+++ b/src/web/src/app/api/community/notifications/devices/[installationId]/route.test.ts
@@ -8,14 +8,7 @@ const mocks = vi.hoisted(() => ({
db: { primary: true },
disablePushDevice: vi.fn(),
params: { installationId: "installation-123" } as Record<string, string>,
- withCommunityActor: vi.fn(
- (handler: (req: NextRequest, ctx: Record<string, unknown>) => Promise<Response>) =>
- async (req: NextRequest) => handler(req, {
- env: { DB: {} },
- actor: mocks.actor,
- params: mocks.params,
- }),
- ),
+ communityActorPolicy: () => ({ resolve: async (req: NextRequest) => ({ context: { env: { DB: {} }, actor: mocks.actor } }) }),
}));
vi.mock("@/lib/db", () => ({
@@ -32,7 +25,7 @@ vi.mock("@alook/shared", () => ({
}));
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: mocks.withCommunityActor,
+ communityActorPolicy: mocks.communityActorPolicy,
}));
import { DELETE } from "./route";
@@ -60,7 +53,7 @@ describe("DELETE /api/community/notifications/devices/:installationId", () => {
it("scopes a decoded installation id to the current session user", async () => {
mocks.params = { installationId: "safe%3Ainstallation_123" };
- const response = await DELETE(request());
+ const response = await DELETE(request(), { params: mocks.params });
expect(response.status).toBe(204);
expect(await response.text()).toBe("");
@@ -93,7 +86,7 @@ describe("DELETE /api/community/notifications/devices/:installationId", () => {
async (installationId) => {
mocks.params = installationId === undefined ? {} : { installationId };
- const response = await DELETE(request());
+ const response = await DELETE(request(), { params: mocks.params });
expect(response.status).toBe(400);
expect(mocks.disablePushDevice).not.toHaveBeenCalled();
@@ -103,7 +96,7 @@ describe("DELETE /api/community/notifications/devices/:installationId", () => {
it("returns the same empty 204 for disabled, missing, or foreign rows", async () => {
mocks.disablePushDevice.mockResolvedValue(false);
- const response = await DELETE(request());
+ const response = await DELETE(request(), { params: mocks.params });
expect(response.status).toBe(204);
expect(await response.text()).toBe("");
diff --git a/src/web/src/app/api/community/notifications/devices/[installationId]/route.ts b/src/web/src/app/api/community/notifications/devices/[installationId]/route.ts
index 532969946..1c17054bf 100644
--- a/src/web/src/app/api/community/notifications/devices/[installationId]/route.ts
+++ b/src/web/src/app/api/community/notifications/devices/[installationId]/route.ts
@@ -1,13 +1,14 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries } from "@alook/shared";
import { getPrimaryDb } from "@/lib/db";
import {
isCookieHumanSameOrigin,
notificationDeviceInstallationIdSchema,
} from "@/lib/community/notification-device-schema";
-import { withCommunityActor } from "@/lib/middleware/community-actor";
+import { communityActorPolicy } from "@/lib/middleware/community-actor";
import { writeError } from "@/lib/middleware/helpers";
-export const DELETE = withCommunityActor(async (req, ctx) => {
+export const DELETE = withAuth(communityActorPolicy(), async (req, ctx) => {
if (req.headers.has("Authorization")) return writeError("unauthorized", 401);
if (ctx.actor.kind !== "human") return writeError("forbidden", 403);
if (!isCookieHumanSameOrigin(req)) return writeError("forbidden", 403);
diff --git a/src/web/src/app/api/community/notifications/devices/route.test.ts b/src/web/src/app/api/community/notifications/devices/route.test.ts
index 59ce02d33..2f39574fb 100644
--- a/src/web/src/app/api/community/notifications/devices/route.test.ts
+++ b/src/web/src/app/api/community/notifications/devices/route.test.ts
@@ -5,17 +5,14 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
db: { primary: true },
registerPushDevice: vi.fn(),
- withCookieHumanAuth: vi.fn(
- (handler: (req: NextRequest, ctx: Record<string, unknown>) => Promise<Response>) =>
- async (req: NextRequest) => handler(req, {
+ cookieHumanAuthPolicy: { resolve: async (req: NextRequest) => ({ context: {
env: {
DB: {},
ENCRYPTION_KEY: "fake-encryption-key",
},
userId: "session-user",
- }),
- ),
+ } }) },
}));
vi.mock("@/lib/db", () => ({
@@ -32,16 +29,11 @@ vi.mock("@alook/shared", () => ({
}));
vi.mock("@/lib/middleware/auth", () => ({
- withCookieHumanAuth: mocks.withCookieHumanAuth,
+ cookieHumanAuthPolicy: mocks.cookieHumanAuthPolicy,
}));
import { POST } from "./route";
-const cookieHumanHandler = mocks.withCookieHumanAuth.mock.calls[0]![0] as (
- req: NextRequest,
- ctx: Record<string, unknown>,
-) => Promise<Response>;
-
const token = "fake-provider-token-123";
const previousToken = "fake-previous-token-123";
@@ -91,7 +83,7 @@ describe("POST /api/community/notifications/devices", () => {
});
it("is defined through the cookie-human-only authentication boundary", () => {
- expect(cookieHumanHandler).toEqual(expect.any(Function));
+ expect(mocks.cookieHumanAuthPolicy.resolve).toEqual(expect.any(Function));
});
it("derives identity, hashes, ciphertext, and timestamps on the server", async () => {
@@ -155,10 +147,11 @@ describe("POST /api/community/notifications/devices", () => {
});
it("fails closed when encryption is not configured", async () => {
- const response = await cookieHumanHandler(request(validBody()), {
- env: { DB: {}, ENCRYPTION_KEY: "" },
- userId: "session-user",
- });
+ const resolve = vi.spyOn(mocks.cookieHumanAuthPolicy, "resolve").mockResolvedValueOnce({ context: {
+ env: { DB: {}, ENCRYPTION_KEY: "" }, userId: "session-user", email: "[email protected]",
+ } });
+ const response = await POST(request(validBody()));
+ resolve.mockRestore();
expect(response.status).toBe(500);
expect(await response.json()).toEqual({ error: "encryption not configured" });
diff --git a/src/web/src/app/api/community/notifications/devices/route.ts b/src/web/src/app/api/community/notifications/devices/route.ts
index d7d97cefb..b57edebd8 100644
--- a/src/web/src/app/api/community/notifications/devices/route.ts
+++ b/src/web/src/app/api/community/notifications/devices/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { encrypt } from "@alook/shared/crypto";
import { queries } from "@alook/shared";
import { getPrimaryDb } from "@/lib/db";
@@ -5,10 +6,10 @@ import {
hashProviderToken,
notificationDeviceRegistrationSchema,
} from "@/lib/community/notification-device-schema";
-import { withCookieHumanAuth } from "@/lib/middleware/auth";
+import { cookieHumanAuthPolicy } from "@/lib/middleware/auth";
import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers";
-export const POST = withCookieHumanAuth(async (req, ctx) => {
+export const POST = withAuth(cookieHumanAuthPolicy, async (req, ctx) => {
const [body, error] = await parseBody(
req,
notificationDeviceRegistrationSchema,
diff --git a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.ts b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.ts
index 3c7a1c58d..223c2328e 100644
--- a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.ts
@@ -34,12 +34,11 @@ vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
}))
-
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 })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts
index d2724ca98..7df7431a0 100644
--- a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts
@@ -1,5 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import {
@@ -11,7 +12,7 @@ import {
import { fanOutToServerMembers } from "@/lib/community/fanout"
import { requireServerAdmin } from "@/lib/community/permissions"
-export const PATCH = withAuth(async (req: NextRequest, ctx) => {
+export const PATCH = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const serverId = ctx.params?.id
const categoryId = ctx.params?.catId
if (!serverId || !categoryId) return writeError("missing params", 400)
@@ -69,11 +70,10 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
changes,
})
-
return writeJSON(updated)
})
-export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
+export const DELETE = withAuth(humanAuthPolicy, async (_req: NextRequest, ctx) => {
const serverId = ctx.params?.id
const categoryId = ctx.params?.catId
if (!serverId || !categoryId) return writeError("missing params", 400)
@@ -103,6 +103,5 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
categoryId,
})
-
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/app/api/community/servers/[id]/categories/reorder/route.test.ts b/src/web/src/app/api/community/servers/[id]/categories/reorder/route.test.ts
index cf73b1065..630d53924 100644
--- a/src/web/src/app/api/community/servers/[id]/categories/reorder/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/categories/reorder/route.test.ts
@@ -27,10 +27,10 @@ vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: (...args: unknown[]) => fanOut(...args),
}))
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: {}, userId: "u1", email: "[email protected]", params })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: {}, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", async () => {
const { NextResponse } = require("next/server")
diff --git a/src/web/src/app/api/community/servers/[id]/categories/reorder/route.ts b/src/web/src/app/api/community/servers/[id]/categories/reorder/route.ts
index d17d3fb41..ad726b96b 100644
--- a/src/web/src/app/api/community/servers/[id]/categories/reorder/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/categories/reorder/route.ts
@@ -1,12 +1,13 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries, WS_EVENTS } from "@alook/shared"
import { fanOutToServerMembers } from "@/lib/community/fanout"
import { requireServerAdmin } from "@/lib/community/permissions"
-export const PATCH = withAuth(async (req: NextRequest, ctx) => {
+export const PATCH = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
diff --git a/src/web/src/app/api/community/servers/[id]/categories/route.test.ts b/src/web/src/app/api/community/servers/[id]/categories/route.test.ts
index f5ad1ca66..726d56b74 100644
--- a/src/web/src/app/api/community/servers/[id]/categories/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/categories/route.test.ts
@@ -30,10 +30,10 @@ vi.mock("@/lib/community/fanout", () => ({
}))
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 })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/servers/[id]/categories/route.ts b/src/web/src/app/api/community/servers/[id]/categories/route.ts
index bcfc83438..179911671 100644
--- a/src/web/src/app/api/community/servers/[id]/categories/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/categories/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { CommunityCategoryResourceSchema } from "@alook/shared"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import {
@@ -13,7 +14,7 @@ import { fanOutToServerMembers } from "@/lib/community/fanout"
import { requireServerAdmin, requireServerMember } from "@/lib/community/permissions"
import { readCommunityServerCategoryRows } from "@/lib/community/server-directory.server"
-export const GET = withAuth(async (_req: NextRequest, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req: NextRequest, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
const db = getDb(ctx.env.DB)
@@ -23,7 +24,7 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {
return writeJSON({ categories: categories.map(row => CommunityCategoryResourceSchema.strip().parse({ ...row, private: !!row.private })) })
})
-export const POST = withAuth(async (req: NextRequest, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
@@ -72,6 +73,5 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
category,
})
-
return writeJSON({ category }, 201)
})
diff --git a/src/web/src/app/api/community/servers/[id]/channels/admin/route.test.ts b/src/web/src/app/api/community/servers/[id]/channels/admin/route.test.ts
index 01d20006f..213157618 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/admin/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/admin/route.test.ts
@@ -24,9 +24,7 @@ vi.mock("@/lib/middleware/community-actor", async () => {
const actual = await vi.importActual<typeof import("@/lib/middleware/community-actor")>("@/lib/middleware/community-actor")
return {
...actual,
- withCommunityActor: (handler: any) => (req: any, ctx: any) => handler(req, {
- env: { DB: {} }, actor: { kind: mocks.kind, userId: "viewer" }, params: ctx?.params,
- }),
+ communityActorPolicy: () => ({ resolve: async (req: any) => ({ context: { env: { DB: {} }, actor: { kind: mocks.kind, userId: "viewer" } } }) }),
}
})
diff --git a/src/web/src/app/api/community/servers/[id]/channels/admin/route.ts b/src/web/src/app/api/community/servers/[id]/channels/admin/route.ts
index 7adcee51c..6161e3d3c 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/admin/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/admin/route.ts
@@ -1,13 +1,14 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse } from "next/server"
import { queries } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"
+import { communityActorPolicy, rejectBot } from "@/lib/middleware/community-actor"
import { writeError } from "@/lib/middleware/helpers"
import { requireServerAdmin } from "@/lib/community/permissions"
const headers = { "Cache-Control": "private, no-store" }
-export const GET = withCommunityActor(async (_req, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (_req, ctx) => {
const rejected = rejectBot(ctx.actor)
if (rejected) {
rejected.headers.set("Cache-Control", headers["Cache-Control"])
diff --git a/src/web/src/app/api/community/servers/[id]/channels/reorder/route.test.ts b/src/web/src/app/api/community/servers/[id]/channels/reorder/route.test.ts
index f9e5068e1..cd2053ff8 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/reorder/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/reorder/route.test.ts
@@ -12,7 +12,7 @@ vi.mock("@alook/shared", async () => ({
},
}))
vi.mock("@/lib/community/fanout", () => ({ fanOutToServerMembers: mocks.fanout }))
-vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: any) => (req: any, ctx?: any) => handler(req, { env: { DB: "binding" }, userId: "u1", params: ctx?.params }) }))
+vi.mock("@/lib/middleware/auth", () => ({ humanAuthPolicy: { resolve: async (req: any) => ({ context: { env: { DB: "binding" }, userId: "u1" } }) } }))
import { PATCH } from "./route"
const ctx = { params: { id: "s1" } } as never
const request = (body: unknown) => new NextRequest("http://localhost/api/community/servers/s1/channels/reorder", { method: "PATCH", body: JSON.stringify(body), headers: { "Content-Type": "application/json" } })
diff --git a/src/web/src/app/api/community/servers/[id]/channels/reorder/route.ts b/src/web/src/app/api/community/servers/[id]/channels/reorder/route.ts
index 3d660fec8..63f9f4119 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/reorder/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/reorder/route.ts
@@ -1,12 +1,13 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getPrimaryDb } from "@/lib/db"
import { channelReorderRequestSchema, queries, WS_EVENTS } from "@alook/shared"
import { fanOutToServerMembers } from "@/lib/community/fanout"
import { requireServerAdmin } from "@/lib/community/permissions"
-export const PATCH = withAuth(async (req: NextRequest, ctx) => {
+export const PATCH = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
const db = getPrimaryDb(ctx.env.DB)
diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts
index c30170f97..50f887f5d 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts
@@ -39,11 +39,7 @@ vi.mock("@alook/shared", async () => {
}
})
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: any) => async (req: any, ctx: any) => handler(req, {
- env: { DB: {} },
- actor: { kind: "human", userId: "user_1", email: "[email protected]" },
- params: ctx.params,
- }),
+ communityActorPolicy: () => ({ resolve: async (req: any) => ({ context: { env: { DB: {} }, actor: { kind: "human", userId: "user_1", email: "[email protected]" } } }) }),
}))
import { GET } from "./route"
diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.ts b/src/web/src/app/api/community/servers/[id]/channels/route.ts
index 1aaa3217f..34fccab43 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { communityChannelResourceFromStorage } from "@alook/shared"
import { BUSINESS_SCHEMA_VERSION, CommunityForumSidebarChannelSummarySchema, CommunityForumSidebarEnvelopeSchema } from "@alook/shared"
import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
@@ -5,7 +6,7 @@ import { NextResponse, NextRequest } from "next/server"
import { supportsSidebarThreads } from "@/lib/community/forum-sidebar"
import { getDb } from "@/lib/db"
import { compareAsciiSqliteBinary, parseNameAndTag, queries } from "@alook/shared"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { buildServerChannelGroups } from "@/lib/community/list-channels"
import { requireServerMember } from "@/lib/community/permissions"
import { readCommunityServerChannelRows } from "@/lib/community/server-directory.server"
@@ -25,7 +26,7 @@ import { readCommunityServerChannelRows } from "@/lib/community/server-directory
* nonexistent server). `buildServerChannelGroups` runs `listChannelsForMember`
* so private-category channels the bot can't see never appear.
*/
-export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
if (ctx.actor.kind === "human") {
diff --git a/src/web/src/app/api/community/servers/[id]/icon/route.test.ts b/src/web/src/app/api/community/servers/[id]/icon/route.test.ts
index 47ef5c58a..b4daf1922 100644
--- a/src/web/src/app/api/community/servers/[id]/icon/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/icon/route.test.ts
@@ -65,13 +65,13 @@ vi.mock("@/lib/community/fanout", () => ({
let isAuthed = true
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ humanAuthPolicy: { resolve: async (req: any) => {
if (!isAuthed) {
const { NextResponse } = require("next/server")
return NextResponse.json({ error: "unauthorized" }, { status: 401 })
}
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, {
+
+ return ({ context: {
env: {
DB: {},
COMMUNITY_MEDIA: {
@@ -83,9 +83,9 @@ vi.mock("@/lib/middleware/auth", () => ({
},
userId: "u1",
- params,
- })
- },
+
+ } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/servers/[id]/icon/route.ts b/src/web/src/app/api/community/servers/[id]/icon/route.ts
index e33f8220e..387a0ca54 100644
--- a/src/web/src/app/api/community/servers/[id]/icon/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/icon/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
@@ -17,7 +18,7 @@ import {
const log = createLogger({ service: "community-server-icon" })
-export const GET = withPrivateMediaCache(withAuth(async (req: NextRequest, ctx) => {
+export const GET = withPrivateMediaCache(withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
@@ -49,7 +50,7 @@ export const GET = withPrivateMediaCache(withAuth(async (req: NextRequest, ctx)
})
}))
-export const POST = withAuth(async (req: NextRequest, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
diff --git a/src/web/src/app/api/community/servers/[id]/invites/route.test.ts b/src/web/src/app/api/community/servers/[id]/invites/route.test.ts
index cc2d64044..efb0dcef3 100644
--- a/src/web/src/app/api/community/servers/[id]/invites/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/invites/route.test.ts
@@ -29,10 +29,10 @@ vi.mock("@/lib/community/fanout", () => ({
}))
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 })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/servers/[id]/invites/route.ts b/src/web/src/app/api/community/servers/[id]/invites/route.ts
index 551decbb9..eedd204b4 100644
--- a/src/web/src/app/api/community/servers/[id]/invites/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/invites/route.ts
@@ -1,7 +1,8 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { BUSINESS_SCHEMA_VERSION, CommunityInvitesReadSchema } from "@alook/shared"
import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
import { writeCommunityContractJSON } from "@/lib/community/read-contract"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import {
@@ -16,7 +17,7 @@ import type { CommunityInviteCreate } from "@alook/shared"
import { fanOutToServerMembers } from "@/lib/community/fanout"
import { requireServerMember } from "@/lib/community/permissions"
-export const GET = withAuth(async (_req, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("server id is required", 400)
@@ -31,7 +32,7 @@ export const GET = withAuth(async (_req, ctx) => {
return writeCommunityContractJSON(CommunityInvitesReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, serverId, invites, resources }))
})
-export const POST = withAuth(async (req, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (req, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("server id is required", 400)
@@ -90,7 +91,6 @@ export const POST = withAuth(async (req, ctx) => {
)
}
-
const event: CommunityInviteCreate = {
type: WS_EVENTS.INVITE_CREATE,
serverId,
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 6a10c23e4..877492a8b 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
@@ -31,24 +31,23 @@ vi.mock("@alook/shared", async () => {
}
})
-
vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
+
const bot = req.headers.get("authorization")?.startsWith("Bearer crk_")
- return handler(req, {
+ return ({ context: {
env: { DB: {} },
actor: bot
? { kind: "bot", userId: "bot1", ownerUserId: "u1", machineId: "m1" }
: { kind: "human", userId: "u1", email: "[email protected]" },
- params,
- })
- }),
+
+ } })
+ } }),
}))
vi.mock("@/lib/middleware/helpers", () => {
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 b6bf39fcc..0efa068a5 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
@@ -1,4 +1,5 @@
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries, isServerOwner, parseNameAndTag, WS_EVENTS } from "@alook/shared"
@@ -7,7 +8,7 @@ import { requireServerMember } from "@/lib/community/permissions"
const REF_PLACEHOLDER_ID = "resolve"
-export const POST = withCommunityActor(async (req, ctx) => {
+export const POST = withAuth(communityActorPolicy({ allowInactiveBot: true }), async (req, ctx) => {
const pathServerId = ctx.params?.id
if (!pathServerId) return writeError("missing server id", 400)
@@ -77,4 +78,4 @@ export const POST = withCommunityActor(async (req, ctx) => {
])
return new Response(null, { status: 204 })
-}, { allowInactiveBot: true })
+})
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 cbb0dbeb5..785059f93 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
@@ -45,17 +45,16 @@ vi.mock("@alook/shared", async () => {
}
})
-
vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
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_admin", email: "[email protected]", params })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u_admin", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
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 38b425cac..7b8e39458 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
@@ -1,5 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import {
@@ -13,7 +14,7 @@ import {
import { broadcastToUserSafe, fanOutToServerMembers } from "@/lib/community/fanout"
import { requireServerAdmin } from "@/lib/community/permissions"
-export const PATCH = withAuth(async (req: NextRequest, ctx) => {
+export const PATCH = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const serverId = ctx.params?.id
const memberId = ctx.params?.memberId
if (!serverId) return writeError("missing server id", 400)
@@ -51,7 +52,6 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
const updated = await queries.communityMember.updateRole(db, memberId, body.role)
if (!updated) return writeError("member not found", 404)
-
fanOutToServerMembers(serverId, {
type: WS_EVENTS.MEMBER_UPDATE,
serverId,
@@ -62,7 +62,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
return writeJSON(updated)
})
-export const DELETE = withAuth(async (_req, ctx) => {
+export const DELETE = withAuth(humanAuthPolicy, async (_req, ctx) => {
const serverId = ctx.params?.id
const memberId = ctx.params?.memberId
if (!serverId) return writeError("missing server id", 400)
diff --git a/src/web/src/app/api/community/servers/[id]/members/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/route.test.ts
index b452feb94..c84f9e641 100644
--- a/src/web/src/app/api/community/servers/[id]/members/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/route.test.ts
@@ -27,14 +27,18 @@ vi.mock("@alook/shared", async () => {
let authOverride: { userId?: string; unauth?: boolean } = {}
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ resolveHumanAuth: async () => {
+ if (authOverride.unauth) return Response.json({ error: "Unauthorized" }, { status: 401 })
+ return { context: { env: { DB: {} }, userId: authOverride.userId ?? "u1", email: "[email protected]" } }
+ },
+ humanAuthPolicy: { resolve: async (req: any) => {
if (authOverride.unauth) {
const { NextResponse } = require("next/server")
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, { env: { DB: {} }, userId: authOverride.userId ?? "u1", email: "[email protected]", params })
- }),
+
+ return ({ context: { env: { DB: {} }, userId: authOverride.userId ?? "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/servers/[id]/members/route.ts b/src/web/src/app/api/community/servers/[id]/members/route.ts
index 3002f2dd0..63e3882c5 100644
--- a/src/web/src/app/api/community/servers/[id]/members/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse, type NextRequest } from "next/server"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
@@ -8,7 +9,7 @@ import {
DEFAULT_MEMBERS_PAGE_SIZE,
MAX_MEMBERS_PAGE_SIZE,
} from "@alook/shared"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { requireServerMember } from "@/lib/community/permissions"
import { parseBoundedInt, parseMemberCursor, buildMemberPaginatedResponse } from "@/lib/community/messages"
import { mapMemberForApi } from "@/lib/community/member-payload"
@@ -32,7 +33,7 @@ import { fetchOnlineUserIds, toMemberStatus } from "@/lib/community/member-prese
* (indistinguishable from a truly nonexistent server — no existence leak). The
* human arm keeps `requireServerMember`'s own 403/404.
*/
-export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
if (ctx.actor.kind === "bot") {
diff --git a/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts
index bc103bddc..5dd5b358f 100644
--- a/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts
@@ -24,10 +24,10 @@ vi.mock("@alook/shared", async () => {
})
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 })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/servers/[id]/members/search/route.ts b/src/web/src/app/api/community/servers/[id]/members/search/route.ts
index abda05415..1ce3560cb 100644
--- a/src/web/src/app/api/community/servers/[id]/members/search/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/search/route.ts
@@ -1,4 +1,5 @@
-import { withAuth } from "@/lib/middleware/auth"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { parseCommunityServerMembersRead, queries, MAX_MEMBERS_PAGE_SIZE } from "@alook/shared"
@@ -10,7 +11,7 @@ import {
parseMemberSearchCursor,
} from "@/lib/community/member-search-cursor"
-export const GET = withAuth(async (req, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (req, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
diff --git a/src/web/src/app/api/community/servers/[id]/onboard/route.test.ts b/src/web/src/app/api/community/servers/[id]/onboard/route.test.ts
index a46cc5cf5..d386e0ac0 100644
--- a/src/web/src/app/api/community/servers/[id]/onboard/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/onboard/route.test.ts
@@ -47,12 +47,7 @@ vi.mock("@alook/shared", async (importOriginal) => {
})
vi.mock("@/lib/db", () => ({ getDb: () => ({}) }))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: Function) => (req: NextRequest, context?: { params?: Record<string, string> }) =>
- handler(req, {
- env: {},
- userId: "owner-1",
- params: context?.params,
- }),
+ humanAuthPolicy: { resolve: async (req: NextRequest) => ({ context: { env: {}, userId: "owner-1" } }) },
}))
vi.mock("@/lib/community/bot-push", () => ({
pushBotEventToMachine: (...args: unknown[]) => mocks.push(...args),
diff --git a/src/web/src/app/api/community/servers/[id]/onboard/route.ts b/src/web/src/app/api/community/servers/[id]/onboard/route.ts
index 33761ba70..74edcdb8d 100644
--- a/src/web/src/app/api/community/servers/[id]/onboard/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/onboard/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { nanoid } from "nanoid"
import {
@@ -21,7 +22,7 @@ import {
import { createCommunityMessage } from "@/lib/community/message-handler"
import { canonicalUserImage } from "@/lib/community/storage"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers"
function joinHandles(handles: string[]) {
@@ -53,7 +54,7 @@ export function onboardingPromptWithSpace(
].join("\n")
}
-export const POST = withAuth(async (req: NextRequest, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const serverId = ctx.params?.id as string
if (!serverId) return writeError("server id is required", 400)
const [body, bodyError] = await parseBody(req, CommunityServerOnboardRequestSchema)
diff --git a/src/web/src/app/api/community/servers/[id]/presence/route.test.ts b/src/web/src/app/api/community/servers/[id]/presence/route.test.ts
index 4a39d196f..0c8b4a7eb 100644
--- a/src/web/src/app/api/community/servers/[id]/presence/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/presence/route.test.ts
@@ -25,14 +25,14 @@ vi.mock("@alook/shared", async () => {
})
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
+ humanAuthPolicy: { resolve: async (req: any) => {
+
const env = {
DB: {},
WS_DO_WORKER: { fetch: (...a: unknown[]) => mockWsDoWorkerFetch(...a) },
}
- return handler(req, { env, userId: "u1", email: "[email protected]", params })
- }),
+ return ({ context: { env, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/servers/[id]/presence/route.ts b/src/web/src/app/api/community/servers/[id]/presence/route.ts
index bb07139ad..7207ec9da 100644
--- a/src/web/src/app/api/community/servers/[id]/presence/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/presence/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries, PRESENCE_MEMBER_CAP, readOrStale } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { requireServerMember } from "@/lib/community/permissions"
import { wsDoFetch } from "@/lib/broadcast"
-export const GET = withAuth(async (_req, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
diff --git a/src/web/src/app/api/community/servers/[id]/route.test.ts b/src/web/src/app/api/community/servers/[id]/route.test.ts
index 5399d84be..6ad6610cf 100644
--- a/src/web/src/app/api/community/servers/[id]/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/route.test.ts
@@ -58,15 +58,15 @@ vi.mock("@/lib/community/community-media-cleanup", async () => {
})
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, {
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: {
env: { DB: {}, COMMUNITY_MEDIA: { delete: vi.fn() } },
userId: "u1",
- params,
- })
- }),
+
+ } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/servers/[id]/route.ts b/src/web/src/app/api/community/servers/[id]/route.ts
index b015a997d..41617354d 100644
--- a/src/web/src/app/api/community/servers/[id]/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb, getPrimaryDb } from "@/lib/db"
import {
@@ -16,7 +17,7 @@ import { requireServerAdmin } from "@/lib/community/permissions"
import { scheduleCommunityMediaCleanup } from "@/lib/community/community-media-cleanup"
import { isOwnedServerIconKey } from "@/lib/community/storage"
-export const PATCH = withAuth(async (req: NextRequest, ctx) => {
+export const PATCH = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
@@ -63,7 +64,6 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
const updated = await queries.communityServer.updateServer(db, serverId, changes)
if (!updated) return writeError("server not found", 404)
-
fanOutToServerMembers(serverId, {
type: WS_EVENTS.SERVER_UPDATE,
serverId,
@@ -73,7 +73,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
return writeJSON(updated)
})
-export const DELETE = withAuth(async (_req, ctx) => {
+export const DELETE = withAuth(humanAuthPolicy, async (_req, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
diff --git a/src/web/src/app/api/community/servers/channels/route.ts b/src/web/src/app/api/community/servers/channels/route.ts
index fe8bd456b..a9dc1e210 100644
--- a/src/web/src/app/api/community/servers/channels/route.ts
+++ b/src/web/src/app/api/community/servers/channels/route.ts
@@ -1,8 +1,9 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse, type NextRequest } from "next/server"
import { queries, formatHandle, isServerOwner } from "@alook/shared"
import type { CommunityCliChannelGroup as ChannelGroup } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { serverIconUrl } from "@/lib/community/storage"
import { buildServerChannelGroups } from "@/lib/community/list-channels"
@@ -22,7 +23,7 @@ import { buildServerChannelGroups } from "@/lib/community/list-channels"
* the bot can't see never appear; there is no server the bot isn't a member of
* in `listUserServers`, so no existence mask is needed here.
*/
-export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
+export const GET = withAuth(communityActorPolicy({ allowInactiveBot: true }), async (_req: NextRequest, ctx) => {
if (ctx.actor.kind !== "bot") {
return NextResponse.json({ error: "not found" }, { status: 404 })
}
@@ -39,4 +40,4 @@ export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
const groups: ChannelGroup[] = perServer.flat()
return NextResponse.json({ groups, servers: servers.map((server) => ({ id: server.id, name: server.name, handle: formatHandle(server.name, server.discriminator), icon: serverIconUrl(server), canLeave: !isServerOwner(server.role) })) })
-}, { allowInactiveBot: true })
+})
diff --git a/src/web/src/app/api/community/servers/route.bot.test.ts b/src/web/src/app/api/community/servers/route.bot.test.ts
index 741393d67..6dbdb5126 100644
--- a/src/web/src/app/api/community/servers/route.bot.test.ts
+++ b/src/web/src/app/api/community/servers/route.bot.test.ts
@@ -4,7 +4,7 @@ import { NextRequest } from "next/server"
// Bot-path coverage for the UNIFIED server-list route (listServers folded onto
// GET /servers, plan §4/§9 phase 4-5). A `crk_` bearer drives
-// withCommunityActor's bot path; GET lists via listUserServers(actor.userId).
+// communityActorPolicy's bot path; GET lists via listUserServers(actor.userId).
// The route returns the SUPERSET (full rows + icon) — the daemon/CLI projects
// each row down to the lean {handle} shape. That daemon-side lean
// projection is asserted by the daemon projection test, NOT here; here we lock
diff --git a/src/web/src/app/api/community/servers/route.human.test.ts b/src/web/src/app/api/community/servers/route.human.test.ts
index 8f736d612..f7f7cec24 100644
--- a/src/web/src/app/api/community/servers/route.human.test.ts
+++ b/src/web/src/app/api/community/servers/route.human.test.ts
@@ -13,11 +13,10 @@ vi.mock("@/lib/community/storage", () => ({
serverIconUrl: vi.fn((row: { icon?: string | null }) => row.icon ?? null),
}))
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: (...args: any[]) => unknown) =>
- (req: NextRequest) => handler(req, {
+ communityActorPolicy: () => ({ resolve: async (req: NextRequest) => ({ context: {
env: { DB: {} },
actor: { kind: "human", userId: "viewer", email: "[email protected]" },
- }),
+ } }) }),
rejectBot: vi.fn(() => null),
}))
vi.mock("@/lib/middleware/helpers", () => ({
diff --git a/src/web/src/app/api/community/servers/route.test.ts b/src/web/src/app/api/community/servers/route.test.ts
index 3d75d6821..39d009db3 100644
--- a/src/web/src/app/api/community/servers/route.test.ts
+++ b/src/web/src/app/api/community/servers/route.test.ts
@@ -28,10 +28,7 @@ vi.mock("@/lib/community/fanout", () => ({
}))
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 })
- }),
+ resolveHumanAuth: async () => ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } }),
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/servers/route.ts b/src/web/src/app/api/community/servers/route.ts
index 9fb80e27d..fcb452942 100644
--- a/src/web/src/app/api/community/servers/route.ts
+++ b/src/web/src/app/api/community/servers/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries, withD1Retry } from "@alook/shared"
import { writeJSON } from "@/lib/middleware/helpers"
import { getPrimaryDb } from "@/lib/db"
-import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"
+import { communityActorPolicy, rejectBot } from "@/lib/middleware/community-actor"
import { serverIconUrl } from "@/lib/community/storage"
import { createServerForUser } from "@/lib/community/create-server.server"
-export const GET = withCommunityActor(async (_req, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (_req, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
const rows = await withD1Retry(
() => queries.communityServer.listUserServers(db, ctx.actor.userId),
@@ -55,7 +56,7 @@ export const GET = withCommunityActor(async (_req, ctx) => {
})
})
-export const POST = withCommunityActor(async (req, ctx) => {
+export const POST = withAuth(communityActorPolicy(), async (req, ctx) => {
const denied = rejectBot(ctx.actor)
if (denied) return denied
return createServerForUser(req, { env: ctx.env, userId: ctx.actor.userId })
diff --git a/src/web/src/app/api/community/share-image/avatar/[userId]/route.test.ts b/src/web/src/app/api/community/share-image/avatar/[userId]/route.test.ts
index 4b26da62b..c35834a75 100644
--- a/src/web/src/app/api/community/share-image/avatar/[userId]/route.test.ts
+++ b/src/web/src/app/api/community/share-image/avatar/[userId]/route.test.ts
@@ -16,10 +16,10 @@ vi.mock("@alook/shared", async () => ({
},
}))
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: "database" }, userId: "viewer-1", params })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: "database" }, userId: "viewer-1" } })
+ } },
}))
import { GET, allowedExternalAvatarUrl } from "./route"
diff --git a/src/web/src/app/api/community/share-image/avatar/[userId]/route.ts b/src/web/src/app/api/community/share-image/avatar/[userId]/route.ts
index d9e53aef8..5aeaafd78 100644
--- a/src/web/src/app/api/community/share-image/avatar/[userId]/route.ts
+++ b/src/web/src/app/api/community/share-image/avatar/[userId]/route.ts
@@ -1,7 +1,8 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { queries } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"
import { writeError } from "@/lib/middleware/helpers"
@@ -73,7 +74,7 @@ async function readLimitedImage(response: Response): Promise<{ bytes: Uint8Array
return { bytes, type }
}
-export const GET = withPrivateMediaCache(withAuth(async (_req: NextRequest, ctx) => {
+export const GET = withPrivateMediaCache(withAuth(humanAuthPolicy, async (_req: NextRequest, ctx) => {
const userId = ctx.params?.userId
if (!userId) return writeError("missing user id", 400)
diff --git a/src/web/src/app/api/community/users/[userId]/avatar/route.test.ts b/src/web/src/app/api/community/users/[userId]/avatar/route.test.ts
index 833125037..37c454069 100644
--- a/src/web/src/app/api/community/users/[userId]/avatar/route.test.ts
+++ b/src/web/src/app/api/community/users/[userId]/avatar/route.test.ts
@@ -27,19 +27,19 @@ vi.mock("@alook/shared", async () => {
let isAuthed = true
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ humanAuthPolicy: { resolve: async (req: any) => {
if (!isAuthed) {
const { NextResponse } = require("next/server")
return NextResponse.json({ error: "unauthorized" }, { status: 401 })
}
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, {
+
+ return ({ context: {
env: { DB: {}, COMMUNITY_MEDIA: { get: (...a: unknown[]) => mediaGet(...a) } },
userId: "caller",
- params,
- })
- },
+
+ } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/users/[userId]/avatar/route.ts b/src/web/src/app/api/community/users/[userId]/avatar/route.ts
index 6dde0db2f..6de15c762 100644
--- a/src/web/src/app/api/community/users/[userId]/avatar/route.ts
+++ b/src/web/src/app/api/community/users/[userId]/avatar/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { CACHE_REVALIDATE, createLogger, queries } from "@alook/shared"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"
import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
@@ -14,7 +15,7 @@ import {
const log = createLogger({ service: "community-user-avatar" })
const PRIVATE_NO_STORE = "private, no-store"
-export const GET = withPrivateMediaCache(withAuth(async (req: NextRequest, ctx) => {
+export const GET = withPrivateMediaCache(withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const userId = ctx.params?.userId
if (!userId) return writeError("missing user id", 400)
diff --git a/src/web/src/app/api/community/users/[userId]/block/route.test.ts b/src/web/src/app/api/community/users/[userId]/block/route.test.ts
index 4f3b76cad..aa9116597 100644
--- a/src/web/src/app/api/community/users/[userId]/block/route.test.ts
+++ b/src/web/src/app/api/community/users/[userId]/block/route.test.ts
@@ -19,10 +19,10 @@ vi.mock("@alook/shared", async () => {
})
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: {}, userId: "u1", email: "[email protected]", params })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: {}, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/users/[userId]/block/route.ts b/src/web/src/app/api/community/users/[userId]/block/route.ts
index 325a190ee..7a1c5e895 100644
--- a/src/web/src/app/api/community/users/[userId]/block/route.ts
+++ b/src/web/src/app/api/community/users/[userId]/block/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries, WS_EVENTS } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
-export const POST = withAuth(async (_req, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const targetId = ctx.params?.userId as string
diff --git a/src/web/src/app/api/community/users/[userId]/profile/route.test.ts b/src/web/src/app/api/community/users/[userId]/profile/route.test.ts
index 65af9a57c..1f7bcefc7 100644
--- a/src/web/src/app/api/community/users/[userId]/profile/route.test.ts
+++ b/src/web/src/app/api/community/users/[userId]/profile/route.test.ts
@@ -20,10 +20,10 @@ vi.mock("@alook/shared", async () => {
})
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: {}, userId: "u1", email: "[email protected]", params })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: {}, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/users/[userId]/profile/route.ts b/src/web/src/app/api/community/users/[userId]/profile/route.ts
index 81199cae5..a11a1d4ec 100644
--- a/src/web/src/app/api/community/users/[userId]/profile/route.ts
+++ b/src/web/src/app/api/community/users/[userId]/profile/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { parseCommunityUserCardRead, queries } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { canonicalUserImage } from "@/lib/community/storage"
-export const GET = withAuth(async (_req, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
const id = ctx.params?.userId
if (!id) return writeError("missing user id", 400)
diff --git a/src/web/src/app/api/community/users/[userId]/unblock/route.ts b/src/web/src/app/api/community/users/[userId]/unblock/route.ts
index 54cb03b0e..f5034abe9 100644
--- a/src/web/src/app/api/community/users/[userId]/unblock/route.ts
+++ b/src/web/src/app/api/community/users/[userId]/unblock/route.ts
@@ -1,9 +1,10 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
-export const POST = withAuth(async (_req, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const targetId = ctx.params?.userId as string
diff --git a/src/web/src/app/api/community/users/me/account-deletion/code/route.test.ts b/src/web/src/app/api/community/users/me/account-deletion/code/route.test.ts
index 805669125..35a7eed71 100644
--- a/src/web/src/app/api/community/users/me/account-deletion/code/route.test.ts
+++ b/src/web/src/app/api/community/users/me/account-deletion/code/route.test.ts
@@ -4,12 +4,11 @@ import { NextRequest } from "next/server"
const sendDeletionCode = vi.fn()
vi.mock("@/lib/middleware/auth", () => ({
- withCookieHumanAuth: (handler: (...args: any[]) => Promise<Response>) =>
- (request: NextRequest) => handler(request, {
+ cookieHumanAuthPolicy: { resolve: async (request: NextRequest) => ({ context: {
env: { DB: {} },
userId: "user-1",
- }),
+ } }) },
}))
vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({}) }))
vi.mock("@/lib/account-deletion/challenge", () => ({
diff --git a/src/web/src/app/api/community/users/me/account-deletion/code/route.ts b/src/web/src/app/api/community/users/me/account-deletion/code/route.ts
index a39dbe2b6..5dfe26031 100644
--- a/src/web/src/app/api/community/users/me/account-deletion/code/route.ts
+++ b/src/web/src/app/api/community/users/me/account-deletion/code/route.ts
@@ -1,8 +1,9 @@
-import { withCookieHumanAuth } from "@/lib/middleware/auth"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { cookieHumanAuthPolicy } from "@/lib/middleware/auth"
import { getPrimaryDb } from "@/lib/db"
import { sendDeletionCode } from "@/lib/account-deletion/challenge"
-export const POST = withCookieHumanAuth(async (_request, context) => {
+export const POST = withAuth(cookieHumanAuthPolicy, async (_request, context) => {
const result = await sendDeletionCode(getPrimaryDb(context.env.DB), context.env, {
userId: context.userId,
email: context.email,
diff --git a/src/web/src/app/api/community/users/me/account-deletion/route.test.ts b/src/web/src/app/api/community/users/me/account-deletion/route.test.ts
index c3b3c590a..cb1ac2f37 100644
--- a/src/web/src/app/api/community/users/me/account-deletion/route.test.ts
+++ b/src/web/src/app/api/community/users/me/account-deletion/route.test.ts
@@ -8,13 +8,12 @@ const getPrimaryDb = vi.fn()
const signOut = vi.fn()
vi.mock("@/lib/middleware/auth", () => ({
- withCookieHumanAuth: (handler: (...args: any[]) => Promise<Response>) =>
- (request: NextRequest) => handler(request, {
+ cookieHumanAuthPolicy: { resolve: async (request: NextRequest) => ({ context: {
env: { DB: {} },
executionContext: { waitUntil: vi.fn() },
userId: "user-1",
- }),
+ } }) },
}))
vi.mock("@/lib/db", () => ({ getPrimaryDb: (...args: unknown[]) => getPrimaryDb(...args) }))
vi.mock("@/lib/auth", () => ({ getAuth: () => ({ api: { signOut } }) }))
diff --git a/src/web/src/app/api/community/users/me/account-deletion/route.ts b/src/web/src/app/api/community/users/me/account-deletion/route.ts
index d04a79a9c..43fc87c91 100644
--- a/src/web/src/app/api/community/users/me/account-deletion/route.ts
+++ b/src/web/src/app/api/community/users/me/account-deletion/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse } from "next/server"
import { z } from "zod"
-import { withCookieHumanAuth } from "@/lib/middleware/auth"
+import { cookieHumanAuthPolicy } from "@/lib/middleware/auth"
import { getPrimaryDb } from "@/lib/db"
import { getAuth } from "@/lib/auth"
import {
@@ -27,7 +28,7 @@ function clearAuthCookies(response: NextResponse): void {
}
}
-export const POST = withCookieHumanAuth(async (request, context) => {
+export const POST = withAuth(cookieHumanAuthPolicy, async (request, context) => {
let input: z.infer<typeof bodySchema>
try {
input = bodySchema.parse(await request.json())
diff --git a/src/web/src/app/api/community/users/me/attention/route.test.ts b/src/web/src/app/api/community/users/me/attention/route.test.ts
index 726253cb4..1740dd7ee 100644
--- a/src/web/src/app/api/community/users/me/attention/route.test.ts
+++ b/src/web/src/app/api/community/users/me/attention/route.test.ts
@@ -32,10 +32,10 @@ vi.mock("@alook/shared", async () => {
})
vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: async (_db: unknown, channelId: string) => ({ ok: true, value: { channel: channelResourceFixture({ id: channelId, serverId: null, type: "dm", name: null }) } }) }))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => (request: any) => handler(request, {
+ humanAuthPolicy: { resolve: async (request: any) => ({ context: {
env: { DB: { binding: "d1" } },
userId: "u1",
- }),
+ } }) },
}))
vi.mock("@/lib/middleware/helpers", () => ({
writeJSON: (data: unknown) => Response.json(data),
diff --git a/src/web/src/app/api/community/users/me/attention/route.ts b/src/web/src/app/api/community/users/me/attention/route.ts
index e9442553b..f4a06813b 100644
--- a/src/web/src/app/api/community/users/me/attention/route.ts
+++ b/src/web/src/app/api/community/users/me/attention/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import {
AccountAttentionSnapshotSchema,
DEFAULT_INBOX_PAGE_SIZE,
@@ -8,10 +9,10 @@ import {
import { getPrimaryDb } from "@/lib/db"
import { hydrateAttentionResources } from "@/lib/community/attention-resources.server"
import { parseBoundedInt } from "@/lib/community/messages"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
-export const GET = withAuth(async (request, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (request, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
const url = new URL(request.url)
const limit = parseBoundedInt(
diff --git a/src/web/src/app/api/community/users/me/avatar/route.test.ts b/src/web/src/app/api/community/users/me/avatar/route.test.ts
index fb9dcbceb..36bcf15b4 100644
--- a/src/web/src/app/api/community/users/me/avatar/route.test.ts
+++ b/src/web/src/app/api/community/users/me/avatar/route.test.ts
@@ -67,20 +67,20 @@ let isAuthed = true
let actorKind: "human" | "bot" = "human"
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
if (!isAuthed) {
const { NextResponse } = require("next/server")
return NextResponse.json({ error: "unauthorized" }, { status: 401 })
}
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, {
+
+ return ({ context: {
env: { DB: {}, COMMUNITY_MEDIA: { delete: vi.fn() } },
actor: actorKind === "bot"
? { kind: "bot", userId: "b1", ownerUserId: "u1", machineId: "m1" }
: { kind: "human", userId: "u1", email: "[email protected]" },
- params,
- })
- }),
+
+ } })
+ } }),
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/users/me/avatar/route.ts b/src/web/src/app/api/community/users/me/avatar/route.ts
index c6e8366bb..4098ae06f 100644
--- a/src/web/src/app/api/community/users/me/avatar/route.ts
+++ b/src/web/src/app/api/community/users/me/avatar/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest, NextResponse } from "next/server"
import { createLogger, queries } from "@alook/shared"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { getAuth } from "@/lib/auth"
@@ -16,7 +17,7 @@ import { fanOutIdentityUpdate } from "@/lib/community/fanout"
const log = createLogger({ service: "community-self-avatar" })
-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
+export const POST = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const userId = ctx.actor.userId
const db = getDb(ctx.env.DB)
diff --git a/src/web/src/app/api/community/users/me/channel-directory/route.test.ts b/src/web/src/app/api/community/users/me/channel-directory/route.test.ts
index c433f8179..f29a7c19d 100644
--- a/src/web/src/app/api/community/users/me/channel-directory/route.test.ts
+++ b/src/web/src/app/api/community/users/me/channel-directory/route.test.ts
@@ -23,9 +23,7 @@ vi.mock("@alook/shared", async () => {
})
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any) =>
- handler(req, { env: { DB: {} }, userId: "viewer_1", email: "[email protected]" }),
- ),
+ humanAuthPolicy: { resolve: async (req: any) => ({ context: { env: { DB: {} }, userId: "viewer_1", email: "[email protected]" } }) },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/users/me/channel-directory/route.ts b/src/web/src/app/api/community/users/me/channel-directory/route.ts
index d7a216dbe..746589f91 100644
--- a/src/web/src/app/api/community/users/me/channel-directory/route.ts
+++ b/src/web/src/app/api/community/users/me/channel-directory/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
import { queries } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
-export const GET = withAuth(async (_req, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
const directory = await queries.communityChannel.listChannelRefDirectoryForUser(
db,
diff --git a/src/web/src/app/api/community/users/me/dms/route.test.ts b/src/web/src/app/api/community/users/me/dms/route.test.ts
index 2d6f35e6c..44f2e5465 100644
--- a/src/web/src/app/api/community/users/me/dms/route.test.ts
+++ b/src/web/src/app/api/community/users/me/dms/route.test.ts
@@ -37,10 +37,10 @@ vi.mock("@/lib/community/permissions", () => ({
}))
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 })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/users/me/dms/route.ts b/src/web/src/app/api/community/users/me/dms/route.ts
index 11726b668..d25ff66a2 100644
--- a/src/web/src/app/api/community/users/me/dms/route.ts
+++ b/src/web/src/app/api/community/users/me/dms/route.ts
@@ -1,11 +1,12 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries, parseCommunityDmsRead, CommunityResourceProfileSchema, CommunityMemberRelationSchema, communityChannelResourceFromStorage } from "@alook/shared"
import { canonicalUserImage } from "@/lib/community/storage"
-export const GET = withAuth(async (_req: NextRequest, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const [rows, unreadRows] = await Promise.all([
queries.communityDm.listDMs(db, ctx.userId),
diff --git a/src/web/src/app/api/community/users/me/inbox/ack/route.ts b/src/web/src/app/api/community/users/me/inbox/ack/route.ts
index f980aa9b6..c916ea2c1 100644
--- a/src/web/src/app/api/community/users/me/inbox/ack/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/ack/route.ts
@@ -1,8 +1,9 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { flattenError } from "zod"
import { NextResponse, type NextRequest } from "next/server"
import { queries, withD1Retry, CommunityAgentAckRequestSchema, type CommunityCliAckResponse } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"
+import { communityActorPolicy, requireBot } from "@/lib/middleware/community-actor"
import { resolveTargetForMember } from "@/lib/community/resolve-ref"
import { isDmTarget } from "@/lib/community/message-handler"
import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"
@@ -40,7 +41,7 @@ import { requireChannelMember, requireDMAccess } from "@/lib/community/permissio
* daemon must not treat the whole call as failed). Only a genuine D1 exception
* escaping `withD1Retry` propagates as a 500 so the daemon retries the batch.
*/
-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
+export const POST = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const gate = requireBot(ctx.actor)
if (!gate.ok) return gate.response
const { userId: botUserId } = gate.bot
diff --git a/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.test.ts b/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.test.ts
index 9dc97c957..131bf3900 100644
--- a/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.test.ts
@@ -26,11 +26,11 @@ vi.mock("@/lib/community/fanout", () => ({
broadcastToUserSafe: (...args: unknown[]) => mocks.broadcast(...args),
}))
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => (req: any) => handler(req, {
+ humanAuthPolicy: { resolve: async (req: any) => ({ context: {
env: { DB: {} },
userId: "u1",
- }),
+ } }) },
}))
vi.mock("@/lib/middleware/helpers", () => ({
writeJSON: (data: unknown) => Response.json(data),
diff --git a/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.ts b/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.ts
index 2e5db89b6..cadc81f95 100644
--- a/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries, WS_EVENTS } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
@@ -12,7 +13,7 @@ import { broadcastToUserSafe } from "@/lib/community/fanout"
* "mark all read" affordance fires three independent POSTs — mentions +
* channel-unreads + dms — each idempotent and independently retryable.
*/
-export const POST = withAuth(async (_req, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
const { count, changed, revision } = await queries.communityReadState.markAllDmsRead(db, ctx.userId)
if (changed) {
diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.test.ts b/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.test.ts
index 50757ed32..ffe684952 100644
--- a/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.test.ts
@@ -29,10 +29,10 @@ vi.mock("@/lib/community/fanout", () => ({
}))
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 })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.ts b/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.ts
index 58dadb708..7dbc12647 100644
--- a/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries, WS_EVENTS } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
-export const DELETE = withAuth(async (_req, ctx) => {
+export const DELETE = withAuth(humanAuthPolicy, async (_req, ctx) => {
const mentionId = ctx.params?.id
if (!mentionId) return writeError("missing mention id", 400)
diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.test.ts b/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.test.ts
index 5865d6c7a..f8af67408 100644
--- a/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.test.ts
@@ -29,10 +29,10 @@ vi.mock("@/lib/community/fanout", () => ({
}))
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 })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.ts b/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.ts
index ea2395bc4..020c5ec3e 100644
--- a/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.ts
@@ -1,10 +1,11 @@
-import { withAuth } from "@/lib/middleware/auth"
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
import { getPrimaryDb } from "@/lib/db"
import { queries, WS_EVENTS } from "@alook/shared"
import { broadcastToUserSafe } from "@/lib/community/fanout"
-export const POST = withAuth(async (_req, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
const result = await queries.communityMention.markAllMentionsReadWithRevision(db, ctx.userId)
if (result.changed) {
diff --git a/src/web/src/app/api/community/users/me/inbox/pull/route.ts b/src/web/src/app/api/community/users/me/inbox/pull/route.ts
index 841388036..835dfae96 100644
--- a/src/web/src/app/api/community/users/me/inbox/pull/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/pull/route.ts
@@ -1,9 +1,10 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { flattenError } from "zod"
import { NextResponse, type NextRequest } from "next/server"
import { queries, withD1Retry, CommunityAgentInboxPullRequestSchema } from "@alook/shared"
import { getDb } from "@/lib/db"
import { log } from "@/lib/logger"
-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"
+import { communityActorPolicy, requireBot } from "@/lib/middleware/community-actor"
const MAX_PULL = 200
@@ -23,7 +24,7 @@ const MAX_PULL = 200
* unread drained fully before the next (`seq` is per-scope). Excludes the bot's
* own authored messages. Never mutates read state — `ack` is the only mutator.
*/
-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
+export const POST = withAuth(communityActorPolicy({ allowInactiveBot: true }), async (req: NextRequest, ctx) => {
const gate = requireBot(ctx.actor)
if (!gate.ok) return gate.response
const { userId: botUserId, isActive } = gate.bot
@@ -111,4 +112,4 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
{ route: "community/users/me/inbox/pull:hydrate" },
)
return NextResponse.json({ messages, hasMore, markedCount })
-}, { allowInactiveBot: true })
+})
diff --git a/src/web/src/app/api/community/users/me/inbox/snapshot/route.ts b/src/web/src/app/api/community/users/me/inbox/snapshot/route.ts
index 2d38d03c6..875c2721d 100644
--- a/src/web/src/app/api/community/users/me/inbox/snapshot/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/snapshot/route.ts
@@ -1,7 +1,8 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse, type NextRequest } from "next/server"
import { queries, withD1Retry } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"
+import { communityActorPolicy, requireBot } from "@/lib/middleware/community-actor"
/**
* GET /api/community/users/me/inbox/snapshot — a non-consuming, bodiless summary
@@ -15,7 +16,7 @@ import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor
* scope is the caller's own userId (`gate.bot.userId`), NO target-user param —
* a bot only ever sees its own inbox summary.
*/
-export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
+export const GET = withAuth(communityActorPolicy({ allowInactiveBot: true }), async (_req: NextRequest, ctx) => {
const gate = requireBot(ctx.actor)
if (!gate.ok) return gate.response
const { userId: botUserId, isActive } = gate.bot
@@ -43,4 +44,4 @@ export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
pendingChannels: rows.length,
pendingMessages: rows.reduce((n, r) => n + r.pendingCount, 0),
})
-}, { allowInactiveBot: true })
+})
diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.test.ts b/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.test.ts
index 4faf957b2..eb523679d 100644
--- a/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.test.ts
@@ -37,10 +37,10 @@ vi.mock("@/lib/community/fanout", () => ({
}))
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 })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.ts b/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.ts
index b03989cae..43386b59e 100644
--- a/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries, WS_EVENTS } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
-export const POST = withAuth(async (_req, ctx) => {
+export const POST = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
// Resolve the viewer's visible channels once (top-level + child threads,
// parent-climbed) and scope the mark-all to them — a private thread under an
diff --git a/src/web/src/app/api/community/users/me/marks/route.test.ts b/src/web/src/app/api/community/users/me/marks/route.test.ts
index cc1784103..4ad4c210a 100644
--- a/src/web/src/app/api/community/users/me/marks/route.test.ts
+++ b/src/web/src/app/api/community/users/me/marks/route.test.ts
@@ -51,24 +51,24 @@ vi.mock("@alook/shared", async () => {
vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: async (_db: unknown, id: string) => ({ ok: true, value: { channel: channelResourceFixture({ id, serverId: "s1", type: id === "c1" ? "thread" : "text", name: id === "c1" ? "general" : "Parent", parentChannelId: id === "c1" ? "parent1" : null, parentMessageId: id === "c1" ? "opener" : null }) } }) }))
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 })
- }),
+ humanAuthPolicy: { resolve: async (req: any) => {
+
+ return ({ context: { env: { DB: {} }, userId: "u1", email: "[email protected]" } })
+ } },
}))
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
+
const bot = req.headers.get("x-test-actor") === "bot"
- return handler(req, {
+ return ({ context: {
env: { DB: {} },
actor: bot
? { kind: "bot", userId: "bot_1", ownerUserId: "u1", machineId: "machine_1" }
: { kind: "human", userId: "u1", email: "[email protected]" },
- params,
- })
- }),
+
+ } })
+ } }),
}))
vi.mock("@/lib/middleware/helpers", () => {
diff --git a/src/web/src/app/api/community/users/me/marks/route.ts b/src/web/src/app/api/community/users/me/marks/route.ts
index 5a618290a..52f8b7ce9 100644
--- a/src/web/src/app/api/community/users/me/marks/route.ts
+++ b/src/web/src/app/api/community/users/me/marks/route.ts
@@ -1,5 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeJSON } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import {
@@ -11,9 +12,6 @@ import {
} from "@alook/shared"
import { parseBoundedInt } from "@/lib/community/messages"
-
-
-
// Cross-channel Marked tab: every message the current user has marked, newest
// first. Scoped to the viewer's visible channels in-query (same guard as the
// Mentions tab) so a mark in a private channel the user has since left never
@@ -21,7 +19,7 @@ import { parseBoundedInt } from "@/lib/community/messages"
// three to navigate: serverId/channelId locate the channel, m.seq jumps to the
// message (a marked message is usually outside the loaded window, so a
// seq-less scroll would silently no-op).
-export const GET = withCommunityActor(async (req, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (req, ctx) => {
const db = getDb(ctx.env.DB)
const userId = ctx.actor.userId
diff --git a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.ts b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.ts
index f04f5300c..1f15ecebb 100644
--- a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.ts
+++ b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.ts
@@ -24,9 +24,7 @@ vi.mock("@alook/shared", async () => {
}
})
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => (req: NextRequest, ctx: any) => handler(req, {
- env: { DB: {} }, userId: "user_1", email: "u@test", params: ctx.params,
- }),
+ humanAuthPolicy: { resolve: async (req: NextRequest) => ({ context: { env: { DB: {} }, userId: "user_1", email: "u@test" } }) },
}))
import { DELETE, PUT } from "./route"
diff --git a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts
index ea8284c34..c0cc241b1 100644
--- a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts
+++ b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts
@@ -1,7 +1,8 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { queries, NOTIFICATION_LEVEL_VALUES, WS_EVENTS } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
import { broadcastToUserSafe } from "@/lib/community/fanout"
@@ -15,7 +16,7 @@ async function broadcastRevision(userId: string, revision: number) {
})
}
-export const PUT = withAuth(async (req: NextRequest, ctx) => {
+export const PUT = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
@@ -45,7 +46,7 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
return writeJSON(result.setting)
})
-export const DELETE = withAuth(async (_req, ctx) => {
+export const DELETE = withAuth(humanAuthPolicy, async (_req, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
diff --git a/src/web/src/app/api/community/users/me/notifications/route.test.ts b/src/web/src/app/api/community/users/me/notifications/route.test.ts
new file mode 100644
index 000000000..ea9ccdb63
--- /dev/null
+++ b/src/web/src/app/api/community/users/me/notifications/route.test.ts
@@ -0,0 +1,34 @@
+import { beforeEach, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const mocks = vi.hoisted(() => ({ resolve: vi.fn(), getSettings: vi.fn(), db: {} }))
+vi.mock("@/lib/middleware/auth", () => ({ humanAuthPolicy: { resolve: mocks.resolve } }))
+vi.mock("@/lib/db", () => ({ getDb: () => mocks.db }))
+vi.mock("@alook/shared", () => ({
+ queries: { communityNotificationSetting: { getSettings: mocks.getSettings } },
+}))
+
+import { GET } from "./route"
+
+const request = () => new NextRequest("http://localhost/api/community/users/me/notifications")
+
+beforeEach(() => vi.resetAllMocks())
+
+it("returns settings for each authenticated user without reusing the previous identity", async () => {
+ const settings = [{ scopeId: "channel-a", muted: true }]
+ mocks.getSettings.mockResolvedValue(settings)
+ for (const userId of ["user-a", "user-b"]) {
+ mocks.resolve.mockResolvedValue({ context: { env: { DB: {} }, userId } })
+ const response = await GET(request())
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual(settings)
+ expect(mocks.getSettings).toHaveBeenLastCalledWith(mocks.db, userId)
+ }
+ expect(mocks.getSettings).toHaveBeenCalledTimes(2)
+})
+
+it("does not read settings when credentials are rejected", async () => {
+ mocks.resolve.mockResolvedValue(new Response(null, { status: 401 }))
+ expect((await GET(request())).status).toBe(401)
+ expect(mocks.getSettings).not.toHaveBeenCalled()
+})
diff --git a/src/web/src/app/api/community/users/me/notifications/route.ts b/src/web/src/app/api/community/users/me/notifications/route.ts
index 26f4fcb2b..9b0d5598b 100644
--- a/src/web/src/app/api/community/users/me/notifications/route.ts
+++ b/src/web/src/app/api/community/users/me/notifications/route.ts
@@ -1,9 +1,10 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
-export const GET = withAuth(async (_req, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const settings = await queries.communityNotificationSetting.getSettings(db, ctx.userId)
return writeJSON(settings)
diff --git a/src/web/src/app/api/community/users/me/notifications/server/[id]/route.test.ts b/src/web/src/app/api/community/users/me/notifications/server/[id]/route.test.ts
index d6bffe552..9384424f3 100644
--- a/src/web/src/app/api/community/users/me/notifications/server/[id]/route.test.ts
+++ b/src/web/src/app/api/community/users/me/notifications/server/[id]/route.test.ts
@@ -24,11 +24,7 @@ vi.mock("@alook/shared", async () => {
}
})
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => (req: NextRequest, ctx: any) => handler(req, {
- env: { DB: {} },
- userId: "user_1",
- params: ctx.params,
- }),
+ humanAuthPolicy: { resolve: async (req: NextRequest) => ({ context: { env: { DB: {} }, userId: "user_1" } }) },
}))
import { PUT } from "./route"
diff --git a/src/web/src/app/api/community/users/me/notifications/server/[id]/route.ts b/src/web/src/app/api/community/users/me/notifications/server/[id]/route.ts
index 0f0b36aeb..7bae4a54d 100644
--- a/src/web/src/app/api/community/users/me/notifications/server/[id]/route.ts
+++ b/src/web/src/app/api/community/users/me/notifications/server/[id]/route.ts
@@ -1,12 +1,13 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { queries, NOTIFICATION_LEVEL_VALUES, WS_EVENTS } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { requireServerMember } from "@/lib/community/permissions"
import { broadcastToUserSafe } from "@/lib/community/fanout"
-export const PUT = withAuth(async (req: NextRequest, ctx) => {
+export const PUT = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
diff --git a/src/web/src/app/api/community/users/me/profile/route.test.ts b/src/web/src/app/api/community/users/me/profile/route.test.ts
index 0e31963d1..bac6fdb69 100644
--- a/src/web/src/app/api/community/users/me/profile/route.test.ts
+++ b/src/web/src/app/api/community/users/me/profile/route.test.ts
@@ -52,16 +52,16 @@ vi.mock("@alook/shared", async () => {
})
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, {
+ communityActorPolicy: () => ({ resolve: async (req: any) => {
+
+ return ({ context: {
env: {},
actor: actorKind === "bot"
? { kind: "bot", userId: "b1", ownerUserId: "u1", machineId: "m1" }
: { kind: "human", userId: "u1", email: "[email protected]" },
- params,
- })
- }),
+
+ } })
+ } }),
}))
vi.mock("@/lib/middleware/helpers", async () => {
diff --git a/src/web/src/app/api/community/users/me/profile/route.ts b/src/web/src/app/api/community/users/me/profile/route.ts
index cfce024c4..af28e00f8 100644
--- a/src/web/src/app/api/community/users/me/profile/route.ts
+++ b/src/web/src/app/api/community/users/me/profile/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest, NextResponse } from "next/server"
import {
queries, parseCommunitySelfProfileRead,
@@ -9,20 +10,20 @@ import {
} from "@alook/shared"
import { getDb } from "@/lib/db"
import { getAuth } from "@/lib/auth"
-import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { communityActorPolicy } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { fanOutProfileUpdate, fanOutStatusUpdate } from "@/lib/community/fanout"
import { canonicalUserImage } from "@/lib/community/storage"
import { readCommunitySelfProfile } from "@/lib/community/self-profile.server"
-export const GET = withCommunityActor(async (_req, ctx) => {
+export const GET = withAuth(communityActorPolicy(), async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const userId = ctx.actor.userId
const self = await readCommunitySelfProfile(db, userId)
return self ? writeJSON(self.profile) : writeError("profile not found", 404)
})
-export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {
+export const PATCH = withAuth(communityActorPolicy(), async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const userId = ctx.actor.userId
diff --git a/src/web/src/app/api/community/users/me/read-state/route.test.ts b/src/web/src/app/api/community/users/me/read-state/route.test.ts
index d7bbf5db4..741205152 100644
--- a/src/web/src/app/api/community/users/me/read-state/route.test.ts
+++ b/src/web/src/app/api/community/users/me/read-state/route.test.ts
@@ -23,11 +23,11 @@ vi.mock("@alook/shared", async () => {
}
})
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => (req: any) => handler(req, {
+ humanAuthPolicy: { resolve: async (req: any) => ({ context: {
env: { DB: {} },
userId: "u1",
- }),
+ } }) },
}))
vi.mock("@/lib/middleware/helpers", () => ({
writeJSON: (data: unknown) => Response.json(data),
diff --git a/src/web/src/app/api/community/users/me/read-state/route.ts b/src/web/src/app/api/community/users/me/read-state/route.ts
index 91a3a8a80..88137d732 100644
--- a/src/web/src/app/api/community/users/me/read-state/route.ts
+++ b/src/web/src/app/api/community/users/me/read-state/route.ts
@@ -1,9 +1,10 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { queries, withD1Retry } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
-export const GET = withAuth(async (_req, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
const snapshot = await withD1Retry(
() => queries.communityReadState.getAccountReadStateSnapshot(db, ctx.userId),
diff --git a/src/web/src/app/api/community/users/me/server-folders/route.test.ts b/src/web/src/app/api/community/users/me/server-folders/route.test.ts
index 5119d64bf..df7abbd5b 100644
--- a/src/web/src/app/api/community/users/me/server-folders/route.test.ts
+++ b/src/web/src/app/api/community/users/me/server-folders/route.test.ts
@@ -8,10 +8,10 @@ vi.mock("@alook/shared", async () => {
return { ...actual, queries: { communityServerFolder: { listFolders } } }
})
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: any) => (request: NextRequest) => handler(request, {
+ humanAuthPolicy: { resolve: async (request: NextRequest) => ({ context: {
userId: "viewer",
env: { DB: {} },
- }),
+ } }) },
}))
import { GET } from "./route"
diff --git a/src/web/src/app/api/community/users/me/server-folders/route.ts b/src/web/src/app/api/community/users/me/server-folders/route.ts
index bbeebc6b6..fe3245755 100644
--- a/src/web/src/app/api/community/users/me/server-folders/route.ts
+++ b/src/web/src/app/api/community/users/me/server-folders/route.ts
@@ -1,10 +1,11 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
import { queries } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
-export const GET = withAuth(async (_req: NextRequest, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (_req: NextRequest, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
return writeJSON(await queries.communityServerFolder.listFolders(db, ctx.userId))
})
diff --git a/src/web/src/app/api/community/users/me/server-rail/route.test.ts b/src/web/src/app/api/community/users/me/server-rail/route.test.ts
index 0c41391c7..f159716e3 100644
--- a/src/web/src/app/api/community/users/me/server-rail/route.test.ts
+++ b/src/web/src/app/api/community/users/me/server-rail/route.test.ts
@@ -30,11 +30,11 @@ vi.mock("@alook/shared", async () => {
}
})
vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any) => handler(req, {
+ humanAuthPolicy: { resolve: async (req: any) => ({ context: {
env: { DB: {} },
userId: "user_1",
- })),
+ } }) },
}))
import { PATCH } from "./route"
diff --git a/src/web/src/app/api/community/users/me/server-rail/route.ts b/src/web/src/app/api/community/users/me/server-rail/route.ts
index 1c99d0298..a23f67077 100644
--- a/src/web/src/app/api/community/users/me/server-rail/route.ts
+++ b/src/web/src/app/api/community/users/me/server-rail/route.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { nanoid } from "nanoid"
import {
MAX_SERVER_RAIL_REQUEST_BYTES,
@@ -8,10 +9,10 @@ import {
} from "@alook/shared"
import { broadcastToUserSafe } from "@/lib/community/fanout"
import { getPrimaryDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
-export const PATCH = withAuth(async (req, ctx) => {
+export const PATCH = withAuth(humanAuthPolicy, async (req, ctx) => {
const rawBody = await req.text()
if (new TextEncoder().encode(rawBody).byteLength > MAX_SERVER_RAIL_REQUEST_BYTES) {
return writeError("request body too large", 413)
diff --git a/src/web/src/app/api/community/users/search/route.test.ts b/src/web/src/app/api/community/users/search/route.test.ts
index 625c65118..82b7c88f0 100644
--- a/src/web/src/app/api/community/users/search/route.test.ts
+++ b/src/web/src/app/api/community/users/search/route.test.ts
@@ -8,8 +8,10 @@ let database: ReturnType<typeof createCommunitySqliteDb>
vi.mock("@/lib/db", () => ({ getDb: () => database.db }))
vi.mock("@/lib/middleware/auth", async () => {
const { protectCommunityJsonResponse } = await import("@/lib/middleware/response-cache")
- return { withAuth: (handler: AuthenticatedHandler) => async (request: NextRequest) => protectCommunityJsonResponse(request,
- await handler(request, { env: { DB: {} } as Env, userId: "viewer", email: "[email protected]" })) }
+ return { humanAuthPolicy: {
+ resolve: async () => ({ context: { env: { DB: {} } as Env, userId: "viewer", email: "[email protected]" } }),
+ respond: protectCommunityJsonResponse,
+ } }
})
import { GET } from "./route"
diff --git a/src/web/src/app/api/community/users/search/route.ts b/src/web/src/app/api/community/users/search/route.ts
index 59a2d577c..4129e0b22 100644
--- a/src/web/src/app/api/community/users/search/route.ts
+++ b/src/web/src/app/api/community/users/search/route.ts
@@ -1,5 +1,6 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import {
@@ -11,7 +12,7 @@ import {
} from "@alook/shared"
import { canonicalUserImage } from "@/lib/community/storage"
-export const GET = withAuth(async (req: NextRequest, ctx) => {
+export const GET = withAuth(humanAuthPolicy, async (req: NextRequest, ctx) => {
const url = new URL(req.url)
const q = url.searchParams.get("q")?.trim()
diff --git a/src/web/src/app/api/email/notify/route.test.ts b/src/web/src/app/api/email/notify/route.test.ts
index 9744a7140..789574e26 100644
--- a/src/web/src/app/api/email/notify/route.test.ts
+++ b/src/web/src/app/api/email/notify/route.test.ts
@@ -1,413 +1,82 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { NextRequest } from "next/server";
-
-const mockGetAgent = vi.fn();
-const mockCreateEmail = vi.fn();
-const mockGetConversation = vi.fn();
-const mockCreateConversation = vi.fn();
-const mockCreateMessage = vi.fn();
-const mockCreateMeetingSession = vi.fn();
-const mockFindByKey = vi.fn();
-const mockCreateMapping = vi.fn();
-const mockEnqueueTask = vi.fn();
-const mockGetUser = vi.fn();
-
-vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
-}));
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
-
-vi.mock("@alook/shared", async () => {
- const actual = await vi.importActual("@alook/shared");
- return {
- ...actual,
- createDb: vi.fn(() => ({})),
- queries: {
- agent: {
- getAgent: (...args: unknown[]) => mockGetAgent(...args),
- },
- email: {
- createEmail: (...args: unknown[]) => mockCreateEmail(...args),
- },
- conversation: {
- getConversation: (...args: unknown[]) => mockGetConversation(...args),
- createConversation: (...args: unknown[]) => mockCreateConversation(...args),
- },
- message: {
- createMessage: (...args: unknown[]) => mockCreateMessage(...args),
- updateMessageTaskId: vi.fn().mockResolvedValue(undefined),
- },
- meetingSession: {
- createMeetingSession: (...args: unknown[]) => mockCreateMeetingSession(...args),
- },
- conversationMap: {
- findByKey: (...args: unknown[]) => mockFindByKey(...args),
- createMapping: (...args: unknown[]) => mockCreateMapping(...args),
- },
- user: {
- getUserSelf: (...args: unknown[]) => mockGetUser(...args),
- },
- },
- };
-});
-
-vi.mock("@/lib/middleware/helpers", async () => {
- const { NextResponse } = require("next/server");
- const actual = await vi.importActual("@/lib/middleware/helpers");
- return {
- ...actual,
- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
- writeError: (msg: string, status: number) => NextResponse.json({ error: msg }, { status }),
- };
-});
-
-vi.mock("@/lib/services/task", () => {
- return {
- TaskService: class {
- enqueueTask(...args: any[]) { return mockEnqueueTask(...args); }
- },
- };
-});
-
-vi.mock("@/lib/broadcast", () => ({
- broadcastToUser: vi.fn().mockResolvedValue(undefined),
-}));
-
-vi.mock("@/lib/api/responses", () => ({
- taskToResponse: (t: unknown) => t,
-}));
-
-import { POST } from "./route";
-
-function makeNotifyReq(body: Record<string, unknown>) {
- return new NextRequest("http://localhost/api/email/notify", {
- method: "POST",
- body: JSON.stringify(body),
- });
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const mocks = vi.hoisted(() => ({
+ agent: vi.fn(), email: vi.fn(), meeting: vi.fn(), broadcast: vi.fn(), invalidate: vi.fn(),
+ conversation: vi.fn(), task: vi.fn(),
+}))
+vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })) }))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@alook/shared", async importOriginal => ({
+ ...await importOriginal<typeof import("@alook/shared")>(),
+ queries: {
+ agent: { getAgent: mocks.agent },
+ email: { createEmail: mocks.email },
+ meetingSession: { createMeetingSession: mocks.meeting },
+ conversation: { createConversation: mocks.conversation },
+ task: { createTask: mocks.task },
+ },
+}))
+vi.mock("@/lib/broadcast", () => ({ broadcastToUser: mocks.broadcast }))
+vi.mock("@/lib/cache", async importOriginal => ({
+ ...await importOriginal<typeof import("@/lib/cache")>(), invalidate: mocks.invalidate,
+}))
+import { POST } from "./route"
+
+const body = {
+ agentId: "a1", workspaceId: "ws1", r2Key: "emails/fixture/raw",
+ from: "[email protected]", to: "[email protected]", subject: "Stored message",
+ isWhitelisted: true, messageId: "<[email protected]>", inReplyTo: "", references: "",
}
-
-const baseBody = {
- agentId: "a1",
- workspaceId: "ws1",
- r2Key: "emails/fake/raw",
- subject: "Test email",
- isWhitelisted: true,
- messageId: "<[email protected]>",
- inReplyTo: "",
- references: "",
-};
-
-describe("POST /api/email/notify", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- mockCreateEmail.mockImplementation((_db: unknown, data: Record<string, unknown>) => Promise.resolve({
- id: "e1",
- fromEmail: data.fromEmail ?? "",
- toEmail: data.toEmail ?? "",
- subject: data.subject ?? "",
- messageId: data.messageId ?? "",
- inReplyTo: data.inReplyTo ?? "",
- references: data.references ?? "",
- agentId: data.agentId ?? "",
- workspaceId: data.workspaceId ?? "",
- }));
- mockCreateMessage.mockResolvedValue({ id: "m1", conversationId: "c1", role: "event", content: "", taskId: null, createdAt: "2026-01-01T00:00:00Z" });
- mockFindByKey.mockResolvedValue(null);
- mockCreateMapping.mockResolvedValue(undefined);
- });
-
- it("creates new conversation when no mapping found", async () => {
- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
- mockCreateConversation.mockResolvedValue({ id: "conv_new" });
- mockEnqueueTask.mockResolvedValue({ id: "t1" });
-
- const res = await POST(makeNotifyReq(baseBody));
- expect(res.status).toBe(200);
-
- expect(mockFindByKey).toHaveBeenCalledWith(
- expect.anything(),
- "email:a1:<[email protected]>",
- "ws1",
- );
- expect(mockCreateConversation).toHaveBeenCalledOnce();
- expect(mockCreateMessage).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({ role: "event" }),
- );
- expect(mockCreateMapping).toHaveBeenCalledWith(expect.anything(), {
- key: "email:a1:<[email protected]>",
- workspaceId: "ws1",
- conversationId: "conv_new",
- });
- expect(mockEnqueueTask).toHaveBeenCalledWith(
- "a1", "conv_new", "ws1",
- expect.any(String),
- "email_notification",
- expect.objectContaining({ contextKey: "conv_new", context: { conversationType: "email_notification", emailId: "e1" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
- );
- });
-
- it("reuses existing conversation when mapping is found (email_notification type)", async () => {
- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
- mockFindByKey.mockResolvedValue("conv_existing");
- mockGetConversation.mockResolvedValue({ id: "conv_existing", type: "email_notification", userId: "u1" });
- mockEnqueueTask.mockResolvedValue({ id: "t1" });
-
- const res = await POST(makeNotifyReq(baseBody));
- expect(res.status).toBe(200);
-
- expect(mockCreateConversation).not.toHaveBeenCalled();
- expect(mockCreateMapping).not.toHaveBeenCalled();
- expect(mockEnqueueTask).toHaveBeenCalledWith(
- "a1", "conv_existing", "ws1",
- expect.any(String),
- "email_notification",
- expect.objectContaining({ contextKey: "conv_existing", context: { conversationType: "email_notification", emailId: "e1" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
- );
- });
-
- // TC4 (the bug): a human replies from their own mail client. Their reply carries
- // In-Reply-To = the wire Message-ID of the agent's original email. Because the worker
- // now puts that SAME id on the wire AND registers it in conversationMap, the inbound
- // lookup keys on In-Reply-To and resolves back to the original conversation — instead
- // of opening a brand-new one (the reported bug).
- it("threads a human reply into the original conversation via In-Reply-To (no new conversation)", async () => {
- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
- const WIRE_ID = "<[email protected]>"; // the id the agent put on the wire + registered
- // The map was registered (on send) keyed on the wire id → the original conversation.
- mockFindByKey.mockImplementation((_db: unknown, key: string) =>
- key === `email:a1:${WIRE_ID}` ? "conv_original" : null,
- );
- mockGetConversation.mockResolvedValue({ id: "conv_original", type: "email_notification", userId: "u1" });
- mockEnqueueTask.mockResolvedValue({ id: "t1" });
-
- const res = await POST(makeNotifyReq({
- ...baseBody,
- messageId: "<[email protected]>", // the human's own new Message-ID
- inReplyTo: WIRE_ID, // points at the agent's wire id
- references: "",
- }));
- expect(res.status).toBe(200);
-
- // Lookup keyed on the In-Reply-To (the wire id), NOT the human's own message id.
- expect(mockFindByKey).toHaveBeenCalledWith(expect.anything(), `email:a1:${WIRE_ID}`, "ws1");
- // Threaded into the original conversation — no new conversation, no new mapping.
- expect(mockCreateConversation).not.toHaveBeenCalled();
- expect(mockCreateMapping).not.toHaveBeenCalled();
- expect(mockEnqueueTask).toHaveBeenCalledWith(
- "a1", "conv_original", "ws1",
- expect.any(String),
- "email_notification",
- expect.objectContaining({ contextKey: "conv_original" }),
- );
- });
-
- it("reuses existing DM conversation and includes dmUser in context", async () => {
- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
- mockFindByKey.mockResolvedValue("conv_dm");
- mockGetConversation.mockResolvedValue({ id: "conv_dm", type: "user_dm_message", userId: "u1" });
- mockGetUser.mockResolvedValue({ id: "u1", name: "Alice", email: "[email protected]" });
- mockEnqueueTask.mockResolvedValue({ id: "t1" });
-
- const res = await POST(makeNotifyReq(baseBody));
- expect(res.status).toBe(200);
-
- expect(mockGetConversation).toHaveBeenCalledWith(expect.anything(), "conv_dm", "ws1");
- expect(mockGetUser).toHaveBeenCalledWith(expect.anything(), "u1");
- expect(mockEnqueueTask).toHaveBeenCalledWith(
- "a1", "conv_dm", "ws1",
- expect.any(String),
- "email_notification",
- expect.objectContaining({ contextKey: "conv_dm", context: { conversationType: "user_dm_message", dmUser: { name: "Alice", email: "[email protected]" }, emailId: "e1" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
- );
- });
-
- it("DM conversation without user still enqueues with conversationType", async () => {
- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
- mockFindByKey.mockResolvedValue("conv_dm");
- mockGetConversation.mockResolvedValue({ id: "conv_dm", type: "user_dm_message", userId: "u1" });
- mockGetUser.mockResolvedValue(null);
- mockEnqueueTask.mockResolvedValue({ id: "t1" });
-
- const res = await POST(makeNotifyReq(baseBody));
- expect(res.status).toBe(200);
-
- expect(mockEnqueueTask).toHaveBeenCalledWith(
- "a1", "conv_dm", "ws1",
- expect.any(String),
- "email_notification",
- expect.objectContaining({ contextKey: "conv_dm", context: { conversationType: "user_dm_message", emailId: "e1" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
- );
- });
-
- it("same thread, two different agents get separate conversations", async () => {
- // Agent A
- mockGetAgent.mockResolvedValueOnce({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
- mockFindByKey.mockResolvedValueOnce(null);
- mockCreateConversation.mockResolvedValueOnce({ id: "conv_a" });
- mockEnqueueTask.mockResolvedValueOnce({ id: "t1" });
-
- await POST(makeNotifyReq(baseBody));
-
- expect(mockFindByKey).toHaveBeenCalledWith(expect.anything(), "email:a1:<[email protected]>", "ws1");
- expect(mockCreateMapping).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
- key: "email:a1:<[email protected]>",
- conversationId: "conv_a",
- }));
-
- vi.clearAllMocks();
- mockCreateEmail.mockImplementation((_db: unknown, data: Record<string, unknown>) => Promise.resolve({
- id: "e2",
- fromEmail: data.fromEmail ?? "",
- toEmail: data.toEmail ?? "",
- subject: data.subject ?? "",
- messageId: data.messageId ?? "",
- inReplyTo: data.inReplyTo ?? "",
- references: data.references ?? "",
- agentId: data.agentId ?? "",
- workspaceId: data.workspaceId ?? "",
- }));
-
- // Agent B - same email thread
- mockGetAgent.mockResolvedValueOnce({ id: "a2", workspaceId: "ws1", runtimeId: "r2", ownerId: "u2" });
- mockFindByKey.mockResolvedValueOnce(null);
- mockCreateConversation.mockResolvedValueOnce({ id: "conv_b" });
- mockEnqueueTask.mockResolvedValueOnce({ id: "t2" });
-
- await POST(makeNotifyReq({ ...baseBody, agentId: "a2" }));
-
- expect(mockFindByKey).toHaveBeenCalledWith(expect.anything(), "email:a2:<[email protected]>", "ws1");
- expect(mockCreateMapping).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
- key: "email:a2:<[email protected]>",
- conversationId: "conv_b",
- }));
- });
-
- it("does not create conversation or task when not whitelisted", async () => {
- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
-
- const res = await POST(makeNotifyReq({ ...baseBody, isWhitelisted: false }));
- expect(res.status).toBe(200);
-
- expect(mockCreateConversation).not.toHaveBeenCalled();
- expect(mockEnqueueTask).not.toHaveBeenCalled();
- expect(mockFindByKey).not.toHaveBeenCalled();
- });
-
- it("does not create conversation or task when agent has no runtime", async () => {
- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: null, ownerId: "u1" });
-
- const res = await POST(makeNotifyReq(baseBody));
- expect(res.status).toBe(200);
-
- expect(mockCreateConversation).not.toHaveBeenCalled();
- expect(mockEnqueueTask).not.toHaveBeenCalled();
- });
-
- it("does not create conversation or task when agent has no ownerId", async () => {
- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: null });
-
- const res = await POST(makeNotifyReq(baseBody));
- expect(res.status).toBe(200);
-
- expect(mockCreateConversation).not.toHaveBeenCalled();
- expect(mockEnqueueTask).not.toHaveBeenCalled();
- expect(mockFindByKey).not.toHaveBeenCalled();
- });
-
- it("returns conversationId in response when whitelisted agent path creates conversation (TC5)", async () => {
- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
- mockCreateConversation.mockResolvedValue({ id: "conv_new" });
- mockEnqueueTask.mockResolvedValue({ id: "t1" });
-
- const res = await POST(makeNotifyReq(baseBody));
- expect(res.status).toBe(200);
-
- const json = await res.json();
- expect(json.conversationId).toBe("conv_new");
- });
-
- it("returns no conversationId for non-whitelisted path (TC6)", async () => {
- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
-
- const res = await POST(makeNotifyReq({ ...baseBody, isWhitelisted: false }));
- expect(res.status).toBe(200);
-
- const json = await res.json();
- expect(json.conversationId).toBeUndefined();
- });
-
- it("stamps targetConversationId in inbound metadata when senderConversationId provided (TC2)", async () => {
- mockGetAgent.mockResolvedValue({ id: "a2", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
- mockCreateConversation.mockResolvedValue({ id: "conv_b" });
- mockEnqueueTask.mockResolvedValue({ id: "t1" });
-
- const res = await POST(makeNotifyReq({
- ...baseBody,
- agentId: "a2",
- isInternal: true,
- senderConversationId: "conv_a",
- senderAgentId: "a1",
- }));
- expect(res.status).toBe(200);
-
- const metadataArg = mockCreateMessage.mock.calls[0]![1] as { metadata: string };
- const parsed = JSON.parse(metadataArg.metadata);
- expect(parsed.targetConversationId).toBe("conv_a");
- expect(parsed.targetAgentId).toBe("a1");
- });
-
- it("does NOT stamp targetConversationId for external emails (TC3)", async () => {
- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
- mockCreateConversation.mockResolvedValue({ id: "conv_ext" });
- mockEnqueueTask.mockResolvedValue({ id: "t1" });
-
- await POST(makeNotifyReq(baseBody));
-
- const metadataArg = mockCreateMessage.mock.calls[0]![1] as { metadata: string };
- const parsed = JSON.parse(metadataArg.metadata);
- expect(parsed.targetConversationId).toBeUndefined();
- expect(parsed.targetAgentId).toBeUndefined();
- });
-
- it("does NOT stamp targetConversationId for self-send (TC16)", async () => {
- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
- mockCreateConversation.mockResolvedValue({ id: "conv_self" });
- mockEnqueueTask.mockResolvedValue({ id: "t1" });
-
- await POST(makeNotifyReq({
- ...baseBody,
- isInternal: true,
- senderConversationId: "conv_a",
- senderAgentId: "a1",
- }));
-
- const metadataArg = mockCreateMessage.mock.calls[0]![1] as { metadata: string };
- const parsed = JSON.parse(metadataArg.metadata);
- expect(parsed.targetConversationId).toBeUndefined();
- expect(parsed.targetAgentId).toBeUndefined();
- });
-
- it("uses References header thread root for mapping lookup", async () => {
- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
- mockFindByKey.mockResolvedValue("conv_thread");
- mockGetConversation.mockResolvedValue({ id: "conv_thread", type: "email_notification", userId: "u1" });
- mockEnqueueTask.mockResolvedValue({ id: "t1" });
-
- const bodyWithRefs = {
- ...baseBody,
- messageId: "<[email protected]>",
- inReplyTo: "<[email protected]>",
- };
-
- await POST(makeNotifyReq(bodyWithRefs));
-
- expect(mockFindByKey).toHaveBeenCalledWith(
- expect.anything(),
- "email:a1:<[email protected]>",
- "ws1",
- );
- });
-});
+const request = (value: unknown) => new NextRequest("http://localhost/api/email/notify", { method: "POST", body: JSON.stringify(value) })
+
+beforeEach(() => {
+ vi.resetAllMocks()
+ mocks.agent.mockResolvedValue({ id: "a1", runtimeId: "old-runtime", ownerId: "owner" })
+ mocks.email.mockResolvedValue({ id: "email-1" })
+ mocks.broadcast.mockResolvedValue(undefined)
+ mocks.invalidate.mockResolvedValue(undefined)
+})
+
+describe("inbound email after legacy execution removal", () => {
+ it.each([true, false])("stores whitelisted=%s email without creating legacy tasks or conversations", async isWhitelisted => {
+ const response = await POST(request({ ...body, isWhitelisted }))
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ ok: true })
+ expect(mocks.email).toHaveBeenCalledWith({}, expect.objectContaining({
+ agentId: "a1", workspaceId: "ws1", r2Key: body.r2Key, fromEmail: body.from,
+ toEmail: body.to, subject: body.subject, messageId: body.messageId, direction: "inbound", isWhitelisted,
+ }))
+ expect(mocks.conversation).not.toHaveBeenCalled()
+ expect(mocks.task).not.toHaveBeenCalled()
+ expect(mocks.broadcast).toHaveBeenCalledWith("owner", { type: "email.received", agentId: "a1" })
+ expect(mocks.invalidate).toHaveBeenCalledTimes(2)
+ })
+
+ it.each([true, false])("retains meeting records for whitelisted=%s mail", async isWhitelisted => {
+ const response = await POST(request({ ...body, isWhitelisted, meetingInfo: {
+ title: "Planning", meetingUrl: "https://meet.example.test/room", startTime: "2026-11-01T10:00:00Z",
+ endTime: null, attendees: [{ name: "Guest", email: "[email protected]" }],
+ } }))
+ expect(response.status).toBe(200)
+ expect(mocks.meeting).toHaveBeenCalledWith({}, expect.objectContaining({
+ agentId: "a1", workspaceId: "ws1", title: "Planning", participants: ["[email protected]"],
+ status: isWhitelisted ? "scheduled" : "pending", isWhitelisted,
+ }))
+ expect(mocks.task).not.toHaveBeenCalled()
+ })
+
+ it("rejects invalid notification input before any data write", async () => {
+ const response = await POST(request({ agentId: "a1" }))
+ expect(response.status).toBe(400)
+ expect(mocks.email).not.toHaveBeenCalled()
+ expect(mocks.task).not.toHaveBeenCalled()
+ })
+
+ it("retains mail storage when the old agent lookup has no result", async () => {
+ mocks.agent.mockResolvedValue(null)
+ expect((await POST(request(body))).status).toBe(200)
+ expect(mocks.email).toHaveBeenCalledOnce()
+ expect(mocks.broadcast).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/email/notify/route.ts b/src/web/src/app/api/email/notify/route.ts
index 89386f37e..bbfc86798 100644
--- a/src/web/src/app/api/email/notify/route.ts
+++ b/src/web/src/app/api/email/notify/route.ts
@@ -5,7 +5,6 @@ import { withEnv } from "@/lib/middleware/env"
import { writeJSON, parseBody } from "@/lib/middleware/helpers"
import { broadcastToUser } from "@/lib/broadcast"
import { invalidate, cacheKeys } from "@/lib/cache"
-import { dispatchEmailToAgent } from "@/lib/services/email-dispatch"
export const POST = withEnv(async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
@@ -15,7 +14,7 @@ export const POST = withEnv(async (req: NextRequest, ctx) => {
const agent = await queries.agent.getAgent(db, body.agentId, body.workspaceId)
- const email = await queries.email.createEmail(db, {
+ await queries.email.createEmail(db, {
agentId: body.agentId,
workspaceId: body.workspaceId,
fromEmail: body.from,
@@ -46,19 +45,6 @@ export const POST = withEnv(async (req: NextRequest, ctx) => {
})
}
- let conversationId: string | null = null;
-
- if (body.isWhitelisted && agent && agent.runtimeId && agent.ownerId) {
- const result = await dispatchEmailToAgent(db, email, agent, {
- isInternal: body.isInternal,
- senderConversationId: body.senderConversationId,
- senderAgentId: body.senderAgentId,
- traceId: body.traceId,
- sourceTaskId: body.sourceTaskId,
- })
- conversationId = result.conversationId
- }
-
const dateStr = new Date().toISOString().slice(0, 10);
await Promise.all([
invalidate(cacheKeys.overviewEmailStats(body.workspaceId)),
@@ -69,5 +55,5 @@ export const POST = withEnv(async (req: NextRequest, ctx) => {
broadcastToUser(agent.ownerId, { type: "email.received", agentId: body.agentId }).catch(() => {})
}
- return writeJSON({ ok: true, ...(conversationId ? { conversationId } : {}) })
+ return writeJSON({ ok: true })
});
diff --git a/src/web/src/app/api/meeting/callback/route.test.ts b/src/web/src/app/api/meeting/callback/route.test.ts
deleted file mode 100644
index 85534f8a8..000000000
--- a/src/web/src/app/api/meeting/callback/route.test.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { NextRequest } from "next/server";
-
-const mockGetMeetingSession = vi.fn();
-const mockUpdateMeetingSession = vi.fn();
-const mockGetAgent = vi.fn();
-const mockGetEmailByMessageId = vi.fn();
-const mockBucketPut = vi.fn();
-const mockSelfRefFetch = vi.fn();
-
-vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(() => ({
- env: {
- DB: {},
- EMAIL_BUCKET: { put: (...args: unknown[]) => mockBucketPut(...args) },
- WORKER_SELF_REFERENCE: { fetch: (...args: unknown[]) => mockSelfRefFetch(...args) },
- },
- })),
-}));
-
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
-
-vi.mock("@alook/shared", async () => {
- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
- return {
- ...real,
- queries: {
- meetingSession: {
- getMeetingSession: (...args: unknown[]) => mockGetMeetingSession(...args),
- updateMeetingSession: (...args: unknown[]) => mockUpdateMeetingSession(...args),
- },
- agent: {
- getAgent: (...args: unknown[]) => mockGetAgent(...args),
- },
- email: {
- getEmailByMessageId: (...args: unknown[]) => mockGetEmailByMessageId(...args),
- },
- },
- };
-});
-
-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: {}, EMAIL_BUCKET: { put: (...args: unknown[]) => mockBucketPut(...args) }, WORKER_SELF_REFERENCE: { fetch: (...args: unknown[]) => mockSelfRefFetch(...args) } }, userId: "u1", email: "[email protected]", workspaceId: "w1", params });
- }),
-}));
-
-vi.mock("@/lib/middleware/helpers", async () =>
- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")
-);
-
-vi.mock("@/lib/logger", () => ({
- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },
-}));
-
-vi.mock("nanoid", () => ({ nanoid: () => "test-nanoid-123", customAlphabet: () => () => "test-nanoid-123" }));
-
-import { POST } from "./route";
-
-function postReq(body: unknown) {
- return new NextRequest("http://localhost/api/meeting/callback", {
- method: "POST",
- body: JSON.stringify(body),
- headers: { "Content-Type": "application/json" },
- });
-}
-
-describe("POST /api/meeting/callback", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- mockBucketPut.mockResolvedValue(undefined);
- mockSelfRefFetch.mockResolvedValue(new Response(JSON.stringify({ ok: true })));
- });
-
- it("stores MIME email in R2 and calls email notify on completed meeting", async () => {
- mockGetMeetingSession.mockResolvedValue({
- id: "ms1",
- agentId: "a1",
- workspaceId: "w1",
- title: "Weekly",
- meetingUrl: "https://meet.google.com/abc",
- participants: ["[email protected]"],
- });
- mockUpdateMeetingSession.mockResolvedValue({
- id: "ms1", status: "completed", transcriptR2Key: "meetings/ms1/transcript",
- });
- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "jarvis", workspaceId: "w1" });
- mockGetEmailByMessageId.mockResolvedValue(null);
-
- const res = await POST(postReq({
- meetingId: "ms1",
- workspaceId: "w1",
- status: "completed",
- transcript: "[00:01] Alice: Hello",
- }));
-
- expect(res.status).toBe(200);
-
- // Should store raw transcript
- expect(mockBucketPut).toHaveBeenCalledWith(
- "meetings/ms1/transcript",
- "[00:01] Alice: Hello",
- { httpMetadata: { contentType: "text/plain" } },
- );
-
- // Should store MIME email at emails/{nanoid}/raw
- const mimeCall = mockBucketPut.mock.calls.find(
- (c: unknown[]) => (c[0] as string).startsWith("emails/")
- );
- expect(mimeCall).toBeDefined();
- expect(mimeCall![0]).toBe("emails/test-nanoid-123/raw");
- const mimeContent = mimeCall![1] as string;
- expect(mimeContent).toContain("From: [email protected]");
- expect(mimeContent).toContain("To: [email protected]");
- expect(mimeContent).toContain("Subject: Meeting completed: Weekly");
- expect(mimeContent).toContain("MIME-Version: 1.0");
- expect(mimeContent).toContain("Content-Type: text/plain; charset=utf-8");
- expect(mimeContent).toContain("Meeting \"Weekly\" has ended.");
- expect(mimeContent).toContain("Please summarize this meeting");
- expect(mimeContent).toContain("[00:01] Alice: Hello");
-
- // Should call email notify with correct r2Key
- expect(mockSelfRefFetch).toHaveBeenCalledTimes(1);
- const notifyBody = JSON.parse(
- (mockSelfRefFetch.mock.calls[0][1] as RequestInit).body as string
- );
- expect(notifyBody.r2Key).toBe("emails/test-nanoid-123/raw");
- expect(notifyBody.from).toBe("[email protected]");
- expect(notifyBody.to).toBe("[email protected]");
- expect(notifyBody.subject).toContain("Meeting completed: Weekly");
- expect(notifyBody.isWhitelisted).toBe(true);
- expect(notifyBody.messageId).toBe("<[email protected]>");
- });
-
- it("skips email notify when agent has no emailHandle", async () => {
- mockGetMeetingSession.mockResolvedValue({
- id: "ms2", agentId: "a2", workspaceId: "w1", title: "Test", meetingUrl: "https://meet.google.com/xyz", participants: [],
- });
- mockUpdateMeetingSession.mockResolvedValue({ id: "ms2", status: "completed" });
- mockGetAgent.mockResolvedValue({ id: "a2", emailHandle: null, workspaceId: "w1" });
-
- const res = await POST(postReq({
- meetingId: "ms2",
- workspaceId: "w1",
- status: "completed",
- transcript: "some transcript",
- }));
-
- expect(res.status).toBe(200);
- expect(mockSelfRefFetch).not.toHaveBeenCalled();
- // Only one put: the raw transcript, no MIME email
- expect(mockBucketPut).toHaveBeenCalledTimes(1);
- expect(mockBucketPut.mock.calls[0][0]).toBe("meetings/ms2/transcript");
- });
-
- it("skips email notify on failed meeting", async () => {
- mockGetMeetingSession.mockResolvedValue({
- id: "ms3", agentId: "a1", workspaceId: "w1", title: "Fail", meetingUrl: "https://meet.google.com/abc", participants: [],
- });
- mockUpdateMeetingSession.mockResolvedValue({ id: "ms3", status: "failed" });
-
- const res = await POST(postReq({
- meetingId: "ms3",
- workspaceId: "w1",
- status: "failed",
- error: "Chrome crashed",
- }));
-
- expect(res.status).toBe(200);
- expect(mockGetAgent).not.toHaveBeenCalled();
- expect(mockSelfRefFetch).not.toHaveBeenCalled();
- });
-
- it("dedup: skips email notify if messageId already exists", async () => {
- mockGetMeetingSession.mockResolvedValue({
- id: "ms4", agentId: "a1", workspaceId: "w1", title: "Dup", meetingUrl: "https://meet.google.com/abc", participants: [],
- });
- mockUpdateMeetingSession.mockResolvedValue({ id: "ms4", status: "completed" });
- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "jarvis", workspaceId: "w1" });
- mockGetEmailByMessageId.mockResolvedValue({ id: "existing-email" });
-
- const res = await POST(postReq({
- meetingId: "ms4",
- workspaceId: "w1",
- status: "completed",
- transcript: "duplicate test",
- }));
-
- expect(res.status).toBe(200);
- expect(mockSelfRefFetch).not.toHaveBeenCalled();
- // Only raw transcript stored, no MIME email
- expect(mockBucketPut).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/src/web/src/app/api/meeting/callback/route.ts b/src/web/src/app/api/meeting/callback/route.ts
deleted file mode 100644
index ad2ce3bf6..000000000
--- a/src/web/src/app/api/meeting/callback/route.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { NextRequest } from "next/server"
-import { nanoid } from "nanoid"
-import { queries, MeetingStatus, DEV_WEB_URL, buildMimeMessage, toAlookAddress } from "@alook/shared"
-import { withAuth } from "@/lib/middleware/auth"
-import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { getDb } from "@/lib/db"
-import { log } from "@/lib/logger"
-
-export const POST = withAuth(async (req: NextRequest, ctx) => {
- const cfEnv = ctx.env
- const db = getDb(cfEnv.DB)
-
- if (!ctx.workspaceId) {
- return writeError("Forbidden: machine token required", 403)
- }
-
- let body: {
- meetingId?: string
- workspaceId?: string
- status?: "completed" | "failed"
- transcript?: string
- error?: string
- }
- try {
- body = await req.json() as typeof body
- } catch {
- return writeError("invalid request body", 400)
- }
-
- if (!body.meetingId || !body.workspaceId || !body.status) {
- return writeError("meetingId, workspaceId, and status are required", 400)
- }
-
- if (body.workspaceId !== ctx.workspaceId) {
- return writeError("workspace mismatch", 403)
- }
-
- const meeting = await queries.meetingSession.getMeetingSession(
- db,
- body.meetingId,
- body.workspaceId
- )
- if (!meeting) return writeError("meeting not found", 404)
-
- let transcriptR2Key: string | undefined
- if (body.transcript) {
- transcriptR2Key = `meetings/${body.meetingId}/transcript`
- await cfEnv.EMAIL_BUCKET.put(transcriptR2Key, body.transcript, {
- httpMetadata: { contentType: "text/plain" },
- })
- }
-
- const updated = await queries.meetingSession.updateMeetingSession(
- db,
- body.meetingId,
- body.workspaceId,
- {
- status: body.status === "completed" ? MeetingStatus.COMPLETED : MeetingStatus.FAILED,
- completedAt: new Date().toISOString(),
- transcriptR2Key,
- error: body.error,
- }
- )
-
- if (body.status === "completed" && body.transcript) {
- const agent = await queries.agent.getAgent(db, meeting.agentId, body.workspaceId)
-
- if (agent?.emailHandle) {
- const messageId = `<meeting-${body.meetingId}@alook.ai>`
- const existing = await queries.email.getEmailByMessageId(db, messageId, body.workspaceId)
- if (!existing) {
- const fromAddr = toAlookAddress("no-reply")
- const toAddr = toAlookAddress(agent.emailHandle)
- const meetingTitle = meeting.title || "Untitled"
- const subject = `Meeting completed: ${meetingTitle} — please summarize`
-
- const emailBody = [
- `Meeting "${meetingTitle}" has ended. The transcript is below.`,
- `Transcript R2 key: ${transcriptR2Key}`,
- "",
- "Please summarize this meeting and send the summary to the owner.",
- "",
- "--- Transcript ---",
- "",
- body.transcript,
- ].join("\n")
-
- const rawMime = buildMimeMessage({
- from: fromAddr,
- to: toAddr,
- subject,
- messageId,
- body: emailBody,
- bodyType: "text/plain",
- })
-
- const emailR2Key = `emails/${nanoid()}/raw`
- await cfEnv.EMAIL_BUCKET.put(emailR2Key, rawMime, {
- httpMetadata: { contentType: "message/rfc822" },
- })
-
- const notifyPayload = JSON.stringify({
- agentId: agent.id,
- workspaceId: body.workspaceId,
- r2Key: emailR2Key,
- from: fromAddr,
- to: toAddr,
- subject,
- isWhitelisted: true,
- forwarded: false,
- messageId,
- inReplyTo: "",
- references: "",
- })
- const notifyInit: RequestInit = {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: notifyPayload,
- }
-
- try {
- await cfEnv.WORKER_SELF_REFERENCE!.fetch("http://internal/api/email/notify", notifyInit)
- } catch {
- try {
- await fetch(`${DEV_WEB_URL}/api/email/notify`, notifyInit)
- } catch (e) {
- log.warn("meeting-callback: email notify failed", { err: String(e) })
- }
- }
- }
- }
- }
-
- return writeJSON({ ok: true, meeting: updated })
-})
diff --git a/src/web/src/app/api/privacy/analytics-consent/route.test.ts b/src/web/src/app/api/privacy/analytics-consent/route.test.ts
index 86b4360f0..45401dd30 100644
--- a/src/web/src/app/api/privacy/analytics-consent/route.test.ts
+++ b/src/web/src/app/api/privacy/analytics-consent/route.test.ts
@@ -9,8 +9,7 @@ const mocks = vi.hoisted(() => ({
}))
vi.mock("@/lib/middleware/auth", () => ({
- withOptionalAuth: (handler: (request: NextRequest, context: { env: typeof mocks.env; userId?: string }) => Promise<Response>) =>
- (request: NextRequest) => handler(request, { env: mocks.env, userId: mocks.userId }),
+ optionalAuthPolicy: { resolve: async (request: NextRequest) => ({ context: { env: mocks.env, userId: mocks.userId } }) },
}))
vi.mock("@/lib/db", () => ({ getPrimaryDb: () => mocks.env.DB }))
vi.mock("@alook/shared", async original => ({ ...await original<typeof import("@alook/shared")>(), queries: { billing: { recordAnalyticsConsent: mocks.recordAnalyticsConsent } } }))
diff --git a/src/web/src/app/api/privacy/analytics-consent/route.ts b/src/web/src/app/api/privacy/analytics-consent/route.ts
index 60d2e363b..4bae61e70 100644
--- a/src/web/src/app/api/privacy/analytics-consent/route.ts
+++ b/src/web/src/app/api/privacy/analytics-consent/route.ts
@@ -1,6 +1,7 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { NextResponse, type NextRequest } from "next/server"
import { queries } from "@alook/shared"
-import { withOptionalAuth } from "@/lib/middleware/auth"
+import { optionalAuthPolicy } from "@/lib/middleware/auth"
import { getPrimaryDb } from "@/lib/db"
import {
ANALYTICS_CONSENT_COOKIE,
@@ -11,7 +12,6 @@ import {
} from "@/lib/analytics-consent"
import { createAnalyticsConsentProof } from "@/lib/analytics-consent-server"
-
function sameOriginUrl(request: NextRequest): URL | null {
const origin = request.headers.get("Origin")
if (!origin) return null
@@ -37,7 +37,7 @@ function parseDecision(value: unknown): AnalyticsConsentDecision | null {
return decision === "granted" || decision === "denied" ? decision : null
}
-export const POST = withOptionalAuth(async (request, ctx) => {
+export const POST = withAuth(optionalAuthPolicy, async (request, ctx) => {
const origin = sameOriginUrl(request)
if (!origin) {
return NextResponse.json({ error: "forbidden" }, { status: 403 })
diff --git a/src/web/src/app/device/page.tsx b/src/web/src/app/device/page.tsx
deleted file mode 100644
index 273432b73..000000000
--- a/src/web/src/app/device/page.tsx
+++ /dev/null
@@ -1,193 +0,0 @@
-"use client"
-
-import { useObservedRegion } from "@/lib/observability/regions"
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { Suspense, useEffect } from "react"
-import { useQuery, useMutation } from "@tanstack/react-query"
-import { PublicQueryProvider, applicationKey, captureApplicationOwner, assertApplicationOwner } from "@/lib/application-owner"
-import { useApplicationViewSource } from "@/hooks/use-application-view-source"
-import { useSearchParams, useRouter } from "next/navigation"
-import { authClient, useSession } from "@/lib/auth-client"
-import { Button } from "@/components/ui/button"
-import { Card, CardContent } from "@/components/ui/card"
-import { Input } from "@/components/ui/input"
-import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
-import { GradientBackground } from "@/components/gradient-background"
-
-type Step = "loading" | "code" | "approve" | "done" | "denied"
-
-export default function DeviceAuthPage() {
- return (
- <Suspense>
- <PublicQueryProvider><DeviceAuthPageInner /></PublicQueryProvider>
- </Suspense>
- )
-}
-
-function DeviceAuthPageInner() {
- const searchParams = useSearchParams()
- const router = useRouter()
- const { data: session, isPending } = useSession()
-
- const urlCode = searchParams.get("user_code") || ""
- const [userCode, setUserCode] = useAtom(useCreateAtom(urlCode))
- const [verificationCode, setVerificationCode] = useAtom(useCreateAtom(urlCode.trim()))
- const source = useApplicationViewSource(`device:${verificationCode}`)
- const { owner } = source
- const verification = useQuery({
- queryKey: applicationKey(owner, "device-verification", verificationCode),
- enabled: !!verificationCode && !!session && !isPending, subscribed: !!verificationCode && !!session && !isPending, retry: false, gcTime: 0,
- queryFn: async ({ signal }) => {
- const token = captureApplicationOwner(owner)
- assertApplicationOwner(token, signal)
- try {
- const res = await authClient.device({ query: { user_code: verificationCode }, fetchOptions: { signal } })
- assertApplicationOwner(token, signal)
- if (res.error) throw new Error(res.error.error_description || "Invalid or expired code")
- return true
- } catch (error) { assertApplicationOwner(token, signal); throw error }
- },
- })
- const command = useMutation({ meta: { observabilityAction: "device.authorization.command" },
- mutationKey: applicationKey(owner, "device-decision"),
- scope: { id: JSON.stringify(applicationKey(owner, "device-decision")) },
- mutationFn: async ({ kind, code, original }: { kind: "approve" | "deny"; code: string; original: ReturnType<typeof source.capture> }) => {
- original.assert()
- try {
- const options = { signal: original.signal, onRequest: () => original.assert(), onSuccess: () => original.assert(), onError: () => original.assert() }
- const res = kind === "approve" ? await authClient.device.approve({ userCode: code, fetchOptions: options }) : await authClient.device.deny({ userCode: code, fetchOptions: options })
- original.assert()
- if (res.error) throw new Error(res.error.error_description || `Failed to ${kind} device`)
- return kind
- } catch (error) { original.assert(); throw error }
- },
- })
- const currentDecision = command.variables?.code === verificationCode ? command : null
- const loading = verification.isFetching || !!currentDecision?.isPending
- const failure = currentDecision?.error ?? verification.error
- const error = failure instanceof DOMException && failure.name === "AbortError" ? "" : failure instanceof Error ? failure.message : ""
- const step: Step = currentDecision?.isSuccess ? currentDecision.data === "approve" ? "done" : "denied"
- : verification.isFetching ? "loading" : verification.isSuccess ? "approve" : "code"
-
- useObservedRegion("page", !isPending && !!session && step !== "loading", 1)
- useEffect(() => {
- if (!isPending && !session) {
- const original = source.capture()
- original.assert()
- const callbackUrl = `/device${userCode ? `?user_code=${encodeURIComponent(userCode)}` : ""}`
- router.push(`/sign-in?redirect=${encodeURIComponent(callbackUrl)}`)
- }
- }, [isPending, session, router, userCode, source])
-
- const handleVerifyCode = (e: React.SubmitEvent) => {
- e.preventDefault()
- const code = userCode.trim()
- command.reset()
- if (code === verificationCode) void verification.refetch({ cancelRefetch: false })
- else setVerificationCode(code)
- }
- const handleApprove = () => command.mutate({ kind: "approve", code: verificationCode, original: source.capture() })
- const handleDeny = () => command.mutate({ kind: "deny", code: verificationCode, original: source.capture() })
-
- if (isPending || !session) {
- return null
- }
-
- return (
- <div className="relative flex min-h-svh flex-col items-center justify-center p-6 sm:p-10">
- <GradientBackground />
- <div className="w-full max-w-sm">
- <Card>
- <CardContent className="p-6">
- <FieldGroup>
- <div className="flex flex-col items-center gap-2 text-center">
- <h1 className="text-2xl font-bold">Authorize Device</h1>
- {step === "loading" && (
- <p className="text-sm text-muted-foreground">
- Verifying...
- </p>
- )}
- {step === "code" && (
- <p className="text-sm text-muted-foreground">
- Enter the code shown on your terminal
- </p>
- )}
- {step === "approve" && (
- <p className="text-sm text-muted-foreground">
- A device is requesting access to your account
- </p>
- )}
- </div>
-
- {error && <FieldError>{error}</FieldError>}
-
- {step === "loading" && (
- <div className="flex justify-center py-4">
- <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
- </div>
- )}
-
- {step === "code" && (
- <form onSubmit={handleVerifyCode}>
- <FieldGroup>
- <Field>
- <FieldLabel htmlFor="user_code">Device Code</FieldLabel>
- <Input
- id="user_code"
- type="text"
- placeholder="XXXX-XXXX"
- value={userCode}
- onChange={(e) => setUserCode(e.target.value.toUpperCase())}
- required
- autoFocus
- className="text-center text-lg tracking-widest font-mono"
- />
- </Field>
- <Field>
- <Button type="submit" disabled={loading || !userCode.trim()} className="w-full">
- {loading ? "Verifying..." : "Verify Code"}
- </Button>
- </Field>
- </FieldGroup>
- </form>
- )}
-
- {step === "approve" && (
- <FieldGroup>
- <p className="text-sm text-center text-muted-foreground">
- Code: <strong className="font-mono">{userCode}</strong>
- </p>
- <Field className="grid grid-cols-2 gap-4">
- <Button variant="outline" onClick={handleDeny} disabled={loading}>
- Deny
- </Button>
- <Button onClick={handleApprove} disabled={loading}>
- {loading ? "Approving..." : "Approve"}
- </Button>
- </Field>
- </FieldGroup>
- )}
-
- {step === "done" && (
- <div className="text-center space-y-2">
- <p className="text-sm font-medium text-green-600">✓ Device authorized</p>
- <p className="text-sm text-muted-foreground">
- You can close this tab. The CLI will continue automatically.
- </p>
- </div>
- )}
-
- {step === "denied" && (
- <div className="text-center space-y-2">
- <p className="text-sm text-muted-foreground">
- Device access denied. You can close this window.
- </p>
- </div>
- )}
- </FieldGroup>
- </CardContent>
- </Card>
- </div>
- </div>
- )
-}
diff --git a/src/web/src/app/onboard.md/route.test.ts b/src/web/src/app/onboard.md/route.test.ts
deleted file mode 100644
index 6f1646430..000000000
--- a/src/web/src/app/onboard.md/route.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { describe, it, expect, afterEach } from "vitest";
-import { GET } from "./route";
-
-describe("GET /onboard.md", () => {
- const origAppUrl = process.env.NEXT_PUBLIC_APP_URL;
- const origServerUrl = process.env.ALOOK_SERVER_URL;
- const origCmdPrefix = process.env.ALOOK_CMD_PREFIX;
- const origNodeEnv = process.env.NODE_ENV;
-
- afterEach(() => {
- restoreEnv("NEXT_PUBLIC_APP_URL", origAppUrl);
- restoreEnv("ALOOK_SERVER_URL", origServerUrl);
- restoreEnv("ALOOK_CMD_PREFIX", origCmdPrefix);
- restoreEnv("NODE_ENV", origNodeEnv);
- });
-
- function restoreEnv(key: string, val: string | undefined) {
- if (val === undefined) delete process.env[key];
- else process.env[key] = val;
- }
-
- it("returns 200 with Content-Type text/markdown", async () => {
- const response = await GET();
- expect(response.status).toBe(200);
- expect(response.headers.get("Content-Type")).toBe("text/markdown; charset=utf-8");
- });
-
- it("uses npx @alook/cli and alook.ai URLs in production mode", async () => {
- delete process.env.NEXT_PUBLIC_APP_URL;
- delete process.env.ALOOK_SERVER_URL;
- delete process.env.ALOOK_CMD_PREFIX;
- process.env.NODE_ENV = "production";
- const response = await GET();
- const body = await response.text();
- expect(body).toContain("npx @alook/cli login");
- expect(body).toContain("https://alook.ai/templates");
- expect(body).toContain("https://alook.ai/c/me");
- expect(body).toContain("workspace init --json-file");
- expect(body).toContain("old workspace web interface has been retired");
- expect(body).not.toContain("/w/{slug}/home");
- });
-
- it("uses localhost in development mode when no URLs are set", async () => {
- delete process.env.NEXT_PUBLIC_APP_URL;
- delete process.env.ALOOK_SERVER_URL;
- delete process.env.ALOOK_CMD_PREFIX;
- process.env.NODE_ENV = "development";
- const response = await GET();
- const body = await response.text();
- expect(body).toContain("pnpm dev:cli login");
- expect(body).toContain("http://localhost:3000/templates");
- });
-
- it("uses npx @alook/app cli for self-hosted (app mode)", async () => {
- process.env.NEXT_PUBLIC_APP_URL = "http://localhost:15210";
- process.env.ALOOK_CMD_PREFIX = "npx @alook/app cli";
- delete process.env.ALOOK_SERVER_URL;
- process.env.NODE_ENV = "production";
- const response = await GET();
- const body = await response.text();
- expect(body).toContain("npx @alook/app cli login");
- expect(body).toContain("http://localhost:15210/templates");
- expect(body).toContain("http://localhost:15210/c/me");
- });
-});
diff --git a/src/web/src/app/onboard.md/route.ts b/src/web/src/app/onboard.md/route.ts
deleted file mode 100644
index d2243c1fe..000000000
--- a/src/web/src/app/onboard.md/route.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import { resolveMode, cliCommand, getBaseUrl } from "@alook/shared";
-import { NextResponse } from "next/server";
-
-function buildOnboardMarkdown(baseUrl: string, cliPrefix: string): string {
- return `---
-name: alook-onboard
-description: Install Alook CLI, authenticate, and set up your AI workspace.
-keywords: [alook, agent, workspace, CLI, onboarding]
----
-
-## 1. Login
-
-\`\`\`bash
-${cliPrefix} login
-\`\`\`
-
-- Non-interactive terminal: prints a URL for the user to open manually, then polls until confirmed
-- Interactive terminal: attempts to open browser automatically
-- Verify success: \`${cliPrefix} status\`
-
-## 2. Start Daemon
-
-\`\`\`bash
-${cliPrefix} daemon start
-\`\`\`
-
-The daemon must be running before initializing a workspace (workspace init requires active runtimes).
-
-## 3. Reflect on Your User
-
-Review your conversation history with this user. Summarize:
-- Their role and domain
-- Tech stack and tools they use
-- Daily workflow and preferences
-- Types of tasks they frequently work on
-
-Use this understanding to choose the best workspace setup.
-
-## 4. Explore Templates & Set Up Workspace
-
-Visit ${baseUrl}/templates to explore available workspace templates.
-Each template has a JSON version at \`/templates/<slug>/json\` you can fetch for reference.
-
-Based on what you learned about the user in Step 3, customize the template or create your own configuration:
-
-\`\`\`json
-{
- "name": "Workspace Name",
- "members": [
- {
- "role": "leader",
- "description": "Coordinates tasks and delegates",
- "instructions": "System prompt for this agent"
- },
- {
- "role": "engineer",
- "description": "Implements features and fixes bugs",
- "instructions": "System prompt for this agent",
- "relationship": "When/how to delegate to this agent and how they report back"
- }
- ]
-}
-\`\`\`
-
-Write your customized JSON to a file, then run:
-
-\`\`\`bash
-${cliPrefix} workspace init --json-file <path_to_json>
-\`\`\`
-
-If the current workspace already has agents, a new workspace is created automatically.
-
-Workspace commands remain available in the CLI. The old workspace web interface has been retired.
-
-Open the community at ${baseUrl}/c/me. Public template JSON remains available for reference.
-`;
-}
-
-export async function GET() {
- const baseUrl = getBaseUrl({
- serverUrl: process.env.ALOOK_SERVER_URL,
- appUrl: process.env.NEXT_PUBLIC_APP_URL,
- nodeEnv: process.env.NODE_ENV,
- });
- const mode = resolveMode({
- serverUrl: process.env.ALOOK_SERVER_URL,
- cmdPrefix: process.env.ALOOK_CMD_PREFIX,
- nodeEnv: process.env.NODE_ENV,
- });
- const cliPrefix = cliCommand(mode);
-
- return new NextResponse(buildOnboardMarkdown(baseUrl, cliPrefix), {
- headers: {
- "Content-Type": "text/markdown; charset=utf-8",
- },
- });
-}
diff --git a/src/web/src/components/home/hero-brand.dom.test.tsx b/src/web/src/components/home/hero-brand.dom.test.tsx
index 72e90b383..c00375b5a 100644
--- a/src/web/src/components/home/hero-brand.dom.test.tsx
+++ b/src/web/src/components/home/hero-brand.dom.test.tsx
@@ -16,7 +16,7 @@ it("reveals the home-logo faces over the combined hero brand and restores them o
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
}));
- render(<HeroSection isLoggedIn={false} showClipboard={false} showCommunityLinks={false} />);
+ render(<HeroSection isLoggedIn={false} showCommunityLinks={false} />);
const brand = screen.getByRole("link", { name: "Alook home" });
const logo = screen.getByRole("img", { name: "Alook" });
expect(logo.parentElement).toBe(brand);
diff --git a/src/web/src/components/home/hero-section.tsx b/src/web/src/components/home/hero-section.tsx
index 387ff8a5e..20a4ea255 100644
--- a/src/web/src/components/home/hero-section.tsx
+++ b/src/web/src/components/home/hero-section.tsx
@@ -3,7 +3,6 @@
import { DISCORD_INVITE_URL } from "@/lib/discord-invite"
/* eslint-disable @next/next/no-html-link-for-pages -- Product entrances require a new document to unload public tracking. */
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { useCallback, useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
import Link from "next/link";
import { TypewriterVisual } from "@/components/typewriter-visual";
@@ -21,7 +20,6 @@ export function HeroSection({
kicker,
headline = "Run Your Personal Company",
subline,
- showClipboard = true,
showCommunityLinks = true,
primaryCtaLabel,
secondaryCta,
@@ -42,7 +40,6 @@ export function HeroSection({
kicker?: string;
headline?: ReactNode;
subline?: ReactNode;
- showClipboard?: boolean;
showCommunityLinks?: boolean;
primaryCtaLabel?: string;
secondaryCta?: HeroSecondaryCta | null;
@@ -82,7 +79,6 @@ export function HeroSection({
}
};
}, [onReady, paperSettled]);
- const [copied, setCopied] = useAtom(useCreateAtom(false));
const ctaSizingClassName = largeCtas
? "px-3 py-3 text-[clamp(0.6875rem,3vw,1rem)] whitespace-nowrap sm:px-8"
: "px-6 py-2 text-sm";
@@ -180,69 +176,6 @@ export function HeroSection({
</div>
</div>
- {/* Clipboard copy widget */}
- {showClipboard && <div
- className="hero-clipboard relative mt-8 shrink-0 w-full max-w-lg cursor-pointer"
- onClick={() => {
- navigator.clipboard.writeText(
- `Read ${window.location.origin}/onboard.md and follow the instructions to install and configure Alook`
- );
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- }}
- >
- {/* Floating badge label */}
- <span
- className="absolute left-1/2 top-0 -translate-x-1/2 -translate-y-1/2 whitespace-nowrap overflow-hidden text-ellipsis px-2 py-1 text-[10px] sm:text-xs"
- style={{
- fontFamily: "var(--font-mono)",
- color: "var(--landing-text-muted)",
- backgroundColor: "var(--landing-bg)",
- }}
- >
- Copy and Paste Into Your Agent&apos;s Chat to Get Started
- </span>
- {/* Content box */}
- <div
- className="flex w-full items-center gap-2 rounded px-3 py-2 pt-3 text-xs sm:text-sm"
- style={{
- fontFamily: "var(--font-mono)",
- color: "var(--landing-text)",
- border: "1px solid color-mix(in srgb, var(--landing-text-muted) 30%, transparent)",
- }}
- >
- <span className="flex-1 overflow-hidden whitespace-nowrap text-ellipsis">
- Read{" "}
- <a
- href="/onboard.md"
- target="_blank"
- rel="noopener noreferrer"
- className="underline transition-opacity hover:opacity-70"
- style={{ color: "var(--landing-text)" }}
- onClick={(e) => e.stopPropagation()}
- >
- Onboard.md
- </a>
- {" "}and follow the instructions to install and configure Alook
- </span>
- <span
- className="shrink-0 p-1"
- style={{ color: copied ? "var(--landing-text)" : "var(--landing-text-muted)" }}
- >
- {copied ? (
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
- <polyline points="20 6 9 17 4 12" />
- </svg>
- ) : (
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
- <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
- <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
- </svg>
- )}
- </span>
- </div>
- </div>}
-
{/* Community links */}
{showCommunityLinks && <div className="hero-providers mt-4 shrink-0 flex items-center justify-center gap-4">
<GithubOutboundLink
diff --git a/src/web/src/components/home/landing-page.tsx b/src/web/src/components/home/landing-page.tsx
index dffe20e96..31b6fb081 100644
--- a/src/web/src/components/home/landing-page.tsx
+++ b/src/web/src/components/home/landing-page.tsx
@@ -243,7 +243,6 @@ export function LandingPage({ isLoggedIn }: { isLoggedIn: boolean }) {
}}
typewriterClassName={styles.landingHeroTypewriter}
largeCtas
- showClipboard={false}
showCommunityLinks={false}
showMobileDesktopHint={false}
primaryCtaLabel={(isLoggedIn ? LANDING_HERO.loggedInCta : LANDING_HERO.loggedOutCta).toUpperCase()}
diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.ts
index e7076c15d..7184fc81a 100644
--- a/src/web/src/env.d.ts
+++ b/src/web/src/env.d.ts
@@ -11,7 +11,6 @@ interface RuntimeEnv {
AUTH_OTP_RATE_LIMIT_MAX?: string
AUTH_OTP_RATE_LIMIT_WINDOW_SEC?: string
DEV_AUTH_OTP?: string
- DEVICE_CLIENT_IDS?: string
NODE_ENV?: string
DEV_WS_DO_URL?: string
DEV_QUEUE_WORKER_URL?: string
diff --git a/src/web/src/hooks/community/member-read.status.test.ts b/src/web/src/hooks/community/member-read.status.test.ts
index 13c59af31..f49052404 100644
--- a/src/web/src/hooks/community/member-read.status.test.ts
+++ b/src/web/src/hooks/community/member-read.status.test.ts
@@ -7,9 +7,9 @@ import { membersPageQueryFn } from "./use-server-members"
const state = vi.hoisted(() => ({ db: null as unknown, wire: null as unknown }))
vi.mock("@/lib/db", () => ({ getDb: () => state.db }))
-vi.mock("@/lib/middleware/community-actor", () => ({ withCommunityActor: (handler: (req: NextRequest, ctx: unknown) => Promise<Response>) => (req: NextRequest) => handler(req, { env: {}, actor: { kind: "human", userId: "viewer" }, params: { id: "server" } }) }))
+vi.mock("@/lib/middleware/community-actor", () => ({ communityActorPolicy: () => ({ resolve: async (req: NextRequest) => ({ context: { env: {}, actor: { kind: "human", userId: "viewer" } } }) }) }))
vi.mock("@/lib/api/client", () => ({ apiFetch: async () => {
- const response = await GET(new NextRequest("https://app.example.test/api/community/servers/server/members"), {} as never)
+ const response = await GET(new NextRequest("https://app.example.test/api/community/servers/server/members"), { params: { id: "server" } })
if (!response.ok) throw new Error(`Actual member producer refused ${response.status}`)
state.wire = await response.json()
return state.wire
diff --git a/src/web/src/hooks/community/use-community-ws.dom.test.ts b/src/web/src/hooks/community/use-community-ws.dom.test.ts
index 80921a921..69fa768d6 100644
--- a/src/web/src/hooks/community/use-community-ws.dom.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.dom.test.ts
@@ -269,7 +269,6 @@ describe("useCommunityWs — double-mount detection", () => {
expect(useUserWsCallCount).toBe(1)
expect(capturedOnMessage).not.toBeNull()
expect(capturedOnReconnect).not.toBeNull()
- expect(capturedUseUserWsOptions?.requestDaemonStatusOnAuth).toBe(false)
expect(capturedUseUserWsOptions).not.toHaveProperty("capabilities")
})
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index df6907bed..8244cc5a9 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -358,7 +358,6 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
onAuthenticated: handleAuthenticated,
onForeground: handleForeground,
onConnectionStateChange: handleConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
useEffect(() => {
reconnectTransportRef.current = reconnectNow
diff --git a/src/web/src/lib/account-deletion/execution.test.ts b/src/web/src/lib/account-deletion/execution.test.ts
index ccf0806f7..9635318c0 100644
--- a/src/web/src/lib/account-deletion/execution.test.ts
+++ b/src/web/src/lib/account-deletion/execution.test.ts
@@ -9,11 +9,9 @@ const mocks = vi.hoisted(() => ({
deleteStorage: vi.fn(),
forceClose: vi.fn(),
pushBot: vi.fn(),
- broadcastDaemon: vi.fn(),
fanOut: vi.fn(),
broadcastUser: vi.fn(),
revokeProvider: vi.fn(),
- invalidateMany: vi.fn(),
warn: vi.fn(),
unsubscribe: vi.fn(),
}))
@@ -35,10 +33,6 @@ vi.mock("@alook/shared", () => ({
}))
vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))
vi.mock("@/lib/resend-contacts", () => ({ unsubscribeResendContact: mocks.unsubscribe }))
-vi.mock("@/lib/cache", () => ({
- cacheKeys: { machineToken: (token: string) => `mt:${token.slice(0, 20)}` },
- invalidateMany: mocks.invalidateMany,
-}))
vi.mock("@/lib/community/community-media-cleanup", () => ({ deleteCommunityMediaObjects: vi.fn() }))
vi.mock("@/lib/billing/service", () => ({ closeAccountBilling: mocks.closeBilling }))
vi.mock("./storage", () => ({ deleteAccountStorage: mocks.deleteStorage }))
@@ -47,7 +41,6 @@ vi.mock("@/lib/community/machine-disconnect", () => ({
forceCloseCommunityMachinesByDoNames: mocks.forceClose,
}))
vi.mock("@/lib/community/bot-push", () => ({ pushBotEventToMachine: mocks.pushBot }))
-vi.mock("@/lib/broadcast", () => ({ broadcastToDaemon: mocks.broadcastDaemon }))
vi.mock("@/lib/community/fanout", () => ({
fanOutToUsers: mocks.fanOut,
broadcastToUserSafe: mocks.broadcastUser,
@@ -62,8 +55,6 @@ function snapshot(id: string) {
providers: [],
ownedWorkspaceIds: [],
ownedAgentIds: [],
- legacyDaemons: [],
- machineTokens: [],
machineDoNames: [],
botBindings: [],
ownedServers: [],
@@ -90,18 +81,16 @@ describe("account deletion execution", () => {
mocks.deleteStorage,
mocks.forceClose,
mocks.pushBot,
- mocks.broadcastDaemon,
mocks.fanOut,
mocks.broadcastUser,
mocks.revokeProvider,
- mocks.invalidateMany,
mocks.unsubscribe,
]) effect.mockResolvedValue(undefined)
})
it("cleans an initial and final primary snapshot before the D1 batch", async () => {
- const initial = { ...snapshot("initial"), machineTokens: ["al_initial_token"] }
- const final = { ...snapshot("final"), machineTokens: ["al_final_token"] }
+ const initial = snapshot("initial")
+ const final = snapshot("final")
mocks.getSnapshot.mockResolvedValueOnce(initial).mockResolvedValueOnce(final)
mocks.deleteRows.mockResolvedValue({ deleted: true, readStateRevisions: [] })
const waitUntil = vi.fn()
@@ -118,17 +107,13 @@ describe("account deletion execution", () => {
expect(mocks.deleteRows).toHaveBeenCalledWith({ primary: true }, final)
expect(mocks.deleteStorage.mock.invocationCallOrder[1])
.toBeLessThan(mocks.deleteRows.mock.invocationCallOrder[0])
- expect(mocks.invalidateMany).toHaveBeenCalledWith([
- "mt:al_initial_token",
- "mt:al_final_token",
- ])
expect(waitUntil).toHaveBeenCalledOnce()
expect(mocks.unsubscribe).toHaveBeenCalledWith(expect.anything(), final.identity.email)
expect(mocks.unsubscribe.mock.invocationCallOrder[0]).toBeGreaterThan(mocks.deleteRows.mock.invocationCallOrder[0])
})
- it("invalidates the initial machine tokens when another request already removed the user", async () => {
- const initial = { ...snapshot("initial"), machineTokens: ["al_initial_token"] }
+ it("cleans initial storage when another request already removed the user", async () => {
+ const initial = snapshot("initial")
mocks.getSnapshot.mockResolvedValueOnce(initial).mockResolvedValueOnce(null)
await expect(executeAccountDeletion(
@@ -138,7 +123,6 @@ describe("account deletion execution", () => {
"user-1",
)).resolves.toEqual({ kind: "missing" })
- expect(mocks.invalidateMany).toHaveBeenCalledWith(["mt:al_initial_token"])
expect(mocks.deleteRows).not.toHaveBeenCalled()
expect(mocks.unsubscribe).not.toHaveBeenCalled()
})
@@ -184,11 +168,10 @@ describe("account deletion execution", () => {
})
it("keeps committed deletion successful when post-commit effects reject", async () => {
+ mocks.pushBot.mockRejectedValue(new Error("socket unavailable"))
const current = {
...snapshot("current"),
providers: [{ providerId: "github", accountId: "account", accessToken: "token", refreshToken: null }],
- legacyDaemons: [{ daemonId: "daemon-1", workspaceId: "workspace-1" }],
- machineTokens: ["al_1234567890abcdefghijklmnop"],
machineDoNames: ["machine-do"],
botBindings: [{ botId: "bot-1", machineId: "machine-1" }],
ownedServers: [{ id: "server-1", icon: null, memberIds: ["member-1"] }],
@@ -199,7 +182,6 @@ describe("account deletion execution", () => {
deleted: true,
readStateRevisions: [{ userId: "member-1", revision: 7 }],
})
- mocks.broadcastDaemon.mockRejectedValue(new Error("socket unavailable"))
let postCommit: Promise<unknown> | undefined
await expect(executeAccountDeletion(
@@ -211,11 +193,9 @@ describe("account deletion execution", () => {
await expect(postCommit).resolves.toBeUndefined()
expect(mocks.pushBot).toHaveBeenCalled()
- expect(mocks.broadcastDaemon).toHaveBeenCalled()
expect(mocks.fanOut).toHaveBeenCalled()
expect(mocks.broadcastUser).toHaveBeenCalled()
expect(mocks.revokeProvider).toHaveBeenCalled()
- expect(mocks.invalidateMany).toHaveBeenCalledWith(["mt:al_1234567890abcdefg"])
expect(mocks.warn).toHaveBeenCalledWith(
"account_deletion_post_commit_effects_failed",
{ failures: 1 },
@@ -274,27 +254,9 @@ describe("account deletion execution", () => {
expect(mocks.deleteStorage).not.toHaveBeenCalled()
expect(mocks.deleteRows).not.toHaveBeenCalled()
- expect(mocks.invalidateMany).toHaveBeenCalled()
expect(mocks.unsubscribe).not.toHaveBeenCalled()
})
- it("keeps a committed deletion successful when machine-token invalidation fails", async () => {
- const current = {
- ...snapshot("current"),
- machineTokens: ["al_stale_token"],
- }
- mocks.getSnapshot.mockResolvedValue(current)
- mocks.deleteRows.mockResolvedValue({ deleted: true, readStateRevisions: [] })
- mocks.invalidateMany.mockRejectedValue(new Error("KV unavailable"))
-
- await expect(executeAccountDeletion(
- {} as never,
- {} as never,
- { waitUntil: vi.fn() },
- "user-1",
- )).resolves.toEqual({ kind: "deleted" })
- })
-
it("fails closed when the delete batch reports no deleted user and the user remains", async () => {
mocks.getSnapshot.mockResolvedValue(snapshot("current"))
mocks.deleteRows.mockResolvedValue({ deleted: false, readStateRevisions: [] })
diff --git a/src/web/src/lib/account-deletion/execution.ts b/src/web/src/lib/account-deletion/execution.ts
index 426ebc881..07842219c 100644
--- a/src/web/src/lib/account-deletion/execution.ts
+++ b/src/web/src/lib/account-deletion/execution.ts
@@ -1,7 +1,5 @@
import { createLogger, queries, WS_EVENTS, type Database } from "@alook/shared"
-import { cacheKeys, invalidateMany } from "@/lib/cache"
import { getPrimaryDb } from "@/lib/db"
-import { broadcastToDaemon } from "@/lib/broadcast"
import { pushBotEventToMachine } from "@/lib/community/bot-push"
import { fanOutToUsers, broadcastToUserSafe } from "@/lib/community/fanout"
import { forceCloseCommunityMachinesByDoNames } from "@/lib/community/machine-disconnect"
@@ -18,10 +16,6 @@ export type ExecuteAccountDeletionResult =
| { kind: "failed" }
| { kind: "pending" }
-async function invalidateMachineTokens(tokens: string[]): Promise<void> {
- await invalidateMany(tokens.map((token) => cacheKeys.machineToken(token))).catch(() => {})
-}
-
function scheduleAfterCommit(
env: Env,
executionContext: Pick<ExecutionContext, "waitUntil">,
@@ -34,10 +28,6 @@ function scheduleAfterCommit(
type: "bot:removed",
botId: binding.botId,
})),
- ...snapshot.legacyDaemons.map((daemon) => broadcastToDaemon(daemon.daemonId, {
- type: "daemon.evict",
- workspaceId: daemon.workspaceId,
- })),
...snapshot.ownedServers.map((server) => fanOutToUsers(server.memberIds, {
type: WS_EVENTS.SERVER_DELETE,
serverId: server.id,
@@ -74,19 +64,13 @@ export async function executeAccountDeletion(
started = true
const firstSnapshot = await queries.accountDeletion.getAccountDeletionSnapshot(db, userId)
if (!firstSnapshot) return { kind: "missing" }
- await invalidateMachineTokens(firstSnapshot.machineTokens)
await forceCloseCommunityMachinesByDoNames(env, firstSnapshot.machineDoNames, true)
await closeAccountBilling(finalDb, env, userId)
const finalSnapshot = await queries.accountDeletion.getAccountDeletionSnapshot(finalDb, userId)
if (!finalSnapshot) {
await deleteAccountStorage(env, firstSnapshot)
- await invalidateMachineTokens(firstSnapshot.machineTokens)
return { kind: "missing" }
}
- const machineTokens = [...new Set([
- ...firstSnapshot.machineTokens,
- ...finalSnapshot.machineTokens,
- ])]
await Promise.all(
finalSnapshot.providers
.filter((provider) => provider.providerId === "apple")
@@ -101,7 +85,6 @@ export async function executeAccountDeletion(
} catch (error) {
const remaining = await queries.user.getUserInternal(getPrimaryDb(env.DB), userId)
if (remaining) throw error
- await invalidateMachineTokens(machineTokens)
scheduleAfterCommit(env, executionContext, finalSnapshot, [])
return { kind: "deleted" }
}
@@ -110,7 +93,6 @@ export async function executeAccountDeletion(
if (remaining) return { kind: "pending" }
}
- await invalidateMachineTokens(machineTokens)
scheduleAfterCommit(env, executionContext, finalSnapshot, deletion.readStateRevisions)
return { kind: "deleted" }
} catch (error) {
diff --git a/src/web/src/lib/auth-client.test.ts b/src/web/src/lib/auth-client.test.ts
index 408cef914..1c349892f 100644
--- a/src/web/src/lib/auth-client.test.ts
+++ b/src/web/src/lib/auth-client.test.ts
@@ -18,7 +18,6 @@ vi.mock("better-auth/react", () => ({
vi.mock("better-auth/client/plugins", () => ({
emailOTPClient: vi.fn(() => ({})),
- deviceAuthorizationClient: vi.fn(() => ({})),
}))
vi.mock("@/lib/community/mobile-system-notification", () => ({
diff --git a/src/web/src/lib/auth-client.ts b/src/web/src/lib/auth-client.ts
index cb2cf344b..23c34653f 100644
--- a/src/web/src/lib/auth-client.ts
+++ b/src/web/src/lib/auth-client.ts
@@ -1,6 +1,6 @@
"use client"
import { createAuthClient } from "better-auth/react"
-import { emailOTPClient, deviceAuthorizationClient } from "better-auth/client/plugins"
+import { emailOTPClient } from "better-auth/client/plugins"
import { captureTelemetryIdentityRetirement } from "@/lib/observability/client"
import {
resumeMobileSystemNotificationRegistration,
@@ -10,7 +10,7 @@ import {
export const authClient = createAuthClient({
baseURL: process.env.NEXT_PUBLIC_APP_URL || "",
- plugins: [emailOTPClient(), deviceAuthorizationClient()],
+ plugins: [emailOTPClient()],
})
export const { signIn, signUp, useSession } = authClient
diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.ts
index e79e8f83f..ed3df5630 100644
--- a/src/web/src/lib/auth.test.ts
+++ b/src/web/src/lib/auth.test.ts
@@ -760,51 +760,14 @@ describe("createAuth Apple provider", () => {
})
})
-describe("createAuth device authorization plugin", () => {
- beforeEach(() => vi.clearAllMocks())
-
- it("includes deviceAuthorization and bearer plugins in production", async () => {
- const createAuth = await loadCreateAuth()
- const opts = (createAuth(makeEnv({ NODE_ENV: "production" }) as never) as { __options: { plugins: any[] } }).__options
- const pluginNames = opts.plugins.map((p: any) => p.__plugin)
- expect(pluginNames).toContain("deviceAuthorization")
- expect(pluginNames).toContain("bearer")
- })
-
- it("includes deviceAuthorization and bearer plugins in development", async () => {
- const createAuth = await loadCreateAuth()
- const opts = (createAuth(makeEnv({ NODE_ENV: "development" }) as never) as { __options: { plugins: any[] } }).__options
- const pluginNames = opts.plugins.map((p: any) => p.__plugin)
- expect(pluginNames).toContain("deviceAuthorization")
- expect(pluginNames).toContain("bearer")
- })
-
- it("validateClient accepts client IDs listed in DEVICE_CLIENT_IDS", async () => {
+describe("retired CLI authentication", () => {
+ it.each(["production", "development"])("does not enable device-code or session-Bearer plugins in %s", async nodeEnv => {
const createAuth = await loadCreateAuth()
- const env = makeEnv({ NODE_ENV: "production", DEVICE_CLIENT_IDS: "cli-app, web-app" })
- const opts = (createAuth(env as never) as { __options: { plugins: any[] } }).__options
- const devicePlugin = opts.plugins.find((p: any) => p.__plugin === "deviceAuthorization")
- const { validateClient } = devicePlugin.cfg
- expect(validateClient("cli-app")).toBe(true)
- expect(validateClient("web-app")).toBe(true)
- })
-
- it("validateClient rejects client IDs not listed in DEVICE_CLIENT_IDS", async () => {
- const createAuth = await loadCreateAuth()
- const env = makeEnv({ NODE_ENV: "production", DEVICE_CLIENT_IDS: "cli-app" })
- const opts = (createAuth(env as never) as { __options: { plugins: any[] } }).__options
- const devicePlugin = opts.plugins.find((p: any) => p.__plugin === "deviceAuthorization")
- const { validateClient } = devicePlugin.cfg
- expect(validateClient("unknown-client")).toBe(false)
- })
-
- it("validateClient rejects empty string when DEVICE_CLIENT_IDS is unset", async () => {
- const createAuth = await loadCreateAuth()
- const env = makeEnv({ NODE_ENV: "production" })
- const opts = (createAuth(env as never) as { __options: { plugins: any[] } }).__options
- const devicePlugin = opts.plugins.find((p: any) => p.__plugin === "deviceAuthorization")
- const { validateClient } = devicePlugin.cfg
- expect(validateClient("")).toBe(false)
+ const opts = (createAuth(makeEnv({ NODE_ENV: nodeEnv }) as never) as { __options: AuthOptions }).__options
+ const names = opts.plugins?.map(plugin => plugin.__plugin)
+ expect(names).not.toContain("deviceAuthorization")
+ expect(names).not.toContain("bearer")
+ expect(names).toContain("oneTimeToken")
})
})
diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.ts
index 2ae0b49b5..1a93fa6cc 100644
--- a/src/web/src/lib/auth.ts
+++ b/src/web/src/lib/auth.ts
@@ -1,6 +1,6 @@
import { annotateWorkerSpan, observeWorkerOperation } from "./observability/worker"
import { betterAuth } from "better-auth"
-import { emailOTP, deviceAuthorization, bearer, oneTimeToken } from "better-auth/plugins"
+import { emailOTP, oneTimeToken } from "better-auth/plugins"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { nanoid } from "nanoid"
import {
@@ -118,10 +118,6 @@ export function createAuth(env: Env) {
const applePlugins = appleAuth.enabled
? [appleOauthHardeningPlugin(appleAuth.config.clientId)]
: []
- const validateClient = (clientId: string) => {
- const allowed = (env.DEVICE_CLIENT_IDS || "").split(",").map((s) => s.trim()).filter(Boolean)
- return allowed.includes(clientId)
- }
return betterAuth({
baseURL: env.BETTER_AUTH_URL,
@@ -337,8 +333,6 @@ export function createAuth(env: Env) {
plugins: (isProd || (mode === "dev" && env.DEV_AUTH_OTP === "1"))
? [
...applePlugins,
- deviceAuthorization({ verificationUri: "/device", validateClient, expiresIn: "5m", schema: {} }),
- bearer(),
oneTimeToken({
expiresIn: 2,
disableClientRequest: true,
@@ -400,8 +394,6 @@ export function createAuth(env: Env) {
]
: [
...applePlugins,
- deviceAuthorization({ verificationUri: "/device", validateClient, expiresIn: "5m", schema: {} }),
- bearer(),
oneTimeToken({
expiresIn: 2,
disableClientRequest: true,
@@ -440,7 +432,6 @@ function authConfiguration(env: Env): readonly (string | undefined)[] {
env.APPLE_TEAM_ID,
env.APPLE_KEY_ID,
env.APPLE_PRIVATE_KEY,
- env.DEVICE_CLIENT_IDS,
env.APP_REVIEW_EMAIL,
env.APP_REVIEW_OTP,
env.DEV_AUTH_OTP,
diff --git a/src/web/src/lib/automation-routes.test.ts b/src/web/src/lib/automation-routes.test.ts
index 7453e89ea..b91d85a97 100644
--- a/src/web/src/lib/automation-routes.test.ts
+++ b/src/web/src/lib/automation-routes.test.ts
@@ -4,7 +4,7 @@ const mocks = vi.hoisted(() => ({ authenticate: vi.fn(), limiter: vi.fn(), actio
vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: async () => ({ env: { DB: {} } }) }))
vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))
vi.mock("@/lib/broadcast", () => ({ wsDoFetch: mocks.limiter }))
-vi.mock("@/lib/middleware/auth", () => ({ withAuth: () => { throw new Error("normal authentication must not be used") } }))
+vi.mock("@/lib/middleware/auth", () => ({ humanAuthPolicy: { resolve: () => { throw new Error("normal authentication must not be used") } } }))
vi.mock("@alook/shared", async (original) => ({ ...await original<typeof import("@alook/shared")>(), queries: { automation: { authenticateAccessCode: mocks.authenticate } } }))
vi.mock("@/lib/community/create-bot.server", () => ({ createBotForUser: mocks.action }))
vi.mock("@/lib/community/create-server.server", () => ({ createServerForUser: mocks.action }))
diff --git a/src/web/src/lib/automation.test.ts b/src/web/src/lib/automation.test.ts
index 6e7a148ce..cbac515f0 100644
--- a/src/web/src/lib/automation.test.ts
+++ b/src/web/src/lib/automation.test.ts
@@ -1,14 +1,19 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
+import { getCloudflareContext } from "@opennextjs/cloudflare"
const { authenticate, expire, transport, fallback } = vi.hoisted(() => ({ authenticate: vi.fn(), expire: vi.fn(), transport: vi.fn(), fallback: vi.fn() }))
-vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: async () => ({ env: { DB: {} } }) }))
+vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })) }))
vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))
vi.mock("@/lib/broadcast", () => ({ wsDoFetch: transport }))
-vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: unknown) => fallback.mockImplementation(async (request: NextRequest) => (handler as (req: NextRequest, ctx: unknown) => Promise<Response>)(request, { env: { DB: {} }, userId: "human" })) }))
+vi.mock("@/lib/middleware/auth", () => ({ humanAuthPolicy: {
+ resolve: fallback.mockImplementation(async () => ({ context: { env: { DB: {} }, userId: "human" } })),
+ respond: (_req: NextRequest, response: Response) => response,
+} }))
vi.mock("@alook/shared", async (importOriginal) => ({ ...await importOriginal<typeof import("@alook/shared")>(), queries: { automation: { authenticateAccessCode: authenticate, expireAccessCode: expire } } }))
-import { hashAutomationSecret, newAutomationSecret, withAutomation, withAutomationManagement } from "./automation"
+import { hashAutomationSecret, newAutomationSecret, automationPolicy, automationManagementPolicy } from "./automation"
import { POST as expireCode } from "@/app/api/community/automation/expire/route"
const secret = "aac_" + "a".repeat(64)
@@ -16,7 +21,7 @@ const request = (token = secret) => new NextRequest("http://localhost/api/commun
beforeEach(() => {
vi.clearAllMocks()
authenticate.mockResolvedValue({ codeId: "code", ownerId: "owner", permission: "bot.create", limit: 64, period: "hour" })
- transport.mockResolvedValue(Response.json({ allowed: true }))
+ transport.mockImplementation(async () => Response.json({ allowed: true }))
})
afterEach(() => vi.restoreAllMocks())
const create = async (_req: NextRequest, ctx: { userId: string; beforeCreate: () => Promise<Response | null> }) =>
@@ -48,7 +53,7 @@ describe("automation authorization boundary", () => {
})
it("derives owner from a hashed primary lookup and uses the indexed permission for its own limiter", async () => {
- const response = await withAutomation("bot.create", create)(request())
+ const response = await withAuth(automationPolicy("bot.create"), create)(request())
expect(response.status).toBe(201)
expect(await response.json()).toEqual({ ownerId: "owner" })
expect(authenticate).toHaveBeenCalledWith({ primary: true }, await hashAutomationSecret(secret), "bot.create")
@@ -61,32 +66,32 @@ describe("automation authorization boundary", () => {
it("rejects missing permission, deleted/expired secrets and malformed credentials before creation", async () => {
const handler = vi.fn(create)
authenticate.mockResolvedValue(null)
- expect((await withAutomation("bot.create", handler)(request())).status).toBe(401)
- expect((await withAutomation("bot.create", handler)(request("al_machine"))).status).toBe(401)
+ expect((await withAuth(automationPolicy("bot.create"), handler)(request())).status).toBe(401)
+ expect((await withAuth(automationPolicy("bot.create"), handler)(request("al_machine"))).status).toBe(401)
expect(handler).not.toHaveBeenCalled()
expect(transport).not.toHaveBeenCalled()
})
it("fails closed on auth/limiter failure, invalid policy and invalid limiter results", async () => {
authenticate.mockRejectedValueOnce(new Error("D1 down"))
- expect((await withAutomation("bot.create", create)(request())).status).toBe(503)
+ expect((await withAuth(automationPolicy("bot.create"), create)(request())).status).toBe(503)
for (const body of [null, { allowed: "true" }, { allowed: false }, { allowed: false, retryAfterSec: -1 }]) {
transport.mockResolvedValueOnce(Response.json(body))
- expect((await withAutomation("bot.create", create)(request())).status).toBe(503)
+ expect((await withAuth(automationPolicy("bot.create"), create)(request())).status).toBe(503)
}
transport.mockRejectedValueOnce(new Error("DO down"))
- expect((await withAutomation("bot.create", create)(request())).status).toBe(503)
+ expect((await withAuth(automationPolicy("bot.create"), create)(request())).status).toBe(503)
authenticate.mockResolvedValueOnce({ codeId: "code", ownerId: "owner", limit: 65, period: "hour" })
- expect((await withAutomation("bot.create", create)(request())).status).toBe(503)
+ expect((await withAuth(automationPolicy("bot.create"), create)(request())).status).toBe(503)
})
it("returns Retry-After and does not run business creation when denied", async () => {
transport.mockResolvedValue(Response.json({ allowed: false, retryAfterSec: 20 }))
- const response = await withAutomation("bot.create", create)(request())
+ const response = await withAuth(automationPolicy("bot.create"), create)(request())
expect(response.status).toBe(429)
expect(response.headers.get("Retry-After")).toBe("20")
})
it("accepts only standalone access codes, even when a session cookie is present", async () => {
const handler = vi.fn(create)
- const route = withAutomation("bot.create", handler)
+ const route = withAuth(automationPolicy("bot.create"), handler)
for (const token of ["aac_bad", "al_machine", "crk_bot", ""]) {
const req = request(token)
req.headers.set("cookie", "session=present")
@@ -97,7 +102,7 @@ describe("automation authorization boundary", () => {
expect(transport).not.toHaveBeenCalled()
})
it("does not permit bearer credentials to manage their own codes", async () => {
- const managed = withAutomationManagement(async () => Response.json({ created: true }))
+ const managed = withAuth(automationManagementPolicy, async () => Response.json({ created: true }))
expect((await managed(request())).status).toBe(401)
expect((await managed(new NextRequest("http://localhost/api/community/automation/access-codes"))).status).toBe(200)
})
@@ -112,8 +117,73 @@ describe("automation authorization boundary", () => {
it("refuses absent credentials and an HTTP failure from the rate limiter", async () => {
const missing = new NextRequest("http://localhost/api/community/bots", { method: "POST" })
- expect((await withAutomation("bot.create", create)(missing)).status).toBe(401)
+ expect((await withAuth(automationPolicy("bot.create"), create)(missing)).status).toBe(401)
expect(authenticate).not.toHaveBeenCalled()
transport.mockResolvedValueOnce(new Response("unavailable", { status: 503 }))
- expect((await withAutomation("bot.create", create)(request())).status).toBe(503)
+ expect((await withAuth(automationPolicy("bot.create"), create)(request())).status).toBe(503)
+})
+
+describe("automation execution order", () => {
+ it("does not read route params or consume quota until credential and policy validation succeeds", async () => {
+ const handler = vi.fn(async (_req, ctx) => Response.json({ owner: ctx.userId, params: ctx.params }))
+ const route = withAuth(automationPolicy("bot.create"), handler)
+ const readParams = vi.fn(() => Promise.resolve({ id: "resource" }))
+ const context = { get params() { return readParams() } }
+ expect((await route(request("invalid"), context)).status).toBe(401)
+ authenticate.mockResolvedValueOnce(null)
+ expect((await route(request(), context)).status).toBe(401)
+ authenticate.mockResolvedValueOnce({ codeId: "code", ownerId: "owner", limit: 100, period: "hour" })
+ expect((await route(request(), context)).status).toBe(503)
+ expect(readParams).not.toHaveBeenCalled()
+ expect(handler).not.toHaveBeenCalled()
+ const response = await route(request(), context)
+ expect(await response.json()).toEqual({ owner: "owner", params: { id: "resource" } })
+ expect(readParams).toHaveBeenCalledOnce()
+ expect(transport).not.toHaveBeenCalled()
+ })
+
+ it("sets no-store only after handler return and propagates thrown business errors", async () => {
+ const route = withAuth(automationPolicy("bot.create"), async () => Response.json({ error: "invalid body" }, { status: 400 }))
+ expect((await route(request("invalid"))).headers.get("Cache-Control")).toBeNull()
+ expect((await route(request())).headers.get("Cache-Control")).toBe("no-store")
+ const failure = new Error("business failed")
+ await expect(withAuth(automationPolicy("bot.create"), async () => { throw failure })(request())).rejects.toBe(failure)
+ expect(transport).not.toHaveBeenCalled()
+ })
+
+ it("keeps concurrent owners, quota keys and params isolated on a reused wrapper", async () => {
+ const secondSecret = "aac_" + "b".repeat(64)
+ const firstHash = await hashAutomationSecret(secret)
+ authenticate.mockImplementation(async (_db, hash) => ({ codeId: hash === firstHash ? "one" : "two", ownerId: hash === firstHash ? "owner-one" : "owner-two", limit: 4, period: "day" }))
+ const route = withAuth(automationPolicy("message.send"), async (_req, ctx) => await ctx.beforeCreate() ?? Response.json({ owner: ctx.userId, params: ctx.params }))
+ const results = await Promise.all([route(request(), { params: Promise.resolve({ id: "one" }) }), route(request(secondSecret), { params: Promise.resolve({ id: "two" }) })])
+ expect(await Promise.all(results.map(result => result.json()))).toEqual([{ owner: "owner-one", params: { id: "one" } }, { owner: "owner-two", params: { id: "two" } }])
+ expect(transport.mock.calls.map(call => JSON.parse(call[2].body).key).sort()).toEqual(["one", "two"])
+ expect(authenticate).toHaveBeenCalledTimes(2)
+ expect(fallback).not.toHaveBeenCalled()
+ })
+})
+
+it("self-expiry ignores route params and never uses permission or quota resolution", async () => {
+ expire.mockResolvedValueOnce(true)
+ const context = { get params(): never { throw new Error("expiry has no route parameters") } }
+ expect((await expireCode(request(), context)).status).toBe(200)
+ expect(expire).toHaveBeenCalledOnce()
+ expect(authenticate).not.toHaveBeenCalled()
+ expect(transport).not.toHaveBeenCalled()
+})
+
+it("fails closed before expiry or permission lookup when request bindings are unavailable", async () => {
+ vi.mocked(getCloudflareContext).mockRejectedValueOnce(new Error("bindings unavailable"))
+ const expired = await expireCode(request())
+ expect(expired.status).toBe(503)
+ expect(await expired.json()).toEqual({ error: "Automation expiration unavailable" })
+ expect(expired.headers.get("Cache-Control")).toBeNull()
+ vi.mocked(getCloudflareContext).mockRejectedValueOnce(new Error("bindings unavailable"))
+ const response = await withAuth(automationPolicy("bot.create"), create)(request())
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "Automation authentication unavailable" })
+ expect(expire).not.toHaveBeenCalled()
+ expect(authenticate).not.toHaveBeenCalled()
+ expect(transport).not.toHaveBeenCalled()
})
diff --git a/src/web/src/lib/automation.ts b/src/web/src/lib/automation.ts
index 1700e2ae2..1046407ea 100644
--- a/src/web/src/lib/automation.ts
+++ b/src/web/src/lib/automation.ts
@@ -4,7 +4,8 @@ import { AutomationPermissionPolicySchema, queries, type AutomationPermission }
import { getPrimaryDb } from "@/lib/db"
import { wsDoFetch } from "@/lib/broadcast"
import { writeError } from "@/lib/middleware/helpers"
-import { withAuth, type AuthenticatedHandler } from "@/lib/middleware/auth"
+import { humanAuthPolicy, type AuthContext } from "@/lib/middleware/auth"
+import { withAuth, type AuthPolicy } from "@/lib/middleware/auth-policy"
export async function hashAutomationSecret(secret: string): Promise<string> {
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret))
@@ -15,64 +16,83 @@ export function newAutomationSecret(): string {
return "aac_" + Array.from(crypto.getRandomValues(new Uint8Array(32)), (byte) => byte.toString(16).padStart(2, "0")).join("")
}
-export function withAutomationManagement(handler: AuthenticatedHandler) {
- const authenticated = withAuth(handler)
- return (...args: Parameters<typeof authenticated>) => args[0].headers.has("Authorization")
- ? Promise.resolve(writeError("Sign in to manage access codes", 401))
- : authenticated(...args)
+export const automationManagementPolicy: AuthPolicy<AuthContext> = {
+ ...humanAuthPolicy,
+ preflight: req => req.headers.has("Authorization")
+ ? writeError("Sign in to manage access codes", 401)
+ : humanAuthPolicy.preflight?.(req) ?? null,
+ respond: (req, response) => req.headers.has("Authorization")
+ ? response
+ : humanAuthPolicy.respond!(req, response),
}
-type RouteContext = { params?: Promise<Record<string, string>> | Record<string, string> }
-type AutomationHandler = (req: NextRequest, ctx: { env: Env; userId: string; params?: Record<string, string>; beforeCreate: () => Promise<Response | null> }) => Promise<Response>
+type AutomationContext = { env: Env; userId: string; beforeCreate: () => Promise<Response | null> }
function readAutomationSecret(req: NextRequest): string | undefined {
return /^Bearer (aac_[a-f0-9]{64})$/.exec(req.headers.get("Authorization") ?? "")?.[1]
}
-export async function expireAutomationAccessCode(req: NextRequest): Promise<Response> {
- const secret = readAutomationSecret(req)
- if (!secret) return writeError("Invalid or unauthorized access code", 401)
+type AutomationExpiryContext = { db: ReturnType<typeof getPrimaryDb>; secretHash: string }
+
+export const automationExpiryPolicy: AuthPolicy<AutomationExpiryContext> = {
+ params: "ignore",
+ resolve: async req => {
+ const secret = readAutomationSecret(req)
+ if (!secret) return writeError("Invalid or unauthorized access code", 401)
+ try {
+ const env = (await getCloudflareContext({ async: true })).env as Env
+ return { context: { db: getPrimaryDb(env.DB), secretHash: await hashAutomationSecret(secret) } }
+ } catch { return writeError("Automation expiration unavailable", 503) }
+ },
+}
+
+export const expireAutomationAccessCode = withAuth(automationExpiryPolicy, async (_req, ctx) => {
try {
- const env = (await getCloudflareContext({ async: true })).env as Env
- const expired = await queries.automation.expireAccessCode(getPrimaryDb(env.DB), await hashAutomationSecret(secret))
+ const expired = await queries.automation.expireAccessCode(ctx.db, ctx.secretHash)
return Response.json(expired ? { expired: true } : { error: "Invalid or unauthorized access code" }, {
status: expired ? 200 : 401, headers: { "Cache-Control": "no-store" },
})
} catch { return writeError("Automation expiration unavailable", 503) }
-}
+})
-export function withAutomation(permission: AutomationPermission, handler: AutomationHandler) {
- return async (req: NextRequest, context?: RouteContext): Promise<Response> => {
- const secret = readAutomationSecret(req)
- if (!secret) return writeError("Invalid or unauthorized access code", 401)
- let env: Env
- let access: Awaited<ReturnType<typeof queries.automation.authenticateAccessCode>>
- try {
- env = (await getCloudflareContext({ async: true })).env as Env
- access = await queries.automation.authenticateAccessCode(getPrimaryDb(env.DB), await hashAutomationSecret(secret), permission)
- } catch { return writeError("Automation authentication unavailable", 503) }
- if (!access) return writeError("Invalid or unauthorized access code", 401)
- const policy = AutomationPermissionPolicySchema.safeParse({ permission, limit: access.limit, period: access.period })
- if (!policy.success) return writeError("Automation policy unavailable", 503)
- const beforeCreate = async (): Promise<Response | null> => {
+export function automationPolicy(permission: AutomationPermission): AuthPolicy<AutomationContext> {
+ return {
+ params: "afterAuth",
+ resolve: async req => {
+ const secret = readAutomationSecret(req)
+ if (!secret) return writeError("Invalid or unauthorized access code", 401)
+ let env: Env
+ let access: Awaited<ReturnType<typeof queries.automation.authenticateAccessCode>>
try {
- const res = await wsDoFetch(env, "/rate-limit/automation", {
- method: "POST", headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name: permission, key: access.codeId, max: policy.data.limit, period: policy.data.period }),
- }, { type: "automation-limit" })
- if (!res.ok) return writeError("Automation rate limiter unavailable", 503)
- const result: unknown = await res.json()
- if (typeof result !== "object" || result === null || !("allowed" in result)) return writeError("Automation rate limiter unavailable", 503)
- if (result.allowed === true) return null
- if (result.allowed === false && "retryAfterSec" in result && typeof result.retryAfterSec === "number" && Number.isFinite(result.retryAfterSec) && result.retryAfterSec > 0) {
- return writeError("Automation rate limit exceeded", 429, { "Retry-After": String(Math.ceil(result.retryAfterSec)) })
- }
- } catch { }
- return writeError("Automation rate limiter unavailable", 503)
- }
- const params = await context?.params
- const response = await handler(req, { env, userId: access.ownerId, params, beforeCreate })
- response.headers.set("Cache-Control", "no-store")
- return response
+ env = (await getCloudflareContext({ async: true })).env as Env
+ access = await queries.automation.authenticateAccessCode(getPrimaryDb(env.DB), await hashAutomationSecret(secret), permission)
+ } catch { return writeError("Automation authentication unavailable", 503) }
+ if (!access) return writeError("Invalid or unauthorized access code", 401)
+ const policy = AutomationPermissionPolicySchema.safeParse({ permission, limit: access.limit, period: access.period })
+ if (!policy.success) return writeError("Automation policy unavailable", 503)
+ const beforeCreate = async (): Promise<Response | null> => {
+ try {
+ const res = await wsDoFetch(env, "/rate-limit/automation", {
+ method: "POST", headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name: permission, key: access.codeId, max: policy.data.limit, period: policy.data.period }),
+ }, { type: "automation-limit" })
+ if (!res.ok) return writeError("Automation rate limiter unavailable", 503)
+ const result: unknown = await res.json()
+ if (typeof result !== "object" || result === null || !("allowed" in result)) return writeError("Automation rate limiter unavailable", 503)
+ if (result.allowed === true) return null
+ if (result.allowed === false && "retryAfterSec" in result && typeof result.retryAfterSec === "number" && Number.isFinite(result.retryAfterSec) && result.retryAfterSec > 0) {
+ return writeError("Automation rate limit exceeded", 429, { "Retry-After": String(Math.ceil(result.retryAfterSec)) })
+ }
+ } catch { }
+ return writeError("Automation rate limiter unavailable", 503)
+ }
+ return {
+ context: { env, userId: access.ownerId, beforeCreate },
+ finish: response => {
+ response.headers.set("Cache-Control", "no-store")
+ return response
+ },
+ }
+ },
}
}
diff --git a/src/web/src/lib/broadcast.ts b/src/web/src/lib/broadcast.ts
index 97c8b2dd7..4a63f2e5a 100644
--- a/src/web/src/lib/broadcast.ts
+++ b/src/web/src/lib/broadcast.ts
@@ -1,6 +1,6 @@
import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import type { WsMessage, DaemonPushMessage } from "@alook/shared"
+import type { WsMessage } from "@alook/shared"
import {
COMMUNITY_BULK_BODY_MAX_BYTES,
COMMUNITY_CONTRACT_HEADER,
@@ -274,21 +274,3 @@ export function broadcastToUsers(
} catch {}
return work
}
-
-
-export function broadcastToDaemon(daemonId: string, message: DaemonPushMessage): Promise<{ sent: number }> {
- const promise = doSend(
- `/broadcast/daemon/${daemonId}`,
- JSON.stringify(message),
- { label: daemonId, type: message.type },
- )
- try {
- // CF worker may terminate before the fetch completes if the response is sent early;
- // waitUntil keeps the isolate alive until the broadcast resolves.
- const { ctx } = getCloudflareContext()
- ctx.waitUntil(promise.catch(() => { }))
- } catch {
- // Not in CF context — promise runs on its own
- }
- return promise
-}
diff --git a/src/web/src/lib/cache.test.ts b/src/web/src/lib/cache.test.ts
index f58e7648e..d63da5fcc 100644
--- a/src/web/src/lib/cache.test.ts
+++ b/src/web/src/lib/cache.test.ts
@@ -192,7 +192,6 @@ describe("cache", () => {
expect(cacheKeys.user("usr1")).toBe("task-payload:user-identity:usr1");
expect(cacheKeys.allEmailAccounts("ws1")).toBe("task-payload:email-addresses:ws1");
expect(cacheKeys.allHandles("ws1")).toBe("handles:ws1");
- expect(cacheKeys.machineToken("al_1234567890abcdefghij_rest")).toBe("mt:al_1234567890abcdefg");
expect(cacheKeys.runtimeIds("ws1", "d1")).toBe("rt:ws1:d1");
});
diff --git a/src/web/src/lib/cache.ts b/src/web/src/lib/cache.ts
index 9d298a626..402bce1e2 100644
--- a/src/web/src/lib/cache.ts
+++ b/src/web/src/lib/cache.ts
@@ -152,7 +152,7 @@ export async function throttled(
export async function invalidate(key: string): Promise<void> {
const kv = getKV();
- if (kv) await kv.delete(key.startsWith("mt:") ? key : businessCacheKey(key)).catch((err) => {
+ if (kv) await kv.delete(businessCacheKey(key)).catch((err) => {
log.warn("KV invalidate failed", { key, err });
});
}
@@ -160,13 +160,12 @@ export async function invalidate(key: string): Promise<void> {
export async function invalidateMany(keys: string[]): Promise<void> {
const kv = getKV();
if (!kv || keys.length === 0) return;
- await Promise.all(keys.map((key) => kv.delete(key.startsWith("mt:") ? key : businessCacheKey(key)).catch((err) => {
+ await Promise.all(keys.map((key) => kv.delete(businessCacheKey(key)).catch((err) => {
log.warn("KV invalidate failed", { key, err });
})));
}
export const cacheKeys = {
- machineToken: (token: string) => `mt:${token.slice(0, 20)}`,
member: (workspaceId: string, userId: string) => `task-payload:member-instruction:${workspaceId}:${userId}`,
runtimeIds: (workspaceId: string, daemonId: string) => `rt:${workspaceId}:${daemonId}`,
user: (userId: string) => `task-payload:user-identity:${userId}`,
diff --git a/src/web/src/lib/community/attention-resources.sql.test.ts b/src/web/src/lib/community/attention-resources.sql.test.ts
index 8a807021b..8ddd2c794 100644
--- a/src/web/src/lib/community/attention-resources.sql.test.ts
+++ b/src/web/src/lib/community/attention-resources.sql.test.ts
@@ -9,8 +9,10 @@ const attentionHttp = vi.hoisted(() => ({ db: null as unknown }))
vi.mock("@/lib/db", () => ({ getPrimaryDb: () => attentionHttp.db, getDb: () => attentionHttp.db }))
vi.mock("@/lib/middleware/auth", async () => {
const { protectCommunityJsonResponse } = await import("@/lib/middleware/response-cache")
- return { withAuth: (handler: AuthenticatedHandler) => async (request: NextRequest) => protectCommunityJsonResponse(request,
- await handler(request, { env: { DB: {} } as Env, userId: "viewer", email: "[email protected]" })) }
+ return { humanAuthPolicy: {
+ resolve: async () => ({ context: { env: { DB: {} } as Env, userId: "viewer", email: "[email protected]" } }),
+ respond: protectCommunityJsonResponse,
+ } }
})
import { GET } from "@/app/api/community/users/me/attention/route"
diff --git a/src/web/src/lib/community/friend-read.resources.dom.test.ts b/src/web/src/lib/community/friend-read.resources.dom.test.ts
index 2ca92707e..10656a922 100644
--- a/src/web/src/lib/community/friend-read.resources.dom.test.ts
+++ b/src/web/src/lib/community/friend-read.resources.dom.test.ts
@@ -7,7 +7,14 @@ import { communityKeys } from "@/lib/query-keys"
const mocks = vi.hoisted(() => ({ accepted: vi.fn(), blocked: vi.fn(), pending: vi.fn(), users: vi.fn(), profiles: vi.fn(), api: vi.fn(), db: {} }))
vi.mock("@/lib/db", () => ({ getDb: () => mocks.db }))
-vi.mock("@/lib/middleware/community-actor", () => ({ withCommunityActor: (handler: (request: NextRequest, context: unknown) => Promise<Response>) => (request: NextRequest) => handler(request, { actor: { kind: "human", userId: "viewer" }, env: { DB: mocks.db } }), rejectBot: () => null }))
+vi.mock("@/lib/middleware/community-actor", () => {
+ const context = () => ({ actor: { kind: "human", userId: "viewer" }, env: { DB: mocks.db } })
+ return {
+
+ communityActorPolicy: () => ({ resolve: async () => ({ context: context() }) }),
+ rejectBot: () => null,
+ }
+})
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => mocks.api(...args) }))
vi.mock("@alook/shared", async original => {
const actual = await original<typeof import("@alook/shared")>()
diff --git a/src/web/src/lib/community/invite-read.resources.dom.test.ts b/src/web/src/lib/community/invite-read.resources.dom.test.ts
index fde123ae9..3e0a136d4 100644
--- a/src/web/src/lib/community/invite-read.resources.dom.test.ts
+++ b/src/web/src/lib/community/invite-read.resources.dom.test.ts
@@ -13,7 +13,7 @@ import { createCommunityQueryOwner } from "@/test/community-query-owner"
const mocks = vi.hoisted(() => ({ list: vi.fn(), users: vi.fn(), profiles: vi.fn(), servers: vi.fn(), api: vi.fn(), member: vi.fn(), db: {} }))
vi.mock("@/lib/db", () => ({ getDb: () => mocks.db }))
-vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: (request: NextRequest, context: unknown) => Promise<Response>) => (request: NextRequest) => handler(request, { userId: "viewer", env: { DB: mocks.db }, params: { id: "s1" } }) }))
+vi.mock("@/lib/middleware/auth", () => ({ humanAuthPolicy: { resolve: async (request: NextRequest) => ({ context: { userId: "viewer", env: { DB: mocks.db } } }) } }))
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => mocks.api(...args) }))
vi.mock("@alook/shared", async original => {
const actual = await original<typeof import("@alook/shared")>()
@@ -45,7 +45,7 @@ beforeEach(() => {
mocks.api.mockImplementation(async (path: string, options: { authenticationAccount?: string }) => {
expect(path).toBe("/api/community/servers/s1/invites")
expect(options.authenticationAccount).toBe("viewer")
- const response = await GET(request())
+ const response = await GET(request(), { params: { id: "s1" } })
expect(response.status).toBe(200)
return response.json()
})
@@ -62,7 +62,7 @@ it("publishes a cold real creator profile and renders the creator name through t
})
it("produces scoped descriptors with full resources and no creator email or second identity", async () => {
- const response = await GET(request())
+ const response = await GET(request(), { params: { id: "s1" } })
expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
const data = CommunityInvitesReadSchema.parse(await response.json())
expect(data.invites).toEqual([{ id: "invite", token: "token", uses: 0, maxUses: null, expiresAt: null, createdAt: "2026-10-01T00:00:00Z", creatorId: "creator" }])
@@ -76,13 +76,13 @@ it("produces scoped descriptors with full resources and no creator email or seco
it("retains an explicitly null deleted creator without a fabricated profile", async () => {
const rows = await mocks.list()
mocks.list.mockResolvedValue([{ ...rows[0], creatorId: null, creatorName: null }])
- const data = CommunityInvitesReadSchema.parse(await (await GET(request())).json())
+ const data = CommunityInvitesReadSchema.parse(await (await GET(request(), { params: { id: "s1" } })).json())
expect(data.invites[0].creatorId).toBeNull()
expect(data.resources.profiles.map(row => row.id)).toEqual(["viewer"])
})
it("gates membership before reading invite or creator resources", async () => {
mocks.member.mockResolvedValue(null)
- expect((await GET(request())).status).toBe(403)
+ expect((await GET(request(), { params: { id: "s1" } })).status).toBe(403)
expect(mocks.list).not.toHaveBeenCalled()
expect(mocks.users).not.toHaveBeenCalled()
})
@@ -97,7 +97,7 @@ it("rejects a missing creator full resource without publishing the descriptor",
it.each(["list", "users", "profiles"] as const)("propagates original %s errors without a false empty result", async query => {
const failure = new Error("unavailable")
mocks[query].mockRejectedValue(failure)
- await expect(GET(request())).rejects.toBe(failure)
+ await expect(GET(request(), { params: { id: "s1" } })).rejects.toBe(failure)
})
const item = { id: "invite", token: "token", uses: 0, maxUses: null, expiresAt: null, createdAt: "now", creatorId: "creator" }
const creator = { id: "creator", name: "Alice", discriminator: "0042", avatar: null, avatarVersion: 2 }
diff --git a/src/web/src/lib/community/message-confirmation.sql.test.ts b/src/web/src/lib/community/message-confirmation.sql.test.ts
index dc1f00302..62c4e4e82 100644
--- a/src/web/src/lib/community/message-confirmation.sql.test.ts
+++ b/src/web/src/lib/community/message-confirmation.sql.test.ts
@@ -8,11 +8,7 @@ import { projectPostedMessage } from "./message-wire"
const state = vi.hoisted(() => ({ db: null as unknown, dispatch: vi.fn() }))
vi.mock("@/lib/db", () => ({ getDb: () => state.db, getPrimaryDb: () => state.db }))
vi.mock("@/lib/middleware/community-actor", () => ({
- withCommunityActor: (handler: CommunityActorHandler) => (request: NextRequest, context: { params: Record<string, string> }) => handler(request, {
- env: { DB: {} } as Env,
- actor: { kind: "human", userId: "sender", email: "[email protected]" },
- params: context.params,
- }),
+ communityActorPolicy: () => ({ resolve: async (request: NextRequest) => ({ context: { env: { DB: {} } as Env, actor: { kind: "human", userId: "sender", email: "[email protected]" } } }) }),
}))
vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: async () => ({ allowed: true }) }))
vi.mock("@/lib/community/message-dispatcher", () => ({ dispatchCommittedMessage: state.dispatch }))
diff --git a/src/web/src/lib/community/reading.routes.test.ts b/src/web/src/lib/community/reading.routes.test.ts
index 5fa02be7c..9f6054a09 100644
--- a/src/web/src/lib/community/reading.routes.test.ts
+++ b/src/web/src/lib/community/reading.routes.test.ts
@@ -8,11 +8,8 @@ const mocks = vi.hoisted(() => ({ db: {}, access: vi.fn(), channel: vi.fn(), fri
vi.mock("@/lib/db", () => ({ getDb: () => mocks.db, getPrimaryDb: () => mocks.db }))
vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: mocks.access, requireChannelAccess: mocks.access }))
vi.mock("@/lib/community/message-door", () => ({ resolveMessageTarget: mocks.resolve }))
-vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: (request: NextRequest, context: unknown) => Promise<Response>) =>
- async (request: NextRequest, context: { params?: Promise<Record<string, string>> }) => handler(request, { params: await context.params, env: { DB: mocks.db }, userId: "viewer" }) }))
-vi.mock("@/lib/middleware/community-actor", () => ({ withCommunityActor: (handler: (request: NextRequest, context: unknown) => Promise<Response>) =>
- async (request: NextRequest, context: { params?: Promise<Record<string, string>> }) => handler(request, { params: await context.params, env: { DB: mocks.db },
- actor: request.headers.has("Authorization") ? { kind: "bot", userId: "bot" } : { kind: "human", userId: "viewer" } }) }))
+vi.mock("@/lib/middleware/auth", () => ({ humanAuthPolicy: { resolve: async (request: NextRequest) => ({ context: { env: { DB: mocks.db }, userId: "viewer" } }) } }))
+vi.mock("@/lib/middleware/community-actor", () => ({ communityActorPolicy: () => ({ resolve: async (request: NextRequest) => ({ context: { env: { DB: mocks.db }, actor: request.headers.has("Authorization") ? { kind: "bot", userId: "bot" } : { kind: "human", userId: "viewer" } } }) }) }))
vi.mock("@alook/shared", async (original) => ({ ...await original<typeof import("@alook/shared")>(), queries: {
communityChannel: { getChannelForMember: mocks.channel, listChildChannels: mocks.children }, communityFriendship: { areFriends: mocks.friends },
communityThread: { listThreadParticipants: mocks.participants, listForumThreadsByCreatedAt: mocks.threads, listParticipantsForChannels: mocks.threadParticipants },
diff --git a/src/web/src/lib/community/self-profile.sql.test.ts b/src/web/src/lib/community/self-profile.sql.test.ts
index 26cf1c6c4..4c21fb439 100644
--- a/src/web/src/lib/community/self-profile.sql.test.ts
+++ b/src/web/src/lib/community/self-profile.sql.test.ts
@@ -7,7 +7,7 @@ const state = vi.hoisted(() => ({ db: null as unknown }))
vi.mock("@/lib/db", () => ({ getDb: () => state.db }))
vi.mock("@/lib/auth", () => ({ getAuth: vi.fn() }))
vi.mock("@/lib/community/fanout", () => ({ fanOutProfileUpdate: vi.fn(), fanOutStatusUpdate: vi.fn() }))
-vi.mock("@/lib/middleware/community-actor", () => ({ withCommunityActor: (handler: (req: NextRequest, ctx: unknown) => Promise<Response>) => (req: NextRequest) => handler(req, { env: {}, actor: { kind: "human", userId: "new-user" } }) }))
+vi.mock("@/lib/middleware/community-actor", () => ({ communityActorPolicy: () => ({ resolve: async (req: NextRequest) => ({ context: { env: {}, actor: { kind: "human", userId: "new-user" } } }) }) }))
import { GET } from "@/app/api/community/users/me/profile/route"
const fixtures: ReturnType<typeof createCommunitySqliteDb>[] = []
diff --git a/src/web/src/lib/middleware/auth-composition.test.ts b/src/web/src/lib/middleware/auth-composition.test.ts
new file mode 100644
index 000000000..685d42652
--- /dev/null
+++ b/src/web/src/lib/middleware/auth-composition.test.ts
@@ -0,0 +1,140 @@
+import { withAuth } from "./auth-policy"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest, NextResponse } from "next/server"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_BOT_ACTOR_HEADER, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { humanAuthPolicy, cookieHumanAuthPolicy, optionalAuthPolicy } from "./auth"
+import { communityActorPolicy, rejectBot } from "./community-actor"
+import { machineAuthPolicy } from "./community-daemon-auth"
+import { pairingTokenPolicy } from "./community-pairing-token"
+import * as responses from "./response-cache"
+import { automationManagementPolicy } from "../automation"
+
+vi.mock("./response-cache", async original => {
+ const actual = await original<typeof import("./response-cache")>()
+ return { ...actual, protectCommunityJsonResponse: vi.fn(actual.protectCommunityJsonResponse) }
+})
+
+const m = vi.hoisted(() => ({
+ session: vi.fn(), signOut: vi.fn(), user: vi.fn(), runner: vi.fn(), binding: vi.fn(), owned: vi.fn(), machine: vi.fn(),
+ env: { DB: {}, CACHE_KV: {} }, execution: { waitUntil: vi.fn() },
+}))
+vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(async () => ({ env: m.env, ctx: m.execution })) }))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})), getPrimaryDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/cache", () => ({ bindCacheKV: vi.fn() }))
+vi.mock("@/lib/auth", () => ({ getAuth: () => ({ api: { getSession: m.session, signOut: m.signOut } }) }))
+vi.mock("@alook/shared", async original => {
+ const actual = await original<typeof import("@alook/shared")>()
+ return { ...actual, withD1Retry: async (fn: () => Promise<unknown>) => fn(), queries: {
+ ...actual.queries,
+ user: { ...actual.queries.user, getUserInternal: m.user },
+ communityMachine: { ...actual.queries.communityMachine, findActiveAgentRunnerKeyByBearer: m.runner, findActiveCredentialByBearer: m.machine },
+ communityBot: { ...actual.queries.communityBot, getBotBinding: m.binding, getBotOwnedBy: m.owned },
+ } }
+})
+
+beforeEach(() => {
+ vi.restoreAllMocks()
+ vi.resetAllMocks()
+ m.session.mockImplementation(async () => ({ headers: new Headers({ "Set-Cookie": "better-auth.session_data=fresh; HttpOnly" }), response: { user: { id: "owner", email: "[email protected]" } } }))
+ m.user.mockImplementation(async (_db, id) => ({ id, email: "[email protected]", isBot: id === "bot", deletedAt: null }))
+ m.runner.mockResolvedValue({ userId: "owner", machineId: "machine", agentId: "bot" })
+ m.binding.mockResolvedValue({ machineId: "machine", isActive: true })
+ m.owned.mockResolvedValue({ id: "bot", machineId: "machine", isActive: true })
+ m.machine.mockResolvedValue({ userId: "owner", machineId: "machine", credentialId: "credential" })
+})
+
+function request(headers: Record<string, string> = {}) {
+ return new NextRequest("https://alook.test/api/community/operation", {
+ method: "POST", body: '{"value":1}',
+ headers: { Origin: "https://alook.test", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), ...headers },
+ })
+}
+
+const cases = [
+ { name: "human", policy: humanAuthPolicy, headers: {}, calls: [1, 0, 0, 0, 0, 0], protected: 1 },
+ { name: "human actor", policy: communityActorPolicy(), headers: {}, calls: [1, 0, 0, 0, 0, 0], protected: 1 },
+ { name: "delegated bot", policy: communityActorPolicy(), headers: { [COMMUNITY_BOT_ACTOR_HEADER]: "bot" }, calls: [1, 0, 0, 0, 1, 0], protected: 1 },
+ { name: "runner", policy: communityActorPolicy(), headers: { Authorization: "Bearer crk_test" }, calls: [0, 1, 1, 1, 0, 0], protected: 1 },
+ { name: "sensitive human", policy: cookieHumanAuthPolicy, headers: {}, calls: [1, 1, 0, 0, 0, 0], protected: 1 },
+ { name: "optional human", policy: optionalAuthPolicy, headers: {}, calls: [1, 0, 0, 0, 0, 0], protected: 1 },
+ { name: "machine", policy: machineAuthPolicy, headers: { Authorization: "Bearer cmk_test" }, calls: [0, 0, 0, 0, 0, 1], protected: 0 },
+ { name: "pairing", policy: pairingTokenPolicy, headers: { Authorization: "Bearer cmt_test" }, calls: [0, 0, 0, 0, 0, 0], protected: 0 },
+]
+
+describe("composed credential execution", () => {
+ it.each(cases)("$name resolves once and leaves the body for business code", async ({ policy, headers, calls, protected: protections }) => {
+ const protect = vi.mocked(responses.protectCommunityJsonResponse)
+ const handler = vi.fn(async (req: NextRequest, ctx: { params?: Record<string, string> }) => {
+ expect(req.bodyUsed).toBe(false)
+ expect(ctx.params).toEqual({ id: "resource" })
+ return NextResponse.json(await req.json())
+ })
+ const response = await withAuth(policy, handler)(request(headers), { params: Promise.resolve({ id: "resource" }) })
+ expect(await response.json()).toEqual({ value: 1 })
+ expect(handler).toHaveBeenCalledOnce()
+ expect([m.session, m.user, m.runner, m.binding, m.owned, m.machine].map(fn => fn.mock.calls.length)).toEqual(calls)
+ expect(protect).toHaveBeenCalledTimes(protections)
+ })
+
+ it("composes a resource gate after credentials and before any business read", async () => {
+ const handler = vi.fn(async () => NextResponse.json({ private: true }))
+ const authorize = vi.fn((_req, ctx) => rejectBot(ctx.actor))
+ const response = await withAuth({ ...communityActorPolicy(), authorize }, handler)(request({ [COMMUNITY_BOT_ACTOR_HEADER]: "bot" }))
+ expect(response.status).toBe(403)
+ expect(handler).not.toHaveBeenCalled()
+ expect(authorize).toHaveBeenCalledOnce()
+ expect(m.session).toHaveBeenCalledOnce()
+ expect(m.owned).toHaveBeenCalledWith({}, "bot", "owner")
+ expect(response.headers.getSetCookie()).toEqual(["better-auth.session_data=fresh; HttpOnly"])
+ expect(await response.json()).toMatchObject({ error: { code: "not_allowed", message: "forbidden: not available to bots" } })
+ })
+
+ it("keeps session refresh on delegation failure without authenticating twice", async () => {
+ m.owned.mockResolvedValue(null)
+ const handler = vi.fn(async () => NextResponse.json({ ok: true }))
+ const response = await withAuth(communityActorPolicy(), handler)(request({ [COMMUNITY_BOT_ACTOR_HEADER]: "foreign" }))
+ expect(response.status).toBe(404)
+ expect(response.headers.getSetCookie()).toEqual(["better-auth.session_data=fresh; HttpOnly"])
+ expect(m.session).toHaveBeenCalledOnce()
+ expect(handler).not.toHaveBeenCalled()
+ })
+
+ it("never tries a cookie after a rejected recognized runner", async () => {
+ m.runner.mockResolvedValue(null)
+ const handler = vi.fn(async () => NextResponse.json({ ok: true }))
+ const response = await withAuth(communityActorPolicy(), handler)(request({ Authorization: "Bearer crk_revoked", Cookie: "better-auth.session_token=live" }))
+ expect(response.status).toBe(401)
+ expect(m.session).not.toHaveBeenCalled()
+ expect(handler).not.toHaveBeenCalled()
+ })
+
+ it("forwards a business cookie in preference to the session refresh", async () => {
+ const response = await withAuth(communityActorPolicy(), async () => new Response("done", { headers: { "Set-Cookie": "better-auth.session_data=business; HttpOnly" } }))(request())
+ expect(response.headers.getSetCookie()).toEqual(["better-auth.session_data=business; HttpOnly"])
+ })
+})
+
+describe("automation management composed with human auth", () => {
+ it.each(["", "Bearer aac_test", "Bearer crk_test", "Bearer cmk_test", "Basic unknown"])("rejects %j before session, bot selection and protocol checks", async authorization => {
+ const handler = vi.fn(async () => Response.json({ ok: true }))
+ const req = request({ Authorization: authorization, Cookie: "present", [COMMUNITY_BOT_ACTOR_HEADER]: "bot", [COMMUNITY_CONTRACT_HEADER]: "invalid" })
+ const response = await withAuth(automationManagementPolicy, handler)(req)
+ expect(response.status).toBe(401)
+ expect(await response.json()).toEqual({ error: "Sign in to manage access codes" })
+ expect(response.headers.get("Cache-Control")).toBeNull()
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBeNull()
+ expect(m.session).not.toHaveBeenCalled()
+ expect(handler).not.toHaveBeenCalled()
+ expect(responses.protectCommunityJsonResponse).not.toHaveBeenCalled()
+ })
+
+ it("shares human resolution once and retains Cookie refresh, params and response protection", async () => {
+ const handler = vi.fn(async (_req, ctx) => Response.json({ owner: ctx.userId, params: ctx.params }))
+ const response = await withAuth(automationManagementPolicy, handler)(request(), { params: Promise.resolve({ codeId: "own-code" }) })
+ expect(await response.json()).toEqual({ owner: "owner", params: { codeId: "own-code" } })
+ expect(response.headers.getSetCookie()).toEqual(["better-auth.session_data=fresh; HttpOnly"])
+ expect(response.headers.get("Cache-Control")).toBe("private, no-store, max-age=0")
+ expect(m.session).toHaveBeenCalledOnce()
+ expect(responses.protectCommunityJsonResponse).toHaveBeenCalledOnce()
+ })
+})
diff --git a/src/web/src/lib/middleware/auth-policy.ts b/src/web/src/lib/middleware/auth-policy.ts
new file mode 100644
index 000000000..df0513ef2
--- /dev/null
+++ b/src/web/src/lib/middleware/auth-policy.ts
@@ -0,0 +1,46 @@
+import type { NextRequest } from "next/server"
+
+export type AuthHandler<C> = (
+ request: NextRequest,
+ context: C & { params?: Record<string, string> },
+) => Promise<Response>
+
+/** Each successful resolution owns a fresh context for this request. */
+export type AuthResolution<C> = Response | {
+ context: C & { params?: Record<string, string> }
+ finish?: (response: Response) => Response
+}
+
+export interface AuthPolicy<C> {
+ params?: "afterAuth" | "ignore"
+ preflight?: (request: NextRequest) => Response | null
+ resolve: (request: NextRequest) => Promise<AuthResolution<C>>
+ authorize?: (request: NextRequest, context: C & { params?: Record<string, string> }) => Response | null | Promise<Response | null>
+ respond?: (request: NextRequest, response: Response) => Response | Promise<Response>
+}
+
+export function withAuth<C>(policy: AuthPolicy<C>, handler: AuthHandler<C>) {
+ return async (
+ request: NextRequest,
+ route?: { params?: Promise<Record<string, string>> | Record<string, string> },
+ ): Promise<Response> => {
+ let response = policy.preflight?.(request) ?? null
+ if (!response) {
+ const params = policy.params ? undefined
+ : route?.params instanceof Promise ? await route.params : route?.params
+ const resolved = await policy.resolve(request)
+ if (resolved instanceof Response) {
+ response = resolved
+ } else {
+ const context = resolved.context
+ context.params = policy.params === "afterAuth" ? await route?.params : params
+ const result = (policy.authorize ? await policy.authorize(request, context) : null)
+ ?? handler(request, context)
+ if (!resolved.finish && !policy.respond) return result
+ response = await result
+ if (resolved.finish) response = resolved.finish(response)
+ }
+ }
+ return policy.respond ? policy.respond(request, response) : response
+ }
+}
diff --git a/src/web/src/lib/middleware/auth.protocol.test.ts b/src/web/src/lib/middleware/auth.protocol.test.ts
index 13e60ff06..9238cc69c 100644
--- a/src/web/src/lib/middleware/auth.protocol.test.ts
+++ b/src/web/src/lib/middleware/auth.protocol.test.ts
@@ -1,9 +1,10 @@
+import { withAuth } from "./auth-policy"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest, NextResponse } from "next/server"
import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
-import { withCommunityActor } from "./community-actor"
+import { communityActorPolicy } from "./community-actor"
import { apiFetch } from "@/lib/api/client"
-import { withAuth, withCookieHumanAuth, withOptionalAuth, type OptionalAuthHandler } from "./auth"
+import { humanAuthPolicy, cookieHumanAuthPolicy, optionalAuthPolicy, type OptionalAuthHandler } from "./auth"
const mocks = vi.hoisted(() => ({ session: vi.fn(), signOut: vi.fn(), user: vi.fn(), machine: vi.fn(), bump: vi.fn(), bot: vi.fn() }))
vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} }, ctx: { waitUntil: vi.fn() } })) }))
@@ -12,7 +13,7 @@ vi.mock("./community-agent-runner-auth", () => ({ resolveBotActor: mocks.bot }))
vi.mock("@/lib/auth", () => ({ getAuth: vi.fn(() => ({ api: { getSession: mocks.session, signOut: mocks.signOut } })) }))
vi.mock("@alook/shared", async original => {
const actual = await original<typeof import("@alook/shared")>()
- return { ...actual, createDb: vi.fn(() => ({})), queries: { ...actual.queries, machineToken: { ...actual.queries.machineToken, getMachineTokenByToken: mocks.machine, updateMachineTokenLastUsed: mocks.bump }, user: { ...actual.queries.user, getUserInternal: mocks.user } } }
+ return { ...actual, createDb: vi.fn(() => ({})), queries: { ...actual.queries, user: { ...actual.queries.user, getUserInternal: mocks.user } } }
})
beforeEach(() => {
@@ -22,7 +23,7 @@ beforeEach(() => {
})
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
-function connect(handler: ReturnType<typeof withOptionalAuth> | ReturnType<typeof withCookieHumanAuth>) {
+function connect(handler: ReturnType<typeof withAuth>) {
let received: NextRequest | undefined, produced: Response | undefined
vi.stubGlobal("fetch", vi.fn(async (path: string, options?: RequestInit) => {
received = new NextRequest(new URL(path, "https://alook.test"), options)
@@ -37,34 +38,34 @@ describe("current auth wrapper producer to API consumer", () => {
it("admits anonymous current invite info through optional auth", async () => {
mocks.session.mockResolvedValue({ headers: new Headers(), response: null })
const handler = vi.fn(async (_req: NextRequest, ctx: Parameters<OptionalAuthHandler>[1]) => NextResponse.json({ serverId: "server", anonymous: ctx.userId === undefined }))
- const transport = connect(withOptionalAuth(handler))
+ const transport = connect(withAuth(optionalAuthPolicy, handler))
expect(await apiFetch("/api/community/invites/token/info")).toEqual({ serverId: "server", anonymous: true })
expect(transport.request.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
expect(transport.response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
expect(transport.response.headers.get("Cache-Control")).toBe("private, no-store, max-age=0")
})
it("preserves optional-auth failure status and current readable error", async () => {
- connect(withOptionalAuth(async () => NextResponse.json({ error: "invite expired" }, { status: 410 })))
+ connect(withAuth(optionalAuthPolicy, async () => NextResponse.json({ error: "invite expired" }, { status: 410 })))
await expect(apiFetch("/api/community/invites/token/info")).rejects.toMatchObject({ name: "ApiError", status: 410, message: "invite expired" })
})
it("confirms a live Cookie human result and forwards refreshed cookies", async () => {
- const transport = connect(withCookieHumanAuth(async (_req, ctx) => NextResponse.json({ userId: ctx.userId, email: ctx.email })))
+ const transport = connect(withAuth(cookieHumanAuthPolicy, async (_req, ctx) => NextResponse.json({ userId: ctx.userId, email: ctx.email })))
expect(await apiFetch("/api/community/billing/portal", { method: "POST", headers: sameOrigin })).toEqual({ userId: "viewer", email: "[email protected]" })
expect(transport.response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
expect(transport.response.headers.get("Set-Cookie")).toContain("session_data=refreshed")
})
it("preserves current operation error messages through Cookie auth and apiFetch", async () => {
- connect(withCookieHumanAuth(async () => NextResponse.json({ error: "INVALID_OTP" }, { status: 400 })))
+ connect(withAuth(cookieHumanAuthPolicy, async () => NextResponse.json({ error: "INVALID_OTP" }, { status: 400 })))
await expect(apiFetch("/api/community/users/me/account-deletion", { method: "POST", headers: sameOrigin })).rejects.toMatchObject({ name: "ApiError", status: 400, message: "INVALID_OTP" })
})
it("keeps Origin rejection before session lookup", async () => {
- connect(withCookieHumanAuth(async () => NextResponse.json({ ok: true })))
+ connect(withAuth(cookieHumanAuthPolicy, async () => NextResponse.json({ ok: true })))
await expect(apiFetch("/api/community/billing/portal", { method: "POST", headers: { Origin: "https://other.test" } })).rejects.toMatchObject({ name: "ApiError", status: 403, message: "FORBIDDEN" })
expect(mocks.session).not.toHaveBeenCalled()
})
it("keeps a qualified401 transition and current protected response", async () => {
mocks.session.mockResolvedValue({ headers: new Headers(), response: null })
- const transport = connect(withCookieHumanAuth(async () => NextResponse.json({ ok: true })))
+ const transport = connect(withAuth(cookieHumanAuthPolicy, async () => NextResponse.json({ ok: true })))
const onUnauthorized = vi.fn(async () => false)
await expect(apiFetch("/api/community/billing/portal", { method: "POST", headers: sameOrigin, onUnauthorized })).rejects.toMatchObject({ name: "AbortError" })
expect(onUnauthorized).toHaveBeenCalledOnce()
@@ -72,14 +73,14 @@ describe("current auth wrapper producer to API consumer", () => {
expect(transport.response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
})
it("keeps outside-community privacy Cookie operations independent", async () => {
- const transport = connect(withCookieHumanAuth(async () => NextResponse.json({ consent: false })))
+ const transport = connect(withAuth(cookieHumanAuthPolicy, async () => NextResponse.json({ consent: false })))
expect(await apiFetch("/api/privacy/analytics-consent", { method: "POST", headers: sameOrigin })).toEqual({ consent: false })
expect(transport.request.headers.get(COMMUNITY_CONTRACT_HEADER)).toBeNull()
expect(transport.response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBeNull()
})
it.each(["optional", "cookie"])("rejects an old request before the %s handler/session", async kind => {
const handler = vi.fn(async () => NextResponse.json({ ok: true }))
- const wrapped = kind === "cookie" ? withCookieHumanAuth(handler) : withOptionalAuth(handler)
+ const wrapped = kind === "cookie" ? withAuth(cookieHumanAuthPolicy, handler) : withAuth(optionalAuthPolicy, handler)
const response = await wrapped(new NextRequest("https://alook.test/api/community/operation", { method: "POST", headers: { ...sameOrigin, [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION - 1) } }))
expect(response.status).toBe(400)
expect(handler).not.toHaveBeenCalled()
@@ -87,10 +88,9 @@ describe("current auth wrapper producer to API consumer", () => {
})
})
-
describe("independent actor qualification", () => {
function wrap(kind: string, handler: () => Promise<Response>) {
- return kind === "optional" ? withOptionalAuth(handler) : kind === "actor" ? withCommunityActor(handler) : withAuth(handler)
+ return kind === "optional" ? withAuth(optionalAuthPolicy, handler) : kind === "actor" ? withAuth(communityActorPolicy(), handler) : withAuth(humanAuthPolicy, handler)
}
it.each(["auth", "optional", "actor"].flatMap(kind => [null, BUSINESS_SCHEMA_VERSION - 1].map(version => ({ kind, version }))))("rejects an unqualified Bearer with live Cookie ($kind/$version)", async ({ kind, version }) => {
const handler = vi.fn(async () => NextResponse.json({ ok: true }))
@@ -104,18 +104,31 @@ describe("independent actor qualification", () => {
expect(response.status).toBe(200); expect(handler).toHaveBeenCalledOnce()
expect(mocks.session).toHaveBeenCalledOnce()
})
- it.each([true, false])("qualifies machine credentials before an independent request (%s)", async valid => {
- mocks.machine.mockResolvedValue(valid ? { id: "mt", userId: "viewer", userEmail: "[email protected]", workspaceId: null } : null)
- const handler = vi.fn(async () => NextResponse.json({ ok: true }))
- const response = await withAuth(handler)(new NextRequest("https://alook.test/api/community/operation", { headers: { Cookie: "better-auth.session_token=live", Authorization: "Bearer al_credential" } }))
- expect(response.status).toBe(valid ? 200 : 401)
- expect(handler).toHaveBeenCalledTimes(valid ? 1 : 0)
- expect(mocks.machine).toHaveBeenCalledOnce(); expect(mocks.session).not.toHaveBeenCalled()
+ it.each(["cookie", "runner"])("preserves asynchronous handler error identity (%s)", async kind => {
+ const failure = new Error("route failed")
+ const handler = vi.fn(async () => { throw failure })
+ mocks.bot.mockResolvedValue({ kind: "ok", actor: { botUserId: "bot", ownerUserId: "viewer", machineId: "machine", isActive: true } })
+ const request = new NextRequest("https://alook.test/api/community/operation", {
+ headers: {
+ Cookie: "better-auth.session_token=live",
+ [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION),
+ ...(kind === "runner" ? { Authorization: "Bearer crk_credential" } : {}),
+ },
+ })
+ await expect(wrap(kind === "runner" ? "actor" : "auth", handler)(request)).rejects.toBe(failure)
+ expect(handler).toHaveBeenCalledOnce()
+ if (kind === "runner") {
+ expect(mocks.bot).toHaveBeenCalledOnce()
+ expect(mocks.session).not.toHaveBeenCalled()
+ } else {
+ expect(mocks.session).toHaveBeenCalledOnce()
+ expect(mocks.bot).not.toHaveBeenCalled()
+ }
})
it.each([true, false])("qualifies bot credentials before an independent request (%s)", async valid => {
mocks.bot.mockResolvedValue(valid ? { kind: "ok", actor: { botUserId: "bot", ownerUserId: "viewer", machineId: "machine", isActive: true } } : { kind: "error", response: NextResponse.json({ error: "invalid runner key" }, { status: 401 }) })
const handler = vi.fn(async () => NextResponse.json({ ok: true }))
- const response = await withCommunityActor(handler)(new NextRequest("https://alook.test/api/community/operation", { headers: { Cookie: "better-auth.session_token=live", Authorization: "Bearer crk_credential" } }))
+ const response = await withAuth(communityActorPolicy(), handler)(new NextRequest("https://alook.test/api/community/operation", { headers: { Cookie: "better-auth.session_token=live", Authorization: "Bearer crk_credential" } }))
expect(response.status).toBe(valid ? 200 : 401)
expect(handler).toHaveBeenCalledTimes(valid ? 1 : 0)
expect(mocks.bot).toHaveBeenCalledOnce(); expect(mocks.session).not.toHaveBeenCalled()
@@ -125,7 +138,7 @@ describe("independent actor qualification", () => {
describe("current independent media capability", () => {
it("admits the actual bot-avatar GET family after Cookie auth without a business header", async () => {
const handler = vi.fn(async () => new Response("png", { headers: { "Content-Type": "image/png" } }))
- const response = await withAuth(handler)(new NextRequest("https://alook.test/api/community/bots/bot/avatar?v=2", { headers: { Cookie: "better-auth.session_token=live" } }))
+ const response = await withAuth(humanAuthPolicy, handler)(new NextRequest("https://alook.test/api/community/bots/bot/avatar?v=2", { headers: { Cookie: "better-auth.session_token=live" } }))
expect(response.status).toBe(200); expect(await response.text()).toBe("png")
expect(handler).toHaveBeenCalledOnce(); expect(mocks.session).toHaveBeenCalledOnce()
expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBeNull()
@@ -133,12 +146,12 @@ describe("current independent media capability", () => {
it("keeps the same media read session-qualified", async () => {
mocks.session.mockResolvedValue({ headers: new Headers(), response: null })
const handler = vi.fn(async () => new Response("png"))
- const response = await withAuth(handler)(new NextRequest("https://alook.test/api/community/bots/bot/avatar"))
+ const response = await withAuth(humanAuthPolicy, handler)(new NextRequest("https://alook.test/api/community/bots/bot/avatar"))
expect(response.status).toBe(401); expect(handler).not.toHaveBeenCalled()
})
it("requires the current JSON contract on bot-avatar upload", async () => {
const handler = vi.fn(async () => NextResponse.json({ url: "avatar" }))
- const response = await withAuth(handler)(new NextRequest("https://alook.test/api/community/bots/bot/avatar", { method: "POST", headers: { Cookie: "better-auth.session_token=live" } }))
+ const response = await withAuth(humanAuthPolicy, handler)(new NextRequest("https://alook.test/api/community/bots/bot/avatar", { method: "POST", headers: { Cookie: "better-auth.session_token=live" } }))
expect(response.status).toBe(400); expect(handler).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/lib/middleware/auth.test.ts b/src/web/src/lib/middleware/auth.test.ts
index 29a18bb81..aaf220766 100644
--- a/src/web/src/lib/middleware/auth.test.ts
+++ b/src/web/src/lib/middleware/auth.test.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "./auth-policy"
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest, NextResponse } from "next/server";
import { getCloudflareContext } from "@opennextjs/cloudflare";
@@ -15,10 +16,6 @@ vi.mock("@alook/shared", async (importOriginal) => ({
...await importOriginal<typeof import("@alook/shared")>(),
createDb: vi.fn(() => ({})),
queries: {
- machineToken: {
- getMachineTokenByToken: vi.fn(),
- updateMachineTokenLastUsed: vi.fn(),
- },
user: {
getUserInternal: vi.fn(),
},
@@ -36,28 +33,13 @@ vi.mock("@/lib/auth", () => ({
})),
}));
-import { withAuth, withCookieHumanAuth, withOptionalAuth, warmMachineTokenCache } from "./auth";
+import { humanAuthPolicy, cookieHumanAuthPolicy, optionalAuthPolicy } from "./auth";
import { BUSINESS_SCHEMA_VERSION, COMMUNITY_BOT_ACTOR_HEADER, COMMUNITY_CONTRACT_HEADER, queries } from "@alook/shared";
-import { withCommunityActor, type CommunityActor } from "./community-actor";
+import { communityActorPolicy, type CommunityActor } from "./community-actor";
-const mockGetMachineTokenByHash = queries.machineToken
- .getMachineTokenByToken as ReturnType<typeof vi.fn>;
-const mockUpdateMachineTokenLastUsed = queries.machineToken
- .updateMachineTokenLastUsed as ReturnType<typeof vi.fn>;
const mockGetUserInternal = queries.user.getUserInternal as ReturnType<typeof vi.fn>;
const mockGetCloudflareContext = getCloudflareContext as unknown as ReturnType<typeof vi.fn>;
-/** Build a stub KV and point the CF context at it for one test. */
-function bindMockKV(overrides?: { get?: ReturnType<typeof vi.fn> }) {
- const kv = {
- get: overrides?.get ?? vi.fn().mockResolvedValue(null),
- put: vi.fn().mockResolvedValue(undefined),
- delete: vi.fn().mockResolvedValue(undefined),
- };
- mockGetCloudflareContext.mockResolvedValue({ env: { DB: {}, CACHE_KV: kv }, ctx: { waitUntil: vi.fn() } });
- return kv;
-}
-
const testHandler = vi.fn(async (_req: NextRequest, ctx: any) =>
NextResponse.json({ ok: true, ctx })
);
@@ -69,7 +51,7 @@ describe("withAuth middleware", () => {
mockGetCloudflareContext.mockResolvedValue({ env: { DB: {} }, ctx: { waitUntil: vi.fn() } });
});
- const wrapped = withAuth(testHandler);
+ const wrapped = withAuth(humanAuthPolicy, testHandler);
it("returns 401 when Authorization header is missing", async () => {
const req = new NextRequest("http://localhost/api/test");
@@ -108,7 +90,7 @@ describe("withAuth middleware", () => {
it("rejects a crk_ runner-key bearer — a bot never authenticates as a human here (§5 red line)", async () => {
// Privilege-escalation invariant: the human-only community
// surfaces (/bots/*, /daemon/*, human inbox, channel management) stay on
- // withAuth, NOT withCommunityActor. A crk_ bearer is neither an al_ machine
+ // withAuth, NOT communityActorPolicy. A crk_ bearer is neither an al_ machine
// token nor a session, so it falls through to the session path and finds no
// session → 401. This is what keeps a bot structurally unable to reach a
// human-only route after the actor unification.
@@ -122,14 +104,14 @@ describe("withAuth middleware", () => {
expect((await res.json()).error).toBe("unauthorized");
});
- it("authenticates valid Better Auth session and passes userId/email to handler", async () => {
+ it("authenticates valid Better Auth Cookie session and passes userId/email to handler", async () => {
mockGetSession.mockResolvedValue({
headers: new Headers(),
response: { user: { id: "user-1", email: "[email protected]" } },
});
const req = new NextRequest("http://localhost/api/test", {
- headers: { Authorization: "Bearer some-session-token" },
+ headers: { Cookie: "better-auth.session_token=live" },
});
const res = await wrapped(req);
const body = await res.json();
@@ -181,7 +163,7 @@ describe("withAuth middleware", () => {
ETag: '"media-v1"',
...(vary ? { Vary: vary } : {}),
} });
- const res = await withAuth(async () => original)(new NextRequest("http://localhost/media", { headers: { Cookie: "viewer=A" } }));
+ const res = await withAuth(humanAuthPolicy, async () => original)(new NextRequest("http://localhost/media", { headers: { Cookie: "viewer=A" } }));
expect(res.headers.get("Vary")).toBe(expected === "*" ? expected : `${expected}, X-Alook-Bot-Id`);
expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable");
expect(res.headers.get("ETag")).toBe('"media-v1"');
@@ -190,26 +172,10 @@ describe("withAuth middleware", () => {
expect(await res.text()).toBe("media");
});
- it.each([200, 304])("varies private machine-token media status %s by both credential headers", async (status) => {
- mockGetMachineTokenByHash.mockResolvedValue({ id: "mt-1", userId: "A", userEmail: "[email protected]", workspaceId: "ws-1" });
- const res = await withAuth(async () => new Response(status === 304 ? null : "media", {
- status, headers: { "Cache-Control": "private, max-age=31536000, immutable", Vary: "Accept-Encoding" },
- }))(new NextRequest("http://localhost/media", { headers: { Authorization: "Bearer al_test" } }));
- expect(res.status).toBe(status);
- expect(res.headers.get("Vary")).toBe("Accept-Encoding, Cookie, Authorization, X-Alook-Bot-Id");
- });
-
- it("preserves asynchronous machine handler error propagation", async () => {
- mockGetMachineTokenByHash.mockResolvedValue({ id: "mt-1", userId: "A", userEmail: "[email protected]", workspaceId: "ws-1" });
- const failure = new Error("route failed");
- const res = withAuth(async () => { throw failure; })(new NextRequest("http://localhost/media", { headers: { Authorization: "Bearer al_test" } }));
- await expect(res).rejects.toBe(failure);
- });
-
it("preserves the declared public response policy", async () => {
mockGetSession.mockResolvedValue({ headers: new Headers(), response: { user: { id: "A", email: "[email protected]" } } });
const original = new Response("public", { headers: { "Cache-Control": "public, max-age=300", Vary: "Accept-Encoding" } });
- const res = await withAuth(async () => original)(new NextRequest("http://localhost/public"));
+ const res = await withAuth(humanAuthPolicy, async () => original)(new NextRequest("http://localhost/public"));
expect(res).toBe(original);
expect(res.headers.get("Vary")).toBe("Accept-Encoding");
});
@@ -260,166 +226,13 @@ describe("withAuth middleware", () => {
expect(body.error).toBe("unauthorized");
});
- it("authenticates machine token (al_ prefix) via hash lookup", async () => {
- mockGetMachineTokenByHash.mockResolvedValue({
- id: "mt-1",
- userId: "user-mt",
- userEmail: "[email protected]",
- workspaceId: "ws-1",
- });
- mockUpdateMachineTokenLastUsed.mockResolvedValue(undefined);
-
- const req = new NextRequest("http://localhost/api/test", {
- headers: { Authorization: "Bearer al_secret_token" },
- });
- const res = await wrapped(req);
- const body = await res.json();
-
- expect(res.status).toBe(200);
- expect(body.ok).toBe(true);
- expect(body.ctx.userId).toBe("user-mt");
- expect(body.ctx.email).toBe("[email protected]");
- expect(body.ctx.workspaceId).toBe("ws-1");
- expect(mockGetMachineTokenByHash).toHaveBeenCalledOnce();
- });
-
- it("returns 401 for unknown machine token (getMachineTokenByToken returns null)", async () => {
- mockGetMachineTokenByHash.mockResolvedValue(null);
-
- const req = new NextRequest("http://localhost/api/test", {
- headers: { Authorization: "Bearer al_invalid_token" },
- });
- const res = await wrapped(req);
- const body = await res.json();
-
- expect(res.status).toBe(401);
- expect(body.error).toBe("invalid token");
- });
-
- it("returns 503 (not 401) when the D1 token lookup throws — transient, daemon must retry", async () => {
- mockGetMachineTokenByHash.mockRejectedValue(new Error("D1 unavailable"));
-
- const req = new NextRequest("http://localhost/api/test", {
- headers: { Authorization: "Bearer al_valid_but_db_down" },
- });
- const res = await wrapped(req);
- const body = await res.json();
-
- // Must NOT be 401 — a DB blip is not a revoked token; the daemon uses 401
- // to mark a workspace auth-failed, so a transient failure must be 503.
- expect(res.status).toBe(503);
- expect(body.error).not.toBe("invalid token");
- });
-
- it("updates lastUsedAt on machine token auth", async () => {
- mockGetMachineTokenByHash.mockResolvedValue({
- id: "mt-2",
- userId: "user-mt2",
- userEmail: "[email protected]",
- workspaceId: null,
- });
- mockUpdateMachineTokenLastUsed.mockResolvedValue(undefined);
-
- const req = new NextRequest("http://localhost/api/test", {
- headers: { Authorization: "Bearer al_another_token" },
- });
- await wrapped(req);
-
- expect(mockUpdateMachineTokenLastUsed).toHaveBeenCalledWith({}, "mt-2");
- });
-
- it("cold KV miss populates the merged entry and bumps last_used immediately", async () => {
- const kv = bindMockKV();
- mockGetMachineTokenByHash.mockResolvedValue({
- id: "mt-cold",
- userId: "user-cold",
- userEmail: "[email protected]",
- workspaceId: null,
- });
-
- const req = new NextRequest("http://localhost/api/test", {
- headers: { Authorization: "Bearer al_cold_token" },
- });
- const res = await wrapped(req);
-
- expect(res.status).toBe(200);
- expect(mockGetMachineTokenByHash).toHaveBeenCalledOnce();
- expect(mockUpdateMachineTokenLastUsed).toHaveBeenCalledWith({}, "mt-cold");
- // Entry written back with luAt so the throttle window starts now.
- expect(kv.put).toHaveBeenCalledOnce();
- const [, storedJson] = kv.put.mock.calls[0];
- const stored = JSON.parse(storedJson);
- expect(stored.row.id).toBe("mt-cold");
- expect(typeof stored.luAt).toBe("number");
- });
-
- it("warm KV hit within throttle window skips D1 and does not bump", async () => {
- const entry = {
- row: { id: "mt-warm", userId: "user-warm", userEmail: "[email protected]", workspaceId: "ws-w" },
- luAt: Date.now(),
- };
- bindMockKV({ get: vi.fn().mockResolvedValue(JSON.stringify(entry)) });
-
- const req = new NextRequest("http://localhost/api/test", {
- headers: { Authorization: "Bearer al_warm_token" },
- });
- const res = await wrapped(req);
- const body = await res.json();
-
- expect(res.status).toBe(200);
- expect(body.ctx.userId).toBe("user-warm");
- expect(mockGetMachineTokenByHash).not.toHaveBeenCalled();
- expect(mockUpdateMachineTokenLastUsed).not.toHaveBeenCalled();
- });
-
- it("warm KV hit past throttle window bumps last_used and refreshes luAt", async () => {
- const stale = {
- row: { id: "mt-stale", userId: "user-stale", userEmail: "[email protected]", workspaceId: null },
- luAt: Date.now() - 901_000,
- };
- const kv = bindMockKV({ get: vi.fn().mockResolvedValue(JSON.stringify(stale)) });
-
- const req = new NextRequest("http://localhost/api/test", {
- headers: { Authorization: "Bearer al_stale_token" },
- });
- const res = await wrapped(req);
-
- expect(res.status).toBe(200);
- expect(mockGetMachineTokenByHash).not.toHaveBeenCalled();
- expect(mockUpdateMachineTokenLastUsed).toHaveBeenCalledWith({}, "mt-stale");
- expect(kv.put).toHaveBeenCalledOnce();
- });
-
- it("negative-caches an invalid token so a repeat request skips D1", async () => {
- bindMockKV({ get: vi.fn().mockResolvedValue(JSON.stringify({ row: null, luAt: Date.now() })) });
-
- const req = new NextRequest("http://localhost/api/test", {
- headers: { Authorization: "Bearer al_negcached_token" },
- });
- const res = await wrapped(req);
- const body = await res.json();
-
+ it("rejects retired al_ credentials without consulting a live cookie or infrastructure", async () => {
+ mockGetSession.mockResolvedValue({ headers: new Headers(), response: { user: { id: "owner", email: "[email protected]" } } });
+ const res = await wrapped(new NextRequest("http://localhost/api/test", { headers: { Authorization: "Bearer al_retired", Cookie: "better-auth.session_token=live" } }));
expect(res.status).toBe(401);
- expect(body.error).toBe("invalid token");
- expect(mockGetMachineTokenByHash).not.toHaveBeenCalled();
- });
-
- it("falls back to D1 when KV read throws (a blip must not 401 a valid token)", async () => {
- bindMockKV({ get: vi.fn().mockRejectedValue(new Error("kv down")) });
- mockGetMachineTokenByHash.mockResolvedValue({
- id: "mt-blip",
- userId: "user-blip",
- userEmail: "[email protected]",
- workspaceId: null,
- });
-
- const req = new NextRequest("http://localhost/api/test", {
- headers: { Authorization: "Bearer al_blip_token" },
- });
- const res = await wrapped(req);
-
- expect(res.status).toBe(200);
- expect(mockGetMachineTokenByHash).toHaveBeenCalledOnce();
+ expect(mockGetSession).not.toHaveBeenCalled();
+ expect(mockGetCloudflareContext).not.toHaveBeenCalled();
+ expect(testHandler).not.toHaveBeenCalled();
});
it("resolves dynamic params from context", async () => {
@@ -439,13 +252,13 @@ describe("withAuth middleware", () => {
});
});
-describe("withOptionalAuth middleware", () => {
+describe("optionalAuthPolicy middleware", () => {
beforeEach(() => {
vi.clearAllMocks();
mockGetCloudflareContext.mockResolvedValue({ env: { DB: {} }, ctx: { waitUntil: vi.fn() } });
});
- const wrapped = withOptionalAuth(testHandler);
+ const wrapped = withAuth(optionalAuthPolicy, testHandler);
it("runs the handler anonymously (userId undefined, NOT 401) when there is no session", async () => {
mockGetSession.mockResolvedValue({ headers: new Headers(), response: null });
@@ -529,7 +342,6 @@ describe("withOptionalAuth middleware", () => {
expect(res.status).toBe(200);
expect(body.ctx.userId).toBeUndefined();
// The optional wrapper never touches the machine-token D1 lookup.
- expect(mockGetMachineTokenByHash).not.toHaveBeenCalled();
});
it("resolves dynamic params from context", async () => {
@@ -544,8 +356,8 @@ describe("withOptionalAuth middleware", () => {
});
});
-describe("withCookieHumanAuth middleware", () => {
- const wrapped = withCookieHumanAuth(testHandler);
+describe("cookieHumanAuthPolicy middleware", () => {
+ const wrapped = withAuth(cookieHumanAuthPolicy, testHandler);
beforeEach(() => {
vi.clearAllMocks();
@@ -653,7 +465,6 @@ describe("withCookieHumanAuth middleware", () => {
expect(res.status).toBe(401);
expect(await res.json()).toEqual({ error: "UNAUTHORIZED" });
expect(mockGetSession).not.toHaveBeenCalled();
- expect(mockGetMachineTokenByHash).not.toHaveBeenCalled();
});
it("rejects a Better Auth bearer because deletion is cookie-session only", async () => {
@@ -789,7 +600,7 @@ describe("withCookieHumanAuth middleware", () => {
headers: { Origin: "https://alook.ai" },
});
- const res = await withCookieHumanAuth(deletingHandler)(req);
+ const res = await withAuth(cookieHumanAuthPolicy, deletingHandler)(req);
const cookies = res.headers.getSetCookie();
expect(cookies).not.toContain("better-auth.session_data=fresh; Path=/");
@@ -798,55 +609,10 @@ describe("withCookieHumanAuth middleware", () => {
});
});
-describe("warmMachineTokenCache", () => {
- beforeEach(() => vi.clearAllMocks());
-
- const row = {
- id: "mt-warm",
- userId: "user-warm",
- userEmail: "[email protected]",
- workspaceId: "ws-w",
- status: "active",
- } as any;
-
- it("writes a positive { row, luAt } entry at the 15-min TTL", async () => {
- const kv = { get: vi.fn(), put: vi.fn().mockResolvedValue(undefined), delete: vi.fn() };
- await warmMachineTokenCache(kv as any, "al_warm_token", row);
-
- expect(kv.put).toHaveBeenCalledOnce();
- const [key, value, opts] = kv.put.mock.calls[0];
- expect(key).toBe(`mt:${"al_warm_token".slice(0, 20)}`);
- const parsed = JSON.parse(value);
- expect(parsed.row).toEqual(row);
- expect(typeof parsed.luAt).toBe("number");
- expect(opts.expirationTtl).toBe(900);
- });
-
- it("a subsequent withAuth read hits the warmed entry without touching D1", async () => {
- const entry = { row, luAt: Date.now() };
- bindMockKV({ get: vi.fn().mockResolvedValue(JSON.stringify(entry)) });
- const wrapped = withAuth(testHandler);
-
- const req = new NextRequest("http://localhost/api/test", {
- headers: { Authorization: "Bearer al_warm_token" },
- });
- const res = await wrapped(req);
-
- expect(res.status).toBe(200);
- // Warm hit — no cold D1 read.
- expect(mockGetMachineTokenByHash).not.toHaveBeenCalled();
- });
-
- it("is a no-op when KV is null (no throw)", async () => {
- await expect(warmMachineTokenCache(null, "al_x", row)).resolves.toBeUndefined();
- });
-});
-
-
describe("human-only bot-selection rejection", () => {
- it.each([withAuth, withCookieHumanAuth, withOptionalAuth])("rejects bot selection before a human-only handler can mutate the owner (%#)", async (wrap) => {
+ it.each([humanAuthPolicy, cookieHumanAuthPolicy, optionalAuthPolicy])("rejects bot selection before a human-only handler can mutate the owner (%#)", async (policy) => {
const handler = vi.fn(async () => NextResponse.json({ ok: true }))
- const response = await wrap(handler)(new NextRequest("http://localhost/api/community/bots", { headers: { "X-Alook-Bot-Id": "bot_1", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, method: "POST" }))
+ const response = await withAuth(policy, handler)(new NextRequest("http://localhost/api/community/bots", { headers: { "X-Alook-Bot-Id": "bot_1", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, method: "POST" }))
expect(response.status).toBe(403)
expect(handler).not.toHaveBeenCalled()
})
@@ -864,11 +630,10 @@ describe("current contract with actual owner-delegated actor authentication", ()
vi.clearAllMocks()
mockGetCloudflareContext.mockResolvedValue({ env: { DB: {} }, ctx: { waitUntil: vi.fn() } })
mockGetSession.mockResolvedValue({ headers: new Headers(), response: { user: { id: "owner", email: "[email protected]", isBot: false, deletedAt: null } } })
- mockGetMachineTokenByHash.mockResolvedValue(null)
ownedBot.mockResolvedValue({ id: "selected-bot", machineId: "machine", isActive: true })
})
it("admits the current owner session only after real auth and scoped bot resolution", async () => {
- const response = await withCommunityActor(route)(request())
+ const response = await withAuth(communityActorPolicy(), route)(request())
expect(response.status).toBe(200)
expect(ownedBot).toHaveBeenCalledWith({}, "selected-bot", "owner")
expect(await response.json()).toEqual({ actor: { kind: "bot", userId: "selected-bot", ownerUserId: "owner", machineId: "machine", isActive: true, delegatedByUserId: "owner" } })
@@ -877,7 +642,7 @@ describe("current contract with actual owner-delegated actor authentication", ()
for (const field of ["Cookie", "Authorization", COMMUNITY_CONTRACT_HEADER, COMMUNITY_BOT_ACTOR_HEADER]) expect(response.headers.get("Vary")).toContain(field)
})
it.each([null, "2", "3", String(BUSINESS_SCHEMA_VERSION + 1)])("does not exempt a cookie request with bot selection and contract %s", async version => {
- const response = await withCommunityActor(route)(request(version))
+ const response = await withAuth(communityActorPolicy(), route)(request(version))
expect(response.status).toBe(400)
expect(mockGetSession).not.toHaveBeenCalled()
expect(ownedBot).not.toHaveBeenCalled()
@@ -885,45 +650,24 @@ describe("current contract with actual owner-delegated actor authentication", ()
})
it("does not resolve or impersonate a selected bot without an authenticated owner", async () => {
mockGetSession.mockResolvedValue({ headers: new Headers(), response: null })
- const response = await withCommunityActor(route)(request())
+ const response = await withAuth(communityActorPolicy(), route)(request())
expect(response.status).toBe(401)
expect(ownedBot).not.toHaveBeenCalled()
expect(route).not.toHaveBeenCalled()
})
it("keeps foreign or missing bot refusal after the owner is authenticated", async () => {
ownedBot.mockResolvedValue(null)
- const response = await withCommunityActor(route)(request())
+ const response = await withAuth(communityActorPolicy(), route)(request())
expect(response.status).toBe(404)
expect(ownedBot).toHaveBeenCalledWith({}, "selected-bot", "owner")
expect(route).not.toHaveBeenCalled()
})
- it("validates an invalid machine token before refusing missing-contract delegation", async () => {
+ it("rejects retired tokens before resolving an owner-selected bot", async () => {
const req = request(null)
- req.headers.set("Authorization", "Bearer al_invalid-composition-control")
- const response = await withCommunityActor(route)(req)
+ req.headers.set("Authorization", "Bearer al_retired")
+ const response = await withAuth(communityActorPolicy(), route)(req)
expect(response.status).toBe(401)
- expect(mockGetMachineTokenByHash).toHaveBeenCalledWith({}, "al_invalid-composition-control")
- expect(ownedBot).not.toHaveBeenCalled()
- expect(route).not.toHaveBeenCalled()
- })
- it("allows the missing version only after a valid independent machine credential", async () => {
- mockGetMachineTokenByHash.mockResolvedValue({ id: "machine-token", userId: "owner", userEmail: "[email protected]" })
- const req = request(null)
- req.headers.set("Authorization", "Bearer al_valid-composition-control")
- const response = await withCommunityActor(route)(req)
- expect(response.status).toBe(200)
- expect(mockGetMachineTokenByHash).toHaveBeenCalledWith({}, "al_valid-composition-control")
expect(mockGetSession).not.toHaveBeenCalled()
- expect(ownedBot).toHaveBeenCalledWith({}, "selected-bot", "owner")
- expect(route).toHaveBeenCalledOnce()
- })
- it.each(["2", "3"])("refuses explicit old contract %s even after valid machine authentication", async version => {
- mockGetMachineTokenByHash.mockResolvedValue({ id: "machine-token", userId: "owner", userEmail: "[email protected]" })
- const req = request(version)
- req.headers.set("Authorization", "Bearer al_valid-composition-control")
- const response = await withCommunityActor(route)(req)
- expect(response.status).toBe(400)
- expect(mockGetMachineTokenByHash).toHaveBeenCalledWith({}, "al_valid-composition-control")
expect(ownedBot).not.toHaveBeenCalled()
expect(route).not.toHaveBeenCalled()
})
diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.ts
index 4fcb502ce..75a6b98f4 100644
--- a/src/web/src/lib/middleware/auth.ts
+++ b/src/web/src/lib/middleware/auth.ts
@@ -1,17 +1,17 @@
+import type { AuthPolicy, AuthResolution } from "./auth-policy"
import { observeWorkerOperation } from "@/lib/observability/worker"
import { NextRequest, NextResponse } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { COMMUNITY_BOT_ACTOR_HEADER, queries } from "@alook/shared"
-import { getDb, getPrimaryDb } from "@/lib/db"
+import { getPrimaryDb } from "@/lib/db"
import { getAuth } from "@/lib/auth"
-import { getKV, cacheKeys, bindCacheKV } from "@/lib/cache"
+import { bindCacheKV } from "@/lib/cache"
import { protectCommunityJsonResponse, rejectUnknownCommunityContract, varyPrivateResponseByCredentials } from "./response-cache"
export interface AuthContext {
env: Env
userId: string
email: string
- workspaceId?: string
/**
* The authenticated user's internal flags. Populated from the request-time
* session guard. `isBot` is always false in production (a bot session is
@@ -26,7 +26,7 @@ interface CookieHumanAuthContext extends AuthContext {
}
/**
- * Context for a `withOptionalAuth` handler: identical to `AuthContext` but
+ * Context for an `optionalAuthPolicy` handler: identical to `AuthContext` but
* `userId`/`email` are OPTIONAL — absent when the caller is anonymous (no
* session, an errored session lookup, or a bot/deleted session degraded to
* anonymous). A distinct interface so `AuthContext.userId` stays required and
@@ -43,55 +43,6 @@ interface OptionalAuthContext {
user?: { isBot: boolean }
}
-/**
- * Merged machine-token cache entry. One KV read per authenticated request
- * yields BOTH the token-validation result (`row`) and the last-used bump
- * throttle (`luAt`, the epoch ms of the last `last_used_at` D1 write),
- * replacing the old two-key `mt:` + `mt_lu:` pair.
- *
- * `row: null` is a NEGATIVE cache — an invalid token is remembered so a
- * repeated bad token doesn't re-hit D1 every request. A token string only
- * exists after `createMachineToken` commits, and revoke/delete paths
- * `invalidate(cacheKeys.machineToken(token))`. The one null→non-null window
- * is read-replica lag on a freshly-created token, so negative entries use a
- * short `MT_NEG_TTL_S` to bound any false-401 lockout.
- */
-type MachineTokenRow = Awaited<ReturnType<typeof queries.machineToken.getMachineTokenByToken>>
-interface MachineTokenEntry {
- row: MachineTokenRow
- luAt: number
-}
-const MT_TTL_S = 900
-// Negative (`row: null`) entries live only briefly. D1 reads go through
-// read-replica sessions (`first-unconstrained`), so a freshly-created token
-// can momentarily read null due to replication lag; a full 15-min negative
-// TTL would then 401 a valid token for the whole window. 60s (KV's floor)
-// still absorbs repeated-bad-token storms without a long lockout.
-const MT_NEG_TTL_S = 60
-const MT_BUMP_INTERVAL_MS = 900_000
-
-/**
- * Warm the positive machine-token cache entry with a known-good row. Called at
- * activation time so the daemon's first poll — a separate Worker invocation
- * that may read a lagged replica (D1 uses `first-unconstrained` sessions) —
- * hits a positive KV entry instead of reading `null` and negative-caching a
- * 401 for `MT_NEG_TTL_S`. Best-effort (a KV blip just means the next poll does
- * a cold read); no-op without KV. This is the ONLY other writer of the `mt:`
- * entry, so it lives beside the reader to keep the `{ row, luAt }` shape and
- * `MT_TTL_S` in one place.
- */
-export async function warmMachineTokenCache(
- kv: KVNamespace | null,
- token: string,
- row: NonNullable<MachineTokenRow>,
-): Promise<void> {
- if (!kv) return
- const entry: MachineTokenEntry = { row, luAt: Date.now() }
- await kv
- .put(cacheKeys.machineToken(token), JSON.stringify(entry), { expirationTtl: MT_TTL_S })
- .catch(() => {})
-}
-
export type AuthenticatedHandler = (
req: NextRequest,
ctx: AuthContext & { params?: Record<string, string> }
@@ -108,10 +59,10 @@ export type CookieHumanAuthHandler = (
) => Promise<NextResponse | Response>
/**
- * Outcome of resolving a Better-Auth cookie session. Shared by `withAuth`
- * (which turns everything but `ok` into a 401/503) and `withOptionalAuth`
+ * Outcome of resolving a Better-Auth cookie session. Shared by `humanAuthPolicy`
+ * (which turns everything but `ok` into a 401/503) and `optionalAuthPolicy`
* (which turns everything but `ok` into anonymous). Keeping the resolution in
- * ONE place means the two wrappers can never drift on session semantics — only
+ * ONE place means the two policies can never drift on session semantics — only
* on what they DO with a non-`ok` outcome.
*
* - `ok` — a valid, non-bot, non-deleted session; `user` is populated.
@@ -237,233 +188,129 @@ function isCookieHumanSameOrigin(req: NextRequest): boolean {
return false
}
if (originHeader !== originUrl.origin) return false
- const requestUrl = new URL(req.url)
+ const requestUrl = req.nextUrl
if (originUrl.origin === requestUrl.origin) return true
return isLoopbackHostname(originUrl.hostname)
&& isLoopbackHostname(requestUrl.hostname)
&& req.headers.get("Host") === originUrl.host
}
-export function withCookieHumanAuth(handler: CookieHumanAuthHandler) {
- const authenticate = createCookieHumanAuthHandler(handler)
- return async (...args: Parameters<typeof authenticate>) => protectCommunityJsonResponse(args[0], await authenticate(...args))
+function rejectBotSelection(req: NextRequest): NextResponse | null {
+ return req.headers.has(COMMUNITY_BOT_ACTOR_HEADER)
+ ? NextResponse.json({ error: "bot selection is not supported by this endpoint" }, { status: 403 })
+ : null
}
-function createCookieHumanAuthHandler(handler: CookieHumanAuthHandler) {
- return async (
- req: NextRequest,
- context?: { params?: Promise<Record<string, string>> | Record<string, string> },
- ) => {
- if (req.headers.has(COMMUNITY_BOT_ACTOR_HEADER)) {
- return NextResponse.json({ error: "bot selection is not supported by this endpoint" }, { status: 403 })
- }
- const resolvedParams = context?.params
- ? context.params instanceof Promise
- ? await context.params
- : context.params
- : undefined
- if (req.method !== "POST" || !isCookieHumanSameOrigin(req)) {
- return accountDeletionAuthError("FORBIDDEN", 403)
- }
- if (req.headers.has("Authorization")) {
- return accountDeletionAuthError("UNAUTHORIZED", 401)
- }
- const unsupported = rejectUnknownCommunityContract(req)
- if (unsupported) return unsupported
-
- const cloudflare = await getCloudflareContext({ async: true })
- const cloudflareEnv = cloudflare.env as Env
- bindCacheKV(cloudflareEnv.CACHE_KV ?? null)
- const resolved = await resolveSession(req, cloudflareEnv)
- if (resolved.kind === "error") {
- return accountDeletionAuthError("SESSION_VALIDATION_FAILED", 503)
- }
- if (resolved.kind === "none") {
- return accountDeletionAuthError("UNAUTHORIZED", 401)
- }
- if (resolved.kind === "invalid") {
- const response = accountDeletionAuthError("UNAUTHORIZED", 401)
- clearCookieHumanAuthCookies(response)
- return response
- }
+async function resolveCookieHuman(req: NextRequest): Promise<AuthResolution<CookieHumanAuthContext>> {
+ if (req.method !== "POST" || !isCookieHumanSameOrigin(req)) {
+ return accountDeletionAuthError("FORBIDDEN", 403)
+ }
+ if (req.headers.has("Authorization")) {
+ return accountDeletionAuthError("UNAUTHORIZED", 401)
+ }
+ const unsupported = rejectUnknownCommunityContract(req)
+ if (unsupported) return unsupported
+
+ const cloudflare = await getCloudflareContext({ async: true })
+ const cloudflareEnv = cloudflare.env as Env
+ bindCacheKV(cloudflareEnv.CACHE_KV ?? null)
+ const resolved = await resolveSession(req, cloudflareEnv)
+ if (resolved.kind === "error") {
+ return accountDeletionAuthError("SESSION_VALIDATION_FAILED", 503)
+ }
+ if (resolved.kind === "none") {
+ return accountDeletionAuthError("UNAUTHORIZED", 401)
+ }
+ if (resolved.kind === "invalid") {
+ const response = accountDeletionAuthError("UNAUTHORIZED", 401)
+ clearCookieHumanAuthCookies(response)
+ return response
+ }
- let liveUser: Awaited<ReturnType<typeof queries.user.getUserInternal>>
- try {
- liveUser = await queries.user.getUserInternal(
- getPrimaryDb(cloudflareEnv.DB),
- resolved.user.id,
- )
- } catch {
- return accountDeletionAuthError("SESSION_VALIDATION_FAILED", 503)
- }
- if (!liveUser || liveUser.isBot || liveUser.deletedAt !== null) {
- const response = accountDeletionAuthError("UNAUTHORIZED", 401)
- clearCookieHumanAuthCookies(response)
- return response
- }
+ let liveUser: Awaited<ReturnType<typeof queries.user.getUserInternal>>
+ try {
+ liveUser = await queries.user.getUserInternal(
+ getPrimaryDb(cloudflareEnv.DB),
+ resolved.user.id,
+ )
+ } catch {
+ return accountDeletionAuthError("SESSION_VALIDATION_FAILED", 503)
+ }
+ if (!liveUser || liveUser.isBot || liveUser.deletedAt !== null) {
+ const response = accountDeletionAuthError("UNAUTHORIZED", 401)
+ clearCookieHumanAuthCookies(response)
+ return response
+ }
- const response = await handler(req, {
+ return {
+ context: {
env: cloudflareEnv,
executionContext: cloudflare.ctx,
userId: liveUser.id,
email: liveUser.email,
user: { isBot: false },
- params: resolvedParams,
- })
- return forwardSetCookies(response, resolved.setCookies)
+ },
+ finish: response => forwardSetCookies(response, resolved.setCookies),
}
}
-export function withAuth(handler: AuthenticatedHandler, options: { allowBotSelection?: boolean } = {}) {
- const authenticate = createAuthenticatedHandler(handler, options)
- return async (...args: Parameters<typeof authenticate>) => protectCommunityJsonResponse(args[0], await authenticate(...args))
-}
-
-function createAuthenticatedHandler(handler: AuthenticatedHandler, options: { allowBotSelection?: boolean }) {
- return async (
- req: NextRequest,
- context?: { params?: Promise<Record<string, string>> | Record<string, string> }
- ) => {
- if (req.headers.has(COMMUNITY_BOT_ACTOR_HEADER) && !options.allowBotSelection) {
- return NextResponse.json({ error: "bot selection is not supported by this endpoint" }, { status: 403 })
- }
- const resolvedParams = context?.params
- ? context.params instanceof Promise
- ? await context.params
- : context.params
- : undefined
-
- const authHeader = req.headers.get("Authorization")
- if (!authHeader?.startsWith("Bearer al_")) {
- const unsupported = rejectUnknownCommunityContract(req)
- if (unsupported) return unsupported
- }
- const { env } = await getCloudflareContext({ async: true })
- const cloudflareEnv = env as Env
- bindCacheKV(cloudflareEnv.CACHE_KV ?? null)
- if (authHeader?.startsWith("Bearer ")) {
- const raw = authHeader.slice(7)
- if (raw.startsWith("al_")) {
- try {
- const db = getDb(cloudflareEnv.DB)
- const kv = getKV()
- const key = cacheKeys.machineToken(raw)
- const now = Date.now()
-
- // Read the merged entry. A KV blip must NOT turn a valid token into
- // a 401 — on read failure we fall through to D1 (mirrors `cached`).
- let entry: MachineTokenEntry | null = null
- if (kv) {
- try {
- const cachedRaw = await kv.get(key)
- if (cachedRaw) {
- const parsed = JSON.parse(cachedRaw) as Partial<MachineTokenEntry>
- // Shape guard: a pre-upgrade deploy stored the bare row under
- // this same `mt:` key (old `cached()` format). Reading that as
- // a MachineTokenEntry would leave `row` undefined → a false 401
- // for a VALID token until the old entry's TTL expires (and the
- // daemon treats sustained 401s as a dead token). Only accept the
- // new `{ row, luAt }` shape; anything else falls through to a
- // cold D1 miss that repopulates in the new format.
- if (parsed && "row" in parsed && typeof parsed.luAt === "number") {
- entry = parsed as MachineTokenEntry
- }
- }
- } catch {
- entry = null
- }
- }
-
- let bump = false
- if (!entry) {
- // Cold miss: hit D1 and populate. On a hit, bump immediately so
- // `last_used_at` reflects first contact (preserves prior
- // semantics), then remember it for the TTL window.
- const row = await queries.machineToken.getMachineTokenByToken(db, raw)
- entry = { row, luAt: now }
- bump = row != null
- if (kv) {
- const ttl = row != null ? MT_TTL_S : MT_NEG_TTL_S
- kv.put(key, JSON.stringify(entry), { expirationTtl: ttl }).catch(() => {})
- }
- } else if (entry.row && now - entry.luAt > MT_BUMP_INTERVAL_MS) {
- // Warm hit, throttle window elapsed: bump and refresh luAt.
- bump = true
- if (kv) {
- kv.put(key, JSON.stringify({ row: entry.row, luAt: now }), { expirationTtl: MT_TTL_S }).catch(() => {})
- }
- }
-
- const mt = entry.row
- if (!mt) {
- // row === null is the ONLY "definitely invalid" signal (token
- // doesn't exist). The daemon uses this 401 to mark a workspace
- // as auth-failed, so it must never fire on transient infra
- // failure — those throw and fall to the 503 catch below.
- return NextResponse.json({ error: "invalid token" }, { status: 401 })
- }
- const unsupported = rejectUnknownCommunityContract(req, true)
- if (unsupported) return unsupported
- if (bump) {
- Promise.resolve(queries.machineToken.updateMachineTokenLastUsed(db, mt.id)).catch(() => {})
- }
- const authCtx: AuthContext = {
- env: cloudflareEnv,
- userId: mt.userId,
- email: mt.userEmail,
- workspaceId: mt.workspaceId ?? undefined,
- }
- return handler(req, { ...authCtx, params: resolvedParams }).then(varyPrivateResponseByCredentials)
- } catch {
- // D1 query / getDb / getKV threw — transient infra failure, NOT an
- // invalid token. Mirror the session path's 503 so the daemon retries
- // instead of treating a DB blip as a revoked token (which would
- // wrongly mark the workspace deleted).
- return NextResponse.json({ error: "auth temporarily unavailable" }, { status: 503 })
- }
- }
- }
-
- // Fall back to Better Auth session (with returnHeaders to propagate cookie cache refresh)
- const session = await resolveSession(req, cloudflareEnv)
+export async function resolveHumanAuth(req: NextRequest): Promise<AuthResolution<AuthContext>> {
+ if (req.headers.get("Authorization")?.startsWith("Bearer al_")) {
+ return NextResponse.json({ error: "invalid token" }, { status: 401 })
+ }
+ const unsupported = rejectUnknownCommunityContract(req)
+ if (unsupported) return unsupported
+ const { env } = await getCloudflareContext({ async: true })
+ const cloudflareEnv = env as Env
+ bindCacheKV(cloudflareEnv.CACHE_KV ?? null)
+ const session = await resolveSession(req, cloudflareEnv)
+
+ if (session.kind === "error") {
+ return NextResponse.json({ error: "session validation failed" }, { status: 503 })
+ }
+ if (session.kind === "none") {
+ return NextResponse.json({ error: "unauthorized" }, { status: 401 })
+ }
+ if (session.kind === "invalid") {
+ const invalid = NextResponse.json(
+ { error: "session no longer valid" },
+ { status: 401 },
+ )
+ clearAuthCookies(invalid)
+ return invalid
+ }
- if (session.kind === "error") {
- return NextResponse.json({ error: "session validation failed" }, { status: 503 })
- }
- if (session.kind === "none") {
- return NextResponse.json({ error: "unauthorized" }, { status: 401 })
- }
- if (session.kind === "invalid") {
- const invalid = NextResponse.json(
- { error: "session no longer valid" },
- { status: 401 },
- )
- clearAuthCookies(invalid)
- return invalid
- }
+ const authCtx: AuthContext = {
+ env: cloudflareEnv,
+ userId: session.user.id,
+ email: session.user.email,
+ user: { isBot: session.user.isBot },
+ }
+ return {
+ context: authCtx,
+ finish: response => varyPrivateResponseByCredentials(forwardSetCookies(response, session.setCookies)),
+ }
+}
- const authCtx: AuthContext = {
- env: cloudflareEnv,
- userId: session.user.id,
- email: session.user.email,
- user: { isBot: session.user.isBot },
- }
- const res = await handler(req, { ...authCtx, params: resolvedParams })
+export const humanAuthPolicy: AuthPolicy<AuthContext> = {
+ preflight: rejectBotSelection,
+ resolve: resolveHumanAuth,
+ respond: protectCommunityJsonResponse,
+}
- // Forward Set-Cookie headers from Better Auth to refresh session_data cookie cache
- return varyPrivateResponseByCredentials(forwardSetCookies(res, session.setCookies))
- }
+export const cookieHumanAuthPolicy: AuthPolicy<CookieHumanAuthContext> = {
+ preflight: rejectBotSelection,
+ resolve: resolveCookieHuman,
+ respond: protectCommunityJsonResponse,
}
/**
- * Session-optional wrapper for pages that render the SAME content whether or
+ * Session-optional policy for pages that render the SAME content whether or
* not the visitor is logged in (e.g. the invite landing page). Unlike
- * `withAuth`, it NEVER 401s on a missing session — the handler always runs.
+ * `humanAuthPolicy`, it NEVER 401s on a missing session — the handler always runs.
*
* Red lines (Cecilia, /Gus/working #1131 #1 / #1147):
- * 1. Single-purpose: resolves the Better-Auth cookie session ONLY. It does NOT
- * read the machine-token / bot `al_...` bearer path — that is `withAuth`'s
- * private concern; a daemon/bot is not a use case for an optional-login page.
+ * 1. Single-purpose: resolves the Better-Auth cookie session ONLY.
* 2. Never 401 for auth reasons. Missing session → anonymous. A bot/deleted
* session degrades to anonymous (cookies cleared best-effort) rather than
* blocking. A transient getSession failure also degrades to anonymous — the
@@ -472,54 +319,36 @@ function createAuthenticatedHandler(handler: AuthenticatedHandler, options: { al
* the route's decision; this wrapper carries no disclosure logic, so it is
* reusable by any future login-optional page.
*/
-export function withOptionalAuth(handler: OptionalAuthHandler) {
- const authenticate = createOptionalAuthHandler(handler)
- return async (...args: Parameters<typeof authenticate>) => protectCommunityJsonResponse(args[0], rejectUnknownCommunityContract(args[0]) ?? await authenticate(...args))
+export const optionalAuthPolicy: AuthPolicy<OptionalAuthContext> = {
+ preflight: req => rejectUnknownCommunityContract(req) ?? rejectBotSelection(req),
+ resolve: resolveOptionalHuman,
+ respond: protectCommunityJsonResponse,
}
-function createOptionalAuthHandler(handler: OptionalAuthHandler) {
- return async (
- req: NextRequest,
- context?: { params?: Promise<Record<string, string>> | Record<string, string> }
- ) => {
- if (req.headers.has(COMMUNITY_BOT_ACTOR_HEADER)) {
- return NextResponse.json({ error: "bot selection is not supported by this endpoint" }, { status: 403 })
- }
- const resolvedParams = context?.params
- ? context.params instanceof Promise
- ? await context.params
- : context.params
- : undefined
-
- const { env } = await getCloudflareContext({ async: true })
- const cloudflareEnv = env as Env
- bindCacheKV(cloudflareEnv.CACHE_KV ?? null)
-
- const session = await resolveSession(req, cloudflareEnv)
-
- // Anonymous context for every non-`ok` outcome — the defining difference
- // from withAuth. `invalid` (bot/deleted session) additionally clears the
- // stale cookies on the way out so the bad session doesn't linger.
- if (session.kind !== "ok") {
- const anonCtx: OptionalAuthContext = { env: cloudflareEnv }
- const res = await handler(req, { ...anonCtx, params: resolvedParams })
- if (session.kind === "invalid") {
- const mutableRes = new NextResponse(res.body, res)
+async function resolveOptionalHuman(req: NextRequest): Promise<AuthResolution<OptionalAuthContext>> {
+ const { env } = await getCloudflareContext({ async: true })
+ const cloudflareEnv = env as Env
+ bindCacheKV(cloudflareEnv.CACHE_KV ?? null)
+
+ const session = await resolveSession(req, cloudflareEnv)
+
+ if (session.kind !== "ok") {
+ return {
+ context: { env: cloudflareEnv },
+ finish: session.kind === "invalid" ? response => {
+ const mutableRes = new NextResponse(response.body, response)
clearAuthCookies(mutableRes)
return mutableRes
- }
- return res
+ } : undefined,
}
-
- const authCtx: OptionalAuthContext = {
+ }
+ return {
+ context: {
env: cloudflareEnv,
userId: session.user.id,
email: session.user.email,
user: { isBot: session.user.isBot },
- }
- const res = await handler(req, { ...authCtx, params: resolvedParams })
-
- // Forward Set-Cookie headers from Better Auth to refresh session_data cookie cache
- return forwardSetCookies(res, session.setCookies)
+ },
+ finish: response => forwardSetCookies(response, session.setCookies),
}
}
diff --git a/src/web/src/lib/middleware/community-actor.test.ts b/src/web/src/lib/middleware/community-actor.test.ts
index dfcf87ba7..26db7e51e 100644
--- a/src/web/src/lib/middleware/community-actor.test.ts
+++ b/src/web/src/lib/middleware/community-actor.test.ts
@@ -1,15 +1,8 @@
+import { withAuth } from "./auth-policy"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest, NextResponse } from "next/server"
import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
-// The unified actor is a thin router over two collaborators:
-// - resolveBotActor (crk_ → bot identity) — the bot path;
-// - withAuth (session/al_ → human AuthContext) — the human path, delegated
-// VERBATIM so we don't re-test its internals here.
-// We mock both so this file tests only the routing + actor-shape adaptation +
-// the crk_-never-falls-through invariant. Behavior of each collaborator is
-// covered by their own suites (community-agent-runner-auth.test.ts, auth.test.ts).
-
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),
}))
@@ -22,38 +15,32 @@ vi.mock("./community-agent-runner-auth", () => ({
resolveBotActor: (...a: unknown[]) => mockResolveBotActor(...a),
}))
-// withAuth is a higher-order wrapper: withAuth(handler) → (req, ctx) => ….
-// Our mock invokes the wrapped handler with a canned human AuthContext so we
-// can assert the actor adaptation. `mockHumanCtx` lets a test simulate an
-// auth failure by having the mock short-circuit instead of calling through.
let mockHumanCtx: Record<string, unknown> | null = {
env: { DB: {} },
userId: "human_1",
- workspaceId: "ws_1",
user: { isBot: false },
}
vi.mock("./auth", () => ({
- withAuth: (handler: (r: NextRequest, ctx: any) => Promise<Response>) =>
- async (req: NextRequest, _ctx?: unknown) => {
- if (!mockHumanCtx) return NextResponse.json({ error: "unauthorized" }, { status: 401 })
- return handler(req, { ...mockHumanCtx, params: undefined })
- },
+ resolveHumanAuth: async () => {
+ if (!mockHumanCtx) return NextResponse.json({ error: "unauthorized" }, { status: 401 })
+ return { context: mockHumanCtx }
+ },
}))
-import { withCommunityActor, rejectBot, requireBot, type CommunityActor } from "./community-actor"
+import { communityActorPolicy, rejectBot, requireBot, type CommunityActor } from "./community-actor"
const handler = vi.fn(async (_req: NextRequest, ctx: any) => NextResponse.json({ ok: true, actor: ctx.actor }))
const bearer = (v: string) => new NextRequest("http://localhost/x", { headers: { Authorization: v } })
-describe("withCommunityActor", () => {
+describe("communityActorPolicy", () => {
beforeEach(() => {
vi.clearAllMocks()
- mockHumanCtx = { env: { DB: {} }, userId: "human_1", email: "[email protected]", workspaceId: "ws_1", user: { isBot: false } }
+ mockHumanCtx = { env: { DB: {} }, userId: "human_1", email: "[email protected]", user: { isBot: false } }
})
- const wrapped = withCommunityActor(handler)
+ const wrapped = withAuth(communityActorPolicy(), handler)
it("resolves a crk_ bearer to a bot actor (kind:bot, userId=botUserId)", async () => {
mockResolveBotActor.mockResolvedValue({
@@ -78,25 +65,42 @@ describe("withCommunityActor", () => {
expect(handler).not.toHaveBeenCalled()
})
- it("routes a session request (no bearer) to the human path via withAuth", async () => {
- const res = await wrapped(new NextRequest("http://localhost/x"))
- expect(res.status).toBe(200)
- const body = (await res.json()) as { actor: CommunityActor }
- expect(body.actor).toEqual({ kind: "human", userId: "human_1", email: "[email protected]", workspaceId: "ws_1", isBot: false })
- // Bot resolution must not have been attempted for a non-crk_ request.
- expect(mockResolveBotActor).not.toHaveBeenCalled()
+ it("fails closed when a runner resolver unexpectedly returns not_bot", async () => {
+ mockResolveBotActor.mockResolvedValue({ kind: "not_bot" })
+ const req = bearer("Bearer crk_unexpected")
+ req.headers.set("Cookie", "valid-human-session")
+ const response = await wrapped(req)
+ expect(response.status).toBe(401)
+ expect(await response.json()).toEqual({ error: "invalid runner key" })
+ expect(handler).not.toHaveBeenCalled()
+ expect(mockResolveOwnedBotActor).not.toHaveBeenCalled()
+ })
+
+ it("rejects an unsupported contract after validating a runner without invoking business code", async () => {
+ mockResolveBotActor.mockResolvedValue({
+ kind: "bot",
+ actor: { botUserId: "bot_1", ownerUserId: "owner_1", machineId: "m_1", isActive: true },
+ })
+ const req = new NextRequest("http://localhost/api/community/operation", {
+ headers: { Authorization: "Bearer crk_valid", [COMMUNITY_CONTRACT_HEADER]: "unsupported" },
+ })
+ const response = await wrapped(req)
+ expect(response.status).toBe(400)
+ expect(mockResolveBotActor).toHaveBeenCalledOnce()
+ expect(handler).not.toHaveBeenCalled()
})
- it("routes an al_ machine-token bearer to the human path (not the bot path)", async () => {
- const res = await wrapped(bearer("Bearer al_machinetoken"))
+ it("routes a session request (no bearer) to the human path via the human credential resolver", async () => {
+ const res = await wrapped(new NextRequest("http://localhost/x"))
expect(res.status).toBe(200)
const body = (await res.json()) as { actor: CommunityActor }
- expect(body.actor.kind).toBe("human")
+ expect(body.actor).toEqual({ kind: "human", userId: "human_1", email: "[email protected]", isBot: false })
+ // Bot resolution must not have been attempted for a non-crk_ request.
expect(mockResolveBotActor).not.toHaveBeenCalled()
})
- it("propagates a human auth failure from withAuth unchanged", async () => {
- mockHumanCtx = null // simulate withAuth 401
+ it("propagates a human auth failure from the human credential resolver unchanged", async () => {
+ mockHumanCtx = null
const res = await wrapped(new NextRequest("http://localhost/x"))
expect(res.status).toBe(401)
expect(handler).not.toHaveBeenCalled()
@@ -111,7 +115,7 @@ describe("withCommunityActor", () => {
status, headers: { "Cache-Control": "private, max-age=31536000, immutable", Vary: "Accept-Encoding" },
})
const mediaHandler = vi.fn(async (_request: NextRequest, _ctx: { actor: CommunityActor }) => original)
- const res = await withCommunityActor(mediaHandler)(bearer("Bearer crk_abc"))
+ const res = await withAuth(communityActorPolicy(), mediaHandler)(bearer("Bearer crk_abc"))
expect(res.status).toBe(status)
expect(res.headers.get("Vary")).toBe("Accept-Encoding, Cookie, Authorization, X-Alook-Bot-Id")
expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable")
@@ -140,7 +144,6 @@ describe("rejectBot / requireBot guards", () => {
})
})
-
describe("owner selected bot", () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -149,7 +152,7 @@ describe("owner selected bot", () => {
})
const request = () => new NextRequest("http://localhost/api/community/servers/channels", { headers: { "X-Alook-Bot-Id": "bot_1", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
it("authenticates the owner then delegates only the selected bot identity, with a private varied response", async () => {
- const response = await withCommunityActor(handler)(request())
+ const response = await withAuth(communityActorPolicy(), handler)(request())
expect(mockResolveOwnedBotActor).toHaveBeenCalledWith({}, "bot_1", "human_1", { allowInactive: undefined })
expect(await response.json()).toMatchObject({ actor: { kind: "bot", userId: "bot_1", ownerUserId: "human_1", machineId: "offline_machine", delegatedByUserId: "human_1" } })
expect(response.headers.get("Cache-Control")).toContain("no-store")
@@ -158,25 +161,25 @@ describe("owner selected bot", () => {
})
it("does not resolve a selected bot before human authentication", async () => {
mockHumanCtx = null
- expect((await withCommunityActor(handler)(request())).status).toBe(401)
+ expect((await withAuth(communityActorPolicy(), handler)(request())).status).toBe(401)
expect(mockResolveOwnedBotActor).not.toHaveBeenCalled()
expect(handler).not.toHaveBeenCalled()
})
it("preserves owned bot lookup rejection without calling the route", async () => {
mockResolveOwnedBotActor.mockResolvedValue({ kind: "error", response: NextResponse.json({ error: "bot not found" }, { status: 404 }) })
- expect((await withCommunityActor(handler)(request())).status).toBe(404)
+ expect((await withAuth(communityActorPolicy(), handler)(request())).status).toBe(404)
expect(handler).not.toHaveBeenCalled()
})
it("rejects runner-key identity selection without falling through to human authentication", async () => {
const req = request()
req.headers.set("Authorization", "Bearer crk_a")
- expect((await withCommunityActor(handler)(req)).status).toBe(403)
+ expect((await withAuth(communityActorPolicy(), handler)(req)).status).toBe(403)
expect(mockResolveOwnedBotActor).not.toHaveBeenCalled()
expect(mockResolveBotActor).not.toHaveBeenCalled()
expect(handler).not.toHaveBeenCalled()
})
it("passes the route's explicit inactive policy to owner delegation", async () => {
- await withCommunityActor(handler, { allowInactiveBot: true })(request())
+ await withAuth(communityActorPolicy({ allowInactiveBot: true }), handler)(request())
expect(mockResolveOwnedBotActor).toHaveBeenCalledWith({}, "bot_1", "human_1", { allowInactive: true })
})
})
diff --git a/src/web/src/lib/middleware/community-actor.ts b/src/web/src/lib/middleware/community-actor.ts
index 367024604..2eb4c7cd7 100644
--- a/src/web/src/lib/middleware/community-actor.ts
+++ b/src/web/src/lib/middleware/community-actor.ts
@@ -1,33 +1,17 @@
import { NextRequest, NextResponse } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { getDb } from "@/lib/db"
-import { withAuth, type AuthContext } from "./auth"
+import { resolveHumanAuth } from "./auth"
+import type { AuthPolicy } from "./auth-policy"
import { COMMUNITY_BOT_ACTOR_HEADER } from "@alook/shared"
import { resolveBotActor, resolveOwnedBotActor } from "./community-agent-runner-auth"
import { protectCommunityJsonResponse, rejectUnknownCommunityContract, varyPrivateResponseByCredentials } from "./response-cache"
-/**
- * The unified community actor — the single identity a `/api/community/*` route
- * handler runs as, whether the caller is a signed-in human (Better-Auth session
- * or `al_` machine token) or a bot (a `crk_` runner key). It fuses the two
- * pre-existing wrappers (`withAuth` for humans, `withAgentRunnerAuth` for bots)
- * behind one decorator so a route can serve both callers and branch on
- * `actor.kind` for the few genuinely bot-specific semantics (channel-alignment
- * gate on send, invite owner-gate on join).
- *
- * Discriminated on `kind` (NOT a flat `isBot` boolean): the semantic branches
- * read `actor.kind === "bot"` and, in that arm, `ownerUserId`/`machineId` are
- * present without a non-null assertion. `userId` is common to both arms — for a
- * bot it IS the bot's own user id ("bots are users"), so an unbranched handler
- * that only reads `actor.userId` works identically for either caller.
- */
export type CommunityActor =
| {
kind: "human"
userId: string
email: string
- /** Present on the `al_`/session human path; absent for a bot. */
- workspaceId?: string
/**
* The session user's `isBot` flag, carried through from withAuth's
* AuthContext. Always false in production (a bot session is rejected at
@@ -61,111 +45,78 @@ export type CommunityActorHandler = (
ctx: CommunityActorContext,
) => Promise<NextResponse | Response>
-/**
- * Wrap a `/api/community/*` route handler with unified actor resolution.
- *
- * Auth routing (by the `Authorization` header):
- * - `Bearer crk_…` → bot path: resolve via the shared `resolveBotActor`.
- * A `crk_` bearer that FAILS to resolve returns its 401/503 and NEVER
- * falls through to the human path (a malformed bot token must not be
- * retried as an anonymous human — that would leak the human 401 shape and
- * mask a revoked key).
- * - anything else → human path: delegated VERBATIM to `withAuth`, reusing its
- * machine-token KV cache, Better-Auth session guard (bot-session rejection,
- * soft-delete check), and Set-Cookie refresh untouched. The human
- * `AuthContext` is adapted into `{ kind: "human", … }`.
- *
- * A bot request never pays the session-validation cost; a human never hits the
- * runner-key lookups.
- */
-export function withCommunityActor(
- handler: CommunityActorHandler,
+export function communityActorPolicy(
options: { allowInactiveBot?: boolean } = {},
-) {
- const authenticate = createCommunityActorHandler(handler, options)
- return async (...args: Parameters<typeof authenticate>) => protectCommunityJsonResponse(args[0], await authenticate(...args))
-}
+): AuthPolicy<CommunityActorContext> {
+ return {
+ respond: protectCommunityJsonResponse,
+ resolve: async req => {
+ const authHeader = req.headers.get("Authorization")
-function createCommunityActorHandler(
- handler: CommunityActorHandler,
- options: { allowInactiveBot?: boolean },
-) {
- return async (
- req: NextRequest,
- context?: { params?: Promise<Record<string, string>> | Record<string, string> },
- ): Promise<NextResponse | Response> => {
- const resolvedParams = context?.params
- ? context.params instanceof Promise
- ? await context.params
- : context.params
- : undefined
+ if (authHeader?.startsWith("Bearer ") && authHeader.slice(7).trim().startsWith("crk_")) {
+ if (req.headers.has(COMMUNITY_BOT_ACTOR_HEADER)) {
+ return NextResponse.json({ error: "runner keys cannot select another bot" }, { status: 403 })
+ }
+ const { env } = await getCloudflareContext({ async: true })
+ const cloudflareEnv = env as Env
+ const db = getDb(cloudflareEnv.DB)
- const authHeader = req.headers.get("Authorization")
-
- // Bot path — only when a crk_ bearer is actually present. `resolveBotActor`
- // returns `not_bot` for any other header (including an `al_` machine token
- // or a session cookie), which we route to the human `withAuth` path below.
- if (authHeader?.startsWith("Bearer ") && authHeader.slice(7).trim().startsWith("crk_")) {
- if (req.headers.has(COMMUNITY_BOT_ACTOR_HEADER)) {
- return NextResponse.json({ error: "runner keys cannot select another bot" }, { status: 403 })
- }
- const { env } = await getCloudflareContext({ async: true })
- const cloudflareEnv = env as Env
- const db = getDb(cloudflareEnv.DB)
+ const resolved = await resolveBotActor(db, authHeader, {
+ allowInactive: options.allowInactiveBot,
+ })
+ if (resolved.kind === "error") return resolved.response
+ // A crk_ bearer that resolves to `not_bot` is unreachable (the guard above
+ // guarantees the crk_ prefix), but treat it as an auth failure rather than
+ // silently falling through to the human path.
+ if (resolved.kind === "not_bot") {
+ return NextResponse.json({ error: "invalid runner key" }, { status: 401 })
+ }
- const resolved = await resolveBotActor(db, authHeader, {
- allowInactive: options.allowInactiveBot,
- })
- if (resolved.kind === "error") return resolved.response
- // A crk_ bearer that resolves to `not_bot` is unreachable (the guard above
- // guarantees the crk_ prefix), but treat it as an auth failure rather than
- // silently falling through to the human path.
- if (resolved.kind === "not_bot") {
- return NextResponse.json({ error: "invalid runner key" }, { status: 401 })
+ const unsupported = rejectUnknownCommunityContract(req, true)
+ if (unsupported) return unsupported
+ return {
+ context: {
+ env: cloudflareEnv,
+ actor: {
+ kind: "bot",
+ userId: resolved.actor.botUserId,
+ ownerUserId: resolved.actor.ownerUserId,
+ machineId: resolved.actor.machineId,
+ isActive: resolved.actor.isActive,
+ },
+ },
+ finish: varyPrivateResponseByCredentials,
+ }
}
- const unsupported = rejectUnknownCommunityContract(req, true)
- if (unsupported) return unsupported
- return varyPrivateResponseByCredentials(await handler(req, {
- env: cloudflareEnv,
- actor: {
- kind: "bot",
- userId: resolved.actor.botUserId,
- ownerUserId: resolved.actor.ownerUserId,
- machineId: resolved.actor.machineId,
- isActive: resolved.actor.isActive,
- },
- params: resolvedParams,
- }))
- }
-
- // Human path — delegate verbatim to withAuth, adapting its AuthContext into
- // the unified actor. withAuth owns all human auth behavior (KV cache,
- // session guard, Set-Cookie refresh); we do not reimplement any of it.
- const delegated = withAuth(async (r, humanCtx: AuthContext & { params?: Record<string, string> }) => {
- const selectedBotId = r.headers.get(COMMUNITY_BOT_ACTOR_HEADER)
+ const human = await resolveHumanAuth(req)
+ if (human instanceof Response) return human
+ const humanCtx = human.context
+ const selectedBotId = req.headers.get(COMMUNITY_BOT_ACTOR_HEADER)
if (selectedBotId !== null) {
const resolved = await resolveOwnedBotActor(getDb(humanCtx.env.DB), selectedBotId, humanCtx.userId, { allowInactive: options.allowInactiveBot })
- if (resolved.kind === "error") return resolved.response
- return handler(r, {
- env: humanCtx.env,
- params: humanCtx.params,
- actor: { kind: "bot", userId: resolved.actor.botUserId, ownerUserId: resolved.actor.ownerUserId, machineId: resolved.actor.machineId, isActive: resolved.actor.isActive, delegatedByUserId: humanCtx.userId },
- })
+ if (resolved.kind === "error") return human.finish ? human.finish(resolved.response) : resolved.response
+ return {
+ context: {
+ env: humanCtx.env,
+ actor: { kind: "bot", userId: resolved.actor.botUserId, ownerUserId: resolved.actor.ownerUserId, machineId: resolved.actor.machineId, isActive: resolved.actor.isActive, delegatedByUserId: humanCtx.userId },
+ },
+ finish: human.finish,
+ }
}
- return handler(r, {
- env: humanCtx.env,
- actor: {
- kind: "human",
- userId: humanCtx.userId,
- email: humanCtx.email,
- workspaceId: humanCtx.workspaceId,
- isBot: humanCtx.user?.isBot,
+ return {
+ context: {
+ env: humanCtx.env,
+ actor: {
+ kind: "human",
+ userId: humanCtx.userId,
+ email: humanCtx.email,
+ isBot: humanCtx.user?.isBot,
+ },
},
- params: humanCtx.params,
- })
- }, { allowBotSelection: true })
- return delegated(req, context)
+ finish: human.finish,
+ }
+ },
}
}
diff --git a/src/web/src/lib/middleware/community-agent-runner-auth.ts b/src/web/src/lib/middleware/community-agent-runner-auth.ts
index 5409641b1..6357a7de7 100644
--- a/src/web/src/lib/middleware/community-agent-runner-auth.ts
+++ b/src/web/src/lib/middleware/community-agent-runner-auth.ts
@@ -7,7 +7,7 @@ const log = createLogger({ service: "community-agent-runner-auth" })
/**
* The bot identity resolved from a `crk_` runner key — the BOT's own user id,
* its OWNER's user id, and the machine it's bound to. Consumed by the unified
- * `withCommunityActor` (see community-actor.ts). The legacy `withAgentRunnerAuth`
+ * `communityActorPolicy` (see community-actor.ts). The legacy `withAgentRunnerAuth`
* wrapper and the `/api/community/agent/*` route tree it guarded were deleted
* once every bot verb moved onto the unified actor;
* `resolveBotActor` is the surviving, shared crk_ validator.
@@ -54,13 +54,13 @@ async function lookupOr503<T>(
/**
* Resolve a `crk_` runner-key bearer to a bot identity, shared by
- * `withAgentRunnerAuth` and the unified `withCommunityActor`. Returns a
+ * `withAgentRunnerAuth` and the unified `communityActorPolicy`. Returns a
* 3-variant discriminant:
* - `{ kind: "bot", actor }` — a valid runner key; `actor` is the resolved
* {botUserId, ownerUserId, machineId}.
* - `{ kind: "not_bot" }` — no `Bearer crk_…` header at all; the caller
* MAY fall through to another auth path
- * (this is how `withCommunityActor` routes a
+ * (this is how `communityActorPolicy` routes a
* human request to `withAuth`).
* - `{ kind: "error", response }` — a `crk_` bearer that failed to resolve
* (bad/revoked key, bot inactive, binding
diff --git a/src/web/src/lib/middleware/community-daemon-auth.test.ts b/src/web/src/lib/middleware/community-daemon-auth.test.ts
index 43098d699..6f9a169a6 100644
--- a/src/web/src/lib/middleware/community-daemon-auth.test.ts
+++ b/src/web/src/lib/middleware/community-daemon-auth.test.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "./auth-policy"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest, NextResponse } from "next/server"
@@ -17,18 +18,18 @@ vi.mock("@alook/shared", () => ({
},
}))
-import { withCommunityDaemonAuth } from "./community-daemon-auth"
+import { machineAuthPolicy } from "./community-daemon-auth"
const handler = vi.fn(async (_req: NextRequest, ctx: any) =>
NextResponse.json({ ok: true, ctx })
)
-describe("withCommunityDaemonAuth", () => {
+describe("machineAuthPolicy", () => {
beforeEach(() => {
vi.clearAllMocks()
})
- const wrapped = withCommunityDaemonAuth(handler)
+ const wrapped = withAuth(machineAuthPolicy, handler)
it("rejects when Authorization is missing", async () => {
const req = new NextRequest("http://localhost/x")
diff --git a/src/web/src/lib/middleware/community-daemon-auth.ts b/src/web/src/lib/middleware/community-daemon-auth.ts
index f8d39ba1d..3052448e7 100644
--- a/src/web/src/lib/middleware/community-daemon-auth.ts
+++ b/src/web/src/lib/middleware/community-daemon-auth.ts
@@ -1,3 +1,4 @@
+import type { AuthPolicy } from "./auth-policy"
import { NextRequest, NextResponse } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { queries, withD1Retry } from "@alook/shared"
@@ -24,17 +25,8 @@ export type CommunityDaemonAuthenticatedHandler = (
* credential. Response body is `{ error: string }`, matching the plan's
* wire contract.
*/
-export function withCommunityDaemonAuth(handler: CommunityDaemonAuthenticatedHandler) {
- return async (
- req: NextRequest,
- context?: { params?: Promise<Record<string, string>> | Record<string, string> }
- ) => {
- const resolvedParams = context?.params
- ? context.params instanceof Promise
- ? await context.params
- : context.params
- : undefined
-
+export const machineAuthPolicy: AuthPolicy<CommunityDaemonAuthContext> = {
+ resolve: async req => {
const authHeader = req.headers.get("Authorization")
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return NextResponse.json({ error: "missing or malformed Authorization header" }, { status: 401 })
@@ -56,12 +48,13 @@ export function withCommunityDaemonAuth(handler: CommunityDaemonAuthenticatedHan
return NextResponse.json({ error: "credential revoked or unrecognized" }, { status: 401 })
}
- return handler(req, {
- env: cloudflareEnv,
- userId: active.userId,
- machineId: active.machineId,
- credentialId: active.credentialId,
- params: resolvedParams,
- })
- }
+ return {
+ context: {
+ env: cloudflareEnv,
+ userId: active.userId,
+ machineId: active.machineId,
+ credentialId: active.credentialId,
+ },
+ }
+ },
}
diff --git a/src/web/src/lib/middleware/community-pairing-token.test.ts b/src/web/src/lib/middleware/community-pairing-token.test.ts
index 6a6d024c0..958928ba5 100644
--- a/src/web/src/lib/middleware/community-pairing-token.test.ts
+++ b/src/web/src/lib/middleware/community-pairing-token.test.ts
@@ -1,3 +1,4 @@
+import { withAuth } from "./auth-policy"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest, NextResponse } from "next/server"
@@ -6,7 +7,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
}))
// Spy on every pairing-token / machine query the middleware could plausibly
-// call. The whole point of `withCommunityPairingToken` is that it validates
+// call. The whole point of `pairingTokenPolicy` is that it validates
// the `cmt_` prefix but leaves the atomic exchange to the route handler
// (`daemon/activate`). If any of these fire during middleware execution, the
// middleware has stopped being stateless.
@@ -29,18 +30,18 @@ vi.mock("@alook/shared", () => ({
},
}))
-import { withCommunityPairingToken } from "./community-pairing-token"
+import { pairingTokenPolicy } from "./community-pairing-token"
const handler = vi.fn(async (_req: NextRequest, ctx: any) =>
NextResponse.json({ ok: true, ctx })
)
-describe("withCommunityPairingToken", () => {
+describe("pairingTokenPolicy", () => {
beforeEach(() => {
vi.clearAllMocks()
})
- const wrapped = withCommunityPairingToken(handler)
+ const wrapped = withAuth(pairingTokenPolicy, handler)
it("rejects when Authorization is missing", async () => {
const req = new NextRequest("http://localhost/x")
diff --git a/src/web/src/lib/middleware/community-pairing-token.ts b/src/web/src/lib/middleware/community-pairing-token.ts
index d6a138a57..0edd8a930 100644
--- a/src/web/src/lib/middleware/community-pairing-token.ts
+++ b/src/web/src/lib/middleware/community-pairing-token.ts
@@ -1,3 +1,4 @@
+import type { AuthPolicy } from "./auth-policy"
import { NextRequest, NextResponse } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
@@ -20,19 +21,10 @@ export type CommunityPairingTokenAuthenticatedHandler = (
*
* Rejects with 401 on missing header, non-Bearer prefix, or wrong token
* prefix. Response body is `{ error: string }`, matching the wire contract
- * used by the sibling `withCommunityDaemonAuth` middleware.
+ * used by the sibling `machineAuthPolicy` middleware.
*/
-export function withCommunityPairingToken(handler: CommunityPairingTokenAuthenticatedHandler) {
- return async (
- req: NextRequest,
- context?: { params?: Promise<Record<string, string>> | Record<string, string> }
- ) => {
- const resolvedParams = context?.params
- ? context.params instanceof Promise
- ? await context.params
- : context.params
- : undefined
-
+export const pairingTokenPolicy: AuthPolicy<CommunityPairingTokenContext> = {
+ resolve: async req => {
const authHeader = req.headers.get("Authorization")
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return NextResponse.json({ error: "missing Authorization header" }, { status: 401 })
@@ -45,11 +37,12 @@ export function withCommunityPairingToken(handler: CommunityPairingTokenAuthenti
const { env, ctx } = await getCloudflareContext({ async: true })
const cloudflareEnv = env as Env
- return handler(req, {
- env: cloudflareEnv,
- rawTokenId,
- waitUntil: ctx ? ctx.waitUntil.bind(ctx) : undefined,
- params: resolvedParams,
- })
- }
+ return {
+ context: {
+ env: cloudflareEnv,
+ rawTokenId,
+ waitUntil: ctx ? ctx.waitUntil.bind(ctx) : undefined,
+ },
+ }
+ },
}
diff --git a/src/web/src/lib/middleware/private-media-cache.test.ts b/src/web/src/lib/middleware/private-media-cache.test.ts
index fdd024eaa..6dc8f2a7f 100644
--- a/src/web/src/lib/middleware/private-media-cache.test.ts
+++ b/src/web/src/lib/middleware/private-media-cache.test.ts
@@ -1,11 +1,10 @@
+import { withAuth } from "./auth-policy"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest, NextResponse } from "next/server"
const mocks = vi.hoisted(() => ({
getSession: vi.fn(),
signOut: vi.fn(),
- getMachineToken: vi.fn(),
- updateMachineToken: vi.fn(),
resolveBotActor: vi.fn(),
}))
@@ -16,24 +15,10 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
vi.mock("@/lib/auth", () => ({
getAuth: vi.fn(() => ({ api: { getSession: mocks.getSession, signOut: mocks.signOut } })),
}))
-vi.mock("@alook/shared", async () => {
- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
- return {
- ...actual,
- queries: {
- ...actual.queries,
- machineToken: {
- ...actual.queries.machineToken,
- getMachineTokenByToken: mocks.getMachineToken,
- updateMachineTokenLastUsed: mocks.updateMachineToken,
- },
- },
- }
-})
vi.mock("./community-agent-runner-auth", () => ({ resolveBotActor: mocks.resolveBotActor }))
-import { withAuth, type AuthenticatedHandler } from "./auth"
-import { withCommunityActor, type CommunityActorHandler } from "./community-actor"
+import { humanAuthPolicy, type AuthenticatedHandler } from "./auth"
+import { communityActorPolicy, type CommunityActorHandler } from "./community-actor"
import { withPrivateMediaCache } from "./private-media-cache"
const IMMUTABLE = "private, max-age=31536000, immutable"
@@ -52,7 +37,6 @@ const media = (status = 200, headers: Record<string, string> = {}) =>
beforeEach(() => {
vi.resetAllMocks()
mocks.getSession.mockResolvedValue(session())
- mocks.getMachineToken.mockResolvedValue({ id: "mt1", userId: "A", userEmail: "[email protected]", workspaceId: "ws1" })
mocks.resolveBotActor.mockResolvedValue({
kind: "bot",
actor: { botUserId: "bot1", ownerUserId: "owner1", machineId: "machine1", isActive: true },
@@ -112,7 +96,7 @@ describe("selected private media response policy", () => {
describe("real authentication wrappers inside media policy", () => {
it.each([200, 304])("keeps fixed media status %s independent of GA, session refresh and authenticated viewer cookies", async (status) => {
const handler = vi.fn<AuthenticatedHandler>(async () => media(status, { Vary: "Accept-Encoding" }))
- const route = withPrivateMediaCache(withAuth(handler))
+ const route = withPrivateMediaCache(withAuth(humanAuthPolicy, handler))
const params = { params: Promise.resolve({ id: "fixed" }) }
for (const [viewer, ga, sessionData] of [["A", "first", "old"], ["A", "second", "renewed"], ["B", "third", "other"]]) {
mocks.getSession.mockResolvedValueOnce(session(viewer))
@@ -133,7 +117,7 @@ describe("real authentication wrappers inside media policy", () => {
if (kind === "bot") mocks.getSession.mockResolvedValue(session("bot1", { isBot: true }))
if (kind === "deleted") mocks.getSession.mockResolvedValue(session("A", { deletedAt: "2026-10-01" }))
const handler = vi.fn<AuthenticatedHandler>(async () => media())
- const result = await withPrivateMediaCache(withAuth(handler))(request())
+ const result = await withPrivateMediaCache(withAuth(humanAuthPolicy, handler))(request())
expect(result.status).toBe(kind === "error" ? 503 : 401)
expect(result.headers.get("Cache-Control")).toBe("private, no-store")
expect(handler).not.toHaveBeenCalled()
@@ -143,36 +127,26 @@ describe("real authentication wrappers inside media policy", () => {
}
})
- it.each([200, 304])("retains Authorization on machine-authenticated media status %s", async (status) => {
- const handler = vi.fn<AuthenticatedHandler>(async () => media(status))
- const result = await withPrivateMediaCache(withAuth(handler))(request({ Authorization: "Bearer al_fixture" }))
- expect(result.status).toBe(status)
- expect(result.headers.get("Vary")).toBe("Authorization, X-Alook-Bot-Id")
- expect(mocks.getSession).not.toHaveBeenCalled()
- expect(handler.mock.lastCall?.[1]).toMatchObject({ userId: "A", workspaceId: "ws1" })
- })
-
- it.each(["invalid", "unavailable"])("makes early %s machine auth non-storable", async (kind) => {
- if (kind === "invalid") mocks.getMachineToken.mockResolvedValue(null)
- else mocks.getMachineToken.mockRejectedValue(new Error("database unavailable"))
+ it("makes retired token rejection non-storable even with a live Cookie", async () => {
const handler = vi.fn<AuthenticatedHandler>(async () => media())
- const result = await withPrivateMediaCache(withAuth(handler))(request({ Authorization: "Bearer al_fixture" }))
- expect(result.status).toBe(kind === "invalid" ? 401 : 503)
+ const result = await withPrivateMediaCache(withAuth(humanAuthPolicy, handler))(request({ Authorization: "Bearer al_retired", Cookie: "better-auth.session_token=live" }))
+ expect(result.status).toBe(401)
expect(result.headers.get("Cache-Control")).toBe("private, no-store")
expect(handler).not.toHaveBeenCalled()
+ expect(mocks.getSession).not.toHaveBeenCalled()
})
it.each(["human", "bot"])("preserves %s actor resolution on fixed attachment thumbnails", async (kind) => {
const handler = vi.fn<CommunityActorHandler>(async () => media())
const headers: Record<string, string> = kind === "bot" ? { Authorization: "Bearer crk_fixture" } : { Cookie: "viewer=A; _ga=changed" }
- const result = await withPrivateMediaCache(withCommunityActor(handler))(request(headers))
+ const result = await withPrivateMediaCache(withAuth(communityActorPolicy(), handler))(request(headers))
expect(result.headers.get("Vary")).toBe("Authorization, X-Alook-Bot-Id")
expect(handler.mock.lastCall?.[1].actor.kind).toBe(kind)
expect(mocks.getSession).toHaveBeenCalledTimes(kind === "human" ? 1 : 0)
})
it("adds no cache TTL to bot downloads and separates them by Authorization", async () => {
- const result = await withPrivateMediaCache(withCommunityActor(async () => new Response("bot bytes", {
+ const result = await withPrivateMediaCache(withAuth(communityActorPolicy(), async () => new Response("bot bytes", {
headers: { "X-Alook-Filename": "file.bin", "Content-Length": "9" },
})))(request({ Authorization: "Bearer crk_fixture" }))
expect(result.headers.get("Cache-Control")).toBeNull()
@@ -184,7 +158,7 @@ describe("real authentication wrappers inside media policy", () => {
it.each([401, 503])("makes bot auth status %s non-storable without falling through to the human session", async (status) => {
mocks.resolveBotActor.mockResolvedValue({ kind: "error", response: NextResponse.json({ error: "runner auth" }, { status }) })
const handler = vi.fn<CommunityActorHandler>(async () => media())
- const result = await withPrivateMediaCache(withCommunityActor(handler))(request({ Authorization: "Bearer crk_fixture" }))
+ const result = await withPrivateMediaCache(withAuth(communityActorPolicy(), handler))(request({ Authorization: "Bearer crk_fixture" }))
expect(result.status).toBe(status)
expect(result.headers.get("Cache-Control")).toBe("private, no-store")
expect(handler).not.toHaveBeenCalled()
@@ -192,7 +166,7 @@ describe("real authentication wrappers inside media policy", () => {
})
it("keeps default private account responses credential-specific outside the selected media wrapper", async () => {
- const result = await withAuth(async () => media())(request())
+ const result = await withAuth(humanAuthPolicy, async () => media())(request())
expect(result.headers.get("Vary")).toBe("Cookie, Authorization, X-Alook-Bot-Id")
})
})
diff --git a/src/web/src/lib/observability/actions.ts b/src/web/src/lib/observability/actions.ts
index b5183b39d..3a318f23c 100644
--- a/src/web/src/lib/observability/actions.ts
+++ b/src/web/src/lib/observability/actions.ts
@@ -11,10 +11,6 @@ export const actionVariants = {
"delete": "machine.delete",
"update": "machine.update"
},
- "device.authorization.command": {
- "approve": "device.authorization.approve",
- "deny": "device.authorization.deny"
- },
"account.deletion.command": {
"code": "account.deletion.code.request",
"delete": "account.delete"
diff --git a/src/web/src/lib/observability/coverage.test.ts b/src/web/src/lib/observability/coverage.test.ts
index 53fd3b6e3..b664c6ed9 100644
--- a/src/web/src/lib/observability/coverage.test.ts
+++ b/src/web/src/lib/observability/coverage.test.ts
@@ -51,11 +51,6 @@ const mutationCoverage = [
"owner": "InviteAcceptInner",
"action": "server.invite.accept"
},
- {
- "file": "src/web/src/app/device/page.tsx",
- "owner": "DeviceAuthPageInner",
- "action": "device.authorization.command"
- },
{
"file": "src/web/src/components/community/machines/machine-list.tsx",
"owner": "MachineList",
diff --git a/src/web/src/lib/observability/coverage.ts b/src/web/src/lib/observability/coverage.ts
index 194a7ceb9..a0cbff516 100644
--- a/src/web/src/lib/observability/coverage.ts
+++ b/src/web/src/lib/observability/coverage.ts
@@ -16,7 +16,6 @@ export const pageRoutes = [
"/c/onboarding-preview",
"/contact",
"/demo",
- "/device",
"/guides",
"/landing-legacy",
"/onboarding-preview",
@@ -173,7 +172,6 @@ export const apiRoutes = [
"/api/email/notify",
"/api/health",
"/api/internal/account-maintenance",
- "/api/meeting/callback",
"/api/pricing",
"/api/privacy/analytics-consent",
"/api/stripe/webhook",
@@ -233,9 +231,6 @@ export const actionNames = [
"command.unknown",
"community.command",
"community.onboarding.initialize",
- "device.authorization.approve",
- "device.authorization.command",
- "device.authorization.deny",
"dm.message.send",
"dm.open",
"forum.tags.update",
diff --git a/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsx b/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsx
index 6a6086418..e89559b5a 100644
--- a/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsx
+++ b/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsx
@@ -55,7 +55,12 @@ it("binds the initial navigation before ready and parents a real native HTTP spa
const navigation = navigationForHref(window.location.href)!
expect(navigation.span).toBeUndefined()
now = 900
- await act(async () => { native.release?.(); await vi.advanceTimersByTimeAsync(1500) })
+ await act(async () => {
+ native.release?.()
+ // Fake timer advancement does not wait for the other tracing imports.
+ await vi.dynamicImportSettled()
+ await vi.advanceTimersByTimeAsync(1500)
+ })
expect(navigation.span?.isRecording()).toBe(true)
expect(navigationForHref(window.location.href)).toBe(navigation)
const parent = navigation.span!.spanContext()
diff --git a/src/web/src/lib/services/email-dispatch.ts b/src/web/src/lib/services/email-dispatch.ts
deleted file mode 100644
index 29c661006..000000000
--- a/src/web/src/lib/services/email-dispatch.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import { queries, TASK_TYPES, extractThreadId, buildEmailMapKey } from "@alook/shared"
-import { nanoid } from "nanoid"
-import type { Database } from "@alook/shared"
-import { TaskService } from "@/lib/services/task"
-import { broadcastToUser } from "@/lib/broadcast"
-import { taskToResponse } from "@/lib/api/responses"
-
-interface EmailRow {
- id: string
- fromEmail: string
- toEmail: string
- subject: string
- messageId: string
- inReplyTo: string
- references: string
- agentId: string
- workspaceId: string
-}
-
-interface AgentRow {
- id: string
- workspaceId: string
- ownerId: string | null
-}
-
-interface DispatchOpts {
- isInternal?: boolean
- senderConversationId?: string
- senderAgentId?: string
- traceId?: string
- sourceTaskId?: string
-}
-
-export async function dispatchEmailToAgent(
- db: Database,
- email: EmailRow,
- agent: AgentRow,
- opts: DispatchOpts = {},
-): Promise<{ conversationId: string; taskId: string }> {
- const ownerId = agent.ownerId!
- const threadId = extractThreadId(email.references, email.inReplyTo, email.messageId)
- const mapKey = threadId ? buildEmailMapKey(agent.id, threadId) : null
- let conversationType: string = TASK_TYPES.EMAIL_NOTIFICATION
- let dmUser: { name: string; email: string } | undefined
- let conversationId: string | null = null
-
- if (mapKey) {
- conversationId = await queries.conversationMap.findByKey(db, mapKey, email.workspaceId)
- }
-
- if (conversationId) {
- const conv = await queries.conversation.getConversation(db, conversationId, email.workspaceId)
- if (conv) {
- conversationType = conv.type
- if (conv.type === TASK_TYPES.USER_DM_MESSAGE && conv.userId) {
- const u = await queries.user.getUserSelf(db, conv.userId)
- if (u) dmUser = { name: u.name, email: u.email }
- }
- }
- } else {
- let inheritedChannel: string | undefined
- if (opts.sourceTaskId) {
- const parentTask = await queries.task.getTask(db, opts.sourceTaskId, email.workspaceId)
- if (parentTask) {
- const parentConv = await queries.conversation.getConversation(db, parentTask.conversationId, email.workspaceId)
- if (parentConv) inheritedChannel = parentConv.channel
- }
- }
- const conv = await queries.conversation.createConversation(db, {
- workspaceId: agent.workspaceId,
- agentId: agent.id,
- userId: ownerId,
- title: `Email: ${email.subject}`.slice(0, 50),
- type: TASK_TYPES.EMAIL_NOTIFICATION,
- ...(inheritedChannel && inheritedChannel !== "default" ? { channel: inheritedChannel } : {}),
- })
- conversationId = conv.id
-
- if (mapKey) {
- await queries.conversationMap.createMapping(db, {
- key: mapKey,
- workspaceId: email.workspaceId,
- conversationId,
- })
- }
- }
-
- const prompt = `New email from ${email.fromEmail}: ${email.subject}`
- const crossLink = opts.isInternal && opts.senderConversationId && opts.senderAgentId !== email.agentId
- ? { targetConversationId: opts.senderConversationId, targetAgentId: opts.senderAgentId }
- : {}
- const emailMetadata = JSON.stringify({ emailId: email.id, subject: email.subject, from: email.fromEmail, to: email.toEmail, direction: "inbound" as const, ...crossLink })
- const msg = await queries.message.createMessage(db, {
- conversationId,
- role: "event",
- content: prompt,
- metadata: emailMetadata,
- })
-
- if (conversationType === TASK_TYPES.USER_DM_MESSAGE) {
- broadcastToUser(ownerId, {
- type: "conversation.message",
- conversationId,
- message: {
- id: msg.id,
- conversation_id: msg.conversationId,
- role: msg.role as "event",
- content: msg.content,
- task_id: msg.taskId,
- attachment_ids: null,
- metadata: { emailId: email.id, subject: email.subject, from: email.fromEmail, to: email.toEmail, direction: "inbound" },
- created_at: msg.createdAt,
- },
- }).catch(() => {})
- }
-
- const taskService = new TaskService(db)
- const context: Record<string, unknown> = { conversationType }
- if (dmUser) context.dmUser = dmUser
- if (opts.isInternal) context.isInternal = true
- context.emailId = email.id
- const traceId = opts.traceId || ("tr_" + nanoid())
- const parentTaskId = opts.traceId ? (opts.sourceTaskId || null) : null
- const task = await taskService.enqueueTask(agent.id, conversationId, agent.workspaceId, prompt, TASK_TYPES.EMAIL_NOTIFICATION, { contextKey: conversationId, context, traceId, parentTaskId })
- queries.message.updateMessageTaskId(db, msg.id, task.id).catch(() => {})
-
- if (conversationType === TASK_TYPES.USER_DM_MESSAGE) {
- broadcastToUser(ownerId, {
- type: "task.created",
- conversationId,
- task: taskToResponse(task),
- }).catch(() => {})
- }
-
- return { conversationId, taskId: task.id }
-}
diff --git a/src/web/src/lib/services/task-payload-builder.test.ts b/src/web/src/lib/services/task-payload-builder.test.ts
deleted file mode 100644
index 8d77e6eea..000000000
--- a/src/web/src/lib/services/task-payload-builder.test.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-
-const mockGetAllAgentsForWorkspace = vi.fn();
-const mockGetAllEmailAccountsForWorkspace = vi.fn();
-const mockGetAllColleaguesForWorkspace = vi.fn();
-const mockGetMemberByUserAndWorkspace = vi.fn();
-const mockGetUser = vi.fn();
-const mockGetConversation = vi.fn();
-const mockGetConversationsByIds = vi.fn();
-
-vi.mock("@alook/shared", async () => {
- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
- return {
- ...real,
- queries: {
- agent: {
- getAllAgentsForWorkspace: (...args: unknown[]) => mockGetAllAgentsForWorkspace(...args),
- },
- emailAccount: {
- getAllEmailAccountsForWorkspace: (...args: unknown[]) => mockGetAllEmailAccountsForWorkspace(...args),
- },
- agentLink: {
- getAllColleaguesForWorkspace: (...args: unknown[]) => mockGetAllColleaguesForWorkspace(...args),
- },
- member: {
- getMemberByUserAndWorkspace: (...args: unknown[]) => mockGetMemberByUserAndWorkspace(...args),
- },
- user: {
- getUserSelf: (...args: unknown[]) => mockGetUser(...args),
- },
- conversation: {
- getConversation: (...args: unknown[]) => mockGetConversation(...args),
- getConversationsByIds: (...args: unknown[]) => mockGetConversationsByIds(...args),
- },
- },
- };
-});
-
-vi.mock("@/lib/cache", () => ({
- cached: vi.fn((_key: string, _ttl: number, fn: () => Promise<any>) => fn()),
- cacheKeys: {
- allAgents: (wsId: string) => `agents:${wsId}`,
- allEmailAccounts: (wsId: string) => `ea:${wsId}`,
- allColleagues: (wsId: string) => `col:${wsId}`,
- member: (wsId: string, userId: string) => `mem:${wsId}:${userId}`,
- user: (userId: string) => `usr:${userId}`,
- },
-}));
-
-vi.mock("@/lib/api/responses", () => ({
- taskToResponse: (t: any) => ({
- id: t.id,
- agent_id: t.agentId,
- runtime_id: t.runtimeId,
- workspace_id: t.workspaceId,
- prompt: t.prompt,
- status: t.status,
- type: t.type,
- }),
-}));
-
-import { TaskPayloadBuilder } from "./task-payload-builder";
-
-function makeTask(overrides: Record<string, unknown> = {}) {
- return {
- id: "t1",
- agentId: "a1",
- runtimeId: "r1",
- workspaceId: "w1",
- conversationId: "c1",
- prompt: "do something",
- status: "dispatched",
- priority: 1,
- result: null,
- context: null,
- type: "user_dm_message",
- contextKey: null,
- sessionId: null,
- createdAt: new Date("2026-01-01"),
- dispatchedAt: new Date("2026-01-01"),
- startedAt: null,
- completedAt: null,
- error: null,
- traceId: null,
- parentTaskId: null,
- ...overrides,
- };
-}
-
-describe("TaskPayloadBuilder", () => {
- const db = {} as any;
- let builder: TaskPayloadBuilder;
-
- beforeEach(() => {
- vi.clearAllMocks();
- builder = new TaskPayloadBuilder(db);
- mockGetAllAgentsForWorkspace.mockResolvedValue([]);
- mockGetAllEmailAccountsForWorkspace.mockResolvedValue([]);
- mockGetAllColleaguesForWorkspace.mockResolvedValue([]);
- mockGetConversationsByIds.mockResolvedValue([]);
- });
-
- it("returns empty array for empty input", async () => {
- const result = await builder.buildFullPayloads([], "w1");
- expect(result).toEqual([]);
- expect(mockGetAllAgentsForWorkspace).not.toHaveBeenCalled();
- });
-
- it("handles kill_task type (returns taskToResponse with agent: null, sender: null)", async () => {
- const task = makeTask({ type: "kill_task" });
- const result = await builder.buildFullPayloads([task], "w1");
-
- expect(result).toHaveLength(1);
- expect(result[0].agent).toBeNull();
- expect(result[0].sender).toBeNull();
- expect(result[0].id).toBe("t1");
- expect(mockGetAllAgentsForWorkspace).not.toHaveBeenCalled();
- });
-
- it("builds full payload for a normal task", async () => {
- mockGetAllAgentsForWorkspace.mockResolvedValue([
- { id: "a1", ownerId: "owner1", instructions: "be helpful", name: "Bot", runtimeConfig: { model: "gpt-4" }, emailHandle: "bot" },
- ]);
- mockGetAllEmailAccountsForWorkspace.mockResolvedValue([
- { agentId: "a1", emailAddress: "[email protected]" },
- ]);
- mockGetAllColleaguesForWorkspace.mockResolvedValue([
- { agentId: "a1", name: "Helper", emailHandle: "helper", description: "helps", instruction: "be nice" },
- ]);
- mockGetUser.mockResolvedValue({ name: "Owner", email: "[email protected]" });
- mockGetMemberByUserAndWorkspace.mockResolvedValue({ globalInstruction: "" });
- mockGetConversationsByIds.mockResolvedValue([{ id: "c1", userId: "sender1", channel: "slack" }]);
- mockGetUser
- .mockResolvedValueOnce({ name: "Owner", email: "[email protected]" })
- .mockResolvedValueOnce({ name: "Sender", email: "[email protected]" });
-
- const task = makeTask({ type: "user_dm_message" });
- const result = await builder.buildFullPayloads([task], "w1");
-
- expect(result).toHaveLength(1);
- expect(result[0].agent).toMatchObject({
- instructions: "be helpful",
- name: "Bot",
- runtime_config: { model: "gpt-4" },
- email_handle: "bot",
- email_addresses: ["[email protected]", "[email protected]"],
- colleagues: [{ name: "Helper", email: "[email protected]", description: "helps", instruction: "be nice" }],
- });
- expect(result[0].channel).toBe("slack");
- expect(result[0].sender).toMatchObject({ name: "Sender", email: "[email protected]" });
- });
-
- it("merges globalInstruction from member into agent instructions", async () => {
- mockGetAllAgentsForWorkspace.mockResolvedValue([
- { id: "a1", ownerId: "owner1", instructions: "agent rules", name: "Bot", runtimeConfig: {} },
- ]);
- mockGetAllEmailAccountsForWorkspace.mockResolvedValue([]);
- mockGetAllColleaguesForWorkspace.mockResolvedValue([]);
- mockGetMemberByUserAndWorkspace.mockResolvedValue({ globalInstruction: "speak english" });
- mockGetUser.mockResolvedValue({ name: "Owner", email: "[email protected]" });
- mockGetConversationsByIds.mockResolvedValue([]);
-
- const task = makeTask();
- const result = await builder.buildFullPayloads([task], "w1");
-
- expect(result[0].agent!.instructions).toBe("speak english\n\nagent rules");
- });
-
- it("handles task where agent is not found (agent: null)", async () => {
- mockGetAllAgentsForWorkspace.mockResolvedValue([]);
- mockGetAllEmailAccountsForWorkspace.mockResolvedValue([]);
- mockGetAllColleaguesForWorkspace.mockResolvedValue([]);
- mockGetConversationsByIds.mockResolvedValue([]);
-
- const task = makeTask({ agentId: "nonexistent" });
- const result = await builder.buildFullPayloads([task], "w1");
-
- expect(result).toHaveLength(1);
- expect(result[0].agent).toBeNull();
- });
-
- it("dedupes DB queries when multiple tasks share the same agent", async () => {
- mockGetAllAgentsForWorkspace.mockResolvedValue([
- { id: "a1", ownerId: "owner1", instructions: "shared", name: "Bot", runtimeConfig: {} },
- ]);
- mockGetAllEmailAccountsForWorkspace.mockResolvedValue([]);
- mockGetAllColleaguesForWorkspace.mockResolvedValue([]);
- mockGetMemberByUserAndWorkspace.mockResolvedValue({ globalInstruction: "" });
- mockGetUser.mockResolvedValue({ name: "Owner", email: "[email protected]" });
- mockGetConversationsByIds.mockResolvedValue([]);
-
- const task1 = makeTask({ id: "t1", agentId: "a1" });
- const task2 = makeTask({ id: "t2", agentId: "a1" });
- const result = await builder.buildFullPayloads([task1, task2], "w1");
-
- expect(result).toHaveLength(2);
- expect(result[0].agent!.name).toBe("Bot");
- expect(result[1].agent!.name).toBe("Bot");
- expect(mockGetAllAgentsForWorkspace).toHaveBeenCalledTimes(1);
- expect(mockGetAllEmailAccountsForWorkspace).toHaveBeenCalledTimes(1);
- expect(mockGetAllColleaguesForWorkspace).toHaveBeenCalledTimes(1);
- expect(mockGetMemberByUserAndWorkspace).toHaveBeenCalledTimes(1);
- });
-});
-
-it.each(["same", "foreign", "missing"])("binds the actual task sender identity cache loader to its requested user: %s", async mode => {
- const { cached } = await import("@/lib/cache")
- const mock = vi.mocked(cached)
- const previous = mock.getMockImplementation()
- mock.mockImplementation(async (_key, _ttl, load, schema) => schema.parse(await load()))
- mockGetAllAgentsForWorkspace.mockResolvedValue([])
- mockGetAllEmailAccountsForWorkspace.mockResolvedValue([])
- mockGetAllColleaguesForWorkspace.mockResolvedValue([])
- mockGetConversationsByIds.mockResolvedValue([{ id: "c1", userId: "sender1", channel: "slack" }])
- mockGetUser.mockResolvedValue(mode === "missing" ? null : { id: mode === "same" ? "sender1" : "foreign", name: "Sender", email: "[email protected]" })
- try {
- const operation = new TaskPayloadBuilder({} as never).buildFullPayloads([makeTask({ type: "user_dm_message" })], "w1")
- if (mode === "foreign") await expect(operation).rejects.toThrow()
- else expect((await operation)[0]!.sender).toEqual(mode === "missing" ? null : { name: "Sender", email: "[email protected]", is_owner: false })
- expect(mockGetUser).toHaveBeenLastCalledWith({}, "sender1")
- } finally { if (previous) mock.mockImplementation(previous) }
-})
diff --git a/src/web/src/lib/services/task-payload-builder.ts b/src/web/src/lib/services/task-payload-builder.ts
deleted file mode 100644
index fab7adf35..000000000
--- a/src/web/src/lib/services/task-payload-builder.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-import type { Database, ClaimedTaskRow } from "@alook/shared";
-import { queries, TASK_TYPES, toAlookAddress, TaskEmailAddressCacheSchema, TaskMemberInstructionCacheSchema, TaskUserIdentityCacheSchema } from "@alook/shared";
-import { taskToResponse } from "@/lib/api/responses";
-import { cached, cacheKeys } from "@/lib/cache";
-
-export class TaskPayloadBuilder {
- constructor(private db: Database) {}
-
- async buildFullPayloads(tasks: ClaimedTaskRow[], workspaceId: string) {
- const nonKillTasks = tasks.filter((t) => t.type !== TASK_TYPES.KILL_TASK);
- const agentIds = [...new Set(nonKillTasks.map((t) => t.agentId))];
-
- const [allAgents, allEmailAccounts, allColleagues] = agentIds.length > 0
- ? await Promise.all([
- queries.agent.getAllAgentsForWorkspace(this.db, workspaceId),
- cached(cacheKeys.allEmailAccounts(workspaceId), 600, async () => (await queries.emailAccount.getAllEmailAccountsForWorkspace(this.db, workspaceId)).map(({ workspaceId, agentId, emailAddress }) => ({ workspaceId, agentId, emailAddress })), TaskEmailAddressCacheSchema.refine(rows => rows.every(row => row.workspaceId === workspaceId))),
- queries.agentLink.getAllColleaguesForWorkspace(this.db, workspaceId).catch(() => [] as Awaited<ReturnType<typeof queries.agentLink.getAllColleaguesForWorkspace>>),
- ]).then(([agents, emails, colleagues]) => {
- const agentIdSet = new Set(agentIds);
- return [
- agents.filter((a) => agentIdSet.has(a.id)),
- emails.filter((a) => agentIdSet.has(a.agentId)),
- colleagues.filter((c) => agentIdSet.has(c.agentId)),
- ] as const;
- })
- : [[], [], [] as Awaited<ReturnType<typeof queries.agentLink.getAllColleaguesForWorkspace>>];
-
- const agentMap = new Map(allAgents.map((a) => [a.id, a]));
- const emailAccountsByAgent = new Map<string, string[]>();
- for (const acc of allEmailAccounts) {
- const list = emailAccountsByAgent.get(acc.agentId) ?? [];
- list.push(acc.emailAddress);
- emailAccountsByAgent.set(acc.agentId, list);
- }
- const colleaguesByAgent = new Map<string, typeof allColleagues>();
- for (const c of allColleagues) {
- const list = colleaguesByAgent.get(c.agentId) ?? [];
- list.push(c);
- colleaguesByAgent.set(c.agentId, list);
- }
-
- const convoIds = [...new Set(nonKillTasks.map((t) => t.conversationId).filter(Boolean))];
- const convos = convoIds.length > 0
- ? await queries.conversation.getConversationsByIds(this.db, convoIds, workspaceId)
- : [];
- const convoMap = new Map(convos.map((c) => [c.id, c]));
-
- const memberCache = new Map<string, { globalInstruction: string } | null>();
- const userCache = new Map<string, { name: string; email: string } | null>();
-
- const results = [];
- for (const task of tasks) {
- if (task.type === TASK_TYPES.KILL_TASK) {
- results.push({ ...taskToResponse(task), agent: null, sender: null });
- continue;
- }
-
- const agent = agentMap.get(task.agentId) ?? null;
- const emailAddresses: string[] = [];
- if (agent) {
- if (agent.emailHandle) emailAddresses.push(toAlookAddress(agent.emailHandle));
- const customAccounts = emailAccountsByAgent.get(agent.id) ?? [];
- emailAddresses.push(...customAccounts);
- }
-
- let instructions = agent?.instructions ?? "";
- if (agent?.ownerId) {
- if (!memberCache.has(agent.ownerId)) {
- const m = await cached(
- cacheKeys.member(workspaceId, agent.ownerId),
- 600,
- async () => {
- const row = await queries.member.getMemberByUserAndWorkspace(this.db, agent.ownerId!, workspaceId);
- return row ? { workspaceId: row.workspaceId, userId: row.userId, globalInstruction: row.globalInstruction } : null;
- },
- TaskMemberInstructionCacheSchema.refine(row => row === null || row.workspaceId === workspaceId && row.userId === agent.ownerId),
- );
- memberCache.set(agent.ownerId, m ? { globalInstruction: m.globalInstruction } : null);
- }
- const cachedMember = memberCache.get(agent.ownerId);
- if (cachedMember?.globalInstruction) {
- instructions = [cachedMember.globalInstruction, instructions].filter(Boolean).join("\n\n");
- }
- }
-
- let ownerName: string | null = null;
- if (agent?.ownerId) {
- if (!userCache.has(agent.ownerId)) {
- const u = await cached(
- cacheKeys.user(agent.ownerId),
- 1800,
- async () => {
- const row = await queries.user.getUserSelf(this.db, agent.ownerId!);
- return row ? { id: row.id, name: row.name, email: row.email } : null;
- },
- TaskUserIdentityCacheSchema.refine(row => row === null || row.id === agent.ownerId),
- );
- userCache.set(agent.ownerId, u ? { name: u.name, email: u.email } : null);
- }
- ownerName = userCache.get(agent.ownerId)?.name ?? null;
- }
-
- const convo = convoMap.get(task.conversationId) ?? null;
- const taskChannel = convo?.channel ?? "default";
-
- let sender: { name: string; email: string; is_owner: boolean } | null = null;
- if (task.type === TASK_TYPES.USER_DM_MESSAGE && convo?.userId) {
- if (!userCache.has(convo.userId)) {
- const u = await cached(
- cacheKeys.user(convo.userId),
- 1800,
- async () => {
- const row = await queries.user.getUserSelf(this.db, convo!.userId!);
- return row ? { id: row.id, name: row.name, email: row.email } : null;
- },
- TaskUserIdentityCacheSchema.refine(row => row === null || row.id === convo!.userId),
- );
- userCache.set(convo.userId, u ? { name: u.name, email: u.email } : null);
- }
- const cachedUser = userCache.get(convo.userId);
- if (cachedUser) {
- sender = {
- name: cachedUser.name,
- email: cachedUser.email,
- is_owner: convo.userId === agent?.ownerId,
- };
- }
- }
-
- const rawColleagues = colleaguesByAgent.get(task.agentId) ?? [];
- const colleagues = rawColleagues.map((c) => ({
- name: c.name,
- email: c.emailHandle ? toAlookAddress(c.emailHandle) : "",
- description: c.description,
- instruction: c.instruction,
- }));
-
- results.push({
- ...taskToResponse(task),
- channel: taskChannel,
- sender,
- agent: agent
- ? {
- instructions,
- name: agent.name,
- runtime_config: (agent.runtimeConfig || {}) as Record<string, unknown>,
- email_handle: agent.emailHandle || null,
- email_addresses: emailAddresses,
- user_email: null as string | null,
- user_name: ownerName,
- colleagues,
- }
- : null,
- });
- }
-
- return results;
- }
-}
diff --git a/src/web/src/lib/services/task.test.ts b/src/web/src/lib/services/task.test.ts
deleted file mode 100644
index ba5196dc4..000000000
--- a/src/web/src/lib/services/task.test.ts
+++ /dev/null
@@ -1,975 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
-
-vi.mock("@alook/shared", () => ({
- TASK_TYPES: {
- USER_DM_MESSAGE: "user_dm_message",
- EMAIL_NOTIFICATION: "email_notification",
- CALENDAR_EVENT: "calendar_event",
- ISSUE_EVENT: "issue_event",
- KILL_TASK: "kill_task",
- },
- MAX_TASKS_PER_TRACE: 256,
- queries: {
- task: {
- createTask: vi.fn(),
- claimTask: vi.fn(),
- startTask: vi.fn(),
- completeTask: vi.fn(),
- failTask: vi.fn(),
- supersedeTask: vi.fn(),
- markFailedAsSuperseded: vi.fn(),
- getTask: vi.fn(),
- countRunningTasks: vi.fn(),
- countTasksByTrace: vi.fn().mockResolvedValue(0),
- getLatestTaskForConversation: vi.fn().mockResolvedValue(null),
- listPendingTasksByRuntimes: vi.fn(),
- claimKillTasks: vi.fn().mockResolvedValue([]),
- getActiveTaskByConversation: vi.fn(),
- cancelTask: vi.fn(),
- dispatchTaskById: vi.fn().mockResolvedValue(null),
- findSteerableReplacement: vi.fn().mockResolvedValue(null),
- },
- agent: {
- getAgent: vi.fn(),
- getAgentsByIds: vi.fn(),
- updateAgentStatus: vi.fn(),
- },
- message: {
- createMessage: vi.fn(),
- updateMessageTaskId: vi.fn().mockResolvedValue(undefined),
- },
- conversation: {
- getConversation: vi.fn(),
- },
- issue: {
- getIssue: vi.fn(),
- getIssueByConversation: vi.fn(),
- updateIssue: vi.fn(),
- },
- runtime: {
- getAgentRuntime: vi.fn(),
- },
- inbox: {
- isUnreadEligible: vi.fn().mockReturnValue(false),
- upsertUnreadEntry: vi.fn().mockResolvedValue(undefined),
- findLatestAssistantMessageId: vi.fn().mockResolvedValue(null),
- },
- },
-}));
-
-vi.mock("@/lib/logger", () => ({
- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() },
-}));
-
-vi.mock("@/lib/broadcast", () => ({
- broadcastToUser: vi.fn().mockResolvedValue(undefined),
- broadcastToDaemon: vi.fn().mockResolvedValue({ sent: 1 }),
-}));
-
-vi.mock("@/lib/api/responses", () => ({
- messageToResponse: (m: unknown) => m,
- taskToResponse: (t: unknown) => t,
-}));
-
-import { TaskService } from "./task";
-import { queries } from "@alook/shared";
-import { broadcastToUser, broadcastToDaemon } from "@/lib/broadcast";
-import { log } from "@/lib/logger";
-
-const taskQ = queries.task as {
- [K in keyof typeof queries.task]: ReturnType<typeof vi.fn>;
-};
-const agentQ = queries.agent as {
- [K in keyof typeof queries.agent]: ReturnType<typeof vi.fn>;
-};
-const messageQ = queries.message as {
- [K in keyof typeof queries.message]: ReturnType<typeof vi.fn>;
-};
-const conversationQ = (queries as any).conversation as {
- getConversation: ReturnType<typeof vi.fn>;
-};
-const issueQ = (queries as any).issue as {
- getIssue: ReturnType<typeof vi.fn>;
- getIssueByConversation: ReturnType<typeof vi.fn>;
- updateIssue: ReturnType<typeof vi.fn>;
-};
-const runtimeQ = (queries as any).runtime as {
- getAgentRuntime: ReturnType<typeof vi.fn>;
-};
-
-const service = new TaskService({} as any);
-
-describe("TaskService", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- // Default: no kill tasks to claim
- taskQ.claimKillTasks.mockResolvedValue([]);
- });
-
- // ── enqueueTask ──────────────────────────────────────────────────
-
- describe("enqueueTask", () => {
- it("throws when agent not found", async () => {
- agentQ.getAgent.mockResolvedValue(null);
-
- await expect(
- service.enqueueTask("a1", "c1", "w1", "do stuff")
- ).rejects.toThrow("agent not found");
- });
-
- it("throws when agent has no runtime", async () => {
- agentQ.getAgent.mockResolvedValue({ id: "a1", runtimeId: null });
-
- await expect(
- service.enqueueTask("a1", "c1", "w1", "do stuff")
- ).rejects.toThrow("agent has no runtime");
- });
-
- it("creates task with correct params on success", async () => {
- agentQ.getAgent.mockResolvedValue({ id: "a1", runtimeId: "r1" });
- taskQ.createTask.mockResolvedValue({ id: "t1" });
-
- const result = await service.enqueueTask("a1", "c1", "w1", "do stuff");
-
- expect(taskQ.createTask).toHaveBeenCalledWith({}, {
- agentId: "a1",
- runtimeId: "r1",
- workspaceId: "w1",
- conversationId: "c1",
- prompt: "do stuff",
- type: "user_dm_message",
- contextKey: null,
- priority: 0,
- context: undefined,
- traceId: null,
- parentTaskId: null,
- });
- expect(result).toEqual({ id: "t1" });
- });
- });
-
- // ── claimTask ────────────────────────────────────────────────────
-
- describe("claimTask", () => {
- it("returns null when agent not found", async () => {
- agentQ.getAgent.mockResolvedValue(null);
-
- const result = await service.claimTask("a1", "w1");
- expect(result).toBeNull();
- });
-
- it("returns null when at max capacity", async () => {
- agentQ.getAgent.mockResolvedValue({
- id: "a1",
- maxConcurrentTasks: 2,
- });
- taskQ.countRunningTasks.mockResolvedValue(2);
-
- const result = await service.claimTask("a1", "w1");
- expect(result).toBeNull();
- });
-
- it("returns null when no queued tasks", async () => {
- agentQ.getAgent.mockResolvedValue({
- id: "a1",
- maxConcurrentTasks: 5,
- });
- taskQ.countRunningTasks.mockResolvedValue(0);
- taskQ.claimTask.mockResolvedValue(null);
-
- const result = await service.claimTask("a1", "w1");
- expect(result).toBeNull();
- });
-
- it("claims task and updates agent to working on success", async () => {
- agentQ.getAgent.mockResolvedValue({
- id: "a1",
- maxConcurrentTasks: 5,
- });
- taskQ.countRunningTasks.mockResolvedValue(1);
- taskQ.claimTask.mockResolvedValue({ id: "t1", agentId: "a1" });
-
- const result = await service.claimTask("a1", "w1");
-
- expect(result).toEqual({ id: "t1", agentId: "a1" });
- expect(agentQ.updateAgentStatus).toHaveBeenCalledWith(
- {},
- "a1",
- "w1",
- "working"
- );
- });
- });
-
- // ── claimTasksForRuntimes ─────────────────────────────────────────
-
- describe("claimTasksForRuntimes", () => {
- it("returns empty array when no pending tasks", async () => {
- taskQ.listPendingTasksByRuntimes.mockResolvedValue([]);
-
- const result = await service.claimTasksForRuntimes(["r1"], 1, "w1");
- expect(result).toEqual([]);
- });
-
- it("deduplicates by agent ID and workspace ID", async () => {
- taskQ.listPendingTasksByRuntimes.mockResolvedValue([
- { agentId: "a1", workspaceId: "w1", id: "t1", runtimeId: "r1" },
- { agentId: "a1", workspaceId: "w1", id: "t2", runtimeId: "r1" },
- ]);
- agentQ.getAgentsByIds.mockResolvedValue([{
- id: "a1",
- maxConcurrentTasks: 5,
- }]);
- taskQ.countRunningTasks.mockResolvedValue(0);
- taskQ.claimTask.mockResolvedValue({
- id: "t1",
- agentId: "a1",
- runtimeId: "r1",
- });
-
- const result = await service.claimTasksForRuntimes(["r1"], 5, "w1");
-
- expect(result).toEqual([{ id: "t1", agentId: "a1", runtimeId: "r1" }]);
- expect(taskQ.claimTask).toHaveBeenCalledTimes(1);
- });
-
- it("respects maxTasks limit", async () => {
- taskQ.listPendingTasksByRuntimes.mockResolvedValue([
- { agentId: "a1", workspaceId: "w1", id: "t1", runtimeId: "r1" },
- { agentId: "a2", workspaceId: "w1", id: "t2", runtimeId: "r1" },
- { agentId: "a3", workspaceId: "w1", id: "t3", runtimeId: "r1" },
- ]);
- agentQ.getAgentsByIds.mockResolvedValue([
- { id: "a1", maxConcurrentTasks: 5 },
- { id: "a2", maxConcurrentTasks: 5 },
- ]);
- taskQ.countRunningTasks.mockResolvedValue(0);
-
- let callCount = 0;
- taskQ.claimTask.mockImplementation(async () => {
- callCount++;
- return { id: `t${callCount}`, agentId: `a${callCount}`, runtimeId: "r1" };
- });
-
- const result = await service.claimTasksForRuntimes(["r1"], 2, "w1");
- expect(result).toHaveLength(2);
- });
-
- it("skips claimed task whose runtimeId is not in the provided set", async () => {
- taskQ.listPendingTasksByRuntimes.mockResolvedValue([
- { agentId: "a1", workspaceId: "w1", id: "t1", runtimeId: "r1" },
- ]);
- agentQ.getAgentsByIds.mockResolvedValue([{ id: "a1", maxConcurrentTasks: 5 }]);
- taskQ.countRunningTasks.mockResolvedValue(0);
- taskQ.claimTask.mockResolvedValue({
- id: "t1",
- agentId: "a1",
- runtimeId: "r2", // different runtime than provided
- });
-
- const result = await service.claimTasksForRuntimes(["r1"], 5, "w1");
- expect(result).toEqual([]);
- });
-
- it("returns tasks across multiple runtimes", async () => {
- taskQ.listPendingTasksByRuntimes.mockResolvedValue([
- { agentId: "a1", workspaceId: "w1", id: "t1", runtimeId: "r1" },
- { agentId: "a2", workspaceId: "w1", id: "t2", runtimeId: "r2" },
- ]);
- agentQ.getAgentsByIds.mockResolvedValue([
- { id: "a1", maxConcurrentTasks: 5 },
- { id: "a2", maxConcurrentTasks: 5 },
- ]);
- taskQ.countRunningTasks.mockResolvedValue(0);
-
- let callCount = 0;
- taskQ.claimTask.mockImplementation(async () => {
- callCount++;
- const rid = callCount === 1 ? "r1" : "r2";
- return { id: `t${callCount}`, agentId: `a${callCount}`, runtimeId: rid };
- });
-
- const result = await service.claimTasksForRuntimes(["r1", "r2"], 5, "w1");
- expect(result).toHaveLength(2);
- });
- });
-
- // ── startTask ────────────────────────────────────────────────────
-
- describe("startTask", () => {
- it("throws when not in dispatched status", async () => {
- taskQ.startTask.mockResolvedValue(null);
-
- await expect(service.startTask("t1", "w1")).rejects.toThrow(
- "task not in dispatched status"
- );
- });
-
- it("returns started task on success", async () => {
- const task = { id: "t1", status: "running" };
- taskQ.startTask.mockResolvedValue(task);
-
- const result = await service.startTask("t1", "w1");
- expect(result).toEqual(task);
- expect(taskQ.startTask).toHaveBeenCalledWith({}, "t1", "w1");
- });
-
- it("moves issue tasks to in_progress when they start", async () => {
- const task = {
- id: "t1",
- type: "issue_event",
- contextKey: "iss_1",
- workspaceId: "w1",
- conversationId: "c1",
- status: "running",
- };
- taskQ.startTask.mockResolvedValue(task);
-
- await service.startTask("t1", "w1");
-
- // Agent now controls issue status via CLI — startTask no longer auto-syncs
- expect(issueQ.updateIssue).not.toHaveBeenCalled();
- });
- });
-
- // ── completeTask ─────────────────────────────────────────────────
-
- describe("completeTask", () => {
- it("does NOT create an assistant message or broadcast from result.output (A1)", async () => {
- // A1: the agent owns its voice via `sync send-dm`. completeTask must no
- // longer auto-extract the final output into a chat bubble.
- const task = {
- id: "t1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- status: "completed",
- };
- taskQ.completeTask.mockResolvedValue(task);
- taskQ.countRunningTasks.mockResolvedValue(0);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
-
- await service.completeTask(
- "t1",
- "w1",
- JSON.stringify({ output: "Here is the answer" }),
- "sess-1"
- );
-
- expect(messageQ.createMessage).not.toHaveBeenCalled();
- expect(broadcastToUser).not.toHaveBeenCalled();
- // lifecycle side-effects still run
- expect(taskQ.completeTask).toHaveBeenCalled();
- expect(agentQ.updateAgentStatus).toHaveBeenCalled();
- });
-
- it("does not create message when result has no output", async () => {
- const task = {
- id: "t1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- status: "completed",
- };
- taskQ.completeTask.mockResolvedValue(task);
- taskQ.countRunningTasks.mockResolvedValue(0);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
-
- await service.completeTask("t1", "w1", JSON.stringify({}), "sess-1");
-
- expect(messageQ.createMessage).not.toHaveBeenCalled();
- });
-
- it("calls reconcileAgentStatus", async () => {
- const task = {
- id: "t1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- status: "completed",
- };
- taskQ.completeTask.mockResolvedValue(task);
- taskQ.countRunningTasks.mockResolvedValue(1);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
-
- await service.completeTask("t1", "w1", JSON.stringify({}), "sess-1");
-
- expect(agentQ.updateAgentStatus).toHaveBeenCalledWith(
- {},
- "a1",
- "w1",
- "working"
- );
- });
-
- it("moves issue tasks to done when they complete", async () => {
- const task = {
- id: "t1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- type: "issue_event",
- contextKey: "iss_1",
- status: "completed",
- };
- taskQ.completeTask.mockResolvedValue(task);
- taskQ.countRunningTasks.mockResolvedValue(0);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
-
- await service.completeTask("t1", "w1", JSON.stringify({}), "sess-1");
-
- // Agent now controls issue status via CLI — completeTask no longer auto-syncs
- expect(issueQ.updateIssue).not.toHaveBeenCalled();
- });
- });
-
- // ── failTask ─────────────────────────────────────────────────────
-
- describe("failTask", () => {
- it("creates a runtime-attributed error message with the resolved provider (TC6)", async () => {
- const task = {
- id: "t1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- runtimeId: "rt1",
- status: "failed",
- };
- taskQ.failTask.mockResolvedValue(task);
- taskQ.countRunningTasks.mockResolvedValue(0);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
- runtimeQ.getAgentRuntime.mockResolvedValue({ id: "rt1", provider: "claude" });
-
- await service.failTask("t1", "w1", "Not logged in · Please run /login");
-
- expect(runtimeQ.getAgentRuntime).toHaveBeenCalledWith({}, "rt1");
- expect(messageQ.createMessage).toHaveBeenCalledWith({}, {
- conversationId: "c1",
- role: "assistant",
- content: "Not logged in · Please run /login",
- taskId: "t1",
- metadata: JSON.stringify({ error_source: "runtime", provider: "claude" }),
- });
- });
-
- it("still attributes the message with provider:null when the runtime can't be resolved (TC7)", async () => {
- const task = {
- id: "t1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- runtimeId: "rt1",
- status: "failed",
- };
- taskQ.failTask.mockResolvedValue(task);
- taskQ.countRunningTasks.mockResolvedValue(0);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
- // Lookup throws — must not block the task lifecycle.
- runtimeQ.getAgentRuntime.mockRejectedValue(new Error("db down"));
-
- await expect(service.failTask("t1", "w1", "boom")).resolves.toBeTruthy();
-
- expect(messageQ.createMessage).toHaveBeenCalledWith({}, {
- conversationId: "c1",
- role: "assistant",
- content: "boom",
- taskId: "t1",
- metadata: JSON.stringify({ error_source: "runtime", provider: null }),
- });
- expect(agentQ.updateAgentStatus).toHaveBeenCalled();
- });
-
- it("attributes with provider:null when the task has no runtimeId", async () => {
- const task = {
- id: "t1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- status: "failed",
- };
- taskQ.failTask.mockResolvedValue(task);
- taskQ.countRunningTasks.mockResolvedValue(0);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
-
- await service.failTask("t1", "w1", "something went wrong");
-
- expect(runtimeQ.getAgentRuntime).not.toHaveBeenCalled();
- expect(messageQ.createMessage).toHaveBeenCalledWith({}, {
- conversationId: "c1",
- role: "assistant",
- content: "something went wrong",
- taskId: "t1",
- metadata: JSON.stringify({ error_source: "runtime", provider: null }),
- });
- });
-
- it("does not create message when error is empty", async () => {
- const task = {
- id: "t1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- status: "failed",
- };
- taskQ.failTask.mockResolvedValue(task);
- taskQ.countRunningTasks.mockResolvedValue(0);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
-
- await service.failTask("t1", "w1", "");
-
- expect(messageQ.createMessage).not.toHaveBeenCalled();
- });
-
- it("calls reconcileAgentStatus", async () => {
- const task = {
- id: "t1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- status: "failed",
- };
- taskQ.failTask.mockResolvedValue(task);
- taskQ.countRunningTasks.mockResolvedValue(2);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
-
- await service.failTask("t1", "w1", "err");
-
- expect(agentQ.updateAgentStatus).toHaveBeenCalledWith(
- {},
- "a1",
- "w1",
- "working"
- );
- });
-
- it("moves issue tasks to failed when they fail", async () => {
- const task = {
- id: "t1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- type: "issue_event",
- contextKey: "iss_1",
- status: "failed",
- };
- taskQ.failTask.mockResolvedValue(task);
- taskQ.countRunningTasks.mockResolvedValue(0);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
- issueQ.getIssueByConversation.mockResolvedValue({ id: "iss_1", status: "in_progress", conversationId: "c1" });
- issueQ.updateIssue.mockResolvedValue({ id: "iss_1", status: "failed", conversationId: "c1" });
- const eventMsg = { id: "m1", conversationId: "c1", role: "event", content: "Issue status changed: in_progress -> failed" };
- messageQ.createMessage.mockResolvedValueOnce(undefined).mockResolvedValueOnce(eventMsg);
- conversationQ.getConversation.mockResolvedValue({ id: "c1", userId: "u1", workspaceId: "w1" });
-
- await service.failTask("t1", "w1", "something went wrong");
-
- expect(issueQ.updateIssue).toHaveBeenCalledWith({}, "iss_1", "w1", { status: "failed" });
- expect(messageQ.createMessage).toHaveBeenCalledWith({}, {
- conversationId: "c1",
- role: "assistant",
- content: "something went wrong",
- taskId: "t1",
- metadata: JSON.stringify({ error_source: "runtime", provider: null }),
- });
- expect(messageQ.createMessage).toHaveBeenCalledWith({}, {
- conversationId: "c1",
- role: "event",
- content: "Issue status changed: in_progress -> failed",
- taskId: "t1",
- metadata: JSON.stringify({ issueId: "iss_1" }),
- });
- expect(broadcastToUser).toHaveBeenCalledWith("u1", expect.objectContaining({
- type: "conversation.message",
- conversationId: "c1",
- message: eventMsg,
- }));
- });
- });
-
- // ── reconcileAgentStatus ─────────────────────────────────────────
-
- describe("reconcileAgentStatus", () => {
- it("sets working when running tasks > 0", async () => {
- taskQ.countRunningTasks.mockResolvedValue(3);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
-
- await service.reconcileAgentStatus("a1", "w1");
-
- expect(agentQ.updateAgentStatus).toHaveBeenCalledWith(
- {},
- "a1",
- "w1",
- "working"
- );
- });
-
- it("sets idle when running tasks = 0", async () => {
- taskQ.countRunningTasks.mockResolvedValue(0);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
-
- await service.reconcileAgentStatus("a1", "w1");
-
- expect(agentQ.updateAgentStatus).toHaveBeenCalledWith(
- {},
- "a1",
- "w1",
- "idle"
- );
- });
- });
-
- // ── failTask creates a runtime-error assistant message (TC6) ────
-
- describe("failTask runtime-error message", () => {
- it("creates a role=assistant message with metadata.error_source=runtime + provider", async () => {
- const task = {
- id: "t1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- status: "failed",
- runtimeId: "r1",
- };
- taskQ.failTask.mockResolvedValue(task);
- taskQ.countRunningTasks.mockResolvedValue(0);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
- runtimeQ.getAgentRuntime.mockResolvedValue({ provider: "claude_code" });
-
- await service.failTask("t1", "w1", "boom");
-
- expect(messageQ.createMessage).toHaveBeenCalledWith(
- {},
- expect.objectContaining({
- conversationId: "c1",
- role: "assistant",
- content: "boom",
- taskId: "t1",
- metadata: JSON.stringify({ error_source: "runtime", provider: "claude_code" }),
- })
- );
- });
- });
-
- // ── failTask skips side-effects for kill_task ──────────────────
-
- describe("failTask kill_task guard", () => {
- it("skips message creation and reconciliation for kill_task type", async () => {
- const task = {
- id: "kt1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- status: "failed",
- type: "kill_task",
- };
- taskQ.failTask.mockResolvedValue(task);
-
- const result = await service.failTask("kt1", "w1", "killed");
-
- expect(result).toEqual(task);
- expect(messageQ.createMessage).not.toHaveBeenCalled();
- expect(taskQ.countRunningTasks).not.toHaveBeenCalled();
- expect(agentQ.updateAgentStatus).not.toHaveBeenCalled();
- });
- });
-
- // ── cancelActiveTask ─────────────────────────────────────────
-
- describe("cancelActiveTask", () => {
- it("returns null when no active task", async () => {
- taskQ.getActiveTaskByConversation.mockResolvedValue(null);
-
- const result = await service.cancelActiveTask("c1", "w1");
- expect(result).toBeNull();
- });
-
- it("cancels queued task without creating kill_task", async () => {
- const task = { id: "t1", status: "queued", agentId: "a1", runtimeId: "r1", conversationId: "c1" };
- taskQ.getActiveTaskByConversation.mockResolvedValue(task);
- taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });
- taskQ.countRunningTasks.mockResolvedValue(0);
-
- const result = await service.cancelActiveTask("c1", "w1");
-
- expect(result!.status).toBe("cancelled");
- expect(taskQ.createTask).not.toHaveBeenCalled();
- expect(messageQ.createMessage).toHaveBeenCalledWith({}, expect.objectContaining({
- content: "Task cancelled by you",
- taskId: "t1",
- // Stamped as a lifecycle note so the chat renders it as a centered
- // system line, not an agent bubble.
- metadata: JSON.stringify({ kind: "lifecycle" }),
- }));
- });
-
- it("creates kill_task for running task", async () => {
- const task = { id: "t1", status: "running", agentId: "a1", runtimeId: "r1", conversationId: "c1" };
- taskQ.getActiveTaskByConversation.mockResolvedValue(task);
- taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });
- taskQ.createTask.mockResolvedValue({ id: "kt1" });
- taskQ.countRunningTasks.mockResolvedValue(0);
- runtimeQ.getAgentRuntime.mockResolvedValue({ daemonId: "d1" });
-
- await service.cancelActiveTask("c1", "w1");
-
- expect(taskQ.createTask).toHaveBeenCalledWith({}, expect.objectContaining({
- type: "kill_task",
- agentId: "a1",
- runtimeId: "r1",
- conversationId: "c1",
- context: { target_task_id: "t1" },
- }));
- });
-
- it("pushes daemon.kill for running task", async () => {
- const task = { id: "t1", status: "running", agentId: "a1", runtimeId: "r1", conversationId: "c1" };
- taskQ.getActiveTaskByConversation.mockResolvedValue(task);
- taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });
- taskQ.createTask.mockResolvedValue({ id: "kt1" });
- taskQ.countRunningTasks.mockResolvedValue(0);
- runtimeQ.getAgentRuntime.mockResolvedValue({ daemonId: "d1" });
-
- await service.cancelActiveTask("c1", "w1");
-
- expect(broadcastToDaemon).toHaveBeenCalledWith("d1", {
- type: "daemon.kill",
- workspaceId: "w1",
- agentId: "a1",
- taskId: "kt1",
- targetTaskId: "t1",
- });
- });
-
- it("pushes daemon.kill for dispatched task", async () => {
- const task = { id: "t1", status: "dispatched", agentId: "a1", runtimeId: "r1", conversationId: "c1" };
- taskQ.getActiveTaskByConversation.mockResolvedValue(task);
- taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });
- taskQ.createTask.mockResolvedValue({ id: "kt1" });
- taskQ.countRunningTasks.mockResolvedValue(0);
- runtimeQ.getAgentRuntime.mockResolvedValue({ daemonId: "d1" });
-
- await service.cancelActiveTask("c1", "w1");
-
- expect(broadcastToDaemon).toHaveBeenCalledWith("d1", expect.objectContaining({
- type: "daemon.kill",
- targetTaskId: "t1",
- }));
- });
-
- it("does not push daemon.kill for queued task", async () => {
- const task = { id: "t1", status: "queued", agentId: "a1", runtimeId: "r1", conversationId: "c1" };
- taskQ.getActiveTaskByConversation.mockResolvedValue(task);
- taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });
- taskQ.countRunningTasks.mockResolvedValue(0);
-
- await service.cancelActiveTask("c1", "w1");
-
- expect(broadcastToDaemon).not.toHaveBeenCalled();
- });
-
- it("creates kill_task for dispatched task", async () => {
- const task = { id: "t1", status: "dispatched", agentId: "a1", runtimeId: "r1", conversationId: "c1" };
- taskQ.getActiveTaskByConversation.mockResolvedValue(task);
- taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });
- taskQ.createTask.mockResolvedValue({ id: "kt1" });
- taskQ.countRunningTasks.mockResolvedValue(0);
- runtimeQ.getAgentRuntime.mockResolvedValue({ daemonId: "d1" });
-
- await service.cancelActiveTask("c1", "w1");
-
- expect(taskQ.createTask).toHaveBeenCalledWith({}, expect.objectContaining({
- type: "kill_task",
- context: { target_task_id: "t1" },
- }));
- });
-
- it("daemon.kill payload includes agentId from active task", async () => {
- const task = { id: "t1", status: "running", agentId: "agent_xyz", runtimeId: "r1", conversationId: "c1" };
- taskQ.getActiveTaskByConversation.mockResolvedValue(task);
- taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });
- taskQ.createTask.mockResolvedValue({ id: "kt1" });
- taskQ.countRunningTasks.mockResolvedValue(0);
- runtimeQ.getAgentRuntime.mockResolvedValue({ daemonId: "d1" });
-
- await service.cancelActiveTask("c1", "w1");
-
- expect(broadcastToDaemon).toHaveBeenCalledWith("d1", expect.objectContaining({
- agentId: "agent_xyz",
- }));
- });
-
- it("logs warning when daemon.kill broadcast fails", async () => {
- const task = { id: "t1", status: "running", agentId: "a1", runtimeId: "r1", conversationId: "c1" };
- taskQ.getActiveTaskByConversation.mockResolvedValue(task);
- taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });
- taskQ.createTask.mockResolvedValue({ id: "kt1" });
- taskQ.countRunningTasks.mockResolvedValue(0);
- runtimeQ.getAgentRuntime.mockResolvedValue({ daemonId: "d1" });
-
- const broadcastError = new Error("connection refused");
- vi.mocked(broadcastToDaemon).mockRejectedValueOnce(broadcastError);
-
- await service.cancelActiveTask("c1", "w1");
-
- await vi.waitFor(() => {
- expect(log.warn).toHaveBeenCalledWith(
- "daemon.kill broadcast failed, relying on poll fallback",
- broadcastError,
- );
- });
- });
-
- it("dispatches kill task before broadcasting daemon.kill", async () => {
- const task = { id: "t1", status: "running", agentId: "a1", runtimeId: "r1", conversationId: "c1" };
- taskQ.getActiveTaskByConversation.mockResolvedValue(task);
- taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });
- taskQ.createTask.mockResolvedValue({ id: "kt1" });
- taskQ.countRunningTasks.mockResolvedValue(0);
- runtimeQ.getAgentRuntime.mockResolvedValue({ daemonId: "d1" });
-
- await service.cancelActiveTask("c1", "w1");
-
- expect(taskQ.dispatchTaskById).toHaveBeenCalledWith({}, "kt1", "w1");
- // dispatchTaskById should be called before broadcastToDaemon
- const dispatchOrder = taskQ.dispatchTaskById.mock.invocationCallOrder[0];
- const broadcastOrder = vi.mocked(broadcastToDaemon).mock.invocationCallOrder[0];
- expect(dispatchOrder).toBeLessThan(broadcastOrder);
- });
- });
-
- // ── retryTask ──────────────────────────────────────────────
-
- describe("retryTask", () => {
- const failedTask = {
- id: "t1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- prompt: "do stuff",
- type: "user_dm_message",
- status: "failed",
- context: null,
- };
-
- it("throws when task not found", async () => {
- taskQ.getTask.mockResolvedValue(null);
-
- await expect(service.retryTask("t1", "w1")).rejects.toThrow("task not found");
- });
-
- it("throws when workspace mismatch", async () => {
- taskQ.getTask.mockResolvedValue({ ...failedTask, workspaceId: "other" });
-
- await expect(service.retryTask("t1", "w1")).rejects.toThrow("task not found");
- });
-
- it("throws when task is not failed", async () => {
- taskQ.getTask.mockResolvedValue({ ...failedTask, status: "completed" });
-
- await expect(service.retryTask("t1", "w1")).rejects.toThrow("only failed tasks can be retried");
- });
-
- it("marks old task as superseded and creates new task", async () => {
- taskQ.getTask.mockResolvedValue(failedTask);
- taskQ.markFailedAsSuperseded.mockResolvedValue({ ...failedTask, status: "superseded" });
- agentQ.getAgent.mockResolvedValue({ id: "a1", runtimeId: "r1" });
- taskQ.createTask.mockResolvedValue({ id: "t2", status: "queued" });
-
- const { oldTask, newTask } = await service.retryTask("t1", "w1");
-
- expect(taskQ.markFailedAsSuperseded).toHaveBeenCalledWith({}, "t1", "w1");
- expect(taskQ.createTask).toHaveBeenCalledWith({}, expect.objectContaining({
- agentId: "a1",
- conversationId: "c1",
- workspaceId: "w1",
- prompt: "do stuff",
- type: "user_dm_message",
- }));
- expect(oldTask.status).toBe("superseded");
- expect(newTask.status).toBe("queued");
- });
-
- it("throws when markFailedAsSuperseded fails", async () => {
- taskQ.getTask.mockResolvedValue(failedTask);
- taskQ.markFailedAsSuperseded.mockResolvedValue(null);
-
- await expect(service.retryTask("t1", "w1")).rejects.toThrow("failed to mark task as superseded");
- });
-
- it("preserves context from original task", async () => {
- const taskWithContext = { ...failedTask, context: { attachment_ids: ["a1"] } };
- taskQ.getTask.mockResolvedValue(taskWithContext);
- taskQ.markFailedAsSuperseded.mockResolvedValue({ ...taskWithContext, status: "superseded" });
- agentQ.getAgent.mockResolvedValue({ id: "a1", runtimeId: "r1" });
- taskQ.createTask.mockResolvedValue({ id: "t2", status: "queued" });
-
- await service.retryTask("t1", "w1");
-
- expect(taskQ.createTask).toHaveBeenCalledWith({}, expect.objectContaining({
- context: { attachment_ids: ["a1"] },
- }));
- });
-
- it("propagates contextKey from original task", async () => {
- const taskWithKey = { ...failedTask, contextKey: "c1" };
- taskQ.getTask.mockResolvedValue(taskWithKey);
- taskQ.markFailedAsSuperseded.mockResolvedValue({ ...taskWithKey, status: "superseded" });
- agentQ.getAgent.mockResolvedValue({ id: "a1", runtimeId: "r1" });
- taskQ.createTask.mockResolvedValue({ id: "t2", status: "queued" });
-
- await service.retryTask("t1", "w1");
-
- expect(taskQ.createTask).toHaveBeenCalledWith({}, expect.objectContaining({
- contextKey: "c1",
- }));
- });
-
- it("handles original task with contextKey: null gracefully", async () => {
- const taskNoKey = { ...failedTask, contextKey: null };
- taskQ.getTask.mockResolvedValue(taskNoKey);
- taskQ.markFailedAsSuperseded.mockResolvedValue({ ...taskNoKey, status: "superseded" });
- agentQ.getAgent.mockResolvedValue({ id: "a1", runtimeId: "r1" });
- taskQ.createTask.mockResolvedValue({ id: "t2", status: "queued" });
-
- await service.retryTask("t1", "w1");
-
- expect(taskQ.createTask).toHaveBeenCalledWith({}, expect.objectContaining({
- contextKey: null,
- }));
- });
- });
-
- // ── claimTasksForRuntimes with kill_tasks ───────────────────
-
- describe("claimTasksForRuntimes with kill_tasks", () => {
- it("claims kill_tasks before normal tasks", async () => {
- const killTask = { id: "kt1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", type: "kill_task" };
- taskQ.claimKillTasks.mockResolvedValue([killTask]);
- taskQ.listPendingTasksByRuntimes.mockResolvedValue([]);
-
- const result = await service.claimTasksForRuntimes(["r1"], 2, "w1");
-
- expect(result).toEqual([killTask]);
- expect(taskQ.claimKillTasks).toHaveBeenCalledWith({}, ["r1"], "w1", 2);
- });
-
- it("subtracts kill_tasks from remaining capacity", async () => {
- const killTask = { id: "kt1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", type: "kill_task" };
- taskQ.claimKillTasks.mockResolvedValue([killTask]);
- taskQ.listPendingTasksByRuntimes.mockResolvedValue([
- { agentId: "a2", workspaceId: "w1", id: "t2", runtimeId: "r1" },
- ]);
- agentQ.getAgent.mockResolvedValue({ id: "a2", maxConcurrentTasks: 5 });
- taskQ.countRunningTasks.mockResolvedValue(0);
- taskQ.claimTask.mockResolvedValue({ id: "t2", agentId: "a2", runtimeId: "r1" });
-
- const result = await service.claimTasksForRuntimes(["r1"], 1, "w1");
-
- // Only the kill_task — maxTasks=1 is fully consumed
- expect(result).toHaveLength(1);
- expect(result[0].id).toBe("kt1");
- });
- });
-});
diff --git a/src/web/src/lib/services/task.ts b/src/web/src/lib/services/task.ts
deleted file mode 100644
index df108f072..000000000
--- a/src/web/src/lib/services/task.ts
+++ /dev/null
@@ -1,430 +0,0 @@
-import type { Database } from "@alook/shared";
-import { queries, TASK_TYPES, MAX_TASKS_PER_TRACE } from "@alook/shared";
-import { log } from "@/lib/logger";
-import { broadcastToUser, broadcastToDaemon } from "@/lib/broadcast";
-import { messageToResponse } from "@/lib/api/responses";
-import { TaskPayloadBuilder } from "@/lib/services/task-payload-builder";
-
-const taskQueries = queries.task;
-const agentQueries = queries.agent;
-const messageQueries = queries.message;
-const conversationQueries = queries.conversation;
-const issueQueries = queries.issue;
-const inboxQueries = queries.inbox;
-
-export class TaskService {
- constructor(private db: Database) {}
-
- async enqueueTask(
- agentId: string,
- conversationId: string,
- workspaceId: string,
- prompt: string,
- type: string = TASK_TYPES.USER_DM_MESSAGE,
- opts?: { contextKey?: string | null; context?: Record<string, unknown>; traceId?: string | null; parentTaskId?: string | null },
- ) {
- const agent = await agentQueries.getAgent(this.db, agentId, workspaceId);
- if (!agent) {
- throw new Error("agent not found");
- }
- if (!agent.runtimeId) {
- throw new Error("agent has no runtime");
- }
-
- if (opts?.traceId && opts.parentTaskId) {
- const traceCount = await taskQueries.countTasksByTrace(this.db, opts.traceId);
- if (traceCount >= MAX_TASKS_PER_TRACE) {
- throw new Error(`Trace limit reached (${MAX_TASKS_PER_TRACE} tasks). This may indicate an infinite loop between agents.`);
- }
- }
-
- const task = await taskQueries.createTask(this.db, {
- agentId,
- runtimeId: agent.runtimeId,
- workspaceId,
- conversationId,
- prompt,
- type,
- contextKey: opts?.contextKey ?? null,
- priority: 0,
- context: opts?.context,
- traceId: opts?.traceId ?? null,
- parentTaskId: opts?.parentTaskId ?? null,
- });
- // Push task to daemon via WS (best-effort). Awaited to ensure task state
- // settles (dispatched on success, reverted to queued on failure) before
- // the HTTP response returns, preventing races with subsequent poll calls.
- await this.pushTaskToDaemon(task, workspaceId).catch(() => {});
- return task;
- }
-
- async claimTask(agentId: string, workspaceId: string) {
- const agent = await agentQueries.getAgent(this.db, agentId, workspaceId);
- return this.claimTaskWithAgent(agentId, workspaceId, agent);
- }
-
- private async claimTaskWithAgent(agentId: string, workspaceId: string, agent: Awaited<ReturnType<typeof agentQueries.getAgent>>) {
- if (!agent) {
- return null;
- }
-
- const running = await taskQueries.countRunningTasks(this.db, agentId, workspaceId);
- if (running >= agent.maxConcurrentTasks) {
- const steerable = await taskQueries.findSteerableReplacement(this.db, agentId, workspaceId);
- if (!steerable) return null;
- const runningExcluding = await taskQueries.countRunningTasks(this.db, agentId, workspaceId, steerable.predecessorId);
- if (runningExcluding >= agent.maxConcurrentTasks) return null;
- }
-
- const task = await taskQueries.claimTask(this.db, agentId, workspaceId);
- if (!task) {
- return null;
- }
-
- await agentQueries.updateAgentStatus(this.db, agentId, workspaceId, "working");
- return task;
- }
-
- async claimTasksForRuntimes(runtimeIds: string[], maxTasks: number, workspaceId: string) {
- const killTasks = await taskQueries.claimKillTasks(this.db, runtimeIds, workspaceId, maxTasks);
- const remaining = maxTasks - killTasks.length;
-
- const tasks = remaining > 0
- ? await taskQueries.listPendingTasksByRuntimes(this.db, runtimeIds, workspaceId)
- : [];
- const runtimeIdSet = new Set(runtimeIds);
- const triedAgents = new Set<string>();
- const claimed: NonNullable<Awaited<ReturnType<typeof this.claimTask>>>[] = [...killTasks];
-
- const uniqueCandidates: { agentId: string; workspaceId: string }[] = [];
- for (const candidate of tasks) {
- if (uniqueCandidates.length >= remaining) break;
- const key = `${candidate.agentId}:${candidate.workspaceId}`;
- if (triedAgents.has(key)) continue;
- triedAgents.add(key);
- uniqueCandidates.push(candidate);
- }
-
- if (uniqueCandidates.length === 0) return claimed;
-
- const agentIds = [...new Set(uniqueCandidates.map((c) => c.agentId))];
- const agents = await agentQueries.getAgentsByIds(this.db, agentIds, workspaceId);
- const agentMap = new Map(agents.map((a) => [a.id, a]));
-
- const results = await Promise.all(
- uniqueCandidates.map((c) => this.claimTaskWithAgent(c.agentId, c.workspaceId, agentMap.get(c.agentId) ?? null))
- );
-
- for (const task of results) {
- if (task && runtimeIdSet.has(task.runtimeId)) {
- claimed.push(task);
- }
- }
-
- return claimed;
- }
-
- async startTask(taskId: string, workspaceId: string) {
- const task = await taskQueries.startTask(this.db, taskId, workspaceId);
- if (!task) {
- throw new Error("task not in dispatched status");
- }
- return task;
- }
-
- async completeTask(
- taskId: string,
- workspaceId: string,
- result: string,
- sessionId: string
- ) {
- let parsed: unknown;
- try {
- parsed = JSON.parse(result);
- } catch {
- parsed = { raw: result };
- }
-
- const task = await taskQueries.completeTask(this.db, taskId, workspaceId, {
- result: parsed,
- sessionId: sessionId || null,
- });
-
- if (!task) {
- const existing = await taskQueries.getTask(this.db, taskId);
- const status = existing?.status ?? "unknown";
- log.warn(`completeTask failed: task is in '${status}' status`, { taskId });
- throw new Error(`cannot complete task in '${status}' status`);
- }
-
- // The agent owns its voice: the success reply bubble is now authored
- // explicitly via `alook sync send-dm` (the agent-DM endpoint), NOT extracted
- // from the task's final `output`. So completeTask no longer creates a
- // `role:"assistant"` message — it only settles the task lifecycle. `output`
- // is still persisted on the task row (in `result`) for debugging.
- // (failTask still surfaces an error bubble — a failed run must not go silent.)
- await this.reconcileAgentStatus(task.agentId, task.workspaceId);
- this.maybeUpsertUnread(task, workspaceId, null).catch(() => {});
- return task;
- }
-
- async failTask(taskId: string, workspaceId: string, error: string) {
- const task = await taskQueries.failTask(this.db, taskId, workspaceId, error);
-
- if (!task) {
- const existing = await taskQueries.getTask(this.db, taskId);
- const status = existing?.status ?? "unknown";
- log.warn(`failTask failed: task is in '${status}' status`, { taskId });
- throw new Error(`cannot fail task in '${status}' status`);
- }
-
- if (task.type === TASK_TYPES.KILL_TASK) {
- return task;
- }
-
- let errorMessageId: string | null = null;
- if (error) {
- // Attribute the error to the agent runtime (Claude Code / Codex /
- // OpenCode) so the chat UI can make clear it did NOT come from Alook.
- // Resolve the provider from the task's runtime; never let this block the
- // task lifecycle (issue #236).
- let provider: string | null = null;
- try {
- if (task.runtimeId) {
- const rt = await queries.runtime.getAgentRuntime(this.db, task.runtimeId);
- provider = rt?.provider ?? null;
- }
- } catch {
- // non-critical: fall back to a generic runtime label
- }
-
- const msg = await messageQueries.createMessage(this.db, {
- conversationId: task.conversationId,
- role: "assistant",
- content: error,
- taskId,
- metadata: JSON.stringify({ error_source: "runtime", provider }),
- });
- errorMessageId = msg?.id ?? null;
-
- try {
- const conversation = await conversationQueries.getConversation(this.db, task.conversationId, workspaceId);
- if (conversation) {
- broadcastToUser(conversation.userId, {
- type: "conversation.message",
- conversationId: task.conversationId,
- message: messageToResponse(msg),
- }).catch(() => {});
- }
- } catch {
- // non-critical: don't let broadcast failure block task lifecycle
- }
- }
-
- await this.reconcileAgentStatus(task.agentId, task.workspaceId);
- await this.syncIssueStatusFromTask(task, "failed");
- this.maybeUpsertUnread(task, workspaceId, errorMessageId).catch(() => {});
- return task;
- }
-
- private async syncIssueStatusFromTask(
- task: { id: string; type?: string | null; contextKey?: string | null; workspaceId: string; conversationId: string },
- status: "failed",
- ) {
- if (task.type !== TASK_TYPES.ISSUE_EVENT) return;
-
- const issue = await issueQueries.getIssueByConversation(this.db, task.conversationId, task.workspaceId);
- if (!issue || issue.status === status) return;
-
- const updated = await issueQueries.updateIssue(this.db, issue.id, task.workspaceId, { status });
- if (!updated) return;
-
- const eventMsg = await messageQueries.createMessage(this.db, {
- conversationId: task.conversationId,
- role: "event",
- content: `Issue status changed: ${issue.status} -> ${status}`,
- taskId: task.id,
- metadata: JSON.stringify({ issueId: issue.id }),
- });
-
- try {
- const conversation = await conversationQueries.getConversation(this.db, task.conversationId, task.workspaceId);
- if (conversation) {
- broadcastToUser(conversation.userId, {
- type: "conversation.message",
- conversationId: task.conversationId,
- message: messageToResponse(eventMsg),
- }).catch(() => {});
- }
- } catch {
- // non-critical: don't let broadcast failure block task lifecycle
- }
- }
-
- private async maybeUpsertUnread(
- task: { id: string; conversationId: string; type: string; parentTaskId?: string | null; traceId?: string | null; prompt: string; status: string; completedAt?: string | null; context?: unknown; workspaceId: string; agentId: string },
- workspaceId: string,
- knownMessageId: string | null,
- ) {
- if (!inboxQueries.isUnreadEligible(task)) return;
- if (!task.completedAt) return;
-
- const conversation = await conversationQueries.getConversation(this.db, task.conversationId, workspaceId);
- if (!conversation) return;
-
- const latestMessageId = knownMessageId ?? await inboxQueries.findLatestAssistantMessageId(this.db, task.conversationId);
-
- await inboxQueries.upsertUnreadEntry(this.db, {
- conversationId: task.conversationId,
- userId: conversation.userId,
- workspaceId,
- agentId: conversation.agentId,
- taskId: task.id,
- taskType: task.type,
- taskStatus: task.status,
- taskPrompt: task.prompt,
- completedAt: task.completedAt,
- latestMessageId,
- });
- }
-
- async supersedeTask(taskId: string, workspaceId: string) {
- const task = await taskQueries.supersedeTask(this.db, taskId, workspaceId);
-
- if (!task) {
- const existing = await taskQueries.getTask(this.db, taskId);
- const status = existing?.status ?? "unknown";
- log.warn(`supersedeTask failed: task is in '${status}' status`, { taskId });
- throw new Error(`cannot supersede task in '${status}' status`);
- }
-
- await this.reconcileAgentStatus(task.agentId, task.workspaceId);
- return task;
- }
-
- async retryTask(taskId: string, workspaceId: string) {
- const original = await taskQueries.getTask(this.db, taskId);
- if (!original) throw new Error("task not found");
- if (original.workspaceId !== workspaceId) throw new Error("task not found");
- if (original.status !== "failed") throw new Error("only failed tasks can be retried");
-
- const marked = await taskQueries.markFailedAsSuperseded(this.db, taskId, workspaceId);
- if (!marked) throw new Error("failed to mark task as superseded");
-
- const newTask = await this.enqueueTask(
- original.agentId,
- original.conversationId,
- workspaceId,
- original.prompt,
- original.type,
- {
- contextKey: original.contextKey ?? null,
- context: original.context as Record<string, unknown> | undefined,
- traceId: original.traceId ?? null,
- parentTaskId: original.parentTaskId ?? null,
- },
- );
-
- return { oldTask: marked, newTask };
- }
-
- async cancelActiveTask(conversationId: string, workspaceId: string, opts?: { reason?: string }) {
- const activeTask = await taskQueries.getActiveTaskByConversation(this.db, conversationId, workspaceId);
- if (!activeTask) return null;
-
- const cancelled = await taskQueries.cancelTask(this.db, activeTask.id, workspaceId);
- if (!cancelled) return null;
-
- if (activeTask.status === "dispatched" || activeTask.status === "running") {
- const killTask = await taskQueries.createTask(this.db, {
- agentId: activeTask.agentId,
- runtimeId: activeTask.runtimeId,
- workspaceId,
- conversationId,
- prompt: "",
- type: TASK_TYPES.KILL_TASK,
- context: { target_task_id: activeTask.id },
- });
-
- // Dispatch (claim) the kill task so it arrives at the daemon in "dispatched" status,
- // allowing the daemon to call failTask without a status mismatch error.
- await taskQueries.dispatchTaskById(this.db, killTask.id, workspaceId);
-
- const runtime = await queries.runtime.getAgentRuntime(this.db, activeTask.runtimeId);
- if (runtime) {
- broadcastToDaemon(runtime.daemonId, {
- type: "daemon.kill",
- workspaceId,
- agentId: activeTask.agentId,
- taskId: killTask.id,
- targetTaskId: activeTask.id,
- }).catch((e) => log.warn("daemon.kill broadcast failed, relying on poll fallback", e));
- }
- }
-
- // Stamp lifecycle messages (cancelled/superseded) so the chat renders them
- // as quiet centered system notes, not agent speech bubbles.
- await messageQueries.createMessage(this.db, {
- conversationId,
- role: "assistant",
- content: opts?.reason ?? "Task cancelled by you",
- taskId: activeTask.id,
- metadata: JSON.stringify({ kind: "lifecycle" }),
- });
-
- await this.reconcileAgentStatus(activeTask.agentId, workspaceId);
- return cancelled;
- }
-
- async reconcileAgentStatus(agentId: string, workspaceId: string) {
- const running = await taskQueries.countRunningTasks(this.db, agentId, workspaceId);
- const status = running > 0 ? "working" : "idle";
- await agentQueries.updateAgentStatus(this.db, agentId, workspaceId, status);
- }
-
- async cancelTrace(traceId: string, workspaceId: string, opts?: { reason?: string }) {
- const tasks = await taskQueries.getTraceTree(this.db, traceId, workspaceId);
- const activeConvIds = [...new Set(
- tasks
- .filter(t => ["queued", "dispatched", "running"].includes(t.status))
- .map(t => t.conversationId)
- )];
- for (const convId of activeConvIds) {
- try {
- await this.cancelActiveTask(convId, workspaceId, { reason: opts?.reason });
- } catch (err) {
- log.warn("cancelTrace: failed to cancel task", { traceId, convId, err });
- }
- }
- }
-
- private async pushTaskToDaemon(
- task: Awaited<ReturnType<typeof taskQueries.createTask>>,
- workspaceId: string,
- ) {
- const runtime = await queries.runtime.getAgentRuntime(this.db, task.runtimeId);
- if (!runtime) return;
-
- const dispatched = await taskQueries.dispatchTaskById(this.db, task.id, workspaceId);
- if (!dispatched) return;
-
- const builder = new TaskPayloadBuilder(this.db);
- const payloads = await builder.buildFullPayloads([dispatched], workspaceId);
- if (payloads.length === 0) {
- await taskQueries.revertDispatchedToQueued(this.db, task.id, workspaceId);
- return;
- }
-
- try {
- const { sent } = await broadcastToDaemon(runtime.daemonId, {
- type: "daemon.tasks",
- tasks: payloads,
- });
- if (sent === 0) {
- await taskQueries.revertDispatchedToQueued(this.db, task.id, workspaceId);
- }
- } catch {
- await taskQueries.revertDispatchedToQueued(this.db, task.id, workspaceId);
- }
- }
-}
diff --git a/src/web/src/lib/use-user-ws.session.dom.test.tsx b/src/web/src/lib/use-user-ws.session.dom.test.tsx
index eb0452006..de2cf85e3 100644
--- a/src/web/src/lib/use-user-ws.session.dom.test.tsx
+++ b/src/web/src/lib/use-user-ws.session.dom.test.tsx
@@ -97,7 +97,7 @@ beforeEach(async () => {
function mount(onMessage = vi.fn()) {
return renderHook(({ viewerUserId }) => useUserWs(onMessage, {
- viewerUserId, communityContract: BUSINESS_SCHEMA_VERSION, requestDaemonStatusOnAuth: false,
+ viewerUserId, communityContract: BUSINESS_SCHEMA_VERSION,
}), { initialProps: { viewerUserId: "account-a" } })
}
diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.ts
index d9eb40ee2..486714dd7 100644
--- a/src/web/src/lib/use-user-ws.test.ts
+++ b/src/web/src/lib/use-user-ws.test.ts
@@ -316,7 +316,7 @@ describe("useUserWs", () => {
it("keeps bootstrap port discovery and authenticates a current SDK reconnect without another HTTP request", async () => {
mockSdkSession.set(sdkSession())
mockFetch.mockResolvedValue({ ok: true, json: async () => ({ userId: "user-1", token: "bootstrap-token", wsPort: 9123 }) })
- await mountHook(vi.fn(), { viewerUserId: "user-1", communityContract: BUSINESS_SCHEMA_VERSION, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { viewerUserId: "user-1", communityContract: BUSINESS_SCHEMA_VERSION })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -335,7 +335,7 @@ describe("useUserWs", () => {
it.each(["pending", "error", "missing", "missing-session", "empty-id", "session-owner", "expired", "invalid-expiry"])("falls back without admitting %s SDK credentials", async (state) => {
mockSdkSession.set(sdkSession())
setupTokenFetch()
- await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { viewerUserId: "user-1" })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -362,7 +362,7 @@ describe("useUserWs", () => {
mockSdkSession.set(sdkSession())
const response = deferred<Response>()
mockFetch.mockReturnValue(response.promise)
- await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { viewerUserId: "user-1" })
const signal = mockFetch.mock.calls[0]![1].signal as AbortSignal
mockSdkSession.set(sdkSession("user-2", "sdk-session-2", "other-sdk-token"))
expect(signal.aborted).toBe(true)
@@ -378,7 +378,7 @@ describe("useUserWs", () => {
it("rejects a foreign HTTP identity before socket construction", async () => {
mockSdkSession.set(sdkSession())
mockFetch.mockResolvedValue(Response.json({ userId: "user-2", token: "foreign-fixture-token" }))
- await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { viewerUserId: "user-1" })
await vi.advanceTimersByTimeAsync(60_000)
expect(MockWebSocket.instances).toEqual([])
expect(mockFetch).toHaveBeenCalledOnce()
@@ -388,7 +388,7 @@ describe("useUserWs", () => {
it.each([401, 403])("stops an HTTP%s credential sequence and refetches the native SDK at most once", async (status) => {
mockSdkSession.set(sdkSession())
mockFetch.mockResolvedValue({ ok: false, status })
- await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { viewerUserId: "user-1" })
mockDocument.dispatch("resume")
mockWindow.dispatch("focus")
await vi.advanceTimersByTimeAsync(60_000)
@@ -404,7 +404,7 @@ describe("useUserWs", () => {
it("makes one authoritative fallback for a rejected SDK session and stops a fresh rejection until explicit Retry", async () => {
mockSdkSession.set(sdkSession())
setupTokenFetch()
- await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { viewerUserId: "user-1" })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -433,7 +433,7 @@ describe("useUserWs", () => {
mockSdkSession.set(sdkSession())
mockSdkSession.refetch.mockRejectedValueOnce(new Error("fixture SDK refetch exception"))
mockFetch.mockResolvedValue({ ok: false, status: 401 })
- await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { viewerUserId: "user-1" })
mockDocument.dispatch("resume")
mockWindow.dispatch("focus")
await vi.advanceTimersByTimeAsync(60_000)
@@ -445,7 +445,7 @@ describe("useUserWs", () => {
it("does not repeat an authoritative read after a transient fallback failure", async () => {
mockSdkSession.set(sdkSession())
setupTokenFetch()
- await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { viewerUserId: "user-1" })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -462,7 +462,7 @@ describe("useUserWs", () => {
it.each(["Unsupported community contract", "Invalid JSON", "Not authenticated"])("keeps protocol policy close %s out of credential refresh", async (reason) => {
mockSdkSession.set(sdkSession())
setupTokenFetch()
- await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { viewerUserId: "user-1" })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -480,7 +480,7 @@ describe("useUserWs", () => {
it("does not refresh credentials after a server contract frame even with an Unauthorized close", async () => {
mockSdkSession.set(sdkSession())
setupTokenFetch()
- await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { viewerUserId: "user-1" })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -536,7 +536,7 @@ describe("useUserWs", () => {
it.each([undefined, 1, 2, 3, 6, BUSINESS_SCHEMA_VERSION + 1])("retires missing or unsupported business confirmation %s before application admission", async contract => {
setupTokenFetch()
const callback = vi.fn(), authenticated = vi.fn()
- await mountHook(callback, { onAuthenticated: authenticated, requestDaemonStatusOnAuth: false })
+ await mountHook(callback, { onAuthenticated: authenticated })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", ...(contract === undefined ? {} : { communityContract: contract }) })
@@ -598,7 +598,7 @@ describe("useUserWs", () => {
}
})
const onAuthenticated = vi.fn()
- await mountHook(callback, { communityContract: BUSINESS_SCHEMA_VERSION, requestDaemonStatusOnAuth: false, onAuthenticated })
+ await mountHook(callback, { communityContract: BUSINESS_SCHEMA_VERSION, onAuthenticated })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
expect(JSON.parse(ws.sent[0]!)).toEqual({ type: "auth", token: "tok-123", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -723,31 +723,11 @@ describe("useUserWs", () => {
expect(firstConnect).toBe(secondConnect)
})
- it.each<[string, UseUserWsOptions | undefined]>([
- ["the option is omitted", undefined],
- ["the option is explicitly true", { requestDaemonStatusOnAuth: true }],
- ])("auth.ok sends the complete daemon-status frame when %s", async (_label, options) => {
+ it("auth.ok sends no legacy daemon-status request", async () => {
setupTokenFetch()
const onMsg = vi.fn()
- await mountHook(onMsg, options)
-
- const ws = MockWebSocket.instances[0]
- ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
-
- expect(ws.sent).toEqual([
- JSON.stringify({ type: "auth", token: "tok-123", communityContract: BUSINESS_SCHEMA_VERSION }),
- JSON.stringify({ type: "check_daemon_status" }),
- ])
- expect(onMsg).not.toHaveBeenCalled()
- })
-
- it("auth.ok suppresses daemon status and remains consumed when the option is false", async () => {
- setupTokenFetch()
-
- const onMsg = vi.fn()
- await mountHook(onMsg, { requestDaemonStatusOnAuth: false })
+ await mountHook(onMsg)
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
@@ -765,7 +745,7 @@ describe("useUserWs", () => {
json: () => Promise.resolve({ userId: "user-1", token: "tok-123", wsPort: 3000 }),
} as Response)
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
expect(MockWebSocket.instances[0]?.url).toBe("ws://localhost:3000/api/ws/user?userId=user-1")
})
@@ -775,7 +755,7 @@ describe("useUserWs", () => {
const onMessage = vi.fn()
const onAuthenticated = vi.fn()
- await mountHook(onMessage, { onAuthenticated, requestDaemonStatusOnAuth: false })
+ await mountHook(onMessage, { onAuthenticated })
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
@@ -792,7 +772,7 @@ describe("useUserWs", () => {
setupTokenFetch()
const onAuthenticated = vi.fn()
- await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { onAuthenticated })
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
effectCleanup?.()
@@ -802,32 +782,6 @@ describe("useUserWs", () => {
expect(onAuthenticated).not.toHaveBeenCalled()
})
- it("uses the latest option on the original socket without changing connect identity", async () => {
- setupTokenFetch()
-
- const onMsg = vi.fn()
- const mod = await mountHook(onMsg, { requestDaemonStatusOnAuth: false })
- const ws = MockWebSocket.instances[0]
- ws.simulateOpen()
- const firstConnect = callbackMemo.get("cb-1")?.fn
-
- refCounter = 0
- callbackCounter = 0
- effectCounter = 0
- mod.useUserWs(onMsg, { requestDaemonStatusOnAuth: true })
- const secondConnect = callbackMemo.get("cb-1")?.fn
-
- expect(secondConnect).toBe(firstConnect)
- expect(MockWebSocket.instances).toEqual([ws])
-
- ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
- expect(ws.sent).toEqual([
- JSON.stringify({ type: "auth", token: "tok-123", communityContract: BUSINESS_SCHEMA_VERSION }),
- JSON.stringify({ type: "check_daemon_status" }),
- ])
- expect(onMsg).not.toHaveBeenCalled()
- })
-
it("effect cleanup nullifies wsRef.current and calls .close() — subsequent onclose skips reconnect", async () => {
setupTokenFetch()
@@ -908,7 +862,6 @@ describe("useUserWs", () => {
const onConnectionStateChange = vi.fn()
await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
const ws = MockWebSocket.instances[0]!
@@ -927,7 +880,6 @@ describe("useUserWs", () => {
const onConnectionStateChange = vi.fn()
await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
@@ -954,7 +906,6 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
expect(onConnectionStateChange).toHaveBeenLastCalledWith("suspended")
expect(mockFetch).not.toHaveBeenCalled()
@@ -977,7 +928,6 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
mockNavigator.onLine = false
mockWindow.dispatch("offline")
@@ -994,7 +944,6 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
expect(onConnectionStateChange).toHaveBeenLastCalledWith("reconnecting")
@@ -1007,7 +956,6 @@ describe("useUserWs", () => {
const onAuthenticated = vi.fn()
await mountHook(vi.fn(), {
onAuthenticated,
- requestDaemonStatusOnAuth: false,
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
@@ -1033,7 +981,7 @@ describe("useUserWs", () => {
it("manual Retry replaces a connecting online recovery and fences its late authentication", async () => {
setupTokenFetch()
const onAuthenticated = vi.fn()
- await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { onAuthenticated })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -1067,7 +1015,7 @@ describe("useUserWs", () => {
it("reports local retirement and remote close exactly once per socket", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -1099,7 +1047,7 @@ describe("useUserWs", () => {
[4321, "other"],
] as const)("normalizes remote close code %i to %s", async (code, reasonBucket) => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -1129,7 +1077,7 @@ describe("useUserWs", () => {
.mockReturnValueOnce(firstTokenResponse.promise)
.mockReturnValueOnce(secondTokenResponse.promise)
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
latestHookResult!.reconnectNow()
expect(mockFetch).toHaveBeenCalledTimes(2)
@@ -1151,7 +1099,7 @@ describe("useUserWs", () => {
it("manual reconnect clears a scheduled automatic retry before opening one replacement", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateClose()
@@ -1169,7 +1117,6 @@ describe("useUserWs", () => {
const onConnectionStateChange = vi.fn()
await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
@@ -1211,7 +1158,7 @@ describe("useUserWs", () => {
it("classifies HTTP auth failures without recording token or close reason content", async () => {
mockFetch.mockResolvedValueOnce({ ok: false, status: 403 })
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
expect(mockTrackCommunityWsAuthFailure).toHaveBeenCalledWith({
failureClass: "credentials",
@@ -1254,7 +1201,7 @@ describe("useUserWs", () => {
it("rechecks offline state before foreground validation after telemetry", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -1277,7 +1224,6 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
expect(onConnectionStateChange).toHaveBeenCalledWith("reconnecting")
@@ -1291,7 +1237,7 @@ describe("useUserWs", () => {
ok: true,
json: () => body.promise,
} as Response)
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
expect(mockFetch).toHaveBeenCalledOnce()
mockNavigator.onLine = false
@@ -1303,7 +1249,7 @@ describe("useUserWs", () => {
it("does not run a scheduled retry if navigator becomes offline before it fires", async () => {
mockFetch.mockRejectedValueOnce(new Error("network unavailable"))
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
expect(mockTrackCommunityWsRetryScheduled).toHaveBeenCalledOnce()
mockNavigator.onLine = false
@@ -1326,7 +1272,7 @@ describe("useUserWs", () => {
vi.stubGlobal("WebSocket", ThrowingWebSocket)
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
expect(mockTrackCommunityWsLifecycleStage).toHaveBeenCalledWith(expect.objectContaining({
stage: "open",
@@ -1337,7 +1283,7 @@ describe("useUserWs", () => {
it("closes without authenticating if navigator becomes offline before open", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
mockNavigator.onLine = false
@@ -1352,7 +1298,7 @@ describe("useUserWs", () => {
it("reports an auth transport failure when the auth frame send throws", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
ws.send = vi.fn(() => { throw new Error("auth send failed") })
@@ -1371,28 +1317,6 @@ describe("useUserWs", () => {
}))
})
- it("retires and retries when the post-auth status frame send throws", async () => {
- setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: true })
- const ws = MockWebSocket.instances[0]!
- const send = ws.send.bind(ws)
- ws.send = vi.fn((data: string) => {
- if (data === JSON.stringify({ type: "check_daemon_status" })) {
- throw new Error("status send failed")
- }
- send(data)
- })
- ws.simulateOpen()
-
- ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
-
- expect(ws.closed).toBe(true)
- expect(mockTrackCommunityWsLifecycleClose).toHaveBeenCalledWith(expect.objectContaining({
- initiator: "local-retire",
- }))
- expect(mockTrackCommunityWsRetryScheduled).toHaveBeenCalledOnce()
- })
-
it("uses offline as a hard gate for pending tokens, retries, and manual recovery", async () => {
const firstTokenResponse = deferred<Response>()
mockFetch
@@ -1402,7 +1326,7 @@ describe("useUserWs", () => {
json: () => Promise.resolve({ userId: "online-user", token: "online-token" }),
})
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const firstSignal = (mockFetch.mock.calls[0]?.[1] as RequestInit).signal
mockNavigator.onLine = false
@@ -1435,7 +1359,7 @@ describe("useUserWs", () => {
it("keeps an authenticated socket silent offline and validates it once online", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -1469,7 +1393,7 @@ describe("useUserWs", () => {
setupTokenFetch()
const onMessage = vi.fn()
const onReconnect = vi.fn()
- await mountHook(onMessage, { onReconnect, requestDaemonStatusOnAuth: false })
+ await mountHook(onMessage, { onReconnect })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -1501,7 +1425,7 @@ describe("useUserWs", () => {
it("defers offline gap reconciliation to replacement auth after validation failure", async () => {
setupTokenFetch()
const onReconnect = vi.fn()
- const mod = await mountHook(vi.fn(), { onReconnect, requestDaemonStatusOnAuth: false })
+ const mod = await mountHook(vi.fn(), { onReconnect })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -1538,7 +1462,6 @@ describe("useUserWs", () => {
const onConnectionStateChange = vi.fn()
await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
@@ -1566,7 +1489,6 @@ describe("useUserWs", () => {
const onConnectionStateChange = vi.fn()
await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
@@ -1588,7 +1510,7 @@ describe("useUserWs", () => {
it("retires an open pre-auth socket offline and ignores every late frame", async () => {
setupTokenFetch()
const onAuthenticated = vi.fn()
- await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { onAuthenticated })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
expect(first.sent).toContain(JSON.stringify({ type: "auth", token: "tok-123", communityContract: BUSINESS_SCHEMA_VERSION }))
@@ -1613,7 +1535,7 @@ describe("useUserWs", () => {
it("cancels a scheduled retry offline and starts one replacement online", async () => {
mockFetch.mockRejectedValueOnce(new Error("network unavailable"))
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
expect(mockTrackCommunityWsRetryScheduled).toHaveBeenCalledOnce()
mockNavigator.onLine = false
@@ -1635,7 +1557,7 @@ describe("useUserWs", () => {
it("suppresses reconnect while hidden and reconnects immediately when visible", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -1660,7 +1582,6 @@ describe("useUserWs", () => {
const interval = vi.spyOn(globalThis, "setInterval")
try {
await mountHook(vi.fn(), {
- requestDaemonStatusOnAuth: false,
onAuthenticated: () => {
mockDocument.visibilityState = "hidden"
mockDocument.dispatch("visibilitychange")
@@ -1691,7 +1612,6 @@ describe("useUserWs", () => {
const onConnectionStateChange = vi.fn()
await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
@@ -1721,7 +1641,7 @@ describe("useUserWs", () => {
it("does not recover for initial pageshow or element focus", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -1739,7 +1659,7 @@ describe("useUserWs", () => {
it("validates once for page-level focus and coalesces the foreground event storm", async () => {
setupTokenFetch()
- const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const mod = await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -1770,7 +1690,7 @@ describe("useUserWs", () => {
it("replaces expired CONNECTING and CLOSING sockets with bounded ready-state telemetry", async () => {
setupTokenFetch()
- const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const mod = await mountHook(vi.fn())
const connecting = MockWebSocket.instances[0]!
vi.setSystemTime(Date.now() + mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS + 1)
@@ -1803,7 +1723,7 @@ describe("useUserWs", () => {
it("preserves a remote initiator when recovery races a remote closing handshake", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -1829,7 +1749,7 @@ describe("useUserWs", () => {
it("clears a pending reconnect when the page becomes hidden", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -1846,7 +1766,7 @@ describe("useUserWs", () => {
it("clears a pending reconnect before an immediate foreground replacement", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -1869,7 +1789,6 @@ describe("useUserWs", () => {
const mod = await mountHook(vi.fn(), {
onDisconnect,
onReconnect,
- requestDaemonStatusOnAuth: false,
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
@@ -1935,7 +1854,6 @@ describe("useUserWs", () => {
const mod = await mountHook(vi.fn(), {
onDisconnect,
onReconnect,
- requestDaemonStatusOnAuth: false,
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
@@ -1972,7 +1890,7 @@ describe("useUserWs", () => {
it("uses a wall-clock gap as a local visible sentinel without ordinary polling", async () => {
setupTokenFetch()
const intervalSpy = vi.spyOn(globalThis, "setInterval")
- const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const mod = await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -2002,7 +1920,7 @@ describe("useUserWs", () => {
it("keeps sentinel work local while hidden and clears it on cleanup", async () => {
setupTokenFetch()
const intervalSpy = vi.spyOn(globalThis, "setInterval")
- const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const mod = await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -2038,7 +1956,6 @@ describe("useUserWs", () => {
const onConnectionStateChange = vi.fn()
await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
const first = MockWebSocket.instances[0]!
@@ -2065,7 +1982,6 @@ describe("useUserWs", () => {
const onAuthenticated = vi.fn()
await mountHook(vi.fn(), {
onAuthenticated,
- requestDaemonStatusOnAuth: false,
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
@@ -2089,7 +2005,7 @@ describe("useUserWs", () => {
it("keeps an OPEN pre-auth event storm inside the original auth deadline", async () => {
setupTokenFetch()
- const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const mod = await mountHook(vi.fn())
const first = MockWebSocket.instances[0]!
first.simulateOpen()
const fetchCount = mockFetch.mock.calls.length
@@ -2120,7 +2036,6 @@ describe("useUserWs", () => {
const onConnectionStateChange = vi.fn()
const mod = await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
@@ -2154,7 +2069,7 @@ describe("useUserWs", () => {
const dataWork = new Promise<void>((resolve) => { finish = resolve })
const onForeground = vi.fn(() => dataWork)
const onReconnect = vi.fn()
- await mountHook(vi.fn(), { onForeground, onReconnect, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { onForeground, onReconnect })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -2182,7 +2097,7 @@ describe("useUserWs", () => {
const token = deferred<Response>()
mockFetch.mockReturnValueOnce(token.promise)
const onForeground = vi.fn()
- await mountHook(vi.fn(), { onForeground, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { onForeground })
dispatchWindowFocus()
expect(onForeground).not.toHaveBeenCalled()
mockDocument.dispatch("resume")
@@ -2208,7 +2123,7 @@ describe("useUserWs", () => {
setupTokenFetch()
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined)
const onForeground = vi.fn(() => { throw new Error("data unavailable") })
- await mountHook(vi.fn(), { onForeground, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { onForeground })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -2231,7 +2146,7 @@ describe("useUserWs", () => {
it("coalesces an offline-online signal pair while foreground validation is pending", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -2248,7 +2163,7 @@ describe("useUserWs", () => {
it("keeps a cleared foreground validation timer inert", async () => {
setupTokenFetch()
- const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const mod = await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -2278,7 +2193,6 @@ describe("useUserWs", () => {
})
await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
@@ -2301,7 +2215,6 @@ describe("useUserWs", () => {
const onDisconnect = vi.fn()
await mountHook(vi.fn(), {
onDisconnect,
- requestDaemonStatusOnAuth: false,
})
const ws = MockWebSocket.instances[0]!
const send = ws.send.bind(ws)
@@ -2329,7 +2242,6 @@ describe("useUserWs", () => {
const mod = await mountHook(vi.fn(), {
onConnectionStateChange,
onDisconnect,
- requestDaemonStatusOnAuth: false,
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
@@ -2371,7 +2283,6 @@ describe("useUserWs", () => {
const onDisconnect = vi.fn()
const mod = await mountHook(vi.fn(), {
onDisconnect,
- requestDaemonStatusOnAuth: false,
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
@@ -2403,7 +2314,7 @@ describe("useUserWs", () => {
it("coalesces visible, pageshow, and online while one replacement token request is pending", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -2430,7 +2341,7 @@ describe("useUserWs", () => {
it("lets an exact response queued first at the deadline win without a reconnect", async () => {
setupTokenFetch()
- const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const mod = await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -2451,7 +2362,6 @@ describe("useUserWs", () => {
const onDisconnect = vi.fn()
const mod = await mountHook(vi.fn(), {
onDisconnect,
- requestDaemonStatusOnAuth: false,
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
@@ -2480,7 +2390,6 @@ describe("useUserWs", () => {
const onConnectionStateChange = vi.fn()
const mod = await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
@@ -2510,7 +2419,6 @@ describe("useUserWs", () => {
const onConnectionStateChange = vi.fn()
await mountHook(vi.fn(), {
onConnectionStateChange,
- requestDaemonStatusOnAuth: false,
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
@@ -2541,7 +2449,7 @@ describe("useUserWs", () => {
it("uses full jitter, preserves the failure window across manual retries, and resets on auth.ok", async () => {
const random = vi.spyOn(Math, "random").mockReturnValue(0.5)
mockFetch.mockRejectedValue(new Error("network error"))
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
expect(mockTrackCommunityWsAuthFailure).toHaveBeenCalledWith({
failureClass: "network",
@@ -2612,8 +2520,8 @@ describe("useUserWs", () => {
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
- send({ type: "check_daemon_status" })
- expect(ws.sent).toContain(JSON.stringify({ type: "check_daemon_status" }))
+ send({ type: "connection.ping", nonce: "manual-ping" })
+ expect(ws.sent).toContain(JSON.stringify({ type: "connection.ping", nonce: "manual-ping" }))
})
it("send() is a no-op when WS is not connected", async () => {
@@ -2732,7 +2640,7 @@ describe("useUserWs", () => {
it("drops application frames until auth.ok commits the connection generation", async () => {
setupTokenFetch()
const onMessage = vi.fn()
- await mountHook(onMessage, { requestDaemonStatusOnAuth: false })
+ await mountHook(onMessage)
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
@@ -2747,7 +2655,7 @@ describe("useUserWs", () => {
it("does not report an access disconnect for a socket that never authenticated", async () => {
setupTokenFetch()
const onDisconnect = vi.fn()
- await mountHook(vi.fn(), { onDisconnect, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { onDisconnect })
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
@@ -2759,7 +2667,7 @@ describe("useUserWs", () => {
it("does not classify a replacement for an unauthenticated failed generation as reconnect", async () => {
setupTokenFetch()
const onReconnect = vi.fn()
- await mountHook(vi.fn(), { onReconnect, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { onReconnect })
const first = MockWebSocket.instances[0]
first.simulateOpen()
first.simulateClose()
@@ -2776,7 +2684,7 @@ describe("useUserWs", () => {
setupTokenFetch()
const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
const onMessage = vi.fn()
- await mountHook(onMessage, { requestDaemonStatusOnAuth: false })
+ await mountHook(onMessage)
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
@@ -2799,7 +2707,7 @@ describe("useUserWs", () => {
setupTokenFetch()
const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
const onMessage = vi.fn()
- await mountHook(onMessage, { requestDaemonStatusOnAuth: false })
+ await mountHook(onMessage)
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
warn.mockClear()
@@ -2813,7 +2721,7 @@ describe("useUserWs", () => {
it("refreshes the liveness deadline when a raw pong arrives", async () => {
setupTokenFetch()
const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn())
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -2833,7 +2741,7 @@ describe("useUserWs", () => {
it("consumes duplicate auth.ok frames once per generation", async () => {
setupTokenFetch()
const onAuthenticated = vi.fn()
- await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { onAuthenticated })
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
@@ -2846,7 +2754,7 @@ describe("useUserWs", () => {
it("fires reconnect only after replacement authentication and passes gap duration", async () => {
setupTokenFetch()
const onReconnect = vi.fn()
- await mountHook(vi.fn(), { onReconnect, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { onReconnect })
const first = MockWebSocket.instances[0]
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -2865,7 +2773,7 @@ describe("useUserWs", () => {
expect(onReconnect).toHaveBeenCalledWith({ reconnectDurationMs: 2_000 })
})
- it("commits auth before callbacks and preserves authenticated → reconnect → status order", async () => {
+ it("commits auth before callbacks and preserves authenticated → reconnect order", async () => {
setupTokenFetch()
const trace: string[] = []
const onMessage = vi.fn(() => trace.push("message"))
@@ -2889,7 +2797,7 @@ describe("useUserWs", () => {
replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
replacement.simulateMessage({ type: "task.updated", taskId: "after-auth" })
- expect(trace).toEqual(["authenticated", "reconnect", "status", "message"])
+ expect(trace).toEqual(["authenticated", "reconnect", "message"])
})
it("does not send or start heartbeat after onAuthenticated synchronously reconnects", async () => {
@@ -2900,7 +2808,7 @@ describe("useUserWs", () => {
reconnectDuringCallback = false
latestHookResult!.reconnectNow()
})
- await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: true })
+ await mountHook(vi.fn(), { onAuthenticated })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -2916,7 +2824,7 @@ describe("useUserWs", () => {
it("does not continue an old auth.ok after onReconnect synchronously replaces it", async () => {
setupTokenFetch()
const onReconnect = vi.fn(() => latestHookResult!.reconnectNow())
- await mountHook(vi.fn(), { onReconnect, requestDaemonStatusOnAuth: true })
+ await mountHook(vi.fn(), { onReconnect })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -2943,20 +2851,19 @@ describe("useUserWs", () => {
onAuthenticated,
onDisconnect,
onReconnect,
- requestDaemonStatusOnAuth: true,
})
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
expect(() => ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })).not.toThrow()
- expect(ws.sent).toContain(JSON.stringify({ type: "check_daemon_status" }))
+ expect(ws.sent).not.toContain(JSON.stringify({ type: "check_daemon_status" }))
expect(() => ws.simulateClose()).not.toThrow()
setupTokenFetch()
await vi.advanceTimersByTimeAsync(2_000)
const replacement = MockWebSocket.instances.at(-1)!
replacement.simulateOpen()
expect(() => replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })).not.toThrow()
- expect(replacement.sent).toContain(JSON.stringify({ type: "check_daemon_status" }))
+ expect(replacement.sent).not.toContain(JSON.stringify({ type: "check_daemon_status" }))
await flushPromises()
expect(warn.mock.calls.flat()).not.toContain("secret sync error")
expect(warn.mock.calls.flat()).not.toContain("secret async error")
@@ -2966,7 +2873,7 @@ describe("useUserWs", () => {
it("caps community frames without imposing the cap on generic frames", async () => {
setupTokenFetch()
const onMessage = vi.fn()
- await mountHook(onMessage, { requestDaemonStatusOnAuth: false })
+ await mountHook(onMessage)
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -3002,7 +2909,7 @@ describe("useUserWs", () => {
const tokenResponse = deferred<never>()
if (kind === "token") mockFetch.mockReturnValueOnce(tokenResponse.promise)
else setupTokenFetch()
- const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const mod = await mountHook(vi.fn())
const old = MockWebSocket.instances[0]
if (old) {
old.close = vi.fn(() => { old.readyState = MockWebSocket.CLOSING })
@@ -3034,7 +2941,7 @@ describe("useUserWs", () => {
it.each(["authentication", "heartbeat"] as const)("retires %s timeout without waiting for close and ignores every stale callback", async (kind) => {
setupTokenFetch()
const onDisconnect = vi.fn(), onReconnect = vi.fn(), onMessage = vi.fn(), onConnectionStateChange = vi.fn()
- const mod = await mountHook(onMessage, { onDisconnect, onReconnect, onConnectionStateChange, requestDaemonStatusOnAuth: false })
+ const mod = await mountHook(onMessage, { onDisconnect, onReconnect, onConnectionStateChange })
const old = MockWebSocket.instances[0]!
old.close = vi.fn(() => { old.readyState = MockWebSocket.CLOSING })
old.simulateOpen()
@@ -3072,7 +2979,7 @@ describe("useUserWs", () => {
}) } } })
setupTokenFetch()
const onForeground = vi.fn(), onConnectionStateChange = vi.fn()
- await mountHook(vi.fn(), { onForeground, onConnectionStateChange, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { onForeground, onConnectionStateChange })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
@@ -3112,7 +3019,7 @@ describe("useUserWs", () => {
}) } } })
setupTokenFetch()
const onForeground = vi.fn(), onConnectionStateChange = vi.fn()
- await mountHook(vi.fn(), { onForeground, onConnectionStateChange, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { onForeground, onConnectionStateChange })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index 8ed44d072..2f61e42b0 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -172,7 +172,6 @@ export type UseUserWsOptions = {
onAuthenticated?: () => void | Promise<void>
onForeground?: () => void | Promise<void>
onConnectionStateChange?: (phase: UserWsConnectionPhase) => void | Promise<void>
- requestDaemonStatusOnAuth?: boolean
}
function runLifecycleCallback(
@@ -229,7 +228,6 @@ export function useUserWs(
const onForegroundRef = useRef(options?.onForeground)
const onConnectionStateChangeRef = useRef(options?.onConnectionStateChange)
const lastConnectionPhaseRef = useRef<UserWsConnectionPhase | null>(null)
- const requestDaemonStatusOnAuthRef = useRef(options?.requestDaemonStatusOnAuth ?? true)
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const pendingTokenRef = useRef<PendingTokenAttempt | null>(null)
const tokenTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -282,10 +280,6 @@ export function useUserWs(
options?.onDisconnect,
])
- useEffect(() => {
- requestDaemonStatusOnAuthRef.current = options?.requestDaemonStatusOnAuth ?? true
- }, [options?.requestDaemonStatusOnAuth])
-
const observedSockets = useRef(new WeakMap<WebSocket, { generation: number; start: number; operation?: PageOperation }>())
const connectRef = useRef<(() => Promise<void>) | null>(null)
@@ -854,17 +848,6 @@ export function useUserWs(
}
reconnectDelay.current = WS_RECONNECT_INIT
reconnectAttemptRef.current = 0
- if (requestDaemonStatusOnAuthRef.current) {
- try {
- ws.send(JSON.stringify({ type: "check_daemon_status" }))
- } catch {
- retireSocket(true, "local-retire")
- if (generation === connectionGenerationRef.current) {
- scheduleReconnect(generation)
- }
- return
- }
- }
if (!ownsAuthenticatedConnection(ws, generation) || isOffline()) return
startHeartbeat(ws, generation)
return
diff --git a/src/web/src/test/architecture/account-deletion-minimal-contract.test.ts b/src/web/src/test/architecture/account-deletion-minimal-contract.test.ts
index 8f2bf2e85..9126c4dba 100644
--- a/src/web/src/test/architecture/account-deletion-minimal-contract.test.ts
+++ b/src/web/src/test/architecture/account-deletion-minimal-contract.test.ts
@@ -15,7 +15,7 @@ describe("minimal account deletion architecture", () => {
"src/app/api/community/users/me/account-deletion/code/route.ts",
"src/app/api/community/users/me/account-deletion/route.ts",
]) {
- expect(source(route)).toContain("withCookieHumanAuth")
+ expect(source(route)).toContain("withAuth(cookieHumanAuthPolicy,")
}
})
diff --git a/src/web/src/test/e2e/device-code.test.ts b/src/web/src/test/e2e/device-code.test.ts
index 895369ffe..c9eb45cb7 100644
--- a/src/web/src/test/e2e/device-code.test.ts
+++ b/src/web/src/test/e2e/device-code.test.ts
@@ -1,177 +1,60 @@
-import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION } from "@alook/shared"
-import { describe, it, expect, beforeAll, afterAll } from "vitest"
-import { randomUUID } from "crypto"
-import { signUp, signIn, sessionRequest, tokenRequest, sqlRun } from "@alook/test-utils"
-
-const APP_URL = process.env.APP_URL ?? "http://localhost:3000"
-const TEST_CLIENT_ID = "e2e-test-client"
-
-const testEmail = `e2e_device_${randomUUID().slice(0, 8)}@test.local`
-const testPassword = "TestPassword123!"
-const testName = "E2E Device User"
-
-let sessionCookie: string
-
-describe("device-code-flow", () => {
- beforeAll(async () => {
- await signUp(testEmail, testPassword, testName)
- sessionCookie = await signIn(testEmail, testPassword)
- })
-
- let deviceCode: string
- let userCode: string
-
- it("POST /api/auth/device/code returns device_code, user_code, and verification URLs", async () => {
- const res = await fetch(`${APP_URL}/api/auth/device/code`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ client_id: TEST_CLIENT_ID }),
- })
- if (res.status !== 200) {
- const text = await res.text()
- console.error("device/code error response:", res.status, text)
- }
- expect(res.status).toBe(200)
- const data = await res.json() as Record<string, unknown>
- expect(data.device_code).toBeTruthy()
- expect(data.user_code).toBeTruthy()
- expect(data.verification_uri).toBeTruthy()
- expect(data.verification_uri_complete).toBeTruthy()
- expect(data.expires_in).toBeGreaterThan(0)
- expect(data.interval).toBeDefined()
- deviceCode = data.device_code as string
- userCode = data.user_code as string
- })
-
- it("POST /api/auth/device/token returns authorization_pending before approval", async () => {
- const res = await fetch(`${APP_URL}/api/auth/device/token`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
- device_code: deviceCode,
- client_id: TEST_CLIENT_ID,
- }),
- })
- expect(res.status).toBe(400)
- const data = await res.json() as Record<string, unknown>
- expect(data.error).toBe("authorization_pending")
- })
-
- it("GET /api/auth/device claims code to authenticated user session", async () => {
- const res = await sessionRequest(
- `/api/auth/device?user_code=${userCode}`,
- sessionCookie,
- )
- expect(res.status).toBe(200)
- })
-
- it("POST /api/auth/device/approve approves the device and token poll succeeds", async () => {
- const approveRes = await sessionRequest("/api/auth/device/approve", sessionCookie, {
- method: "POST",
- headers: { "Content-Type": "application/json", Origin: APP_URL },
- body: JSON.stringify({ userCode }),
- })
- expect(approveRes.status).toBe(200)
-
- // Wait for polling interval to elapse (plugin enforces 5s minimum between polls)
- await new Promise(r => setTimeout(r, 5100))
-
- const tokenRes = await fetch(`${APP_URL}/api/auth/device/token`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
- device_code: deviceCode,
- client_id: TEST_CLIENT_ID,
- }),
- })
- expect(tokenRes.status).toBe(200)
- const data = await tokenRes.json() as Record<string, unknown>
- expect(data.access_token).toBeTruthy()
- expect(data.token_type).toBe("Bearer")
- })
-
- it("access_token from device flow works as Bearer token for API calls", async () => {
- // Get a fresh token via a new flow
- const codeRes = await fetch(`${APP_URL}/api/auth/device/code`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ client_id: TEST_CLIENT_ID }),
- })
- const codeData = await codeRes.json() as Record<string, unknown>
- const dc = codeData.device_code as string
- const uc = codeData.user_code as string
-
- await sessionRequest(`/api/auth/device?user_code=${uc}`, sessionCookie)
- await sessionRequest("/api/auth/device/approve", sessionCookie, {
- method: "POST",
- headers: { "Content-Type": "application/json", Origin: APP_URL },
- body: JSON.stringify({ userCode: uc }),
- })
-
- const tokenRes = await fetch(`${APP_URL}/api/auth/device/token`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
- device_code: dc,
- client_id: TEST_CLIENT_ID,
- }),
- })
- const tokenData = await tokenRes.json() as Record<string, unknown>
- const accessToken = tokenData.access_token as string
-
- const meRes = await tokenRequest("/api/community/users/me/profile", accessToken, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_CONTRACT_VERSION) } })
- expect(meRes.status).toBe(200)
- const me = await meRes.json() as Record<string, unknown>
- expect(me.name).toBe(testName)
- })
-
- it("POST /api/auth/device/deny denies authorization and token poll returns access_denied", async () => {
- const codeRes = await fetch(`${APP_URL}/api/auth/device/code`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ client_id: TEST_CLIENT_ID }),
- })
- const codeData = await codeRes.json() as Record<string, unknown>
- const dc = codeData.device_code as string
- const uc = codeData.user_code as string
-
- await sessionRequest(`/api/auth/device?user_code=${uc}`, sessionCookie)
- await sessionRequest("/api/auth/device/deny", sessionCookie, {
- method: "POST",
- headers: { "Content-Type": "application/json", Origin: APP_URL },
- body: JSON.stringify({ userCode: uc }),
- })
-
- const tokenRes = await fetch(`${APP_URL}/api/auth/device/token`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
- device_code: dc,
- client_id: TEST_CLIENT_ID,
- }),
- })
- const data = await tokenRes.json() as Record<string, unknown>
- expect(data.error).toBe("access_denied")
- })
-
- afterAll(() => {
- try {
- sqlRun(`DELETE FROM "deviceCode" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, testEmail)
- sqlRun(`DELETE FROM "session" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, testEmail)
- sqlRun(`DELETE FROM "account" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, testEmail)
- sqlRun(`DELETE FROM "user" WHERE email = ?`, testEmail)
- } catch { /* ignore cleanup errors */ }
- })
+import { afterAll, beforeAll, describe, expect, it } from "vitest"
+import { randomUUID } from "node:crypto"
+import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, DEV_WEB_URL } from "@alook/shared"
+import { signUp, signIn, sessionRequest, sqlRun } from "@alook/test-utils"
+
+const appUrl = process.env.APP_URL ?? DEV_WEB_URL
+const email = `retired-cli-${randomUUID()}@test.local`
+let cookie: string
+
+beforeAll(async () => {
+ expect((await signUp(email, "TestPassword123!", "Current login")).status).toBe(200)
+ cookie = await signIn(email, "TestPassword123!")
+})
+afterAll(() => {
+ sqlRun('DELETE FROM "session" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)', email)
+ sqlRun('DELETE FROM "account" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)', email)
+ sqlRun('DELETE FROM "user" WHERE email = ?', email)
})
-describe("onboard.md", () => {
- it("GET /onboard.md returns markdown with correct content-type", async () => {
- const res = await fetch(`${APP_URL}/onboard.md`)
- expect(res.status).toBe(200)
- expect(res.headers.get("content-type")).toContain("text/markdown")
+describe("retired CLI connection", () => {
+ it.each([
+ ["GET", "/api/auth/device?user_code=RETIRED"],
+ ["POST", "/api/auth/device/code"],
+ ["POST", "/api/auth/device/token"],
+ ["POST", "/api/auth/device/approve"],
+ ["POST", "/api/auth/device/deny"],
+ ["GET", "/api/me"],
+ ["GET", "/api/workspaces"],
+ ["POST", "/api/machine-tokens"],
+ ["POST", "/api/machine-tokens/activate"],
+ ["GET", "/api/ws/daemon"],
+ ["POST", "/api/workspaces"],
+ ...["register", "heartbeat", "sweep", "deregister", "tasks/poll",
+ "tasks/retired/start", "tasks/retired/complete", "tasks/retired/fail",
+ "tasks/retired/supersede", "tasks/retired/messages", "workspace/report", "skills/sync",
+ ].map(path => ["POST", `/api/daemon/${path}`]),
+ ])("%s %s is absent even with a valid browser session", async (method, path) => {
+ const response = await fetch(`${appUrl}${path}`, {
+ method,
+ headers: { Cookie: cookie, Origin: appUrl, "Content-Type": "application/json" },
+ ...(method === "POST" ? { body: JSON.stringify({ client_id: "alook-cli", userCode: "RETIRED" }) } : {}),
+ })
+ expect(response.status).toBe(404)
+ })
+
+ it.each(["/device", "/onboard.md"])("%s no longer offers the old CLI connection", async path => {
+ expect((await fetch(`${appUrl}${path}`, { redirect: "manual" })).status).toBe(404)
+ })
+
+ it("keeps current Cookie login while rejecting an old CLI session bearer", async () => {
+ const path = "/api/community/users/me/profile"
+ expect((await sessionRequest(path, cookie)).status).toBe(200)
+ const sessionToken = decodeURIComponent(cookie.slice(cookie.indexOf("=") + 1)).split(".")[0]
+ const response = await fetch(`${appUrl}${path}`, { headers: {
+ Authorization: `Bearer ${sessionToken}`,
+ [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_CONTRACT_VERSION),
+ } })
+ expect(response.status).toBe(401)
})
})
diff --git a/src/web/src/test/e2e/email-inbound-to-reply.test.ts b/src/web/src/test/e2e/email-inbound-to-reply.test.ts
index 0b5c32fa1..8632efec0 100644
--- a/src/web/src/test/e2e/email-inbound-to-reply.test.ts
+++ b/src/web/src/test/e2e/email-inbound-to-reply.test.ts
@@ -1,97 +1,45 @@
-/**
- * Cross-service E2E: Email Worker → App → Task Created
- * Verifies the full inbound email flow across services.
- * Refs: #190
- */
import { describe, it, expect, beforeAll, afterAll } from "vitest"
import { randomUUID } from "crypto"
-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlQuery, postEmail } from "@alook/test-utils"
+import { seedTestData, cleanupTestData, type TestSeed, sqlQuery, postEmail } from "@alook/test-utils"
let seed: TestSeed
-beforeAll(() => {
- seed = seedTestData()
-})
+beforeAll(() => { seed = seedTestData() })
afterAll(() => cleanupTestData(seed))
-async function waitForTask(
- agentId: string,
- workspaceId: string,
- type: string,
- promptContains?: string,
- maxMs = 8000,
-): Promise<Record<string, unknown> | null> {
- const start = Date.now()
- const promptFilter = promptContains
- ? ` AND prompt LIKE '%${promptContains}%'`
- : ""
- while (Date.now() - start < maxMs) {
+async function waitForEmail(subject: string): Promise<Record<string, unknown> | null> {
+ const deadline = Date.now() + 8000
+ while (Date.now() < deadline) {
const rows = sqlQuery<Record<string, unknown>>(
- `SELECT * FROM agent_task_queue WHERE agent_id = '${agentId}' AND workspace_id = '${workspaceId}' AND type = '${type}'${promptFilter} ORDER BY created_at DESC LIMIT 1`,
+ "SELECT * FROM emails WHERE agent_id = ? AND workspace_id = ? AND subject = ?",
+ seed.agentId, seed.workspaceId, subject,
)
if (rows.length > 0) return rows[0]
- await new Promise((r) => setTimeout(r, 300))
+ await new Promise(resolve => setTimeout(resolve, 100))
}
return null
}
-describe("cross-service: email inbound → task creation", () => {
- it("whitelisted email via email-worker → app notify → task created with type=email_notification", async () => {
- const from = `${seed.userId}@test.local`
- const to = `${seed.agentEmailHandle}@alook.ai`
- const subject = `E2E cross-service ${randomUUID().slice(0, 8)}`
-
- const emailRes = await postEmail(from, to, subject, "Cross-service test body")
- expect(emailRes.status).toBe(200)
-
- const task = await waitForTask(seed.agentId, seed.workspaceId, "email_notification", subject)
- expect(task).not.toBeNull()
- expect(task!.type).toBe("email_notification")
- expect(task!.prompt).toContain(from)
- expect(task!.prompt).toContain(subject)
- expect(task!.status).toMatch(/queued|dispatched/)
- })
-
- it("task has correct metadata: conversation_id set, context_key matches conversation", async () => {
- const from = `${seed.userId}@test.local`
- const to = `${seed.agentEmailHandle}@alook.ai`
- const subject = `E2E metadata ${randomUUID().slice(0, 8)}`
-
- await postEmail(from, to, subject, "Metadata test")
-
- const task = await waitForTask(seed.agentId, seed.workspaceId, "email_notification", subject)
- expect(task).not.toBeNull()
- expect(task!.conversation_id).toBeTruthy()
- expect(task!.context_key).toBe(task!.conversation_id)
- })
-
- it("email record exists in DB with correct agent_id and is_whitelisted=1", async () => {
- const from = `${seed.userId}@test.local`
+describe("cross-service: inbound email storage after legacy task retirement", () => {
+ it.each([true, false])("stores email with whitelist=%s without creating a legacy task or conversation", async whitelisted => {
+ const from = whitelisted ? `${seed.userId}@test.local` : "[email protected]"
const to = `${seed.agentEmailHandle}@alook.ai`
- const subject = `E2E email-record ${randomUUID().slice(0, 8)}`
-
- await postEmail(from, to, subject, "Record check")
-
- await new Promise((r) => setTimeout(r, 2000))
- const rows = sqlQuery<Record<string, unknown>>(
- `SELECT * FROM emails WHERE agent_id = '${seed.agentId}' AND subject = '${subject}'`,
- )
- expect(rows.length).toBeGreaterThan(0)
- expect(rows[0].is_whitelisted).toBe(1)
- expect(rows[0].from_email).toBe(from)
- })
-
- it("non-whitelisted email does NOT create a task", async () => {
- const from = "[email protected]"
- const to = `${seed.agentEmailHandle}@alook.ai`
- const subject = `E2E no-task ${randomUUID().slice(0, 8)}`
-
- await postEmail(from, to, subject, "Should not trigger task")
-
- await new Promise((r) => setTimeout(r, 3000))
- const rows = sqlQuery<Record<string, unknown>>(
- `SELECT * FROM agent_task_queue WHERE agent_id = '${seed.agentId}' AND prompt LIKE '%${subject}%'`,
- )
- expect(rows).toHaveLength(0)
+ const subject = `E2E email ${randomUUID()}`
+ const response = await postEmail(from, to, subject, "Cross-service storage test")
+ expect(response.status).toBe(whitelisted ? 200 : 400)
+
+ const email = await waitForEmail(subject)
+ expect(email).toMatchObject({
+ agent_id: seed.agentId,
+ workspace_id: seed.workspaceId,
+ from_email: from,
+ to_email: to,
+ subject,
+ is_whitelisted: whitelisted ? 1 : 0,
+ direction: "inbound",
+ })
+ expect(email?.r2_key).toBeTruthy()
+ expect(sqlQuery("SELECT id FROM agent_task_queue WHERE agent_id = ? AND workspace_id = ?", seed.agentId, seed.workspaceId)).toHaveLength(0)
+ expect(sqlQuery("SELECT id FROM conversation WHERE workspace_id = ?", seed.workspaceId)).toHaveLength(0)
})
})
diff --git a/src/web/src/test/e2e/meeting-flow.test.ts b/src/web/src/test/e2e/meeting-flow.test.ts
deleted file mode 100644
index bd01db949..000000000
--- a/src/web/src/test/e2e/meeting-flow.test.ts
+++ /dev/null
@@ -1,183 +0,0 @@
-import { describe, it, expect, beforeAll, afterAll } from "vitest"
-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun, sqlQuery } from "@alook/test-utils"
-
-let seed: TestSeed
-
-beforeAll(() => {
- seed = seedTestData()
-}, 60_000)
-afterAll(() => {
- sqlRun(`DELETE FROM meeting_session WHERE workspace_id = ?`, seed.workspaceId)
- cleanupTestData(seed)
-}, 60_000)
-
-function req(path: string, opts?: RequestInit) {
- return tokenRequest(path, seed.machineToken, {
- headers: { "Content-Type": "application/json" },
- ...opts,
- })
-}
-
-describe("meeting callback flow", () => {
- let callbackMeetingId: string
-
- beforeAll(() => {
- callbackMeetingId = "ms_callback_test"
- const now = new Date().toISOString()
- sqlRun(`INSERT INTO meeting_session (id, agent_id, workspace_id, title, meeting_url, status, is_whitelisted, participants, started_at, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, callbackMeetingId, seed.agentId, seed.workspaceId, 'Callback Test', 'https://meet.google.com/abc-defg-hij', 'recording', 1, '["[email protected]"]', now, now, now)
- })
-
- it("POST /api/meeting/callback requires auth", async () => {
- const res = await tokenRequest(
- "/api/meeting/callback",
- "bad_token",
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- meetingId: callbackMeetingId,
- workspaceId: seed.workspaceId,
- status: "completed",
- transcript: "test transcript",
- }),
- },
- )
- expect(res.status).toBe(401)
- })
-
- it("rejects mismatched workspace", async () => {
- const res = await req("/api/meeting/callback", {
- method: "POST",
- body: JSON.stringify({
- meetingId: callbackMeetingId,
- workspaceId: "wrong_workspace",
- status: "completed",
- }),
- })
- expect(res.status).toBe(403)
- })
-
- it("completes meeting and stores transcript", async () => {
- const res = await req("/api/meeting/callback", {
- method: "POST",
- body: JSON.stringify({
- meetingId: callbackMeetingId,
- workspaceId: seed.workspaceId,
- status: "completed",
- transcript: "[00:00:05] Alice:\nHello everyone",
- }),
- })
- expect(res.status).toBe(200)
- const data = await res.json() as { ok: boolean; meeting: { status: string; transcriptR2Key: string } }
- expect(data.ok).toBe(true)
- expect(data.meeting.status).toBe("completed")
- expect(data.meeting.transcriptR2Key).toContain(callbackMeetingId)
- })
-
- it("marks failed meetings", async () => {
- const failId = "ms_fail_test"
- const now = new Date().toISOString()
- sqlRun(`INSERT INTO meeting_session (id, agent_id, workspace_id, title, meeting_url, status, is_whitelisted, participants, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, failId, seed.agentId, seed.workspaceId, 'Fail Test', 'https://meet.google.com/abc-defg-hij', 'joining', 1, '[]', now, now)
-
- const res = await req("/api/meeting/callback", {
- method: "POST",
- body: JSON.stringify({
- meetingId: failId,
- workspaceId: seed.workspaceId,
- status: "failed",
- error: "Chrome crashed",
- }),
- })
- expect(res.status).toBe(200)
- const data = await res.json() as { meeting: { status: string; error: string } }
- expect(data.meeting.status).toBe("failed")
- expect(data.meeting.error).toBe("Chrome crashed")
- })
-})
-
-describe("email notify with meetingInfo", () => {
- it("creates scheduled meeting for whitelisted sender with ICS", async () => {
- const res = await req("/api/email/notify", {
- method: "POST",
- body: JSON.stringify({
- agentId: seed.agentId,
- workspaceId: seed.workspaceId,
- r2Key: "emails/test-ics/raw",
- from: `${seed.userId}@test.local`,
- subject: "Meeting Invite",
- isWhitelisted: true,
- meetingInfo: {
- title: "Weekly Standup",
- meetingUrl: "https://meet.google.com/abc-defg-hij",
- startTime: "2026-05-01T10:00:00Z",
- endTime: "2026-05-01T11:00:00Z",
- attendees: [
- { name: "Alice", email: "[email protected]" },
- ],
- },
- }),
- })
- expect(res.status).toBe(200)
-
- const rows = sqlQuery<{ status: string; title: string; meeting_url: string }>(
- `SELECT status, title, meeting_url FROM meeting_session WHERE workspace_id = ? AND title = ?`, seed.workspaceId, 'Weekly Standup'
- )
- expect(rows.length).toBe(1)
- expect(rows[0].status).toBe("scheduled")
- expect(rows[0].meeting_url).toBe("https://meet.google.com/abc-defg-hij")
- })
-
- it("creates pending meeting for non-whitelisted sender", async () => {
- const res = await req("/api/email/notify", {
- method: "POST",
- body: JSON.stringify({
- agentId: seed.agentId,
- workspaceId: seed.workspaceId,
- r2Key: "emails/test-ics-2/raw",
- subject: "Unknown Invite",
- isWhitelisted: false,
- meetingInfo: {
- title: "Stranger Meeting",
- meetingUrl: "https://meet.google.com/xyz-wxyz-abc",
- startTime: "2026-05-02T10:00:00Z",
- endTime: null,
- attendees: [],
- },
- }),
- })
- expect(res.status).toBe(200)
-
- const rows = sqlQuery<{ status: string }>(
- `SELECT status FROM meeting_session WHERE workspace_id = ? AND title = ?`, seed.workspaceId, 'Stranger Meeting'
- )
- expect(rows.length).toBe(1)
- expect(rows[0].status).toBe("pending")
- })
-
- it("skips meeting creation when no meetingInfo", async () => {
- const countBefore = sqlQuery<{ cnt: number }>(
- `SELECT count(*) as cnt FROM meeting_session WHERE workspace_id = ?`, seed.workspaceId
- )
-
- const res = await req("/api/email/notify", {
- method: "POST",
- body: JSON.stringify({
- agentId: seed.agentId,
- workspaceId: seed.workspaceId,
- r2Key: "emails/no-ics/raw",
- from: `${seed.userId}@test.local`,
- subject: "Plain Email",
- isWhitelisted: true,
- }),
- })
- expect(res.status).toBe(200)
-
- const countAfter = sqlQuery<{ cnt: number }>(
- `SELECT count(*) as cnt FROM meeting_session WHERE workspace_id = ?`, seed.workspaceId
- )
- expect(countAfter[0].cnt).toBe(countBefore[0].cnt)
- })
-})
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 eddaee3fe..a513a9747 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
@@ -1,11 +1,3 @@
-/**
- * Regression: WS broadcast HTTP endpoint on task lifecycle events
- * Verifies the broadcast HTTP endpoint responds correctly (server-side only).
- * Refs: #194 (Priority 5)
- *
- * NOTE: Tests are conditional on WS-DO being available at :8789.
- * If WS-DO is not running, tests skip gracefully.
- */
import { describe, it, expect, beforeAll, afterAll } from "vitest"
import { randomUUID } from "crypto"
import { DEV_WS_DO_URL } from "@alook/shared"
@@ -29,14 +21,13 @@ beforeAll(async () => {
})
afterAll(() => cleanupTestData(seed))
-describe("regression: WS broadcast HTTP endpoint on task events", () => {
- it("task completion broadcast returns 200", async () => {
+describe("WS user broadcast and retired daemon endpoint", () => {
+ it("current user email notification broadcast returns 200", async () => {
if (!wsAvailable) return
const eventPayload = {
- type: "task.completed",
- taskId: `task_${randomUUID().slice(0, 8)}`,
- conversationId: `conv_${randomUUID().slice(0, 8)}`,
+ type: "email.received",
+ agentId: seed.agentId,
}
const broadcastRes = await fetch(`${DEV_WS_DO_URL}/broadcast/user/${seed.userId}`, {
method: "POST",
@@ -60,13 +51,13 @@ describe("regression: WS broadcast HTTP endpoint on task events", () => {
expect(data.sent).toBe(0)
})
- it("daemon broadcast endpoint delivers to daemon WS clients", async () => {
+ it("retired daemon broadcast cannot deliver legacy tasks", async () => {
if (!wsAvailable) return
const res = await fetch(`${DEV_WS_DO_URL}/broadcast/daemon/${seed.daemonId}`, {
method: "POST",
body: JSON.stringify({ type: "daemon.tasks", tasks: [] }),
})
- expect(res.status).toBe(200)
+ expect(res.status).toBe(400)
})
})
diff --git a/src/web/src/test/e2e/ws.test.ts b/src/web/src/test/e2e/ws.test.ts
index 7b4d287e8..f7260c866 100644
--- a/src/web/src/test/e2e/ws.test.ts
+++ b/src/web/src/test/e2e/ws.test.ts
@@ -102,8 +102,8 @@ describe("ws (dev direct to ws-do)", () => {
const ack = await waitForMessage<{ type: string }>(ws, (m) => m.type === "auth.ok")
expect(ack.type).toBe("auth.ok")
- const payload = { type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" }
- const recv = waitForMessage<typeof payload>(ws, (m) => m.type === "runtime.status")
+ const payload = { type: "email.received", agentId: "synthetic-agent" }
+ const recv = waitForMessage<typeof payload>(ws, (m) => m.type === "email.received")
const broadcastRes = await fetch(`${DEV_WS_DO_URL}/broadcast/user/${userId}`, {
method: "POST",
diff --git a/src/web/test-runtime/account-deletion-minimal.runtime.test.ts b/src/web/test-runtime/account-deletion-minimal.runtime.test.ts
index bbcd6c8be..5750a1713 100644
--- a/src/web/test-runtime/account-deletion-minimal.runtime.test.ts
+++ b/src/web/test-runtime/account-deletion-minimal.runtime.test.ts
@@ -179,7 +179,6 @@ describe("minimal account deletion real D1 batch", () => {
expect(snapshot?.identities.map((row) => row.id).sort()).toEqual([bot, owner].sort())
expect(snapshot?.ownedWorkspaceIds).toEqual([workspace])
expect(snapshot?.ownedAgentIds.sort()).toEqual([`agent_${stamp}`, ownedSharedAgent].sort())
- expect(snapshot?.machineTokens.sort()).toEqual([ownerMachineToken, workspaceMachineToken].sort())
expect(snapshot?.media.communityExactKeys).not.toContain(threadAttachment)
expect(snapshot?.media.communityExactKeys).not.toContain(pendingServerAttachmentKey)
expect(snapshot?.media.communityExactKeys).not.toContain(pendingThreadAttachmentKey)
diff --git a/src/web/test-runtime/auth-schema-validation.runtime.test.ts b/src/web/test-runtime/auth-schema-validation.runtime.test.ts
index ef435754a..dca9c9474 100644
--- a/src/web/test-runtime/auth-schema-validation.runtime.test.ts
+++ b/src/web/test-runtime/auth-schema-validation.runtime.test.ts
@@ -88,9 +88,15 @@ describe("Auth sessions without runtime schema introspection", () => {
const authEnv = authEnvironment(statements)
const auth = getAuth(authEnv)
expect(getAuth({ ...authEnv })).toBe(auth)
- const results = await Promise.all([first.token, second.token, undefined, "invalid-session-token", expired.token].map((token) =>
- auth.api.getSession({ headers: new Headers(token ? { authorization: `Bearer ${token}` } : {}) }),
- ))
+ const context = await auth.$context
+ const results = await Promise.all([first.token, second.token, undefined, "invalid-session-token", expired.token].map(async (token) => {
+ const headers = new Headers()
+ if (token) {
+ const signed = encodeURIComponent(`${token}.${await makeSignature(token, authEnv.BETTER_AUTH_SECRET)}`)
+ headers.set("cookie", `${context.authCookies.sessionToken.name}=${signed}`)
+ }
+ return auth.api.getSession({ headers })
+ }))
expect(results.map((result) => result?.user.id ?? null)).toEqual([first.id, second.id, null, null, null])
})
})
diff --git a/src/web/test-runtime/worker.runtime.test.ts b/src/web/test-runtime/worker.runtime.test.ts
index c1a846b4b..15a280c97 100644
--- a/src/web/test-runtime/worker.runtime.test.ts
+++ b/src/web/test-runtime/worker.runtime.test.ts
@@ -3,9 +3,7 @@
import { runInDurableObject } from "cloudflare:test"
import { env, exports } from "cloudflare:workers"
import { describe, expect, it } from "vitest"
-import { BUSINESS_SCHEMA_VERSION, CommunityForumSidebarEnvelopeSchema, CommunityForumSidebarChannelSummarySchema, ClaimedTaskRowSchema, createDb, queries, schema } from "@alook/shared"
-import { bindCacheKV, businessCacheKey, cacheKeys } from "@/lib/cache"
-import { TaskPayloadBuilder } from "@/lib/services/task-payload-builder"
+import { BUSINESS_SCHEMA_VERSION, CommunityForumSidebarEnvelopeSchema, CommunityForumSidebarChannelSummarySchema, createDb, queries } from "@alook/shared"
import { hydrateAttentionResources, readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
const runtimeEnv = env as unknown as CloudflareEnv
@@ -86,64 +84,6 @@ describe("Web workerd runtime", () => {
]) expect(CommunityForumSidebarEnvelopeSchema.safeParse(broken).success).toBe(false)
})
- it.each(["hit", "wrong-version", "bad-json", "missing-field", "wrong-scope", "wrong-value-identity", "unversioned"])(
- "uses actual TaskPayloadBuilder D1/KV inputs for a %s cache value",
- async mode => {
- const db = createDb(runtimeEnv.DB)
- bindCacheKV(runtimeEnv.CACHE_KV)
- const owner = await queries.user.createUser(db, { name: "D1 Owner", email: `${crypto.randomUUID()}@runtime.test` })
- const [workspace] = await db.insert(schema.workspace).values({ name: "Runtime workspace", slug: crypto.randomUUID() }).returning()
- const [runtime] = await db.insert(schema.agentRuntime).values({ workspaceId: workspace.id, daemonId: crypto.randomUUID(), provider: "codex" }).returning()
- await queries.member.createMember(db, { workspaceId: workspace.id, userId: owner.id, role: "owner" })
- await queries.member.updateMemberGlobalInstruction(db, owner.id, workspace.id, "D1 instructions")
- const agent = await queries.agent.createAgent(db, { workspaceId: workspace.id, name: "Runtime agent", ownerId: owner.id, runtimeId: runtime.id })
- const conversation = await queries.conversation.createConversation(db, { workspaceId: workspace.id, agentId: agent.id, userId: owner.id, title: "Runtime conversation" })
- const row = await queries.task.createTask(db, { workspaceId: workspace.id, agentId: agent.id, runtimeId: runtime.id, conversationId: conversation.id, prompt: "Runtime cache check" })
- await queries.emailAccount.createEmailAccount(db, {
- workspaceId: workspace.id, agentId: agent.id, emailAddress: "[email protected]",
- imapHost: "imap.runtime.test", imapUsername: "fixture", imapPassword: "fixture-unused",
- smtpHost: "smtp.runtime.test", smtpUsername: "fixture", smtpPassword: "fixture-unused",
- })
- const values = [
- [cacheKeys.allEmailAccounts(workspace.id), [{ workspaceId: workspace.id, agentId: agent.id, emailAddress: "[email protected]" }]],
- [cacheKeys.member(workspace.id, owner.id), { workspaceId: workspace.id, userId: owner.id, globalInstruction: "Cached instructions" }],
- [cacheKeys.user(owner.id), { id: owner.id, name: "Cached Owner", email: owner.email }],
- ] as const
- for (const [key, value] of values) {
- let cacheKey: string = key
- let payload: unknown = value
- if (mode === "missing-field") payload = Array.isArray(value) ? [{}] : {}
- if (mode === "wrong-scope") cacheKey = `other:${key}`
- if (mode === "wrong-value-identity") {
- if (Array.isArray(value)) payload = value.map(row => ({ ...row, workspaceId: "other-workspace" }))
- else if ("userId" in value) payload = { ...value, userId: "other-user", workspaceId: "other-workspace" }
- else payload = { ...value, id: "other-user" }
- }
- const body = mode === "unversioned" ? payload : {
- schemaVersion: mode === "wrong-version" ? BUSINESS_SCHEMA_VERSION - 1 : BUSINESS_SCHEMA_VERSION,
- cacheKey, value: payload,
- }
- await runtimeEnv.CACHE_KV.put(businessCacheKey(key), mode === "bad-json" ? "not-json" : JSON.stringify(body))
- }
- try {
- const [payload] = await new TaskPayloadBuilder(db).buildFullPayloads([ClaimedTaskRowSchema.parse(row)], workspace.id)
- expect(payload.agent?.user_name).toBe(mode === "hit" ? "Cached Owner" : "D1 Owner")
- expect(payload.agent?.instructions).toBe(mode === "hit" ? "Cached instructions" : "D1 instructions")
- expect(payload.agent?.email_addresses).toEqual([mode === "hit" ? "[email protected]" : "[email protected]"])
- expect(payload.sender?.name).toBe(mode === "hit" ? "Cached Owner" : "D1 Owner")
- for (const [key] of values) {
- const saved = JSON.parse((await runtimeEnv.CACHE_KV.get(businessCacheKey(key)))!)
- expect(saved).toMatchObject({ schemaVersion: BUSINESS_SCHEMA_VERSION, cacheKey: key })
- expect(Object.keys(saved).sort()).toEqual(["cacheKey", "schemaVersion", "value"])
- expect(JSON.stringify(saved.value)).not.toContain("fixture-unused")
- }
- } finally {
- await Promise.all(values.map(([key]) => runtimeEnv.CACHE_KV.delete(businessCacheKey(key))))
- bindCacheKV(null)
- }
- },
- )
-
it("loads production migrations and local storage bindings", async () => {
const schema = await runtimeEnv.DB.prepare(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.ts
index 43fe7db5d..f0b4a56ca 100644
--- a/src/ws-do/src/index.test.ts
+++ b/src/ws-do/src/index.test.ts
@@ -69,13 +69,12 @@ describe("ws-do router", () => {
expect(await res.text()).toBe("fallback")
})
- it("keeps every old handler in order and places strict community routes before generic user routes", () => {
+ it("keeps current handlers in order and places strict community routes before generic user routes", () => {
const source = readFileSync(new URL("./index.ts", import.meta.url), "utf8")
const orderedHandlers = [...source.matchAll(/response = await (handle\w+)\(context\)/g)]
.map((match) => match[1])
expect(orderedHandlers).toEqual([
- "handleDaemonBroadcast",
"handleCommunityUserBroadcast",
"handleCommunityUsersBroadcast",
"handleMessageDelivery",
diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.ts
index 0d334762c..ff14403ae 100644
--- a/src/ws-do/src/index.ts
+++ b/src/ws-do/src/index.ts
@@ -4,7 +4,6 @@ import { handleAuditBroadcast } from "./routes/audit-broadcast"
import {
handleCommunityUserBroadcast,
handleCommunityUsersBroadcast,
- handleDaemonBroadcast,
handleUserBroadcast,
handleUsersBroadcast,
} from "./routes/broadcast"
@@ -50,8 +49,6 @@ export default {
log,
}
- response = await handleDaemonBroadcast(context)
- if (response) return response
response = await handleCommunityUserBroadcast(context)
if (response) return response
response = await handleCommunityUsersBroadcast(context)
diff --git a/src/ws-do/src/routes/broadcast.test.ts b/src/ws-do/src/routes/broadcast.test.ts
index 9405fb75e..ea374e134 100644
--- a/src/ws-do/src/routes/broadcast.test.ts
+++ b/src/ws-do/src/routes/broadcast.test.ts
@@ -102,30 +102,10 @@ describe("ws-do router", () => {
})
describe("broadcast route", () => {
- it("preserves daemon routing, trace logging, streamed body, and the internal response", async () => {
- doMock.stubFetch.mockResolvedValue(new Response("daemon-ok", {
- status: 202,
- headers: { "x-broadcast": "accepted" },
- }))
- const req = new Request("http://localhost/broadcast/daemon/daemon-42", {
- method: "POST",
- headers: { "X-Trace-Id": "trace-9" },
- body: "stream-me",
- })
-
- const res = await handler.fetch(req, env as any)
-
- expect(loggerMocks.child).toHaveBeenCalledWith({ traceId: "trace-9", daemonId: "daemon-42" })
- expect(loggerMocks.debug).toHaveBeenCalledWith("broadcasting to daemon")
- expect(doMock.idFromName).toHaveBeenCalledWith("daemon:daemon-42")
- expect(doMock.get).toHaveBeenCalledWith("mock-do-id")
- const internal = doMock.stubFetch.mock.calls[0][0] as Request
- expect(internal.url).toBe("http://internal/broadcast")
- expect(internal.method).toBe("POST")
- expect(await internal.text()).toBe("stream-me")
- expect(res.status).toBe(202)
- expect(res.headers.get("x-broadcast")).toBe("accepted")
- expect(await res.text()).toBe("daemon-ok")
+ it("does not route retired daemon broadcasts", async () => {
+ const res = await handler.fetch(new Request("http://localhost/broadcast/daemon/retired", { method: "POST", body: "{}" }), env as any)
+ expect(res.status).toBe(400)
+ expect(doMock.idFromName).not.toHaveBeenCalled()
})
it("forwards POST /broadcast/user/:userId with a router-owned target marker", async () => {
diff --git a/src/ws-do/src/routes/broadcast.ts b/src/ws-do/src/routes/broadcast.ts
index c9065fd1c..c815b1ffb 100644
--- a/src/ws-do/src/routes/broadcast.ts
+++ b/src/ws-do/src/routes/broadcast.ts
@@ -126,19 +126,6 @@ async function broadcastCommunityToBulkTarget(
return { ok: true, sent: payload.sent }
}
-export async function handleDaemonBroadcast({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
- const daemonBroadcast = url.pathname.match(/^\/broadcast\/daemon\/(.+)$/)
- if (!daemonBroadcast || request.method !== "POST") return null
-
- const daemonId = daemonBroadcast[1]
- const reqLog = log.child({ traceId, daemonId })
- reqLog.debug("broadcasting to daemon")
-
- const doId = env.WS_DO.idFromName("daemon:" + daemonId)
- const stub = env.WS_DO.get(doId)
- return stub.fetch(new Request("http://internal/broadcast", { method: "POST", body: request.body, duplex: "half" } as RequestInit))
-}
-
export async function handleUserBroadcast({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
const userBroadcast = url.pathname.match(/^\/broadcast\/user\/(.+)$/)
if (!userBroadcast || request.method !== "POST") return null
diff --git a/src/ws-do/src/routes/upgrade.test.ts b/src/ws-do/src/routes/upgrade.test.ts
index 9dd4c0691..0fe0a8166 100644
--- a/src/ws-do/src/routes/upgrade.test.ts
+++ b/src/ws-do/src/routes/upgrade.test.ts
@@ -61,7 +61,7 @@ describe("ws-do router", () => {
expect(res.status).toBe(200)
})
- it("prioritizes daemonId over userId when no community-machine bearer is present", async () => {
+ it("ignores the retired daemon target and routes only the supplied user", async () => {
doMock.stubFetch.mockResolvedValue(new Response(null, { status: 200 }))
const req = new Request("http://localhost/?daemonId=daemon-1&userId=user-1", {
headers: { Upgrade: "websocket" },
@@ -71,7 +71,7 @@ describe("ws-do router", () => {
expect(mockHashCredential).not.toHaveBeenCalled()
expect(doMock.idFromName).toHaveBeenCalledTimes(1)
- expect(doMock.idFromName).toHaveBeenCalledWith("daemon:daemon-1")
+ expect(doMock.idFromName).toHaveBeenCalledWith("user:user-1")
expect(doMock.stubFetch).toHaveBeenCalledWith(req)
expect(res.status).toBe(200)
})
diff --git a/src/ws-do/src/routes/upgrade.ts b/src/ws-do/src/routes/upgrade.ts
index f16539cff..39df00158 100644
--- a/src/ws-do/src/routes/upgrade.ts
+++ b/src/ws-do/src/routes/upgrade.ts
@@ -17,16 +17,6 @@ export async function handleUpgrade({ request, env, url, traceId, log }: RouterC
return stub.fetch(request)
}
- const daemonId = url.searchParams.get("daemonId")
- if (daemonId) {
- const reqLog = log.child({ traceId, daemonId })
- reqLog.info("daemon websocket upgrade")
-
- const doId = env.WS_DO.idFromName("daemon:" + daemonId)
- const stub = env.WS_DO.get(doId)
- return stub.fetch(request)
- }
-
const userId = url.searchParams.get("userId")
if (!userId) return new Response("userId required", { status: 400 })
diff --git a/src/ws-do/src/ws-durable/internal.ts b/src/ws-do/src/ws-durable/internal.ts
index 7adba1b08..aa2a1a05d 100644
--- a/src/ws-do/src/ws-durable/internal.ts
+++ b/src/ws-do/src/ws-durable/internal.ts
@@ -23,7 +23,6 @@ export type ConnectionState =
communityContract?: CommunityContract
communityDeliveryProgress?: CompactCommunityDeliveryProgress[]
}
- | { type: "daemon"; daemonId: string; userId: string; authenticated: boolean }
| {
type: "community-machine"
machineId: string
diff --git a/src/ws-do/src/ws-durable/machine-control.test.ts b/src/ws-do/src/ws-durable/machine-control.test.ts
index 735e5b808..70d8dd9eb 100644
--- a/src/ws-do/src/ws-durable/machine-control.test.ts
+++ b/src/ws-do/src/ws-durable/machine-control.test.ts
@@ -16,10 +16,7 @@ import {
mockGetCoMemberUserIds,
mockGetDM,
mockGetFriendUserIds,
- mockGetLatestTokenForUser,
- mockGetMachineByDaemon,
mockGetMachineByIdForUser,
- mockGetMachineTokenByToken,
mockGetPrivateChannelAudienceUserIds,
mockGetProfile,
mockGetRuntimeIdsByDaemon,
diff --git a/src/ws-do/src/ws-durable/machine-frames.test.ts b/src/ws-do/src/ws-durable/machine-frames.test.ts
index e2b872220..27fc91a3a 100644
--- a/src/ws-do/src/ws-durable/machine-frames.test.ts
+++ b/src/ws-do/src/ws-durable/machine-frames.test.ts
@@ -17,10 +17,7 @@ import {
mockGetCoMemberUserIds,
mockGetDM,
mockGetFriendUserIds,
- mockGetLatestTokenForUser,
- mockGetMachineByDaemon,
mockGetMachineByIdForUser,
- mockGetMachineTokenByToken,
mockGetPrivateChannelAudienceUserIds,
mockGetProfile,
mockGetRuntimeIdsByDaemon,
diff --git a/src/ws-do/src/ws-durable/machine-lifecycle.test.ts b/src/ws-do/src/ws-durable/machine-lifecycle.test.ts
index 4ca35050b..11c9389d0 100644
--- a/src/ws-do/src/ws-durable/machine-lifecycle.test.ts
+++ b/src/ws-do/src/ws-durable/machine-lifecycle.test.ts
@@ -15,10 +15,7 @@ import {
mockGetCoMemberUserIds,
mockGetDM,
mockGetFriendUserIds,
- mockGetLatestTokenForUser,
- mockGetMachineByDaemon,
mockGetMachineByIdForUser,
- mockGetMachineTokenByToken,
mockGetPrivateChannelAudienceUserIds,
mockGetProfile,
mockGetRuntimeIdsByDaemon,
diff --git a/src/ws-do/src/ws-durable/machine-restart.test.ts b/src/ws-do/src/ws-durable/machine-restart.test.ts
index 1cd4c75c5..61ff82fab 100644
--- a/src/ws-do/src/ws-durable/machine-restart.test.ts
+++ b/src/ws-do/src/ws-durable/machine-restart.test.ts
@@ -16,10 +16,7 @@ import {
mockGetCoMemberUserIds,
mockGetDM,
mockGetFriendUserIds,
- mockGetLatestTokenForUser,
- mockGetMachineByDaemon,
mockGetMachineByIdForUser,
- mockGetMachineTokenByToken,
mockGetPrivateChannelAudienceUserIds,
mockGetProfile,
mockGetRuntimeIdsByDaemon,
diff --git a/src/ws-do/src/ws-durable/machine-telemetry.test.ts b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
index 9020702ac..8d82a6748 100644
--- a/src/ws-do/src/ws-durable/machine-telemetry.test.ts
+++ b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
@@ -21,10 +21,7 @@ import {
mockIsBlocked,
mockAreFriends,
mockGetFriendUserIds,
- mockGetLatestTokenForUser,
- mockGetMachineByDaemon,
mockGetMachineByIdForUser,
- mockGetMachineTokenByToken,
mockGetPrivateChannelAudienceUserIds,
mockGetProfile,
mockGetRuntimeIdsByDaemon,
diff --git a/src/ws-do/src/ws-durable/presence-typing.test.ts b/src/ws-do/src/ws-durable/presence-typing.test.ts
index 39d81c92b..87763fd4a 100644
--- a/src/ws-do/src/ws-durable/presence-typing.test.ts
+++ b/src/ws-do/src/ws-durable/presence-typing.test.ts
@@ -23,10 +23,7 @@ import {
mockIsThreadParticipant,
mockAreFriends,
mockGetFriendUserIds,
- mockGetLatestTokenForUser,
- mockGetMachineByDaemon,
mockGetMachineByIdForUser,
- mockGetMachineTokenByToken,
mockGetPrivateChannelAudienceUserIds,
mockGetProfile,
mockGetRuntimeIdsByDaemon,
@@ -209,34 +206,6 @@ describe("WebSocketDurableObject", () => {
})
- describe("fetch — /check-alive characterization", () => {
- it("reports alive only when an authenticated daemon socket is attached", async () => {
- const { durable, ctx } = createDO()
- const daemon = createMockWebSocket()
- daemon.serializeAttachment({ type: "daemon", daemonId: "daemon-1", userId: "user-1", authenticated: true })
- const user = createMockWebSocket()
- user.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
- ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([user, daemon])
-
- const response = await durable.fetch(new Request("http://internal/check-alive"))
-
- expect(await response.json()).toEqual({ alive: true })
- })
-
- it("reports not alive for unauthenticated daemon and authenticated non-daemon attachments", async () => {
- const { durable, ctx } = createDO()
- const daemon = createMockWebSocket()
- daemon.serializeAttachment({ type: "daemon", daemonId: "daemon-1", userId: "user-1", authenticated: false })
- const machine = createMockWebSocket()
- machine.serializeAttachment({ type: "community-machine", machineId: "machine-1", userId: "user-1", authenticated: true })
- ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([daemon, machine])
-
- const response = await durable.fetch(new Request("http://internal/check-alive"))
-
- expect(await response.json()).toEqual({ alive: false })
- })
- })
-
describe("fetch — /check-user-online (bot-aware, keyed by ?userId=)", () => {
// This DO instance is keyed by `user:<id>` (idFromName) but can't read
diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.ts
index daa2abbc5..04c53db5e 100644
--- a/src/ws-do/src/ws-durable/test-harness.ts
+++ b/src/ws-do/src/ws-durable/test-harness.ts
@@ -87,10 +87,7 @@ vi.mock("cloudflare:workers", () => ({
export const mockGetValidSession = vi.fn<(db: unknown, token: string) => Promise<string | null>>()
export const mockGetValidSessionByIdForUser = vi.fn().mockResolvedValue({ expiresAt: "2099-01-01T00:00:00.000Z" })
export const mockGetValidSessionWithIdentity = vi.fn<(db: unknown, token: string) => Promise<{ userId: string; name: string; discriminator: string } | null>>()
-export const mockGetMachineTokenByToken = vi.fn()
-export const mockGetLatestTokenForUser = vi.fn()
export const mockGetRuntimeIdsByDaemon = vi.fn()
-export const mockGetMachineByDaemon = vi.fn().mockResolvedValue({ daemonId: "my-daemon", workspaceId: "sp_ws1" })
export const mockCreateDb = vi.fn().mockReturnValue({})
export const mockHashCredential = vi.fn(async (bearer: string) => `hash:${bearer}`)
export const mockFindCredentialByHash = vi.fn()
@@ -396,12 +393,7 @@ vi.mock("@alook/shared", async () => {
},
getValidSessionByIdForUser: (...args: unknown[]) => mockGetValidSessionByIdForUser(...args),
},
- machineToken: {
- getMachineTokenByToken: (...a: any[]) => mockGetMachineTokenByToken(...a),
- getLatestTokenForUser: (...a: any[]) => mockGetLatestTokenForUser(...a),
- },
runtime: { getRuntimeIdsByDaemon: (...a: any[]) => mockGetRuntimeIdsByDaemon(...a) },
- machine: { getMachineByDaemon: (...a: any[]) => mockGetMachineByDaemon(...a) },
communityMachine: {
hashCredential: (bearer: string) => mockHashCredential(bearer),
findCredentialByHash: (...a: any[]) => mockFindCredentialByHash(...a),
@@ -592,7 +584,6 @@ export function resetHarness() {
// Daemon-auth binds the token to a machine row for daemonId+workspace;
// default to a present row so auth-flow success tests pass. Tests that
// exercise a missing machine override this.
- mockGetMachineByDaemon.mockResolvedValue({ daemonId: "my-daemon", workspaceId: "sp_ws1" })
}
diff --git a/src/ws-do/src/ws-durable/user-auth.test.ts b/src/ws-do/src/ws-durable/user-auth.test.ts
index 441e84b9d..f94d40ee2 100644
--- a/src/ws-do/src/ws-durable/user-auth.test.ts
+++ b/src/ws-do/src/ws-durable/user-auth.test.ts
@@ -1,4 +1,5 @@
import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { makeD1Error } from "@alook/shared/db/resilience-testing"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import {
deriveCommunityDeliveryOperationId,
@@ -28,10 +29,7 @@ import {
mockGetCoMemberUserIds,
mockGetDM,
mockGetFriendUserIds,
- mockGetLatestTokenForUser,
- mockGetMachineByDaemon,
mockGetMachineByIdForUser,
- mockGetMachineTokenByToken,
mockGetPrivateChannelAudienceUserIds,
mockGetProfile,
mockGetRuntimeIdsByDaemon,
@@ -153,8 +151,13 @@ describe("WebSocketDurableObject", () => {
mockListReadableChannelsForUser.mockResolvedValueOnce([])
await expect((await send(typing)).json()).resolves.toEqual({ sent: 0 })
expect(socket.send).not.toHaveBeenCalled()
- mockListReadableChannelsForUser.mockRejectedValueOnce(new Error("D1 temporary"))
+ const cause = new Error("D1_ERROR: Failed to get session commit token")
+ const error = new Error("Failed query", { cause })
+ mockListReadableChannelsForUser.mockRejectedValueOnce(error)
expect((await send(typing)).status).toBe(503)
+ expect(mockLogWarn).toHaveBeenCalledWith("community_content_access_failed", {
+ targetUserId: "user-42", error: String(error), cause: cause.message,
+ })
expect(socket.send).not.toHaveBeenCalled()
const control = { type: "community:channel.membership.change", channelId: "private", serverId: "server", userId: "user-42", relation: "access", present: false }
expect((await send(control)).status).toBe(200)
@@ -229,6 +232,47 @@ describe("WebSocketDurableObject", () => {
})
}
+ it.each([
+ ["recover", 2, 200, 1],
+ ["revoked", 2, 200, 0],
+ ["exhausted", 4, 503, 0],
+ ["permanent", 1, 503, 0],
+ ["healthy", 1, 200, 1],
+ ] as const)("uses real D1 retries for %s access checks on both routes", async (mode, calls, status, sent) => {
+ const { withD1Retry } = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ mockWithD1Retry.mockImplementation(async <T>(fn: () => Promise<T>): Promise<T> =>
+ withD1Retry(fn, { baseDelayMs: 0 }))
+ for (const bundle of [false, true]) {
+ const { durable, ctx } = createDO()
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])
+ mockListReadableChannelsForUser.mockReset()
+ const failure = makeD1Error(mode === "permanent" ? "sqlite_constraint" : "internal_error")
+ if (mode !== "permanent" && failure.cause instanceof Error) {
+ failure.cause.message = "D1_ERROR: Failed to get session commit token: internal error; reference = fixture"
+ }
+ if (mode === "exhausted" || mode === "permanent") {
+ mockListReadableChannelsForUser.mockRejectedValue(failure)
+ } else {
+ mockListReadableChannelsForUser.mockResolvedValue(mode === "revoked" ? [] : [{ id: "ch-1" }])
+ if (mode !== "healthy") mockListReadableChannelsForUser.mockRejectedValueOnce(failure)
+ }
+ const request = bundle ? await requestFor([events[0]]) : new Request("http://internal/community-broadcast", {
+ method: "POST",
+ headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), [INTERNAL_USER_TARGET_HEADER]: "user-42" },
+ body: JSON.stringify({ ...events[0], schemaVersion: BUSINESS_SCHEMA_VERSION }),
+ })
+ const response = await durable.fetch(request)
+ expect(response.status).toBe(status)
+ expect(mockListReadableChannelsForUser).toHaveBeenCalledTimes(calls)
+ expect(ws.send).toHaveBeenCalledTimes(sent)
+ if (mode === "revoked") {
+ expect(await response.json()).toMatchObject(bundle ? { status: "cancelled", reason: "access-revoked" } : { sent: 0 })
+ }
+ }
+ })
+
it("cancels revoked content without changing progress, and retries transient failures", async () => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
@@ -242,8 +286,13 @@ describe("WebSocketDurableObject", () => {
expect(await denied.json()).toEqual({ status: "cancelled", reason: "access-revoked", targetUserId: "user-42", operationId: body.operationId, operationDigest: body.operationDigest, eventCount: body.events.length })
expect(ws.send).not.toHaveBeenCalled()
expect(ws.deserializeAttachment()).toEqual(original)
- mockListReadableChannelsForUser.mockRejectedValueOnce(new Error("temporary"))
+ const cause = new Error("D1_ERROR: Failed to get session commit token")
+ const error = new Error("Failed query", { cause })
+ mockListReadableChannelsForUser.mockRejectedValueOnce(error)
expect((await durable.fetch(request.clone())).status).toBe(503)
+ expect(mockLogWarn).toHaveBeenCalledWith("community_delivery_access_failed", {
+ targetUserId: "user-42", error: String(error), cause: cause.message,
+ })
expect(ws.send).not.toHaveBeenCalled()
expect((await durable.fetch(request.clone())).status).toBe(200)
expect(ws.send).toHaveBeenCalledTimes(1)
@@ -1272,191 +1321,15 @@ describe("WebSocketDurableObject", () => {
})
- describe("webSocketMessage — daemon auth flow", () => {
- it("rejects daemon with pending token (not yet activated)", async () => {
- const { durable } = createDO()
- mockGetMachineTokenByToken.mockResolvedValue({
- id: "mt_1", userId: "u1", status: "pending", workspaceId: null,
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", userId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "al_pending123", daemonId: "my-daemon" }),
- )
-
- expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
- expect(mockGetRuntimeIdsByDaemon).not.toHaveBeenCalled()
- })
-
- it("authenticates daemon with active token (no runtime check in auth)", async () => {
- const { durable } = createDO()
- mockGetMachineTokenByToken.mockResolvedValue({
- id: "mt_1", userId: "u1", status: "active", workspaceId: "sp_ws1",
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "al_active123", daemonId: "my-daemon" }),
- )
-
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))
- // Runtime presence is no longer part of auth — it must not gate the WS
- // connection (tasks route by workspaceId; runtimes may be mid-register).
- expect(mockGetRuntimeIdsByDaemon).not.toHaveBeenCalled()
- })
-
- it("authenticates daemon with active token even when it has no runtimes yet", async () => {
- const { durable } = createDO()
- mockGetMachineTokenByToken.mockResolvedValue({
- id: "mt_1", userId: "u1", status: "active", workspaceId: "sp_ws1",
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "al_noruntimes", daemonId: "my-daemon" }),
- )
-
- // No-runtime is a valid state (not an auth failure) — auth.ok, no reject.
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))
- expect(ws.send).not.toHaveBeenCalledWith(JSON.stringify({ type: "error", code: "AUTH_REJECTED" }))
- })
-
- it("sends AUTH_REJECTED then closes on definitely-invalid token", async () => {
- const { durable } = createDO()
- mockGetMachineTokenByToken.mockResolvedValue(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "al_dead", daemonId: "my-daemon" }),
- )
-
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "error", code: "AUTH_REJECTED" }))
- expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
- })
-
- it("closes WITHOUT AUTH_REJECTED on transient D1 failure (daemon must retry)", async () => {
- const { durable } = createDO()
- mockGetMachineTokenByToken.mockRejectedValue(new Error("D1 unavailable"))
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "al_blip", daemonId: "my-daemon" }),
- )
-
- expect(ws.send).not.toHaveBeenCalledWith(JSON.stringify({ type: "error", code: "AUTH_REJECTED" }))
- expect(ws.close).toHaveBeenCalledWith(1011, "Auth temporarily unavailable")
- })
-
- it("rejects daemon with unknown token", async () => {
- const { durable } = createDO()
- mockGetMachineTokenByToken.mockResolvedValue(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "al_unknown", daemonId: "my-daemon" }),
- )
-
- expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
- })
-
- it("rejects daemon with non-al_ prefixed token", async () => {
- const { durable } = createDO()
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "bad_prefix", daemonId: "my-daemon" }),
- )
-
- expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
- expect(mockGetMachineTokenByToken).not.toHaveBeenCalled()
- })
- })
-
-
- describe("webSocketMessage — check_daemon_status (cross-DO)", () => {
- it("returns runtime.status online when daemon DO reports alive", async () => {
- const { durable, env } = createDO()
- mockGetLatestTokenForUser.mockResolvedValue({ hostname: "MyMachine.local" })
-
- const aliveStub = { fetch: vi.fn().mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ alive: true }))) }
- ; (env.WS_DO as any).get = vi.fn().mockReturnValue(aliveStub)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
-
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
-
- expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("daemon:MyMachine.local")
- expect(ws.send).toHaveBeenCalledWith(
- JSON.stringify({ type: "runtime.status", status: "online", daemonId: "MyMachine.local" }),
- )
- })
-
- it("does not respond when daemon DO reports not alive", async () => {
- const { durable, env } = createDO()
- mockGetLatestTokenForUser.mockResolvedValue({ hostname: "MyMachine.local" })
-
- const deadStub = { fetch: vi.fn().mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ alive: false }))) }
- ; (env.WS_DO as any).get = vi.fn().mockReturnValue(deadStub)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
-
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
-
- expect(ws.send).not.toHaveBeenCalled()
- })
-
- it("does not respond when no token/hostname found", async () => {
- const { durable } = createDO()
- mockGetLatestTokenForUser.mockResolvedValue(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
-
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
-
- expect(ws.send).not.toHaveBeenCalled()
- })
-
- it("does not respond when the daemon durable object fetch rejects", async () => {
- const { durable, env } = createDO()
- mockGetLatestTokenForUser.mockResolvedValue({ hostname: "MyMachine.local" })
- ;(env.WS_DO as any).get = vi.fn().mockReturnValue({
- fetch: vi.fn().mockRejectedValue(new Error("daemon DO unavailable")),
- })
- const ws = createMockWebSocket()
- ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
-
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
-
- expect(ws.send).not.toHaveBeenCalled()
- expect(ws.close).not.toHaveBeenCalled()
- })
+ it("refuses the retired machine-token handshake without querying credentials", async () => {
+ const { durable } = createDO()
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", targetUserId: "user-1", authenticated: false })
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", machineToken: "al_retired", daemonId: "old-daemon" }))
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
+ expect(mockGetValidSessionWithIdentity).not.toHaveBeenCalled()
})
-
describe("webSocketError", () => {
it("closes with 1011", async () => {
const { durable } = createDO()
@@ -1470,7 +1343,7 @@ describe("WebSocketDurableObject", () => {
})
- describe("webSocketClose — user and daemon characterization", () => {
+ describe("webSocketClose — user characterization", () => {
it("keeps user presence online while another authenticated tab remains", async () => {
const { durable, ctx } = createDO()
const closing = createMockWebSocket()
@@ -1520,26 +1393,7 @@ describe("WebSocketDurableObject", () => {
})
})
- it("reports daemon offline and swallows a rejected owner notification", async () => {
- const { durable } = createDO()
- mockStubFetch.mockRejectedValue(new Error("owner DO unavailable"))
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "daemon-1", userId: "user-1", authenticated: true })
-
- await expect(
- durable.webSocketClose(ws as any, 1001, "daemon going away", true),
- ).resolves.toBeUndefined()
- await flushAsyncWork()
- expect(ws.close).toHaveBeenCalledWith(1001, "daemon going away")
- expect(mockStubFetch).toHaveBeenCalledTimes(1)
- const [request] = mockStubFetch.mock.calls[0] as [Request]
- expect(await request.clone().json()).toEqual({
- type: "runtime.status",
- status: "offline",
- daemonId: "daemon-1",
- })
- })
})
})
diff --git a/src/ws-do/src/ws-durable/user-auth.ts b/src/ws-do/src/ws-durable/user-auth.ts
index 33818c9a5..1d2409278 100644
--- a/src/ws-do/src/ws-durable/user-auth.ts
+++ b/src/ws-do/src/ws-durable/user-auth.ts
@@ -24,7 +24,6 @@ import {
broadcastPresence,
handleClientTypingStart,
handleClientTypingStop,
- notifyUserDO,
sendPresenceSnapshot,
} from "./presence-typing"
import {
@@ -77,7 +76,7 @@ export async function handleUserFetch(
request: Request,
url: URL,
): Promise<Response | null> {
- if (["/community-broadcast-bundle", "/community-broadcast", "/broadcast", "/check-alive", "/check-user-online"].includes(url.pathname)) {
+ if (["/community-broadcast-bundle", "/community-broadcast", "/broadcast", "/check-user-online"].includes(url.pathname)) {
for (const ws of context.ctx.getWebSockets()) await refreshUserSession(context, ws)
}
if (url.pathname === "/community-broadcast-bundle" && request.method === "POST") {
@@ -96,7 +95,10 @@ export async function handleUserFetch(
return deliverCommunityBundle(context, bundle, targetUserId)
}
try {
- if (!await canDeliverCommunityContent(createDb(context.env.DB), targetUserId, bundle.prepared.events)) {
+ if (!await withD1Retry(
+ () => canDeliverCommunityContent(createDb(context.env.DB), targetUserId, bundle.prepared.events),
+ { route: "ws-do:community-delivery-access" },
+ )) {
return jsonResponse({
status: "cancelled",
reason: "access-revoked",
@@ -107,7 +109,11 @@ export async function handleUserFetch(
} satisfies CommunityDeliveryCancellation, 200)
}
} catch (error) {
- context.log.warn("community_delivery_access_failed", { targetUserId, error: String(error) })
+ context.log.warn("community_delivery_access_failed", {
+ targetUserId,
+ error: String(error),
+ cause: error instanceof Error && error.cause instanceof Error ? error.cause.message : undefined,
+ })
return jsonResponse({ operationId: bundle.operationId, error: "access_check_failed" }, 503)
}
return deliverCommunityBundle(context, bundle, targetUserId)
@@ -129,12 +135,19 @@ export async function handleUserFetch(
return jsonResponse({ sent: broadcastCommunity(context, event.event, targetUserId, event.contract) })
}
try {
- if (!await canDeliverCommunityContent(createDb(context.env.DB), targetUserId, [event.event])) {
+ if (!await withD1Retry(
+ () => canDeliverCommunityContent(createDb(context.env.DB), targetUserId, [event.event]),
+ { route: "ws-do:community-content-access" },
+ )) {
context.log.info("community_content_access_denied", { targetUserId, type: event.event.type })
return jsonResponse({ sent: 0 }, 200)
}
} catch (error) {
- context.log.warn("community_content_access_failed", { targetUserId, error: String(error) })
+ context.log.warn("community_content_access_failed", {
+ targetUserId,
+ error: String(error),
+ cause: error instanceof Error && error.cause instanceof Error ? error.cause.message : undefined,
+ })
return jsonResponse({ error: "access_check_failed" }, 503)
}
const sent = broadcastCommunity(context, event.event, targetUserId, event.contract)
@@ -151,16 +164,6 @@ export async function handleUserFetch(
})
}
- if (url.pathname === "/check-alive") {
- const hasAuthDaemon = context.ctx.getWebSockets().some(ws => {
- const s = ws.deserializeAttachment() as ConnectionState
- return s?.type === "daemon" && s.authenticated
- })
- return new Response(JSON.stringify({ alive: hasAuthDaemon }), {
- headers: { "Content-Type": "application/json" },
- })
- }
-
if (url.pathname === "/check-user-online") {
const targetUserId = url.searchParams.get("userId")
let hasAuthUser = false
@@ -275,33 +278,10 @@ export async function handleWebSocketMessage(
const msg = parsed as {
type: string
token?: string
- machineToken?: string
- daemonId?: string
communityContract?: unknown
}
if (msg.type === "auth") {
- if (msg.machineToken && msg.daemonId) {
- const authResult = await validateMachineToken(context, msg.machineToken, msg.daemonId)
- if (authResult.kind === "invalid") {
- context.log.warn("daemon websocket auth rejected", { daemonId: msg.daemonId })
- try { ws.send(JSON.stringify({ type: "error", code: "AUTH_REJECTED" })) } catch { }
- ws.close(1008, "Unauthorized")
- return
- }
- if (authResult.kind === "transient") {
- context.log.warn("daemon websocket auth transient failure", { daemonId: msg.daemonId })
- ws.close(1011, "Auth temporarily unavailable")
- return
- }
- ws.serializeAttachment({ type: "daemon", daemonId: msg.daemonId, userId: authResult.userId, authenticated: true } as ConnectionState)
- context.log.info("daemon websocket authenticated", { daemonId: msg.daemonId })
- ws.send(JSON.stringify({ type: "auth.ok" }))
-
- notifyUserDO(context, authResult.userId, { type: "runtime.status", status: "online", daemonId: msg.daemonId }).catch(() => { })
- return
- }
-
if (!msg.token) {
ws.close(1008, "Unauthorized")
return
@@ -366,24 +346,6 @@ export async function handleWebSocketMessage(
return
}
- if (msg.type === "check_daemon_status" && state.type === "user") {
- const daemonId = await getDaemonIdForUser(context, state.userId)
- if (daemonId) {
- try {
- const daemonDoId = context.env.WS_DO.idFromName("daemon:" + daemonId)
- const daemonStub = context.env.WS_DO.get(daemonDoId)
- const resp = await daemonStub.fetch(new Request("http://internal/check-alive"))
- const { alive } = await resp.json() as { alive: boolean }
- if (alive) {
- ws.send(JSON.stringify({ type: "runtime.status", status: "online", daemonId }))
- }
- } catch {
- context.log.debug("check_daemon_status: failed to reach daemon DO", { daemonId })
- }
- }
- return
- }
-
if (state.type === "user" && !isCurrentBusinessSocket(ws, state)) return
if (state.type === "user" && msg.type.startsWith("community:") && (parsed as Record<string, unknown>).schemaVersion !== BUSINESS_SCHEMA_VERSION) {
ws.close(1008, "Unsupported community contract")
@@ -410,10 +372,6 @@ export async function handleWebSocketClose(
handleCommunityMachineClose: (state: CommunityMachineConnectionState) => Promise<void>,
): Promise<void> {
const state = ws.deserializeAttachment() as ConnectionState
- if (state?.type === "daemon" && state.authenticated) {
- context.log.info("daemon websocket closed", { daemonId: state.daemonId })
- notifyUserDO(context, state.userId, { type: "runtime.status", status: "offline", daemonId: state.daemonId }).catch(() => { })
- }
if (state?.type === "user" && state.authenticated) {
if (!hasOtherAuthenticatedUserConnection(context, ws, state.userId)) {
broadcastPresence(context, state.userId, false).catch(() => { })
@@ -751,12 +709,6 @@ function hasOtherAuthenticatedUserConnection(
})
}
-async function getDaemonIdForUser(context: WsDurableContext, userId: string): Promise<string | null> {
- const db = createDb(context.env.DB)
- const token = await queries.machineToken.getLatestTokenForUser(db, userId)
- return token?.hostname || null
-}
-
async function validateToken(
context: WsDurableContext,
token: string,
@@ -767,26 +719,3 @@ async function validateToken(
{ route: "ws-do:user-auth-session" },
)
}
-
-async function validateMachineToken(
- context: WsDurableContext,
- token: string,
- daemonId: string,
-): Promise<
- | { kind: "valid"; userId: string }
- | { kind: "invalid" }
- | { kind: "transient" }
-> {
- if (!token.startsWith("al_")) return { kind: "invalid" }
- try {
- const db = createDb(context.env.DB)
- const mt = await queries.machineToken.getMachineTokenByToken(db, token)
- if (!mt || mt.status !== "active" || !mt.workspaceId) return { kind: "invalid" }
- const machine = await queries.machine.getMachineByDaemon(db, daemonId, mt.workspaceId)
- if (!machine) return { kind: "invalid" }
- return { kind: "valid", userId: mt.userId }
- } catch (err) {
- context.log.warn("daemon websocket auth lookup threw", { err: String(err) })
- return { kind: "transient" }
- }
-}
diff --git a/tests/utils/src/auth.test.ts b/tests/utils/src/auth.test.ts
index 0e8c6344f..9b2cf25b5 100644
--- a/tests/utils/src/auth.test.ts
+++ b/tests/utils/src/auth.test.ts
@@ -44,8 +44,8 @@ describe("current human community session requests", () => {
const { COMMUNITY_CONTRACT_HEADER } = await import("@alook/shared")
const fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({}))
await sessionRequest("/api/community/users/me/profile", "session=unit", { headers: { [COMMUNITY_CONTRACT_HEADER]: "wrong" } })
- await sessionRequest("/api/auth/device/approve", "session=unit")
- await tokenRequest("/api/daemon/status", "unit-credential")
+ await sessionRequest("/api/auth/sign-out", "session=unit")
+ await tokenRequest("/api/community/daemon/me", "unit-credential")
expect(new Headers(fetch.mock.calls[0]![1]!.headers).get(COMMUNITY_CONTRACT_HEADER)).toBe("wrong")
expect(new Headers(fetch.mock.calls[1]![1]!.headers).has(COMMUNITY_CONTRACT_HEADER)).toBe(false)
expect(new Headers(fetch.mock.calls[2]![1]!.headers).has(COMMUNITY_CONTRACT_HEADER)).toBe(false)
diff --git a/tests/utils/src/seed.ts b/tests/utils/src/seed.ts
index 385d2c8d1..511b8a370 100644
--- a/tests/utils/src/seed.ts
+++ b/tests/utils/src/seed.ts
@@ -9,9 +9,6 @@ export interface TestSeed {
daemonId: string
agentId: string
agentEmailHandle: string
- /** Raw machine token (starts with al_) */
- machineToken: string
- machineTokenId: string
whitelistId: string
/** Email used for better-auth sign-in */
authEmail: string
@@ -30,8 +27,6 @@ export function seedTestData(): TestSeed {
const runtimeId = `rt_${nanoid()}`
const agentId = `ag_${nanoid()}`
const daemonId = `daemon_${nanoid()}`
- const machineTokenId = `mt_${nanoid()}`
- const rawToken = `al_${randomUUID().replace(/-/g, "")}`
const emailHandle = `e2e-${nanoid()}`
const whitelistId = `wl_${nanoid()}`
@@ -44,7 +39,6 @@ export function seedTestData(): TestSeed {
sqlRun(`INSERT INTO machine (daemon_id, workspace_id, device_info, last_seen_at, created_at, updated_at, owner_id) VALUES (?, ?, ?, ?, ?, ?, ?)`, daemonId, workspaceId, 'test-device', now, now, now, userId)
sqlRun(`INSERT INTO agent_runtime (id, workspace_id, daemon_id, runtime_mode, provider, status, device_info, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, runtimeId, workspaceId, daemonId, 'local', 'claude', 'online', 'test-device', now, now)
sqlRun(`INSERT INTO agent (id, workspace_id, name, runtime_id, email_handle, owner_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, agentId, workspaceId, 'Test Agent', runtimeId, emailHandle, userId, now, now)
- sqlRun(`INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`, machineTokenId, userId, workspaceId, rawToken, 'test-token', 'active', now)
sqlRun(`INSERT INTO agent_whitelist (id, agent_id, workspace_id, email, created_at) VALUES (?, ?, ?, ?, ?)`, whitelistId, agentId, workspaceId, `${userId}@test.local`, now)
// Insert account record for better-auth credential provider (scrypt hash of "e2e-test-pass")
@@ -55,7 +49,7 @@ export function seedTestData(): TestSeed {
const authEmail = `${userId}@test.local`
const authPassword = "e2e-test-pass"
- return { userId, workspaceId, memberId, runtimeId, daemonId, agentId, agentEmailHandle: emailHandle, machineToken: rawToken, machineTokenId, whitelistId, authEmail, authPassword }
+ return { userId, workspaceId, memberId, runtimeId, daemonId, agentId, agentEmailHandle: emailHandle, whitelistId, authEmail, authPassword }
}
export function cleanupTestData(seed: TestSeed) {