Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): type-aware channel write validation

Gener9a54775a62e6
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index cf11c79ee..3df362cf4 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -580,6 +580,7 @@ export {
isForumPost,
isThread,
isDm,
+ isMessageBearingSurface,
ROLES,
ASSIGNABLE_ROLES,
CHANNEL_TYPES,
diff --git a/src/shared/src/utils/community-roles.test.ts b/src/shared/src/utils/community-roles.test.ts
new file mode 100644
index 000000000..257bf5c8c
--- /dev/null
+++ b/src/shared/src/utils/community-roles.test.ts
@@ -0,0 +1,31 @@
+import { describe, it, expect } from "vitest"
+import { isMessageBearingSurface, isChannelType } from "./community-roles"
+
+describe("isMessageBearingSurface", () => {
+ it("is true for surfaces that bear messages: text, forum_post, thread, dm", () => {
+ expect(isMessageBearingSurface("text")).toBe(true)
+ expect(isMessageBearingSurface("forum_post")).toBe(true)
+ expect(isMessageBearingSurface("thread")).toBe(true)
+ expect(isMessageBearingSurface("dm")).toBe(true)
+ })
+
+ it("is false for a forum top-level (a post index, not a message surface)", () => {
+ expect(isMessageBearingSurface("forum")).toBe(false)
+ })
+
+ it("is false for null/undefined/unknown", () => {
+ expect(isMessageBearingSurface(null)).toBe(false)
+ expect(isMessageBearingSurface(undefined)).toBe(false)
+ expect(isMessageBearingSurface("bogus")).toBe(false)
+ })
+})
+
+describe("isChannelType (creatable top-level types)", () => {
+ it("accepts only text and forum", () => {
+ expect(isChannelType("text")).toBe(true)
+ expect(isChannelType("forum")).toBe(true)
+ expect(isChannelType("forum_post")).toBe(false)
+ expect(isChannelType("thread")).toBe(false)
+ expect(isChannelType("dm")).toBe(false)
+ })
+})
diff --git a/src/shared/src/utils/community-roles.ts b/src/shared/src/utils/community-roles.ts
index dc58d5521..a69f01693 100644
--- a/src/shared/src/utils/community-roles.ts
+++ b/src/shared/src/utils/community-roles.ts
@@ -74,3 +74,7 @@ export function isThread(t: string | null | undefined): boolean {
export function isDm(t: string | null | undefined): boolean {
return t === "dm"
}
+
+export function isMessageBearingSurface(t: string | null | undefined): boolean {
+ return t === "text" || t === "forum_post" || t === "thread" || t === "dm"
+}
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 508dfc5a2..15d1986ad 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
@@ -2,7 +2,7 @@ import { NextRequest } from "next/server"
import { withAuth } from "@/lib/middleware/auth"
import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { queries, WS_EVENTS } from "@alook/shared"
+import { queries, WS_EVENTS, isThread, isForumPost } from "@alook/shared"
import { broadcastToUserSafe } from "@/lib/community/fanout"
import { logAudit } from "@/lib/community/audit"
import { requireChannelAccess } from "@/lib/community/permissions"
@@ -26,6 +26,9 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
if (!access.ok) return writeError(access.error, access.status)
const channel = access.value.channel
+ if (isThread(channel.type) || isForumPost(channel.type) || channel.parentMessageId) {
+ return writeError("threads and forum posts inherit their parent's members — remove participants instead", 400)
+ }
if (channel.creatorId === targetUserId) {
// Covers both "creator can't be removed" and "creator can't leave".
return writeError("can't remove the channel creator", 400)
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 c8a20f985..4ccb88eaa 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
@@ -133,7 +133,7 @@ const ctx = { params: { id: "c1" } } as any
describe("POST /api/community/channels/[id]/messages", () => {
beforeEach(() => {
vi.clearAllMocks()
- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" })
mockCreateMessage.mockResolvedValue({ id: "m1" })
// Human author by default — `createCommunityMessage`'s bot-authored audit
// (plan §10) only fires when `isBot === true`, which none of these tests exercise.
@@ -164,6 +164,20 @@ describe("POST /api/community/channels/[id]/messages", () => {
mockCheckMessageRateLimit.mockResolvedValue({ allowed: true })
})
+ it("rejects a bare message to a forum top-level with 400 (not a message-bearing surface)", async () => {
+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum" })
+ const res = await POST(postReq({ content: "bare into forum index" }), ctx)
+ expect(res.status).toBe(400)
+ expect(mockCreateMessage).not.toHaveBeenCalled()
+ })
+
+ it("rejects a message to a DM channel id via the generic channel route with 400 (block-bypass guard)", async () => {
+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: null, type: "dm" })
+ const res = await POST(postReq({ content: "sneaking past block" }), ctx)
+ expect(res.status).toBe(400)
+ expect(mockCreateMessage).not.toHaveBeenCalled()
+ })
+
it("returns 429 with Retry-After when the sender is rate limited", async () => {
mockCheckMessageRateLimit.mockResolvedValue({ allowed: false, retryAfterSec: 7 })
@@ -280,6 +294,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
mockGetChannelForMember.mockResolvedValue({
id: "c1",
serverId: "s1",
+ type: "thread",
parentChannelId: "c-parent",
})
mockGetChannel.mockResolvedValue({
@@ -310,6 +325,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
mockGetChannelForMember.mockResolvedValue({
id: "c1",
serverId: "s1",
+ type: "text",
parentChannelId: null,
})
@@ -340,7 +356,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
describe("GET /api/community/channels/[id]/messages", () => {
beforeEach(() => {
vi.clearAllMocks()
- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" })
mockListChildChannels.mockResolvedValue([])
mockListByMessageIds.mockResolvedValue([])
mockListReactionsByMessageIds.mockResolvedValue([])
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 678f6f620..7fe46c1df 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
@@ -13,6 +13,7 @@ import {
} from "@/lib/community/messages"
import { enrichMessages } from "@/lib/community/enrich-messages"
import { requireChannelMember } from "@/lib/community/permissions"
+import { requireMessageBearingSurface } from "@/lib/community/channel-write-guard"
import { checkRateLimit } from "@/lib/rate-limit"
import { createCommunityMessage } from "@/lib/community/message-handler"
@@ -90,6 +91,9 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
if (!auth.ok) return writeError(auth.error, auth.status)
const channel = auth.value
+ const bearing = requireMessageBearingSurface(channel.type)
+ if (!bearing.ok) return writeError(bearing.error, bearing.status)
+
const rateLimit = await checkRateLimit(ctx.env, "community:msgSend", ctx.userId)
if (!rateLimit.allowed) {
return writeError("rate limited", 429, { "Retry-After": String(rateLimit.retryAfterSec) })
diff --git a/src/web/src/app/api/community/messages/[id]/threads/route.test.ts b/src/web/src/app/api/community/messages/[id]/threads/route.test.ts
index 2fe1a1353..7b778bf37 100644
--- a/src/web/src/app/api/community/messages/[id]/threads/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/threads/route.test.ts
@@ -82,6 +82,7 @@ describe("POST /api/community/messages/[id]/threads", () => {
mockGetChannelForMember.mockResolvedValue({
id: "c-parent",
serverId: "s1",
+ type: "text",
})
mockListChildChannels.mockResolvedValue([])
mockCreateChannel.mockResolvedValue({
@@ -199,6 +200,18 @@ describe("POST /api/community/messages/[id]/threads", () => {
expect(mockCreateChannel).not.toHaveBeenCalled()
})
+ it("400s when rooting a thread on a forum top-level message (not a message-bearing surface)", async () => {
+ mockGetChannelForMember.mockResolvedValue({
+ id: "forum-1",
+ serverId: "s1",
+ type: "forum",
+ parentChannelId: null,
+ })
+ const res = await POST(req({ name: "x" }), ctx)
+ expect(res.status).toBe(400)
+ expect(mockCreateChannel).not.toHaveBeenCalled()
+ })
+
it("seeds the creator (spoke) AND the parent-message author (added) as default participants", async () => {
const res = await POST(req({ name: "my thread" }), ctx)
expect(res.status).toBe(201)
@@ -239,7 +252,7 @@ describe("POST /api/community/messages/[id]/threads", () => {
// per-userId getChannelForMember returns null for them, so seeding skips
// the author to avoid pushing a private thread to a non-member.
mockGetChannelForMember.mockImplementation(async (_db: unknown, _channelId: string, userId: string) => {
- if (userId === "u1") return { id: "c-parent", serverId: "s1" }
+ if (userId === "u1") return { id: "c-parent", serverId: "s1", type: "text" }
return null
})
const res = await POST(req({ name: "my thread" }), ctx)
diff --git a/src/web/src/app/api/community/messages/[id]/threads/route.ts b/src/web/src/app/api/community/messages/[id]/threads/route.ts
index a100f0816..2168ca58a 100644
--- a/src/web/src/app/api/community/messages/[id]/threads/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/threads/route.ts
@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db"
import { queries, MAX_CHANNEL_NAME_LENGTH, WS_EVENTS, PARTICIPANT_SOURCE } from "@alook/shared"
import { fanOutToChannel } from "@/lib/community/fanout"
import { requireChannelMember } from "@/lib/community/permissions"
+import { requireMessageBearingSurface } from "@/lib/community/channel-write-guard"
export const POST = withAuth(async (req: NextRequest, ctx) => {
const messageId = ctx.params?.id
@@ -30,6 +31,13 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
return writeError("can't start a thread on a message in a thread or forum post", 400)
}
+ // A thread roots on a real message, so the anchor's channel must be a
+ // message-bearing surface. A `forum` top-level is a post index, not a
+ // message surface — any bare message there is illegitimate (see the
+ // channel-type write guard), so no thread may root on it.
+ const bearing = requireMessageBearingSurface(channel.type)
+ if (!bearing.ok) return writeError(bearing.error, bearing.status)
+
let body: { name?: string }
try {
body = await req.json()
diff --git a/src/web/src/app/api/community/send/route.test.ts b/src/web/src/app/api/community/send/route.test.ts
index 9b8a7e44e..775b9de34 100644
--- a/src/web/src/app/api/community/send/route.test.ts
+++ b/src/web/src/app/api/community/send/route.test.ts
@@ -104,7 +104,7 @@ describe("POST /api/community/agent/send", () => {
mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])
mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])
- mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })
+ mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", type: "text", parentChannelId: null })
mockGetLatestSeqForScope.mockResolvedValue(0)
// Default aligned (no deliverable unread) — matches the beforeEach
// latest=0. Tests asserting `blocked/unaligned` set this true explicitly;
@@ -197,7 +197,7 @@ describe("POST /api/community/agent/send", () => {
it("an explicit seenUpToSeq overrides the bot's own tracked lastReadSeq for the alignment check", async () => {
mockGetLatestSeqForScope.mockResolvedValue(10)
mockGetReadState.mockResolvedValue({ lastReadSeq: 2 }) // would block if used
- mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })
+ mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", type: "text", parentChannelId: null })
mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 10 } })
const res = await POST(
req(
@@ -243,7 +243,7 @@ describe("POST /api/community/agent/send", () => {
// thread ref, without needing to also mock the root-message/thread-row
// lookups `resolveTargetForMember`'s thread-form parsing would trigger.
mockResolveChannelByNameForMember.mockResolvedValue([{ id: "thread_1" }])
- mockGetChannelForMember.mockResolvedValue({ id: "thread_1", serverId: "srv_1", parentChannelId: "ch_parent" })
+ mockGetChannelForMember.mockResolvedValue({ id: "thread_1", serverId: "srv_1", type: "thread", parentChannelId: "ch_parent" })
mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 1, content: "hi" } })
const res = await POST(
req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })
diff --git a/src/web/src/app/api/community/send/route.ts b/src/web/src/app/api/community/send/route.ts
index 47c28bdc4..9201dbc0e 100644
--- a/src/web/src/app/api/community/send/route.ts
+++ b/src/web/src/app/api/community/send/route.ts
@@ -4,6 +4,7 @@ import { getDb } from "@/lib/db"
import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"
import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"
import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"
+import { requireMessageBearingSurface } from "@/lib/community/channel-write-guard"
import { createCommunityMessage, isDmTarget, type MessageTarget } from "@/lib/community/message-handler"
/**
@@ -115,6 +116,8 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
const gate = await requireChannelMember(db, resolved.channelId, botUserId)
if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })
const channel = gate.value
+ const bearing = requireMessageBearingSurface(channel.type)
+ if (!bearing.ok) return NextResponse.json({ error: bearing.error }, { status: bearing.status })
// Only threads have a non-null parentChannelId in this path — the ref
// resolver filters name lookups to top-level (parent_channel_id IS NULL)
// and thread refs (`#N`) create/reuse rows with type="thread". Forum
diff --git a/src/web/src/app/api/community/threads/[id]/read/route.test.ts b/src/web/src/app/api/community/threads/[id]/read/route.test.ts
index 9e8cff195..3599bc41c 100644
--- a/src/web/src/app/api/community/threads/[id]/read/route.test.ts
+++ b/src/web/src/app/api/community/threads/[id]/read/route.test.ts
@@ -76,7 +76,7 @@ describe("PUT /api/community/threads/[id]/read", () => {
})
it("body id present: fetches message, scope-checks, batches read + mention-clear to (msg.id, msg.createdAt)", async () => {
- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1" })
+ mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "thread" })
mockGetChannelForMember.mockResolvedValue({ id: "t1", serverId: "s1" })
mockGetMessage.mockResolvedValue({
id: "m9",
@@ -102,7 +102,7 @@ describe("PUT /api/community/threads/[id]/read", () => {
})
it("body id present but message belongs to another channel → 400, no write", async () => {
- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1" })
+ mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "thread" })
mockGetChannelForMember.mockResolvedValue({ id: "t1", serverId: "s1" })
mockGetMessage.mockResolvedValue({
id: "m9",
@@ -116,7 +116,7 @@ describe("PUT /api/community/threads/[id]/read", () => {
})
it("body id present but message does not exist → 404, no write", async () => {
- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1" })
+ mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "thread" })
mockGetChannelForMember.mockResolvedValue({ id: "t1", serverId: "s1" })
mockGetMessage.mockResolvedValue(null)
@@ -126,7 +126,7 @@ describe("PUT /api/community/threads/[id]/read", () => {
})
it("no body: uses latest message and aligns write to it", async () => {
- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1" })
+ mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "thread" })
mockGetChannelForMember.mockResolvedValue({ id: "t1", serverId: "s1" })
mockGetLatestMessage.mockResolvedValue({
id: "m_latest",
@@ -147,7 +147,7 @@ describe("PUT /api/community/threads/[id]/read", () => {
})
it("no body on EMPTY thread: no write at all, returns 200 { ok: true }", async () => {
- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1" })
+ mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "thread" })
mockGetChannelForMember.mockResolvedValue({ id: "t1", serverId: "s1" })
mockGetLatestMessage.mockResolvedValue(null)
@@ -174,11 +174,20 @@ describe("PUT /api/community/threads/[id]/read", () => {
})
it("returns 403 when the channel exists but the caller is not a member", async () => {
- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1" })
+ mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "thread" })
mockGetChannelForMember.mockResolvedValue(null)
const res = await PUT(putReq(), { params: { id: "t1" } } as any)
expect(res.status).toBe(403)
expect(mockBatch).not.toHaveBeenCalled()
})
+
+ it("returns 400 when the channel id is a top-level channel, not a thread/forum_post", async () => {
+ mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "text" })
+
+ const res = await PUT(putReq(), { params: { id: "t1" } } as any)
+ expect(res.status).toBe(400)
+ expect(mockGetChannelForMember).not.toHaveBeenCalled()
+ expect(mockBatch).not.toHaveBeenCalled()
+ })
})
diff --git a/src/web/src/app/api/community/threads/[id]/read/route.ts b/src/web/src/app/api/community/threads/[id]/read/route.ts
index f16a72ffa..94e013a9e 100644
--- a/src/web/src/app/api/community/threads/[id]/read/route.ts
+++ b/src/web/src/app/api/community/threads/[id]/read/route.ts
@@ -4,6 +4,7 @@ import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries } from "@alook/shared"
import { requireChannelMember } from "@/lib/community/permissions"
+import { requireChildSurface } from "@/lib/community/channel-write-guard"
/**
* PUT /api/community/threads/:id/read
@@ -26,6 +27,8 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
// both into 403 because the JOIN can't tell the difference.
const channel = await queries.communityChannel.getChannel(db, channelId)
if (!channel) return writeError("channel not found", 404)
+ const child = requireChildSurface(channel.type)
+ if (!child.ok) return writeError(child.error, child.status)
const auth = await requireChannelMember(db, channelId, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
diff --git a/src/web/src/lib/community/channel-write-guard.test.ts b/src/web/src/lib/community/channel-write-guard.test.ts
new file mode 100644
index 000000000..4a4a2db92
--- /dev/null
+++ b/src/web/src/lib/community/channel-write-guard.test.ts
@@ -0,0 +1,56 @@
+import { describe, it, expect } from "vitest"
+import {
+ requireMessageBearingSurface,
+ requireChildSurface,
+ rejectDmOnGenericChannelRoute,
+} from "./channel-write-guard"
+
+describe("requireMessageBearingSurface", () => {
+ it("accepts message-bearing surfaces (text, forum_post, thread)", () => {
+ for (const t of ["text", "forum_post", "thread"]) {
+ expect(requireMessageBearingSurface(t).ok).toBe(true)
+ }
+ })
+
+ it("rejects a forum top-level (post index, not a message surface) with 400", () => {
+ const r = requireMessageBearingSurface("forum")
+ expect(r.ok).toBe(false)
+ if (!r.ok) expect(r.status).toBe(400)
+ })
+
+ it("rejects a DM hitting a generic channel route with 400 (block-bypass guard)", () => {
+ const r = requireMessageBearingSurface("dm")
+ expect(r.ok).toBe(false)
+ if (!r.ok) expect(r.status).toBe(400)
+ })
+
+ it("rejects null/unknown types", () => {
+ expect(requireMessageBearingSurface(null).ok).toBe(false)
+ expect(requireMessageBearingSurface(undefined).ok).toBe(false)
+ expect(requireMessageBearingSurface("bogus").ok).toBe(false)
+ })
+})
+
+describe("rejectDmOnGenericChannelRoute", () => {
+ it("rejects only dm; passes every non-dm type", () => {
+ expect(rejectDmOnGenericChannelRoute("dm").ok).toBe(false)
+ for (const t of ["text", "forum", "forum_post", "thread", null, undefined]) {
+ expect(rejectDmOnGenericChannelRoute(t).ok).toBe(true)
+ }
+ })
+})
+
+describe("requireChildSurface", () => {
+ it("accepts thread and forum_post", () => {
+ expect(requireChildSurface("thread").ok).toBe(true)
+ expect(requireChildSurface("forum_post").ok).toBe(true)
+ })
+
+ it("rejects top-level and dm types with 400", () => {
+ for (const t of ["text", "forum", "dm", null, undefined]) {
+ const r = requireChildSurface(t)
+ expect(r.ok).toBe(false)
+ if (!r.ok) expect(r.status).toBe(400)
+ }
+ })
+})
diff --git a/src/web/src/lib/community/channel-write-guard.ts b/src/web/src/lib/community/channel-write-guard.ts
new file mode 100644
index 000000000..a2af520cc
--- /dev/null
+++ b/src/web/src/lib/community/channel-write-guard.ts
@@ -0,0 +1,32 @@
+import { isMessageBearingSurface, isThread, isForumPost, isDm } from "@alook/shared"
+
+type GuardOk = { ok: true }
+type GuardErr = { ok: false; status: 400; error: string }
+export type WriteGuardResult = GuardOk | GuardErr
+
+const pass: GuardOk = { ok: true }
+
+export function rejectDmOnGenericChannelRoute(channelType: string | null | undefined): WriteGuardResult {
+ if (!isDm(channelType)) return pass
+ return {
+ ok: false,
+ status: 400,
+ error: "this is a direct message — use the DM endpoints (/api/community/dm/[id]/*), which enforce block checks.",
+ }
+}
+
+export function requireMessageBearingSurface(channelType: string | null | undefined): WriteGuardResult {
+ const dmGuard = rejectDmOnGenericChannelRoute(channelType)
+ if (!dmGuard.ok) return dmGuard
+ if (isMessageBearingSurface(channelType)) return pass
+ return {
+ ok: false,
+ status: 400,
+ error: "cannot post a message here — a forum top-level holds posts, not messages. Create a post (a title is required).",
+ }
+}
+
+export function requireChildSurface(channelType: string | null | undefined): WriteGuardResult {
+ if (isThread(channelType) || isForumPost(channelType)) return pass
+ return { ok: false, status: 400, error: "not a thread or forum post" }
+}
diff --git a/src/web/src/lib/community/upload.test.ts b/src/web/src/lib/community/upload.test.ts
index 5a64ee92e..513cc4769 100644
--- a/src/web/src/lib/community/upload.test.ts
+++ b/src/web/src/lib/community/upload.test.ts
@@ -14,6 +14,21 @@ vi.mock("@/lib/middleware/helpers", () => {
const mockGetDb = vi.fn(() => ({ __db: true }))
vi.mock("@/lib/db", () => ({ getDb: (...a: unknown[]) => mockGetDb(...a) }))
+const mockGetChannelType = vi.fn()
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ ...actual.queries,
+ communityChannel: {
+ ...actual.queries.communityChannel,
+ getChannelType: (...a: unknown[]) => mockGetChannelType(...a),
+ },
+ },
+ }
+})
+
import {
handleAttachmentUpload,
handleServerIconUpload,
@@ -332,7 +347,10 @@ describe("handleBotAvatarUpload", () => {
})
describe("runAttachmentUpload", () => {
- beforeEach(() => vi.clearAllMocks())
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetChannelType.mockResolvedValue("text")
+ })
function ctxWith(env: Env, params: Record<string, string> | undefined) {
return {
@@ -423,6 +441,7 @@ describe("runAttachmentUpload", () => {
})
it("routes 'thread' kind through the thread/ R2 prefix", async () => {
+ mockGetChannelType.mockResolvedValue("thread")
const put = vi.fn().mockResolvedValue(undefined)
const perm = vi.fn().mockResolvedValue({ ok: true, value: { id: "t1" } })
const res = await runAttachmentUpload(
@@ -436,6 +455,34 @@ describe("runAttachmentUpload", () => {
expect(key).toMatch(/^thread\/t1\//)
})
+ it("rejects a 'channel' upload targeted at a forum top-level with 400", async () => {
+ mockGetChannelType.mockResolvedValue("forum")
+ const put = vi.fn()
+ const perm = vi.fn().mockResolvedValue({ ok: true, value: { id: "c1" } })
+ const res = await runAttachmentUpload(
+ reqWithFile(fakeFile("hi.png", "image/png", 10)),
+ ctxWith(envWithR2(put), { id: "c1" }),
+ "channel",
+ perm as never,
+ )
+ expect(res.status).toBe(400)
+ expect(put).not.toHaveBeenCalled()
+ })
+
+ it("rejects a 'channel' upload targeted at a DM channel id with 400 (block-bypass guard)", async () => {
+ mockGetChannelType.mockResolvedValue("dm")
+ const put = vi.fn()
+ const perm = vi.fn().mockResolvedValue({ ok: true, value: { id: "c1" } })
+ const res = await runAttachmentUpload(
+ reqWithFile(fakeFile("hi.png", "image/png", 10)),
+ ctxWith(envWithR2(put), { id: "c1" }),
+ "channel",
+ perm as never,
+ )
+ expect(res.status).toBe(400)
+ expect(put).not.toHaveBeenCalled()
+ })
+
it("forwards handleAttachmentUpload errors (e.g. oversize) unchanged", async () => {
const put = vi.fn()
const perm = vi.fn().mockResolvedValue({ ok: true, value: { id: "c1" } })
diff --git a/src/web/src/lib/community/upload.ts b/src/web/src/lib/community/upload.ts
index 15041ab00..0178d97d2 100644
--- a/src/web/src/lib/community/upload.ts
+++ b/src/web/src/lib/community/upload.ts
@@ -4,7 +4,9 @@ import {
MAX_SERVER_ICON_SIZE_BYTES,
ALLOWED_ATTACHMENT_MIME_PREFIXES,
ALLOWED_ICON_MIME_TYPES,
+ queries,
} from "@alook/shared"
+import { requireMessageBearingSurface, requireChildSurface } from "./channel-write-guard"
import type { Database } from "@alook/shared"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
@@ -269,6 +271,16 @@ export async function runAttachmentUpload(
const auth = await permissionCheck(db, id, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
+ if (kind === "channel") {
+ const channelType = await queries.communityChannel.getChannelType(db, id)
+ const surface = requireMessageBearingSurface(channelType)
+ if (!surface.ok) return writeError(surface.error, surface.status)
+ } else if (kind === "thread") {
+ const channelType = await queries.communityChannel.getChannelType(db, id)
+ const child = requireChildSurface(channelType)
+ if (!child.ok) return writeError(child.error, child.status)
+ }
+
const result = await handleAttachmentUpload(req, ctx.env, kind, id, {
uploader: "user",
uploaderUserId: ctx.userId,