Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): enforce symmetric dm communication (#817)

Gener17d7bef82daf
diff --git a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts
index 13368d8c9..6ffc6ffbf 100644
--- a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts
@@ -7,7 +7,13 @@ vi.mock("@opennextjs/cloudflare", () => ({
env: { DB: {}, COMMUNITY_MEDIA: { put: vi.fn(), delete: (...a: unknown[]) => mockR2Delete(...(a as [])) } },
})),
}))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+const primaryDb = { __db: "primary" }
+const replicaDb = { __db: "replica" }
+const mockGetPrimaryDb = vi.fn(() => primaryDb)
+vi.mock("@/lib/db", () => ({
+ getDb: vi.fn(() => replicaDb),
+ getPrimaryDb: (...args: unknown[]) => mockGetPrimaryDb(...args),
+}))
// Unified actor: a request with no `crk_` bearer falls through to the human
// withAuth path. Mock Better-Auth to resolve "no session" so a no-auth request
// yields the human-path 401 — the real unified-actor contract.
@@ -19,12 +25,15 @@ vi.mock("@/lib/auth", () => ({
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
const mockGetUserInternal = vi.fn()
+const mockGetUserByNameAndDiscriminator = vi.fn()
const mockGetBotBinding = vi.fn()
const mockResolveServerByNameForMember = vi.fn()
const mockResolveChannelByNameForMember = vi.fn()
const mockGetChannelForMember = vi.fn()
const mockGetDM = vi.fn()
const mockGetDMBetween = vi.fn()
+const mockGetDMPeer = vi.fn()
+const mockAreFriends = vi.fn()
const mockCreatePendingAttachment = vi.fn()
const mockLogError = vi.fn()
@@ -36,7 +45,11 @@ vi.mock("@alook/shared", async () => {
queries: {
...actual.queries,
communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },
- user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },
+ user: {
+ getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),
+ getUserByNameAndDiscriminator: (...a: unknown[]) =>
+ mockGetUserByNameAndDiscriminator(...a),
+ },
communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },
communityServer: { resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a) },
communityChannel: {
@@ -46,8 +59,12 @@ vi.mock("@alook/shared", async () => {
communityDm: {
getDM: (...a: unknown[]) => mockGetDM(...a),
getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a),
+ getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),
+ },
+ communityFriendship: {
+ isBlocked: async () => false,
+ areFriends: (...a: unknown[]) => mockAreFriends(...a),
},
- communityFriendship: { isBlocked: async () => false },
communityAttachment: {
createPendingAttachment: (...a: unknown[]) => mockCreatePendingAttachment(...a),
},
@@ -137,13 +154,31 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attac
"c1",
{ uploader: "bot", uploaderUserId: "bot_1" },
)
- expect(mockCreatePendingAttachment).toHaveBeenCalledWith({}, expect.objectContaining({
+ expect(mockGetPrimaryDb).toHaveBeenCalledOnce()
+ expect(mockCreatePendingAttachment).toHaveBeenCalledWith(primaryDb, expect.objectContaining({
uploaderId: "bot_1",
targetId: "c1",
r2Key: "channel/c1/uuid/hi.png",
}))
})
+ it("denies a bot DM attachment upload after unfriend", async () => {
+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1" })
+ mockGetDMBetween.mockResolvedValue({ id: "dm_1", type: "dm" })
+ mockGetDM.mockResolvedValue({ id: "dm_1", lastMessageAt: null, createdAt: "2026-09-22" })
+ mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })
+ mockAreFriends.mockResolvedValue(false)
+
+ const res = await POST(botReq("/.dm/Peer#0001", {
+ Authorization: "Bearer crk_abc",
+ }), botCtx)
+
+ expect(res.status).toBe(403)
+ expect(await res.json()).toEqual({ error: "accepted friendship required" })
+ expect(mockHandleAttachmentUpload).not.toHaveBeenCalled()
+ expect(mockCreatePendingAttachment).not.toHaveBeenCalled()
+ })
+
it("persists thumbnail key and dimensions, returning hasThumbnail true", async () => {
mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])
mockResolveChannelByNameForMember.mockResolvedValue([
@@ -162,7 +197,7 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attac
})
const response = await POST(botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }), botCtx)
expect(await response.json()).toMatchObject({ hasThumbnail: true })
- expect(mockCreatePendingAttachment).toHaveBeenCalledWith({}, expect.objectContaining({
+ expect(mockCreatePendingAttachment).toHaveBeenCalledWith(primaryDb, expect.objectContaining({
thumbnailR2Key: "channel/c1/uuid/hi.png.thumbnail.jpg",
width: 640,
height: 480,
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 a3b7f6be4..27e5314de 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,9 +1,12 @@
import { NextResponse, type NextRequest } from "next/server"
import { queries, createLogger } from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { getPrimaryDb } from "@/lib/db"
import { withCommunityActor, requireBot, type CommunityActor } from "@/lib/middleware/community-actor"
import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"
-import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"
+import {
+ requireChannelMember,
+ requireDMCommunicationAccess,
+} from "@/lib/community/permissions"
import { handleAttachmentUpload, runAttachmentUpload } from "@/lib/community/upload"
import { communityMediaCleanupErrorCategory } from "@/lib/community/community-media-cleanup"
@@ -37,7 +40,8 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
return handleBotAttachmentUpload(req, ctx)
}
// Human arm — id-in-path, shared upload trunk (surface dispatch +
- // per-surface guard + DM block gate live inside runAttachmentUpload).
+ // per-surface guard + DM accepted-friend communication gate live inside
+ // runAttachmentUpload).
return runAttachmentUpload(req, {
env: ctx.env,
userId: ctx.actor.userId,
@@ -75,7 +79,9 @@ async function handleBotAttachmentUpload(
return NextResponse.json({ error: "missing target query param" }, { status: 400 })
}
- const db = getDb(ctx.env.DB)
+ // Resolve and authorize against primary before writing R2/D1 so a recent
+ // unfriend/block cannot be bypassed through a lagging replica.
+ const db = getPrimaryDb(ctx.env.DB)
const resolved = await resolveTargetForMember(db, botUserId, target)
if ("error" in resolved) return resolveErrorResponse(resolved)
@@ -83,7 +89,7 @@ async function handleBotAttachmentUpload(
let kind: "channel" | "dm"
let targetId: string
if (resolved.kind === "dm") {
- const gate = await requireDMAccess(db, resolved.channelId, botUserId)
+ const gate = await requireDMCommunicationAccess(db, resolved.channelId, botUserId)
if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })
kind = "dm"
targetId = resolved.channelId
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 da613f75e..54d1c40fc 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
@@ -42,7 +42,10 @@ vi.mock("@alook/shared", async () => {
}
})
vi.mock("@/lib/community/resolve-ref", () => ({ resolveTargetForMember: (...args: unknown[]) => mockResolveTargetForMember(...args) }))
-vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireMessageSurfaceAccess(...args) }))
+vi.mock("@/lib/community/permissions", () => ({
+ requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireMessageSurfaceAccess(...args),
+ requireMessageSurfaceCommunicationAccess: (...args: unknown[]) => mockRequireMessageSurfaceAccess(...args),
+}))
vi.mock("@/lib/community/create-channels", () => ({ createMessageWithThread: (...args: unknown[]) => mockCreateMessageWithThread(...args) }))
vi.mock("@/lib/community/message-handler", () => ({
createCommunityMessage: vi.fn(),
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 a6f06675e..e88743481 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
@@ -30,6 +30,7 @@ const mockGetUserInternal = vi.fn()
const mockGetDM = vi.fn()
const mockGetDMPeer = vi.fn()
const mockIsBlocked = vi.fn()
+const mockAreFriends = vi.fn()
const mockCreateOrGetDM = vi.fn()
const mockListMessagesBySeq = vi.fn()
const mockToAgentMessages = vi.fn()
@@ -134,6 +135,7 @@ vi.mock("@alook/shared", async () => {
},
communityFriendship: {
isBlocked: (...a: unknown[]) => mockIsBlocked(...a),
+ areFriends: (...a: unknown[]) => mockAreFriends(...a),
},
// Bot read arm (GET dual-actor): seq-window + agent-message projection.
communityAgentInbox: {
@@ -276,6 +278,9 @@ describe("POST /api/community/channels/[id]/messages", () => {
mockAddThreadParticipant.mockResolvedValue(null)
mockListThreadParticipantUserIds.mockResolvedValue([])
mockBroadcastToUserSafe.mockResolvedValue(undefined)
+ mockIsBlocked.mockResolvedValue(false)
+ mockAreFriends.mockResolvedValue(true)
+ mockGetDMBetween.mockResolvedValue(null)
})
it("starts the write path on a first-primary D1 session", async () => {
@@ -309,6 +314,19 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(mockCreateMessage).not.toHaveBeenCalled()
})
+ it("keeps an existing DM readable but denies a human send after unfriend", async () => {
+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: null, type: "dm", parentChannelId: null })
+ mockGetDM.mockResolvedValue({ id: "c1", lastMessageAt: "t", createdAt: "t0" })
+ mockGetDMPeer.mockResolvedValue({ otherUserId: "u2" })
+ mockAreFriends.mockResolvedValue(false)
+
+ const res = await POST(postReq({ content: "after unfriend" }), ctx)
+
+ expect(res.status).toBe(403)
+ expect(await res.json()).toEqual({ error: "accepted friendship required" })
+ expect(mockCreateMessage).not.toHaveBeenCalled()
+ })
+
it("returns 429 with Retry-After when the sender is rate limited", async () => {
mockCheckMessageRateLimit.mockResolvedValue({ allowed: false, retryAfterSec: 7 })
@@ -762,6 +780,26 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(mockAddThreadParticipant).not.toHaveBeenCalled()
})
+ it("denies a CLI bot DM send when the friendship is no longer accepted", async () => {
+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })
+ mockGetDMBetween.mockResolvedValue({ id: "dm_1" })
+ mockGetChannel.mockResolvedValue({ id: "dm_1", serverId: null, type: "dm", parentChannelId: null })
+ mockGetDM.mockResolvedValue({ id: "dm_1", lastMessageAt: "t", createdAt: "t0" })
+ mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })
+ mockIsBlocked.mockResolvedValue(false)
+ mockAreFriends.mockResolvedValue(false)
+
+ const res = await POST(botPostReq({
+ channel: "/.dm/peer#0001",
+ content: { text: "after unfriend" },
+ }), ctx)
+
+ expect(res.status).toBe(403)
+ expect(await res.json()).toEqual({ error: "accepted friendship required" })
+ expect(mockCreateOrGetDM).not.toHaveBeenCalled()
+ expect(mockCreateMessage).not.toHaveBeenCalled()
+ })
+
it("bot full-command replay bypasses alignment and pending checks after the first committed send", async () => {
const stored = { id: "a1", targetId: "c1", filename: "x.png", contentType: "image/png", size: 10, width: 1, height: 1 }
const row = { ...await mockGetMessage(), authorId: "bot_1", clientNonce: "cmd:reply" }
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 bc4686ba2..e682703d0 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
@@ -186,7 +186,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
* 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
- * by `requireMessageSurfaceAccess` (via resolveMessageTarget) — the dispatch
+ * by `requireMessageSurfaceCommunicationAccess` (via resolveMessageTarget) — the dispatch
* subsumes the member check AND returns the channel, so there is EXACTLY ONE
* authorization entry (no standalone member/DM gate remains — a second gate
* would be a bypass of the single mask). A bot hitting this id route passes the
@@ -237,9 +237,9 @@ async function handleHumanSend(
return NextResponse.json({ error: "rate limited" }, { status: 429, headers: { "Retry-After": String(rateLimit.retryAfterSec) } })
}
- // SINGLE authorization entry — resolveMessageTarget → requireMessageSurfaceAccess
- // subsumes member/DM + returns the target (no standalone requireChannelMember).
- const resolved = await resolveMessageTarget(db, userId, descriptor, "human")
+ // SINGLE authorization entry — resolveMessageTarget's communication intent
+ // subsumes member/DM friendship + returns the target (no standalone gate).
+ const resolved = await resolveMessageTarget(db, userId, descriptor, "human", "communicate")
if (!resolved.ok) return NextResponse.json({ error: resolved.error }, { status: resolved.status })
const body = raw as { nonce?: unknown; attachments?: unknown }
@@ -321,7 +321,7 @@ async function handleBotSend(
createDmIfMissing: true,
createThreadIfMissing: true,
}
- const resolved = await resolveMessageTarget(db, botUserId, descriptor, "bot")
+ const resolved = await resolveMessageTarget(db, botUserId, descriptor, "bot", "communicate")
if (!resolved.ok) {
return NextResponse.json(
{ error: resolved.error, ...(resolved.hint ? { hint: resolved.hint } : {}) },
diff --git a/src/web/src/app/api/community/channels/[id]/upload/route.ts b/src/web/src/app/api/community/channels/[id]/upload/route.ts
index 0b009c924..1619459bf 100644
--- a/src/web/src/app/api/community/channels/[id]/upload/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/upload/route.ts
@@ -3,7 +3,7 @@ import { withAuth } from "@/lib/middleware/auth"
import { runAttachmentUpload } from "@/lib/community/upload"
// The unified attachment-upload trunk: one route, dispatched by surface inside
-// runAttachmentUpload (requireMessageSurfaceAccess → kind derived from surface +
-// channel.type). A DM id runs the DM block gate; a child-thread id runs
-// the child-surface gate — all surfaces upload through this one door.
+// runAttachmentUpload (communication surface access → kind derived from
+// surface + channel.type). A DM id runs the block + accepted-friend gate; a
+// child-thread id runs the child-surface gate — all surfaces use one door.
export const POST = withAuth((req: NextRequest, ctx) => runAttachmentUpload(req, ctx))
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 2b3adfcb7..b88ffbfd1 100644
--- a/src/web/src/app/api/community/channels/route.test.ts
+++ b/src/web/src/app/api/community/channels/route.test.ts
@@ -9,7 +9,14 @@ const mockCreateServerChannel = vi.fn()
const mockCreateDm = vi.fn()
const mockCreateThread = vi.fn()
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+const replicaDb = { __db: "replica" }
+const primaryDb = { __db: "primary" }
+const mockGetDb = vi.fn(() => replicaDb)
+const mockGetPrimaryDb = vi.fn(() => primaryDb)
+vi.mock("@/lib/db", () => ({
+ getDb: (...args: unknown[]) => mockGetDb(...args),
+ getPrimaryDb: (...args: unknown[]) => mockGetPrimaryDb(...args),
+}))
// Dual-actor: crk_ bearer → bot, else human. The bot arm is a capability
// boundary — creating channels is not a bot capability (channel-create permanent
@@ -68,7 +75,7 @@ describe("POST /api/community/channels (create door — human arm)", () => {
const res = await POST(req({ type: "text", serverId: "s1", name: "general" }))
expect(res.status).toBe(201)
expect(mockCreateServerChannel).toHaveBeenCalledWith(
- expect.anything(),
+ replicaDb,
expect.objectContaining({ serverId: "s1", actorUserId: "u1", name: "general", type: "text" }),
)
const body = await res.json()
@@ -105,9 +112,10 @@ describe("POST /api/community/channels (create door — human arm)", () => {
const res = await POST(req({ type: "dm", userId: "u2" }))
expect(res.status).toBe(201)
expect(mockCreateDm).toHaveBeenCalledWith(
- expect.anything(),
+ primaryDb,
expect.objectContaining({ actorUserId: "u1", peerUserId: "u2" }),
)
+ expect(mockGetPrimaryDb).toHaveBeenCalledOnce()
const body = await res.json()
expect(body.conversation.id).toBe("dm-1")
})
diff --git a/src/web/src/app/api/community/channels/route.ts b/src/web/src/app/api/community/channels/route.ts
index 5bab57bd2..82daa75b9 100644
--- a/src/web/src/app/api/community/channels/route.ts
+++ b/src/web/src/app/api/community/channels/route.ts
@@ -1,7 +1,7 @@
import { NextRequest } from "next/server"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { getDb } from "@/lib/db"
+import { getDb, getPrimaryDb } from "@/lib/db"
import {
createServerChannelForUser,
createDmForUser,
@@ -50,8 +50,6 @@ import {
* userId / root messageId).
*/
export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
- const db = getDb(ctx.env.DB)
-
let body: {
type?: unknown
serverId?: unknown
@@ -75,6 +73,10 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
return writeError("forbidden: creating channels is not available to bots", 403)
}
const actorUserId = ctx.actor.userId
+ // Opening a DM is read-before-write authorization. Keep other channel kinds
+ // on their existing session policy, but force the DM guard onto primary so a
+ // recent unfriend/block is immediately authoritative.
+ const db = body.type === "dm" ? getPrimaryDb(ctx.env.DB) : getDb(ctx.env.DB)
switch (body.type) {
case "text":
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 e19ab62a8..93c0840e5 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
@@ -12,7 +12,14 @@ const mockIsMessageMarked = vi.fn()
const mockMarkMessage = vi.fn()
const mockUnmarkMessage = vi.fn()
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+const replicaDb = { __db: "replica" }
+const primaryDb = { __db: "primary" }
+const mockGetDb = vi.fn(() => replicaDb)
+const mockGetPrimaryDb = vi.fn(() => primaryDb)
+vi.mock("@/lib/db", () => ({
+ getDb: (...args: unknown[]) => mockGetDb(...args),
+ getPrimaryDb: (...args: unknown[]) => mockGetPrimaryDb(...args),
+}))
vi.mock("@/lib/community/resolve-message-ref", () => ({
resolveMessageRefForBot: (...args: unknown[]) => mockResolve(...args),
}))
@@ -108,7 +115,7 @@ describe("bot message property route", () => {
{ type: "mark", value: false },
],
})
- expect(mockResolve).toHaveBeenCalledWith({}, "bot1", {
+ expect(mockResolve).toHaveBeenCalledWith(replicaDb, "bot1", {
channel: "/demo#1234/forum",
seq: 7,
}, { requireSurfaceAccess: true })
@@ -178,7 +185,7 @@ describe("bot message property route", () => {
value: ["existing", "new"],
changed: true,
})
- expect(mockMutateTags).toHaveBeenCalledWith({}, {
+ expect(mockMutateTags).toHaveBeenCalledWith(primaryDb, {
messageId: "m1",
userId: "bot1",
action: "set",
@@ -199,7 +206,8 @@ describe("bot message property route", () => {
mockGetChannelType.mockResolvedValue("thread")
const setEmoji = await PUT(mutationRequest("PUT", { type: "emoji", value: "👍" }), ctx)
expect(await setEmoji.json()).toEqual({ type: "emoji", value: "👍", changed: true })
- expect(mockSetReaction).toHaveBeenCalledWith({}, {
+ expect(mockGetPrimaryDb).toHaveBeenCalled()
+ expect(mockSetReaction).toHaveBeenCalledWith(primaryDb, {
messageId: "m1",
userId: "bot1",
emoji: "👍",
@@ -207,7 +215,7 @@ describe("bot message property route", () => {
const removeEmoji = await DELETE(mutationRequest("DELETE", { type: "emoji", value: "👍" }), ctx)
expect(await removeEmoji.json()).toEqual({ type: "emoji", value: "👍", changed: false })
- expect(mockRemoveReaction).toHaveBeenCalledWith({}, {
+ expect(mockRemoveReaction).toHaveBeenCalledWith(replicaDb, {
messageId: "m1",
userId: "bot1",
emoji: "👍",
@@ -222,7 +230,7 @@ describe("bot message property route", () => {
it("sets, lists, and removes the calling bot's universal mark", async () => {
const setRes = await PUT(mutationRequest("PUT", { type: "mark", value: true }), ctx)
expect(await setRes.json()).toEqual({ type: "mark", value: true, changed: true })
- expect(mockMarkMessage).toHaveBeenCalledWith({}, {
+ expect(mockMarkMessage).toHaveBeenCalledWith(primaryDb, {
userId: "bot1",
channelId: "c1",
messageId: "m1",
@@ -234,7 +242,7 @@ describe("bot message property route", () => {
const removeRes = await DELETE(mutationRequest("DELETE", { type: "mark", value: true }), ctx)
expect(await removeRes.json()).toEqual({ type: "mark", value: true, changed: true })
- expect(mockUnmarkMessage).toHaveBeenCalledWith({}, {
+ expect(mockUnmarkMessage).toHaveBeenCalledWith(replicaDb, {
userId: "bot1",
messageId: "m1",
})
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 e0ab7e4ff..11ddbc272 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
@@ -4,7 +4,7 @@ import {
messagePropertyCapabilities,
type MessagePropertyMutation,
} from "@alook/shared"
-import { getDb } from "@/lib/db"
+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"
@@ -121,7 +121,10 @@ async function mutate(req: NextRequest, ctx: Parameters<Parameters<typeof withCo
return writeError("invalid JSON body", 400)
}
- const db = getDb(ctx.env.DB)
+ // A property set can add a reaction, which is a DM communication write.
+ // Resolve + authorize the entire set operation on primary; removals retain
+ // the history-access path and may use the ordinary read session.
+ const db = action === "set" ? getPrimaryDb(ctx.env.DB) : getDb(ctx.env.DB)
const target = await resolveTarget(db, gate.bot.userId, raw)
if (!target.ok) return writeError(target.error, target.status)
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 3036700ae..0c6033a2c 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
@@ -12,8 +12,15 @@ const mockAddReaction = vi.fn();
const mockRemoveReaction = vi.fn();
const mockFanOutToChannel = vi.fn();
const mockFanOutToDM = vi.fn();
-
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+const replicaDb = { __db: "replica" };
+const primaryDb = { __db: "primary" };
+const mockGetDb = vi.fn(() => replicaDb);
+const mockGetPrimaryDb = vi.fn(() => primaryDb);
+
+vi.mock("@/lib/db", () => ({
+ getDb: (...a: unknown[]) => mockGetDb(...a),
+ getPrimaryDb: (...a: unknown[]) => mockGetPrimaryDb(...a),
+}));
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
@@ -36,6 +43,7 @@ vi.mock("@alook/shared", async () => {
vi.mock("@/lib/community/permissions", () => ({
requireMessageSurfaceAccess: (...a: unknown[]) => mockRequireSurfaceAccess(...a),
+ requireMessageSurfaceCommunicationAccess: (...a: unknown[]) => mockRequireSurfaceAccess(...a),
}));
vi.mock("@/lib/community/fanout", () => ({
@@ -161,12 +169,13 @@ describe("reactions [emoji] surface guard", () => {
mockGetChannelType.mockResolvedValue("text");
const res = await PUT(botReq("PUT", { channel: "/s/general", seq: 42 }), ctxResolve);
expect(res.status).toBe(200);
- expect(mockResolveTargetForMember).toHaveBeenCalledWith({}, "bot_1", "/s/general", {
+ expect(mockGetPrimaryDb).toHaveBeenCalledOnce();
+ expect(mockResolveTargetForMember).toHaveBeenCalledWith(primaryDb, "bot_1", "/s/general", {
createDmIfMissing: false,
createThreadIfMissing: false,
callerKind: "bot",
});
- expect(mockGetMessageIdentityByChannelAndSeq).toHaveBeenCalledWith({}, { channelId: "c1" }, 42);
+ expect(mockGetMessageIdentityByChannelAndSeq).toHaveBeenCalledWith(primaryDb, { channelId: "c1" }, 42);
expect(mockAddReaction).toHaveBeenCalled();
});
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 0eb822012..d38a4d513 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,7 +1,7 @@
import { NextRequest } from "next/server"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { getDb } from "@/lib/db"
+import { getDb, getPrimaryDb } from "@/lib/db"
import { resolveMessageRefForBot } from "@/lib/community/resolve-message-ref"
import {
removeReactionForActor,
@@ -16,9 +16,10 @@ import {
* Message-keyed reaction door (route/disc trunk — message-keyed faces dual-actor).
* withCommunityActor: 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 per-surface gate (requireDMAccess for a
- * DM incl block, requireChannelMember otherwise) keyed on `ctx.actor.userId`, so a
- * bot reaction runs the SAME mask a human does (no bot bypass). The bot's ref+seq→
+ * resolves the message → its channel → the communication surface gate (DM
+ * participant + block + accepted friendship, channel member otherwise) keyed
+ * on `ctx.actor.userId`, so a bot reaction runs the SAME mask a human does (no
+ * bot bypass). The bot's ref+seq→
* messageId resolution happens upstream at the flat-verb→door retarget (proxy); this
* route is message-keyed (messageId in path) for both actors.
*/
@@ -29,7 +30,9 @@ export const PUT = withCommunityActor(async (req: NextRequest, ctx) => {
const emoji = decodeURIComponent(rawEmoji)
const userId = ctx.actor.userId
- const db = getDb(ctx.env.DB)
+ // Reaction add is a communication write; its read-before-write permission
+ // check must observe the latest unfriend/block.
+ const db = getPrimaryDb(ctx.env.DB)
// Target messageId: bot ref+seq (member-scoped → 404), human path id. A bot
// body is `{ channel, seq, emoji }` — emoji is already the path segment, so
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 1c31ade25..2e8c88918 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
@@ -29,6 +29,7 @@ const mockGetPrivateChannelAudienceUserIds = vi.fn()
const mockGetDM = vi.fn()
const mockGetDMPeer = vi.fn()
const mockIsBlocked = vi.fn()
+const mockAreFriends = vi.fn()
const mockListByMessageIds = vi.fn()
const mockListReactionsByMessageIds = vi.fn()
const mockGetMessageByChannelAndSeq = vi.fn()
@@ -38,7 +39,14 @@ const mockFanOutToChannel = vi.fn()
const mockFanOutToServerMembers = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})), getPrimaryDb: vi.fn(() => ({})) }))
+const replicaDb = { __db: "replica" }
+const primaryDb = { __db: "primary" }
+const mockGetDb = vi.fn(() => replicaDb)
+const mockGetPrimaryDb = vi.fn(() => primaryDb)
+vi.mock("@/lib/db", () => ({
+ getDb: (...args: unknown[]) => mockGetDb(...args),
+ getPrimaryDb: (...args: unknown[]) => mockGetPrimaryDb(...args),
+}))
vi.mock("@/lib/community/resolve-ref", () => ({
resolveTargetForMember: (...a: unknown[]) => mockResolveTargetForMember(...a),
@@ -89,6 +97,7 @@ vi.mock("@alook/shared", async () => {
},
communityFriendship: {
isBlocked: (...a: unknown[]) => mockIsBlocked(...a),
+ areFriends: (...a: unknown[]) => mockAreFriends(...a),
},
},
}
@@ -351,12 +360,12 @@ describe("GET /api/community/messages/[id]", () => {
const res = await GET(botReq("/s/general", "42"), ctxResolve)
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ message: expect.objectContaining({ seq: "#42" }) })
- expect(mockResolveTargetForMember).toHaveBeenCalledWith({}, "bot_1", "/s/general", {
+ expect(mockResolveTargetForMember).toHaveBeenCalledWith(replicaDb, "bot_1", "/s/general", {
createDmIfMissing: false,
createThreadIfMissing: false,
callerKind: "bot",
})
- expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith({}, { channelId: "c1" }, 42)
+ expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith(replicaDb, { channelId: "c1" }, 42)
})
it("①-C: bot ref to an UNREACHABLE channel → 404 (member-scoped resolve, not a 403 leak)", async () => {
@@ -403,6 +412,8 @@ describe("PATCH /api/community/messages/[id]", () => {
mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1", authorId: "u1", content: "old" })
mockUpdateOwnMessageContent.mockResolvedValue({ id: "m1", channelId: "c1", content: "new" })
mockFanOutToChannel.mockResolvedValue(undefined)
+ mockIsBlocked.mockResolvedValue(false)
+ mockAreFriends.mockResolvedValue(true)
})
function editReq(content: unknown, bot = false) {
@@ -416,7 +427,8 @@ describe("PATCH /api/community/messages/[id]", () => {
it("updates the author's own content", async () => {
const res = await PATCH(editReq("new"), { params: { id: "m1" } } as any)
expect(res.status).toBe(200)
- expect(mockUpdateOwnMessageContent).toHaveBeenCalledWith(expect.anything(), {
+ expect(mockGetPrimaryDb).toHaveBeenCalledOnce()
+ expect(mockUpdateOwnMessageContent).toHaveBeenCalledWith(primaryDb, {
messageId: "m1", authorId: "u1", content: "new",
})
expect(mockFanOutToChannel).toHaveBeenCalledWith("c1", {
@@ -481,6 +493,20 @@ describe("PATCH /api/community/messages/[id]", () => {
})
})
+ it("denies editing an old DM message after unfriend", async () => {
+ mockGetChannel.mockResolvedValue({ id: "dm_1", serverId: null, type: "dm" })
+ mockGetMessage.mockResolvedValue({ id: "m1", channelId: "dm_1", authorId: "u1", content: "old" })
+ mockGetDM.mockResolvedValue({ id: "dm_1", lastMessageAt: null, createdAt: "2026-09-22" })
+ mockGetDMPeer.mockResolvedValue({ otherUserId: "u2" })
+ mockAreFriends.mockResolvedValue(false)
+
+ const res = await PATCH(editReq("new"), { params: { id: "m1" } } as any)
+
+ expect(res.status).toBe(403)
+ expect(await res.json()).toEqual({ error: "accepted friendship required" })
+ expect(mockUpdateOwnMessageContent).not.toHaveBeenCalled()
+ })
+
it("rejects bot credentials and empty content", async () => {
expect((await PATCH(editReq("new", true), { params: { id: "m1" } } as any)).status).toBe(401)
expect((await PATCH(editReq(" "), { params: { id: "m1" } } as any)).status).toBe(400)
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 69df08c7f..2267877d3 100644
--- a/src/web/src/app/api/community/messages/[id]/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.ts
@@ -7,6 +7,7 @@ import { canManageServer, queries, MAX_MESSAGE_CONTENT_LENGTH, WS_EVENTS } from
import {
requireChannelMember,
requireDMAccess,
+ requireDMCommunicationAccess,
requireMessageSurfaceAccess,
requireServerMember,
} from "@/lib/community/permissions"
@@ -81,14 +82,16 @@ export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {
return writeError(`content must be ≤ ${MAX_MESSAGE_CONTENT_LENGTH} characters`, 400)
}
- const db = getDb(ctx.env.DB)
+ // Editing is a communication write. Authorize and mutate in a primary
+ // session so a recent unfriend/block cannot be missed by replica lag.
+ const db = getPrimaryDb(ctx.env.DB)
const message = await queries.communityMessage.getMessage(db, messageId)
if (!message) return writeError("message not found", 404)
const channel = await queries.communityChannel.getChannel(db, message.channelId)
const channelType = channel?.type ?? null
const access = channelType === "dm"
- ? await requireDMAccess(db, message.channelId, ctx.actor.userId)
+ ? await requireDMCommunicationAccess(db, message.channelId, ctx.actor.userId)
: await requireChannelMember(db, message.channelId, ctx.actor.userId)
if (!access.ok) return writeError(access.error, access.status)
if (message.authorId !== ctx.actor.userId) return writeError("only the message author may edit it", 403)
diff --git a/src/web/src/lib/community/dm-guard.test.ts b/src/web/src/lib/community/dm-guard.test.ts
index 2628e7f60..b3fe86d8e 100644
--- a/src/web/src/lib/community/dm-guard.test.ts
+++ b/src/web/src/lib/community/dm-guard.test.ts
@@ -48,24 +48,36 @@ describe("guardDmOpen", () => {
expect(res).toEqual({ ok: false, status: 403, error: "blocked", code: "blocked" })
})
- it("human ↔ human: not blocked → ok", async () => {
+ it("human ↔ human: not blocked but not accepted → 403 not_friends", async () => {
mockGetUserInternal.mockResolvedValue({ id: "u_2", isBot: false, deletedAt: null })
mockIsBlocked.mockResolvedValue(false)
+ mockAreFriends.mockResolvedValue(false)
+ const res = await guardDmOpen(db, "u_1", "u_2")
+ expect(res).toEqual({ ok: false, status: 403, error: "not friends", code: "not_friends" })
+ })
+
+ it("human ↔ human: accepted and not blocked → ok", async () => {
+ mockGetUserInternal.mockResolvedValue({ id: "u_2", isBot: false, deletedAt: null })
+ mockIsBlocked.mockResolvedValue(false)
+ mockAreFriends.mockResolvedValue(true)
const res = await guardDmOpen(db, "u_1", "u_2")
expect(res).toEqual({ ok: true })
})
describe("peer is a bot", () => {
- it("sender is the bot's owner → allowed, skips both friend and block checks", async () => {
+ it("sender is the bot's owner → implicit friendship passes after block check", async () => {
mockGetUserInternal.mockResolvedValue({ id: "bot_1", isBot: true, ownerUserId: "u_owner", deletedAt: null })
+ mockIsBlocked.mockResolvedValue(false)
+ mockAreFriends.mockResolvedValue(true)
const res = await guardDmOpen(db, "u_owner", "bot_1")
expect(res).toEqual({ ok: true })
- expect(mockAreFriends).not.toHaveBeenCalled()
- expect(mockIsBlocked).not.toHaveBeenCalled()
+ expect(mockIsBlocked).toHaveBeenCalledWith(db, "u_owner", "bot_1")
+ expect(mockAreFriends).toHaveBeenCalledWith(db, "u_owner", "bot_1")
})
it("not the owner, not friends, callerKind human (default) → 404 user_not_found (pass-as-human)", async () => {
mockGetUserInternal.mockResolvedValue({ id: "bot_1", isBot: true, ownerUserId: "u_owner", deletedAt: null })
+ mockIsBlocked.mockResolvedValue(false)
mockAreFriends.mockResolvedValue(false)
const res = await guardDmOpen(db, "u_stranger", "bot_1")
expect(res).toEqual({ ok: false, status: 404, error: "user not found", code: "user_not_found" })
@@ -73,15 +85,16 @@ describe("guardDmOpen", () => {
it("not the owner, not friends, callerKind bot → 403 not_friends", async () => {
mockGetUserInternal.mockResolvedValue({ id: "bot_1", isBot: true, ownerUserId: "u_owner", deletedAt: null })
+ mockIsBlocked.mockResolvedValue(false)
mockAreFriends.mockResolvedValue(false)
const res = await guardDmOpen(db, "bot_caller", "bot_1", { callerKind: "bot" })
- expect(res).toEqual({ ok: false, status: 403, error: "not friends with this bot", code: "not_friends" })
+ expect(res).toEqual({ ok: false, status: 403, error: "not friends", code: "not_friends" })
})
it("friends with the bot → block-gated, then ok", async () => {
mockGetUserInternal.mockResolvedValue({ id: "bot_1", isBot: true, ownerUserId: "u_owner", deletedAt: null })
- mockAreFriends.mockResolvedValue(true)
mockIsBlocked.mockResolvedValue(false)
+ mockAreFriends.mockResolvedValue(true)
const res = await guardDmOpen(db, "u_friend", "bot_1", { callerKind: "bot" })
expect(res).toEqual({ ok: true })
expect(mockIsBlocked).toHaveBeenCalled()
@@ -89,10 +102,10 @@ describe("guardDmOpen", () => {
it("friends with the bot but blocked → 403 blocked", async () => {
mockGetUserInternal.mockResolvedValue({ id: "bot_1", isBot: true, ownerUserId: "u_owner", deletedAt: null })
- mockAreFriends.mockResolvedValue(true)
mockIsBlocked.mockResolvedValue(true)
const res = await guardDmOpen(db, "u_friend", "bot_1", { callerKind: "bot" })
expect(res).toEqual({ ok: false, status: 403, error: "blocked", code: "blocked" })
+ expect(mockAreFriends).not.toHaveBeenCalled()
})
})
})
diff --git a/src/web/src/lib/community/dm-guard.ts b/src/web/src/lib/community/dm-guard.ts
index 9ac86df3a..0b8a90d10 100644
--- a/src/web/src/lib/community/dm-guard.ts
+++ b/src/web/src/lib/community/dm-guard.ts
@@ -18,16 +18,12 @@ export type GuardDmOpenResult =
* preserves pass-as-human for the human route; a `crk_`-authenticated bot
* caller has no "pass as human" risk, so 404 here is just "not found",
* not deliberate obfuscation).
- * - Peer is a bot: allowed if `senderId` is the bot's owner, else requires
- * `areFriends`. On friend-check failure:
- * - `callerKind: "human"` → 404 `user_not_found` (pass-as-human).
- * - `callerKind: "bot"` → 403 `not_friends` (crk_ authenticated; no
- * pass-as-human risk to preserve).
- * - `requireNotBlocked` → 403 `blocked` — EXCEPT when `senderId` is the
- * peer's owner, matching the existing human route's `isOwner` skip
- * exactly (a deliberate behavior-preservation decision, not an oversight:
- * a verbatim extraction without this skip would change existing
- * production behavior for owners DMing their own bot).
+ * - Block always wins, including owner ↔ own-bot pairs.
+ * - Every human/bot pairing requires `areFriends`; that query includes the
+ * owner ↔ own-bot implicit friendship. On friend-check failure:
+ * - human caller targeting a bot → 404 `user_not_found` (pass-as-human).
+ * - every other caller/peer pairing → 403 `not_friends`.
+ * - `requireNotBlocked` → 403 `blocked` before the friendship check.
*/
export async function guardDmOpen(
db: Database,
@@ -46,25 +42,17 @@ export async function guardDmOpen(
return { ok: false, status: 404, error: "user not found", code: "user_not_found" }
}
- if (peer.isBot === true) {
- const isOwner = peer.ownerUserId === senderId
- if (!isOwner) {
- const areFriends = await queries.communityFriendship.areFriends(db, senderId, peerId)
- if (!areFriends) {
- return callerKind === "bot"
- ? { ok: false, status: 403, error: "not friends with this bot", code: "not_friends" }
- : { ok: false, status: 404, error: "user not found", code: "user_not_found" }
- }
- }
- if (!isOwner) {
- const blocked = await requireNotBlocked(db, senderId, peerId)
- // `requireNotBlocked` only ever fails with 403 — narrow the wider
- // `PermissionError` status union to satisfy this function's return type.
- if (!blocked.ok) return { ok: false, status: 403, error: blocked.error, code: "blocked" }
+ const blocked = await requireNotBlocked(db, senderId, peerId)
+ if (!blocked.ok) {
+ return { ok: false, status: 403, error: blocked.error, code: "blocked" }
+ }
+
+ const accepted = await queries.communityFriendship.areFriends(db, senderId, peerId)
+ if (!accepted) {
+ if (peer.isBot === true && callerKind === "human") {
+ return { ok: false, status: 404, error: "user not found", code: "user_not_found" }
}
- } else {
- const blocked = await requireNotBlocked(db, senderId, peerId)
- if (!blocked.ok) return { ok: false, status: 403, error: blocked.error, code: "blocked" }
+ return { ok: false, status: 403, error: "not friends", code: "not_friends" }
}
return { ok: true }
diff --git a/src/web/src/lib/community/message-door.test.ts b/src/web/src/lib/community/message-door.test.ts
index ccd514628..b2fb5b0b5 100644
--- a/src/web/src/lib/community/message-door.test.ts
+++ b/src/web/src/lib/community/message-door.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
const mockResolveTargetForMember = vi.fn()
const mockRequireMessageSurfaceAccess = vi.fn()
+const mockRequireMessageSurfaceCommunicationAccess = vi.fn()
const mockRequireMessageBearingSurface = vi.fn()
vi.mock("./resolve-ref", () => ({
@@ -9,6 +10,8 @@ vi.mock("./resolve-ref", () => ({
}))
vi.mock("./permissions", () => ({
requireMessageSurfaceAccess: (...a: unknown[]) => mockRequireMessageSurfaceAccess(...a),
+ requireMessageSurfaceCommunicationAccess: (...a: unknown[]) =>
+ mockRequireMessageSurfaceCommunicationAccess(...a),
}))
vi.mock("./channel-write-guard", () => ({
requireMessageBearingSurface: (...a: unknown[]) => mockRequireMessageBearingSurface(...a),
@@ -91,6 +94,25 @@ describe("resolveMessageTarget — single mask output + surface→target (Aignei
expect(res).toEqual({ ok: false, status: 404, error: "not found" })
})
+ it("communication intent uses the stricter shared Web/CLI write gate", async () => {
+ mockRequireMessageSurfaceCommunicationAccess.mockResolvedValue({
+ ok: true,
+ value: { surface: "dm", dm: { id: "d1", otherUserId: "u2" } },
+ })
+
+ const res = await resolveMessageTarget(
+ db,
+ "u1",
+ { id: "d1" },
+ "human",
+ "communicate",
+ )
+
+ expect(res).toMatchObject({ ok: true, value: { target: { kind: "dm" } } })
+ expect(mockRequireMessageSurfaceCommunicationAccess).toHaveBeenCalledWith(db, "d1", "u1")
+ expect(mockRequireMessageSurfaceAccess).not.toHaveBeenCalled()
+ })
+
it("dm surface → dm-kind target, otherUserId consumed from the dispatch peer (no re-query)", async () => {
mockRequireMessageSurfaceAccess.mockResolvedValue({
ok: true,
diff --git a/src/web/src/lib/community/message-door.ts b/src/web/src/lib/community/message-door.ts
index 100167202..95cec9005 100644
--- a/src/web/src/lib/community/message-door.ts
+++ b/src/web/src/lib/community/message-door.ts
@@ -1,6 +1,9 @@
import type { Database } from "@alook/shared"
import { resolveTargetForMember, type TargetResolution } from "./resolve-ref"
-import { requireMessageSurfaceAccess } from "./permissions"
+import {
+ requireMessageSurfaceAccess,
+ requireMessageSurfaceCommunicationAccess,
+} from "./permissions"
import { requireMessageBearingSurface } from "./channel-write-guard"
import { type MessageTarget } from "./message-handler"
@@ -87,12 +90,12 @@ function err(status: number, error: string): DoorResult<never> {
* existence-mask output both arms share (Aigneis ④, the hard red line).
*
* ⚠ The id arm does NOT trust the caller-supplied id: a web-sent id is put
- * through the EXACT same `requireMessageSurfaceAccess` gate as a ref-resolved
- * id. "id is web-trusted, skip the mask" would be strictly worse than the old
+ * through the EXACT same intent-selected surface gate as a ref-resolved id.
+ * "id is web-trusted, skip the mask" would be strictly worse than the old
* two-door inconsistency — an id door with no mask. So both arms:
* 1. arrive at a channelId (id: direct; ref: resolveTargetForMember),
- * 2. pass through requireMessageSurfaceAccess (one collapse point, one opaque
- * 404 body — a stranger constructing an unreachable id eats the same four
+ * 2. pass through the read gate or communication-write gate (one collapse
+ * point, one opaque 404 body — a stranger constructing an unreachable id eats the same four
* cells: unknown→404 / non-member→403 / DM-non-participant→404 / blocked→403),
* 3. build the MessageTarget from (surface + channel.type).
*
@@ -105,6 +108,7 @@ export async function resolveMessageTarget(
userId: string,
descriptor: MessageTargetDescriptor,
callerKind: "human" | "bot",
+ intent: "read" | "communicate" = "read",
): Promise<DoorResult<DoorTarget>> {
let channelId: string
@@ -126,7 +130,9 @@ export async function resolveMessageTarget(
}
// SINGLE mask output — both arms converge here (Aigneis ④).
- const access = await requireMessageSurfaceAccess(db, channelId, userId)
+ const access = intent === "communicate"
+ ? await requireMessageSurfaceCommunicationAccess(db, channelId, userId)
+ : await requireMessageSurfaceAccess(db, channelId, userId)
if (!access.ok) return access
if (access.value.surface === "dm") {
diff --git a/src/web/src/lib/community/permissions.test.ts b/src/web/src/lib/community/permissions.test.ts
index 32f0f8dd9..9b9fbeb1d 100644
--- a/src/web/src/lib/community/permissions.test.ts
+++ b/src/web/src/lib/community/permissions.test.ts
@@ -7,6 +7,7 @@ const resolveChannelAccessContext = vi.fn()
const getDM = vi.fn()
const getDMPeer = vi.fn()
const isBlocked = vi.fn()
+const areFriends = vi.fn()
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -23,7 +24,10 @@ vi.mock("@alook/shared", async () => {
getDM: (...a: unknown[]) => getDM(...a),
getDMPeer: (...a: unknown[]) => getDMPeer(...a),
},
- communityFriendship: { isBlocked: (...a: unknown[]) => isBlocked(...a) },
+ communityFriendship: {
+ isBlocked: (...a: unknown[]) => isBlocked(...a),
+ areFriends: (...a: unknown[]) => areFriends(...a),
+ },
},
}
})
@@ -34,8 +38,10 @@ import {
requireChannelMember,
requireChannelAccess,
requireDMAccess,
+ requireDMCommunicationAccess,
requireNotBlocked,
requireMessageSurfaceAccess,
+ requireMessageSurfaceCommunicationAccess,
} from "./permissions"
// Build a resolveChannelAccessContext return row. `anchor` defaults to the
@@ -289,6 +295,47 @@ describe("requireDMAccess", () => {
})
})
+describe("requireDMCommunicationAccess", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("allows an accepted friend after the participant and block checks", async () => {
+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "2026-06-30" })
+ getDMPeer.mockResolvedValue({ otherUserId: "u2" })
+ isBlocked.mockResolvedValue(false)
+ areFriends.mockResolvedValue(true)
+
+ const res = await requireDMCommunicationAccess(db, "d1", "u1")
+
+ expect(res.ok).toBe(true)
+ expect(areFriends).toHaveBeenCalledWith(db, "u1", "u2")
+ })
+
+ it("keeps history accessible but denies communication after unfriend", async () => {
+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "2026-06-30" })
+ getDMPeer.mockResolvedValue({ otherUserId: "u2" })
+ isBlocked.mockResolvedValue(false)
+ areFriends.mockResolvedValue(false)
+
+ await expect(requireDMAccess(db, "d1", "u1")).resolves.toMatchObject({ ok: true })
+ await expect(requireDMCommunicationAccess(db, "d1", "u1")).resolves.toEqual({
+ ok: false,
+ status: 403,
+ error: "accepted friendship required",
+ })
+ })
+
+ it("keeps block higher priority and never consults friendship", async () => {
+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "2026-06-30" })
+ getDMPeer.mockResolvedValue({ otherUserId: "u2" })
+ isBlocked.mockResolvedValue(true)
+
+ const res = await requireDMCommunicationAccess(db, "d1", "u1")
+
+ expect(res).toEqual({ ok: false, status: 403, error: "blocked" })
+ expect(areFriends).not.toHaveBeenCalled()
+ })
+})
+
describe("requireNotBlocked", () => {
beforeEach(() => vi.clearAllMocks())
@@ -375,3 +422,29 @@ describe("requireMessageSurfaceAccess — id-in-path trunk dispatch (surface axi
if (res.ok) expect(res.value.surface).toBe("channel")
})
})
+
+describe("requireMessageSurfaceCommunicationAccess", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("denies an unaccepted DM without changing its read access", async () => {
+ getChannel.mockResolvedValue({ id: "d1", type: "dm" })
+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "2026-06-30" })
+ getDMPeer.mockResolvedValue({ otherUserId: "u2" })
+ isBlocked.mockResolvedValue(false)
+ areFriends.mockResolvedValue(false)
+
+ const res = await requireMessageSurfaceCommunicationAccess(db, "d1", "u1")
+
+ expect(res).toEqual({ ok: false, status: 403, error: "accepted friendship required" })
+ })
+
+ it("leaves non-DM channel communication on the existing member gate", async () => {
+ getChannel.mockResolvedValue({ id: "c1", type: "text" })
+ getChannelForMember.mockResolvedValue({ id: "c1", type: "text", serverId: "s1" })
+
+ const res = await requireMessageSurfaceCommunicationAccess(db, "c1", "u1")
+
+ expect(res).toMatchObject({ ok: true, value: { surface: "channel" } })
+ expect(areFriends).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/lib/community/permissions.ts b/src/web/src/lib/community/permissions.ts
index a454f0b96..bfe54a6a9 100644
--- a/src/web/src/lib/community/permissions.ts
+++ b/src/web/src/lib/community/permissions.ts
@@ -164,6 +164,30 @@ export async function requireDMAccess(
})
}
+/**
+ * Verify the caller may continue communicating in this DM. History access and
+ * communication are deliberately separate contracts: `requireDMAccess` keeps
+ * an existing DM readable after an unfriend, while this gate additionally
+ * requires an accepted friendship (owner ↔ own-bot is implicit in
+ * `areFriends`). The access gate runs first so block remains the highest
+ * priority denial.
+ */
+export async function requireDMCommunicationAccess(
+ db: Database,
+ channelId: string,
+ userId: string,
+): Promise<Result<DMAccess>> {
+ const access = await requireDMAccess(db, channelId, userId)
+ if (!access.ok) return access
+ const accepted = await queries.communityFriendship.areFriends(
+ db,
+ userId,
+ access.value.otherUserId,
+ )
+ if (!accepted) return err(403, "accepted friendship required")
+ return access
+}
+
export type MessageSurfaceAccess =
| { surface: "dm"; dm: DMAccess }
| {
@@ -199,6 +223,21 @@ export async function requireMessageSurfaceAccess(
db: Database,
channelId: string,
userId: string,
+): Promise<Result<MessageSurfaceAccess>> {
+ return requireMessageSurfaceAccessWithDmGate(db, channelId, userId, requireDMAccess)
+}
+
+type DMGate = (
+ db: Database,
+ channelId: string,
+ userId: string,
+) => Promise<Result<DMAccess>>
+
+async function requireMessageSurfaceAccessWithDmGate(
+ db: Database,
+ channelId: string,
+ userId: string,
+ dmGate: DMGate,
): Promise<Result<MessageSurfaceAccess>> {
// One existence probe, reused for the type dispatch AND the channel-arm's
// 404 leg — so an unknown id is a single 404 on every surface.
@@ -213,7 +252,7 @@ export async function requireMessageSurfaceAccess(
// type→route judgement) and avoids seeding a literal type-switch the later
// forum/thread arms would copy into a parallel type tree.
if (visibilityIsDmParticipant(channel.type)) {
- const dm = await requireDMAccess(db, channelId, userId)
+ const dm = await dmGate(db, channelId, userId)
if (!dm.ok) {
// ④ opaque 404 (Aigneis #157): a 404 here and the top-level unknown-id
// 404 must be byte-identical in body, not just status — else a stranger
@@ -235,6 +274,24 @@ export async function requireMessageSurfaceAccess(
return ok({ surface: "channel", channel: member.value })
}
+/**
+ * Communication-write sibling of `requireMessageSurfaceAccess`. Non-DM
+ * channels retain their existing member gate; DMs use the stricter accepted-
+ * friendship gate while preserving the same opaque existence mask.
+ */
+export async function requireMessageSurfaceCommunicationAccess(
+ db: Database,
+ channelId: string,
+ userId: string,
+): Promise<Result<MessageSurfaceAccess>> {
+ return requireMessageSurfaceAccessWithDmGate(
+ db,
+ channelId,
+ userId,
+ requireDMCommunicationAccess,
+ )
+}
+
/**
* Verify neither user has blocked the other. Returns an error if blocked, ok
* otherwise. Kept exported for two non-DM callers where the participants
diff --git a/src/web/src/lib/community/reaction-access.test.ts b/src/web/src/lib/community/reaction-access.test.ts
index 93478938a..35c0304e0 100644
--- a/src/web/src/lib/community/reaction-access.test.ts
+++ b/src/web/src/lib/community/reaction-access.test.ts
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
const mockGetMessage = vi.fn()
const mockGetChannelType = vi.fn()
const mockRequireSurfaceAccess = vi.fn()
+const mockRequireCommunicationAccess = vi.fn()
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -23,6 +24,8 @@ vi.mock("@alook/shared", async () => {
})
vi.mock("@/lib/community/permissions", () => ({
requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireSurfaceAccess(...args),
+ requireMessageSurfaceCommunicationAccess: (...args: unknown[]) =>
+ mockRequireCommunicationAccess(...args),
}))
import { authorizeReaction } from "./reaction-access"
@@ -59,4 +62,18 @@ describe("authorizeReaction", () => {
error: "emoji reactions are not supported on this message surface",
})
})
+
+ it("uses communication access only when adding a reaction", async () => {
+ mockRequireCommunicationAccess.mockResolvedValue({
+ ok: false,
+ status: 403,
+ error: "accepted friendship required",
+ })
+
+ const result = await authorizeReaction({} as any, "m1", "member", "add")
+
+ expect(result).toEqual({ ok: false, status: 403, error: "accepted friendship required" })
+ expect(mockRequireCommunicationAccess).toHaveBeenCalledWith({}, "private-forum", "member")
+ expect(mockRequireSurfaceAccess).not.toHaveBeenCalled()
+ })
})
diff --git a/src/web/src/lib/community/reaction-access.ts b/src/web/src/lib/community/reaction-access.ts
index 8643ab947..5d55a3585 100644
--- a/src/web/src/lib/community/reaction-access.ts
+++ b/src/web/src/lib/community/reaction-access.ts
@@ -1,6 +1,9 @@
import { queries } from "@alook/shared"
import type { Database } from "@alook/shared"
-import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
+import {
+ requireMessageSurfaceAccess,
+ requireMessageSurfaceCommunicationAccess,
+} from "@/lib/community/permissions"
import { requireReactableSurface } from "@/lib/community/channel-write-guard"
type ReactionAccessScope =
@@ -20,6 +23,7 @@ export async function authorizeReaction(
db: Database,
messageId: string,
userId: string,
+ intent: "read-or-remove" | "add" = "read-or-remove",
): Promise<ReactionAccessResult> {
const message = await queries.communityMessage.getMessage(db, messageId)
if (!message) return { ok: false, status: 404, error: "message not found" }
@@ -27,7 +31,9 @@ export async function authorizeReaction(
// Preserve the existing surface-specific no-access contract before exposing
// whether this message's channel supports emoji. In particular, a private
// forum must remain 403 to a non-member rather than leaking its type via 400.
- const access = await requireMessageSurfaceAccess(db, message.channelId, userId)
+ const access = intent === "add"
+ ? await requireMessageSurfaceCommunicationAccess(db, message.channelId, userId)
+ : await requireMessageSurfaceAccess(db, message.channelId, userId)
if (!access.ok) return access
const channelType = await queries.communityChannel.getChannelType(db, message.channelId)
diff --git a/src/web/src/lib/community/reaction-operations.test.ts b/src/web/src/lib/community/reaction-operations.test.ts
index a1c47e775..b02244302 100644
--- a/src/web/src/lib/community/reaction-operations.test.ts
+++ b/src/web/src/lib/community/reaction-operations.test.ts
@@ -87,6 +87,28 @@ describe("reaction operations", () => {
expect(mockList).not.toHaveBeenCalled()
})
+ it("requires communication only for add while remove and list stay history-safe", async () => {
+ await setReactionForActor({} as any, {
+ messageId: "m1",
+ userId: "bot1",
+ emoji: "👍",
+ })
+ await removeReactionForActor({} as any, {
+ messageId: "m1",
+ userId: "bot1",
+ emoji: "👍",
+ })
+ mockList.mockResolvedValue([])
+ mockActors.mockResolvedValue([])
+ await listReactionsForActor({} as any, { messageId: "m1", userId: "bot1" })
+
+ expect(mockAuthorize.mock.calls.map((call) => call[3])).toEqual([
+ "add",
+ undefined,
+ undefined,
+ ])
+ })
+
it("treats a duplicate add as changed:false and emits no fanout", async () => {
const error = new Error("UNIQUE constraint failed")
mockAdd.mockRejectedValue(error)
diff --git a/src/web/src/lib/community/reaction-operations.ts b/src/web/src/lib/community/reaction-operations.ts
index 1c72292d7..5c0049f47 100644
--- a/src/web/src/lib/community/reaction-operations.ts
+++ b/src/web/src/lib/community/reaction-operations.ts
@@ -43,7 +43,7 @@ export async function setReactionForActor(
): Promise<OperationResult<{ emoji: string; changed: boolean; reaction?: unknown }>> {
const emoji = validateEmoji(input.emoji)
if (!emoji.ok) return emoji
- const access = await authorizeReaction(db, input.messageId, input.userId)
+ const access = await authorizeReaction(db, input.messageId, input.userId, "add")
if (!access.ok) return access
let reaction: unknown
diff --git a/src/web/src/lib/community/resolve-ref.test.ts b/src/web/src/lib/community/resolve-ref.test.ts
index 5371d2aad..798fe617e 100644
--- a/src/web/src/lib/community/resolve-ref.test.ts
+++ b/src/web/src/lib/community/resolve-ref.test.ts
@@ -58,6 +58,9 @@ const db = {} as never
describe("resolveTargetForMember", () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockGetDMBetween.mockResolvedValue(null)
+ mockIsBlocked.mockResolvedValue(false)
+ mockAreFriends.mockResolvedValue(true)
})
it("400 malformed channel ref for a ref not starting with /", async () => {
@@ -115,6 +118,23 @@ describe("resolveTargetForMember", () => {
expect(mockCreateOrGetDM).not.toHaveBeenCalled()
})
+ it("with createDmIfMissing: an existing DM defers communication policy to the shared message gate", async () => {
+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })
+ mockGetDMBetween.mockResolvedValue({ id: "dm_1" })
+
+ const res = await resolveTargetForMember(
+ db,
+ "u_1",
+ "/.dm/peer#0001",
+ { createDmIfMissing: true, callerKind: "bot" },
+ )
+
+ expect(res).toEqual({ kind: "dm", channelId: "dm_1", otherUserId: "peer_1" })
+ expect(mockGetUserInternal).not.toHaveBeenCalled()
+ expect(mockAreFriends).not.toHaveBeenCalled()
+ expect(mockCreateOrGetDM).not.toHaveBeenCalled()
+ })
+
it("with createDmIfMissing: creates/gets the DM when guard passes", async () => {
mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })
mockGetUserInternal.mockResolvedValue({ id: "peer_1", deletedAt: null })
diff --git a/src/web/src/lib/community/resolve-ref.ts b/src/web/src/lib/community/resolve-ref.ts
index dfde97c2a..58243799c 100644
--- a/src/web/src/lib/community/resolve-ref.ts
+++ b/src/web/src/lib/community/resolve-ref.ts
@@ -76,15 +76,13 @@ export async function resolveTargetForMember(
}
const peerId = peer.id
- if (opts?.createDmIfMissing) {
- const guard = await guardDmOpen(db, userId, peerId, { callerKind: opts.callerKind })
- if (!guard.ok) return { error: guard.status, message: guard.error }
- const dm = await queries.communityDm.createOrGetDM(db, { userId1: userId, userId2: peerId })
- return { kind: "dm", channelId: dm.id, otherUserId: peerId }
- }
+ const existing = await queries.communityDm.getDMBetween(db, userId, peerId)
+ if (existing) return { kind: "dm", channelId: existing.id, otherUserId: peerId }
+ if (!opts?.createDmIfMissing) return { error: 404, message: "dm not found" }
- const dm = await queries.communityDm.getDMBetween(db, userId, peerId)
- if (!dm) return { error: 404, message: "dm not found" }
+ const guard = await guardDmOpen(db, userId, peerId, { callerKind: opts.callerKind })
+ if (!guard.ok) return { error: guard.status, message: guard.error }
+ const dm = await queries.communityDm.createOrGetDM(db, { userId1: userId, userId2: peerId })
return { kind: "dm", channelId: dm.id, otherUserId: peerId }
}
diff --git a/src/web/src/lib/community/upload.test.ts b/src/web/src/lib/community/upload.test.ts
index 19bc892ac..e0b415191 100644
--- a/src/web/src/lib/community/upload.test.ts
+++ b/src/web/src/lib/community/upload.test.ts
@@ -12,8 +12,11 @@ vi.mock("@/lib/middleware/helpers", () => {
}
})
-const mockGetDb = vi.fn(() => ({ __db: true }))
-vi.mock("@/lib/db", () => ({ getDb: (...a: unknown[]) => mockGetDb(...a) }))
+const primaryDb = { __db: "primary" }
+const mockGetPrimaryDb = vi.fn(() => primaryDb)
+vi.mock("@/lib/db", () => ({
+ getPrimaryDb: (...a: unknown[]) => mockGetPrimaryDb(...a),
+}))
const mockGetChannelType = vi.fn()
const mockCreatePendingAttachment = vi.fn()
@@ -38,11 +41,12 @@ vi.mock("@alook/shared", async () => {
})
// runAttachmentUpload now owns access + surface dispatch via
-// requireMessageSurfaceAccess (kind is DERIVED from its returned surface +
+// requireMessageSurfaceCommunicationAccess (kind is DERIVED from its returned surface +
// channel.type, no separate getChannelType re-query). Mock it to drive each arm.
-const mockRequireMessageSurfaceAccess = vi.fn()
+const mockRequireMessageSurfaceCommunicationAccess = vi.fn()
vi.mock("./permissions", () => ({
- requireMessageSurfaceAccess: (...a: unknown[]) => mockRequireMessageSurfaceAccess(...a),
+ requireMessageSurfaceCommunicationAccess: (...a: unknown[]) =>
+ mockRequireMessageSurfaceCommunicationAccess(...a),
}))
import {
@@ -650,13 +654,13 @@ describe("runAttachmentUpload", () => {
// Drive the surface dispatch: `surface="dm"` or `surface="channel"` with a
// channel row carrying `.type`. kind is DERIVED from these (no getChannelType).
function surfaceChannel(type: string) {
- mockRequireMessageSurfaceAccess.mockResolvedValue({
+ mockRequireMessageSurfaceCommunicationAccess.mockResolvedValue({
ok: true,
value: { surface: "channel", channel: { id: "c1", type } },
})
}
function surfaceDm() {
- mockRequireMessageSurfaceAccess.mockResolvedValue({
+ mockRequireMessageSurfaceCommunicationAccess.mockResolvedValue({
ok: true,
value: { surface: "dm", dm: { id: "d1" } },
})
@@ -669,13 +673,13 @@ describe("runAttachmentUpload", () => {
ctxWith(envWithR2(put), undefined),
)
expect(res.status).toBe(400)
- expect(mockRequireMessageSurfaceAccess).not.toHaveBeenCalled()
+ expect(mockRequireMessageSurfaceCommunicationAccess).not.toHaveBeenCalled()
expect(put).not.toHaveBeenCalled()
})
it("forwards surface-access failures with the reported status + error", async () => {
const put = vi.fn()
- mockRequireMessageSurfaceAccess.mockResolvedValue({ ok: false, status: 403, error: "forbidden" })
+ mockRequireMessageSurfaceCommunicationAccess.mockResolvedValue({ ok: false, status: 403, error: "forbidden" })
const res = await runAttachmentUpload(
reqWithFile(fakeFile("hi.png", "image/png", 10)),
ctxWith(envWithR2(put), { id: "c1" }),
@@ -683,6 +687,12 @@ describe("runAttachmentUpload", () => {
expect(res.status).toBe(403)
const body = (await res.json()) as { error: string }
expect(body.error).toBe("forbidden")
+ expect(mockGetPrimaryDb).toHaveBeenCalledOnce()
+ expect(mockRequireMessageSurfaceCommunicationAccess).toHaveBeenCalledWith(
+ primaryDb,
+ "c1",
+ "u1",
+ )
expect(put).not.toHaveBeenCalled()
})
@@ -714,7 +724,7 @@ describe("runAttachmentUpload", () => {
expect(body.url).toBeUndefined()
// Pending row created with the credential uploaderId + resolved target.
expect(mockCreatePendingAttachment).toHaveBeenCalledWith(
- { __db: true },
+ primaryDb,
expect.objectContaining({ uploaderId: "u1", targetId: "c1" }),
)
expect(put).toHaveBeenCalledOnce()
@@ -756,7 +766,7 @@ describe("runAttachmentUpload", () => {
expect(body.width).toBe(1920)
expect(body.height).toBe(1080)
expect(mockCreatePendingAttachment).toHaveBeenCalledWith(
- { __db: true },
+ primaryDb,
expect.objectContaining({ width: 1920, height: 1080 }),
)
})
diff --git a/src/web/src/lib/community/upload.ts b/src/web/src/lib/community/upload.ts
index 8e55454a9..cb8ab5224 100644
--- a/src/web/src/lib/community/upload.ts
+++ b/src/web/src/lib/community/upload.ts
@@ -10,9 +10,9 @@ import {
} from "@alook/shared"
import { requireMessageBearingSurface, requireChildSurface } from "./channel-write-guard"
import { isThread } from "@alook/shared"
-import { requireMessageSurfaceAccess } from "./permissions"
+import { requireMessageSurfaceCommunicationAccess } from "./permissions"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
-import { getDb } from "@/lib/db"
+import { getPrimaryDb } from "@/lib/db"
import type { AuthContext } from "@/lib/middleware/auth"
import { isInlineAttachmentContentType } from "./attachment-content-type"
import { communityMediaCleanupErrorCategory } from "./community-media-cleanup"
@@ -470,9 +470,9 @@ export function handleBotAvatarUpload(
* collapsed onto this one; the DM/thread routes are now deleted and the web
* client uploads through `channels/[id]/upload` for every surface.
*
- * Access + surface come from `requireMessageSurfaceAccess` (the same dispatch
- * the read/read-state routes use), so a DM id runs `requireDMAccess` (block
- * gate) — closing the incidental P0 the trunk covers.
+ * Access + surface come from `requireMessageSurfaceCommunicationAccess`, so a
+ * DM id requires both participant access and an accepted friendship before any
+ * R2 object or pending attachment row is written.
*
* `kind` (which feeds `buildMediaKey` → the R2 key path, so its VALUE is
* load-bearing, not just its guard) is DERIVED from `(surface, channel.type)`
@@ -495,12 +495,14 @@ export async function runAttachmentUpload(
const id = ctx.params?.id
if (!id) return writeError("missing channel id", 400)
- const db = getDb(ctx.env.DB)
- const auth = await requireMessageSurfaceAccess(db, id, ctx.userId)
+ // This authorization is read-before-write. Use the primary so an immediately
+ // preceding unfriend/block cannot be hidden by replica lag.
+ const db = getPrimaryDb(ctx.env.DB)
+ const auth = await requireMessageSurfaceCommunicationAccess(db, id, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
// Derive kind + apply the per-surface guard from the dispatch's return — no
- // re-query. The DM arm needs no surface guard (a DM is a valid target).
+ // re-query. The DM arm already passed its communication gate.
let kind: AttachmentKind
if (auth.value.surface === "dm") {
kind = "dm"
diff --git a/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts b/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts
index 1396d1e89..9d476fbc9 100644
--- a/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts
+++ b/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts
@@ -9,6 +9,7 @@ import {
seedMessage,
seedDm,
seedDmMessage,
+ seedRemoveFriendship,
} from "./_fixtures/seed"
// Journey 14 — forum-post notify scope, per-post tags, post-card participant
@@ -108,14 +109,15 @@ test.describe.serial("DM presence stability on refresh", () => {
let dmId: string
test.beforeAll(async () => {
- // Server + join makes Alice and Bob co-members (they are NOT friends —
- // that's the exact shape that reproduced the flicker). The server's default
- // channel is enough; no extra channel needed.
+ // Server + join makes Alice and Bob co-members. Create the DM and its
+ // history while accepted, then remove the friendship: co-members but NOT
+ // friends is the exact shape that reproduced the flicker.
serverId = await seedServer("alice", `Presence ${Date.now()}`)
await seedJoinServer("alice", "bob", serverId)
dmId = await seedDm("alice", userId("bob"))
// A message so the DM row is populated in Bob's sidebar.
await seedDmMessage("alice", dmId, "hi")
+ await seedRemoveFriendship("alice", userId("bob"))
})
test("peer stays online after the viewer refreshes the DM view", async ({ asUser }) => {
diff --git a/src/web/src/test/e2e-ui/_fixtures/seed.ts b/src/web/src/test/e2e-ui/_fixtures/seed.ts
index 8e51bbd6f..a01083bd6 100644
--- a/src/web/src/test/e2e-ui/_fixtures/seed.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/seed.ts
@@ -2,6 +2,7 @@ import { WEB_URL } from "../_setup/paths"
import { sessionCookie, userId } from "./community-fixture"
import type { UserKey } from "../_setup/users"
import { isRetryableSeedStatus, retrySeedRequest, seedRetryDelayMs } from "./seed-retry"
+import { manifest } from "./manifest"
// API-driven precondition seeding for the Playwright specs. Deliberately does
// NOT import @alook/test-utils (that barrel pulls in better-sqlite3 +
@@ -95,6 +96,16 @@ export async function seedChannelMember(owner: UserKey, channelId: string, userI
}
export async function seedDm(from: UserKey, targetUserId: string): Promise<string> {
+ const addressee = (Object.entries(manifest().users) as Array<[
+ UserKey,
+ { userId: string },
+ ]>).find(([, user]) => user.userId === targetUserId)?.[0]
+ if (!addressee) throw new Error(`seedDm: unknown fixture user ${targetUserId}`)
+
+ // A normal DM fixture models an accepted conversation. Tests that need
+ // non-friend history must create the DM/message first, then remove the
+ // friendship; creating a non-friend DM is no longer a valid precondition.
+ await seedFriendship(from, addressee, targetUserId)
const res = await post(from, "/api/community/channels", { type: "dm", userId: targetUserId })
const data = (await res.json()) as { conversation: { id: string } }
return data.conversation.id
@@ -116,9 +127,10 @@ export async function seedBlock(blocker: UserKey, targetUserId: string): Promise
// user, from the requester's friends list. Used to recover idempotently when a
// re-run (Playwright retry) finds the pair already friends.
async function findFriendshipId(requester: UserKey, targetUserId: string): Promise<string | undefined> {
- const res = await fetch(`${WEB_URL}/api/community/friends/accepted`, {
- headers: { Cookie: sessionCookie(requester), Origin: WEB_URL },
- })
+ const res = await retrySeedRequest(() => fetch(
+ `${WEB_URL}/api/community/friends/accepted`,
+ { headers: { Cookie: sessionCookie(requester), Origin: WEB_URL } },
+ ))
if (!res.ok) return undefined
const data = (await res.json()) as { friends: Array<{ id: string; userId: string }> }
return data.friends.find((f) => f.userId === targetUserId)?.id
@@ -154,6 +166,41 @@ async function deleteSeedRelationship(key: UserKey, id: string): Promise<Respons
}))
}
+// Remove an accepted friendship while preserving any existing DM and history.
+// Use after seedDm/seedDmMessage when a spec needs the post-unfriend read-only
+// state; creating a DM directly as non-friends is no longer a valid fixture.
+export async function seedRemoveFriendship(
+ requester: UserKey,
+ targetUserId: string,
+): Promise<void> {
+ const friendshipId = await findFriendshipId(requester, targetUserId)
+ if (!friendshipId) throw new Error("seedRemoveFriendship: accepted friendship not found")
+ const response = await deleteSeedRelationship(requester, friendshipId)
+ if (!response.ok) throw new Error(`seedRemoveFriendship failed (${response.status})`)
+}
+
+async function acceptSeedFriendship(
+ requester: UserKey,
+ addressee: UserKey,
+ targetUserId: string,
+ pending: SeedRelationship,
+): Promise<string> {
+ const accepter = pending.kind === "outgoing" ? addressee : requester
+ const response = await retrySeedRequest(() => postRaw(
+ accepter,
+ `/api/community/friends/${pending.id}/accept`,
+ ))
+ if (response.ok) return pending.id
+ // Parallel fixtures may both observe the same pending row; one wins the
+ // accept while the other receives a terminal-state response. Confirm the
+ // accepted state instead of treating that harmless race as a seed failure.
+ if (response.status === 400 || response.status === 409) {
+ const existing = await findFriendshipId(requester, targetUserId)
+ if (existing) return existing
+ }
+ throw new Error(`seedFriendship accept failed (${response.status})`)
+}
+
// Normalize a human-to-human pair to one actionable pending request. This uses
// only the public HTTP routes and is repeatable after an earlier E2E spec (or a
// Playwright retry) left the pair accepted, blocked, or pending in either
@@ -207,6 +254,19 @@ export async function seedCancelFriendRequest(requester: UserKey, friendshipId:
// Playwright retry: if the pair is already friends the request 409s, so we
// recover the existing friendship id and skip the accept.
export async function seedFriendship(requester: UserKey, addressee: UserKey, targetUserId: string): Promise<string> {
+ await Promise.all([
+ post(requester, `/api/community/users/${targetUserId}/unblock`),
+ post(addressee, `/api/community/users/${userId(requester)}/unblock`),
+ ])
+
+ const relationships = await listSeedRelationships(requester)
+ const accepted = relationships.accepted.find((row) => row.userId === targetUserId)
+ if (accepted) return accepted.id
+ const pending = relationships.pending.find((row) => row.userId === targetUserId)
+ if (pending) {
+ return acceptSeedFriendship(requester, addressee, targetUserId, pending)
+ }
+
let reqRes: Response | undefined
for (let attempt = 0; attempt < 3; attempt++) {
const response = await postRaw(requester, "/api/community/friends/request", { userId: targetUserId })
@@ -218,14 +278,20 @@ export async function seedFriendship(requester: UserKey, addressee: UserKey, tar
if (reqRes!.status === 409) {
const existing = await findFriendshipId(requester, targetUserId)
if (existing) return existing
- throw new Error("seedFriendship: 409 but no existing friendship found")
+ const refreshed = await listSeedRelationships(requester)
+ const pending = refreshed.pending.find((row) => row.userId === targetUserId)
+ if (pending) return acceptSeedFriendship(requester, addressee, targetUserId, pending)
+ throw new Error("seedFriendship: 409 but no accepted or pending friendship found")
}
if (!reqRes!.ok) throw new Error(`seedFriendship request failed (${reqRes!.status})`)
const reqData = (await reqRes!.json()) as { id?: string; friendship?: { id: string } | null }
const friendshipId = reqData.id ?? reqData.friendship?.id
if (!friendshipId) throw new Error("seedFriendship: no friendship id in response")
- await post(addressee, `/api/community/friends/${friendshipId}/accept`)
- return friendshipId
+ return acceptSeedFriendship(requester, addressee, targetUserId, {
+ id: friendshipId,
+ userId: targetUserId,
+ kind: "outgoing",
+ })
}
// Post a message into a channel via API (persisted with a real server id).
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 8507ff94d..a4990de3a 100644
--- a/src/ws-do/src/ws-durable/machine-telemetry.test.ts
+++ b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
@@ -16,6 +16,9 @@ import {
mockGetChannelType,
mockGetCoMemberUserIds,
mockGetDM,
+ mockGetDMPeer,
+ mockIsBlocked,
+ mockAreFriends,
mockGetFriendUserIds,
mockGetLatestTokenForUser,
mockGetMachineByDaemon,
@@ -683,6 +686,9 @@ describe("WebSocketDurableObject", () => {
mockGetChannelForMember.mockReset()
mockGetChannelType.mockReset()
mockGetChannelType.mockResolvedValue("dm")
+ mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })
+ mockIsBlocked.mockResolvedValue(false)
+ mockAreFriends.mockResolvedValue(true)
mockListChannelMemberUserIds.mockReset()
mockListChannelMemberUserIds.mockResolvedValue([])
mockStubFetch.mockClear()
@@ -702,7 +708,7 @@ describe("WebSocketDurableObject", () => {
name: "Bot",
discriminator: "0007",
})
- mockGetChannelForMember.mockResolvedValue({ id: "dm_1", serverId: null })
+ mockGetChannelForMember.mockResolvedValue({ id: "dm_1", serverId: null, type: "dm" })
mockGetChannelType.mockResolvedValue("dm")
mockListChannelMemberUserIds.mockResolvedValue(["bot_1", "peer_1"])
@@ -858,7 +864,7 @@ describe("WebSocketDurableObject", () => {
name: "Bot",
discriminator: "0007",
})
- mockGetChannelForMember.mockResolvedValue({ id: "dm_1", serverId: null })
+ mockGetChannelForMember.mockResolvedValue({ id: "dm_1", serverId: null, type: "dm" })
mockGetChannelType.mockResolvedValue("dm")
mockListChannelMemberUserIds.mockResolvedValue(["bot_1", "peer_1"])
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 1dbfddff9..8b820599b 100644
--- a/src/ws-do/src/ws-durable/presence-typing.test.ts
+++ b/src/ws-do/src/ws-durable/presence-typing.test.ts
@@ -9,6 +9,7 @@ import {
flushAsyncWork,
mockCheckAliveFetch,
mockCreateDb,
+ mockD1WithSession,
mockFindCredentialByHash,
mockGetBotBinding,
mockGetBotBindingWithOwner,
@@ -16,6 +17,9 @@ import {
mockGetChannelType,
mockGetCoMemberUserIds,
mockGetDM,
+ mockGetDMPeer,
+ mockIsBlocked,
+ mockAreFriends,
mockGetFriendUserIds,
mockGetLatestTokenForUser,
mockGetMachineByDaemon,
@@ -821,9 +825,10 @@ describe("WebSocketDurableObject", () => {
it("fans out to the other participant when sender IS a DM participant", async () => {
const { durable, env } = createDO()
- mockGetChannelForMember.mockResolvedValueOnce({ id: "dm-1", serverId: null })
+ mockGetChannelForMember.mockResolvedValueOnce({ id: "dm-1", serverId: null, type: "dm" })
mockGetChannelType.mockResolvedValueOnce("dm")
mockListChannelMemberUserIds.mockResolvedValueOnce(["alice", "bob"])
+ mockGetDMPeer.mockResolvedValueOnce({ otherUserId: "bob" })
const ws = createMockWebSocket()
ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true })
@@ -839,6 +844,52 @@ describe("WebSocketDurableObject", () => {
expect(mockStubFetch).toHaveBeenCalledTimes(1)
})
+ it("does not fan out DM typing start or stop after unfriend", async () => {
+ const { durable, env } = createDO()
+ mockGetChannelForMember.mockResolvedValue({ id: "dm-1", serverId: null, type: "dm" })
+ mockGetDMPeer.mockResolvedValue({ otherUserId: "bob" })
+ mockIsBlocked.mockResolvedValue(false)
+ mockAreFriends.mockResolvedValue(false)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "dm-1" }),
+ )
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.stop", channelId: "dm-1" }),
+ )
+ await flushAsyncWork()
+
+ expect(mockD1WithSession).toHaveBeenCalledWith("first-primary")
+ expect(mockAreFriends).toHaveBeenCalledWith(expect.anything(), "alice", "bob")
+ expect(mockResolveChannelRecipientUserIds).not.toHaveBeenCalled()
+ expect((env.WS_DO as any).get).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("keeps block above accepted friendship for DM typing", async () => {
+ const { durable } = createDO()
+ mockGetChannelForMember.mockResolvedValue({ id: "dm-1", serverId: null, type: "dm" })
+ mockGetDMPeer.mockResolvedValue({ otherUserId: "bob" })
+ mockIsBlocked.mockResolvedValue(true)
+ mockAreFriends.mockResolvedValue(true)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true })
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "dm-1" }),
+ )
+ await flushAsyncWork()
+
+ expect(mockAreFriends).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
it("keeps membership retry separate while recipient retry re-runs the complete shared resolver", async () => {
const { durable } = createDO()
mockGetChannelForMember.mockResolvedValue({ id: "chan-1", serverId: "server-1" })
@@ -862,6 +913,7 @@ describe("WebSocketDurableObject", () => {
expect(mockResolveChannelRecipientUserIds).toHaveBeenCalledTimes(2)
expect(mockWithD1Retry.mock.calls.map((call) => (call[1] as { route?: string }).route)).toEqual([
"ws-do:agent-typing-membership",
+ "ws-do:agent-typing-communication",
"ws-do:agent-typing-recipients",
])
const request = mockStubFetch.mock.calls[0]![0] as Request
diff --git a/src/ws-do/src/ws-durable/presence-typing.ts b/src/ws-do/src/ws-durable/presence-typing.ts
index 6a9073c04..9079b1624 100644
--- a/src/ws-do/src/ws-durable/presence-typing.ts
+++ b/src/ws-do/src/ws-durable/presence-typing.ts
@@ -5,6 +5,8 @@ import {
WS_EVENTS,
encodeCommunityBrowserEvent,
isCommunityEventCandidate,
+ visibilityIsDmParticipant,
+ type Database,
} from "@alook/shared"
import type { UserConnectionState, WsDurableContext } from "./internal"
import { createInternalBrowserBroadcastRequest } from "../internal-user-broadcast"
@@ -26,6 +28,29 @@ function normalizeBrowserPayload(
return { ok: true, payload: normalized.event }
}
+function createPrimaryDb(d1: D1Database): Database {
+ const session = d1.withSession("first-primary")
+ return createDb(session as unknown as Parameters<typeof createDb>[0])
+}
+
+async function canCommunicateInTypingScope(
+ db: Database,
+ channelType: string,
+ channelId: string,
+ senderUserId: string,
+): Promise<boolean> {
+ if (!visibilityIsDmParticipant(channelType)) return true
+ const peer = await queries.communityDm.getDMPeer(db, channelId, senderUserId)
+ if (!peer) return false
+ const blocked = await queries.communityFriendship.isBlocked(
+ db,
+ senderUserId,
+ peer.otherUserId,
+ )
+ if (blocked) return false
+ return queries.communityFriendship.areFriends(db, senderUserId, peer.otherUserId)
+}
+
async function serializeTypingFanOut(
context: WsDurableContext,
userId: string,
@@ -170,7 +195,9 @@ export async function fanOutTyping(
const normalized = normalizeBrowserPayload(context, event)
if (!normalized.ok) return
const outboundEvent = normalized.payload
- const db = createDb(context.env.DB)
+ // Typing is a communication write. Membership, block, and friendship reads
+ // must observe the primary immediately after an unfriend/block.
+ const db = createPrimaryDb(context.env.DB)
let recipientUserIds: string[] = []
const membership = await withD1Retry(
@@ -181,6 +208,11 @@ export async function fanOutTyping(
context.log.warn("fanOutTyping: sender not a channel member", { senderUserId, channelId })
return
}
+ const mayCommunicate = await withD1Retry(
+ () => canCommunicateInTypingScope(db, membership.type, channelId, senderUserId),
+ { route: "ws-do:agent-typing-communication" },
+ )
+ if (!mayCommunicate) return
recipientUserIds = await withD1Retry(
() => queries.communityMembersResolver.resolveChannelContentRecipientUserIds(db, channelId),
{ route: "ws-do:agent-typing-recipients" },
@@ -207,7 +239,7 @@ export async function fanOutTypingStop(
senderUserId: string,
channelId: string,
): Promise<void> {
- const db = createDb(context.env.DB)
+ const db = createPrimaryDb(context.env.DB)
const membership = await withD1Retry(
() => queries.communityChannel.getChannelForMember(db, channelId, senderUserId),
{ route: "ws-do:agent-typing-stop-membership" },
@@ -216,6 +248,11 @@ export async function fanOutTypingStop(
context.log.warn("fanOutTypingStop: sender not a channel member", { senderUserId, channelId })
return
}
+ const mayCommunicate = await withD1Retry(
+ () => canCommunicateInTypingScope(db, membership.type, channelId, senderUserId),
+ { route: "ws-do:agent-typing-stop-communication" },
+ )
+ if (!mayCommunicate) return
let recipientUserIds = await withD1Retry(
() => queries.communityMembersResolver.resolveChannelContentRecipientUserIds(db, channelId),
{ route: "ws-do:agent-typing-stop-recipients" },
diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.ts
index 0205e540a..a9867dbe6 100644
--- a/src/ws-do/src/ws-durable/test-harness.ts
+++ b/src/ws-do/src/ws-durable/test-harness.ts
@@ -116,6 +116,9 @@ async function resolveChannelContentRecipientUserIdsMock(db: unknown, channelId:
export const mockResolveChannelRecipientUserIds = vi.fn(resolveChannelContentRecipientUserIdsMock)
export const mockWithD1Retry = vi.fn(async <T>(fn: () => Promise<T>, _opts?: unknown): Promise<T> => fn())
export const mockGetDM = vi.fn()
+export const mockGetDMPeer = vi.fn()
+export const mockIsBlocked = vi.fn()
+export const mockAreFriends = vi.fn()
export const mockListMembers = vi.fn()
export const mockListBotsForMachine = vi.fn<(db: unknown, machineId: string) => Promise<Array<{ id: string; name: string; discriminator: string; description: string }>>>().mockResolvedValue([])
export const mockIsBotOnline = vi.fn<(db: unknown, botUserId: string) => Promise<boolean>>().mockResolvedValue(false)
@@ -140,6 +143,7 @@ export const mockReconcileBotActivityFromRunningAgents = vi
const mockD1Prepare = vi.fn((sql: string) => ({
bind: (...values: unknown[]) => ({ sql, values }),
}))
+export const mockD1WithSession = vi.fn().mockReturnValue({})
export const mockD1Batch = vi.fn(async (statements: unknown[]) =>
statements.map(() => ({ success: true, meta: { changes: 1 } })))
export const mockGetUserInternal = vi.fn<(db: unknown, id: string) => Promise<{ isBot: boolean; ownerUserId: string | null } | null>>().mockResolvedValue(null)
@@ -443,6 +447,8 @@ vi.mock("@alook/shared", async () => {
},
communityFriendship: {
getFriendUserIds: (...a: [unknown, string]) => mockGetFriendUserIds(...a),
+ isBlocked: (...a: any[]) => mockIsBlocked(...a),
+ areFriends: (...a: any[]) => mockAreFriends(...a),
},
communityChannel: {
listReadableChannelsForUser: (...a: unknown[]) => mockListReadableChannelsForUser(...a),
@@ -463,6 +469,7 @@ vi.mock("@alook/shared", async () => {
},
communityDm: {
getDM: (...a: any[]) => mockGetDM(...a),
+ getDMPeer: (...a: any[]) => mockGetDMPeer(...a),
},
communityBot: {
listBotsForMachine: (...a: [unknown, string]) => mockListBotsForMachine(...a),
@@ -508,6 +515,7 @@ export function createDO() {
DB: {
prepare: (sql: string) => mockD1Prepare(sql),
batch: (statements: unknown[]) => mockD1Batch(statements),
+ withSession: (constraint: string) => mockD1WithSession(constraint),
} as unknown as D1Database,
WS_DO: {
idFromName: vi.fn().mockReturnValue("mock-do-id"),
@@ -525,6 +533,7 @@ export const flushAsyncWork = async () => {
}
export function resetHarness() {
vi.clearAllMocks()
+ mockD1WithSession.mockReturnValue({})
mockAssertMachineCapacity.mockReset().mockResolvedValue(undefined)
mockGetMachineByIdForUser.mockResolvedValue({ id: "cm_1", status: "online", availableRuntimes: [] })
mockListReadableChannelsForUser.mockImplementation(async (_db, _userId, ids: string[]) => ids.map((id) => ({ id, serverId: null, parentChannelId: null })))
@@ -544,6 +553,9 @@ export function resetHarness() {
mockGetChannelType.mockResolvedValue("text")
mockListThreadParticipantUserIds.mockResolvedValue([])
mockListChannelMemberUserIds.mockResolvedValue([])
+ mockGetDMPeer.mockResolvedValue(null)
+ mockIsBlocked.mockResolvedValue(false)
+ mockAreFriends.mockResolvedValue(true)
mockResolveScopeMemberUserIds.mockResolvedValue([])
mockResolveChannelRecipientUserIds.mockImplementation(resolveChannelContentRecipientUserIdsMock)
mockWithD1Retry.mockImplementation(async <T>(fn: () => Promise<T>, _opts?: unknown): Promise<T> => fn())