Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): reject out-of-scope replyToId on the send path

Melisa8c7f277a0d85
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index 4bfc14f85..fdd45413b 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -19,13 +19,14 @@ const mockCreateChannelMember = vi.fn()
const mockAddThreadParticipants = vi.fn()
const mockLogError = vi.fn()
+const mockLogWarn = vi.fn()
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
return {
...actual,
createLogger: () => ({
info: vi.fn(),
- warn: vi.fn(),
+ warn: (...a: unknown[]) => mockLogWarn(...a),
debug: vi.fn(),
error: (...a: unknown[]) => mockLogError(...a),
}),
@@ -244,6 +245,138 @@ describe("createCommunityMessage — audit relocation (plan §10)", () => {
})
})
+describe("createCommunityMessage — replyToId write-path scope validation (dangling-reply / #204 bot=user)", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockCreateMessage.mockResolvedValue({ id: "msg_1" })
+ mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: false, deletedAt: null })
+ mockFanOutToChannel.mockResolvedValue(undefined)
+ mockFanOutToDM.mockResolvedValue(undefined)
+ mockBroadcastToUser.mockResolvedValue(undefined)
+ })
+
+ // The reply target the client asked to answer, living in the SAME channel.
+ const inScopeReply = {
+ id: "reply_1",
+ authorId: "author_2",
+ authorName: "Other",
+ content: "the parent",
+ channelId: "c1",
+ }
+
+ it("in-scope replyToId: persists it, and resolves the target with a SINGLE getMessageInScope lookup (no re-query for the preview)", async () => {
+ mockGetMessageInScope.mockResolvedValue(inScopeReply)
+ mockGetMessage.mockResolvedValue(messageRow({ replyToId: "reply_1" }))
+
+ const result = await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "answering", replyToId: "reply_1" },
+ })
+
+ expect(result.ok).toBe(true)
+ // replyToId reaches the insert unchanged.
+ expect(mockCreateMessage).toHaveBeenCalledWith(
+ {},
+ expect.objectContaining({ replyToId: "reply_1" }),
+ )
+ // The write-path validation replaces the preview's fetch — not one each.
+ expect(mockGetMessageInScope).toHaveBeenCalledTimes(1)
+ expect(mockGetMessageInScope).toHaveBeenCalledWith({}, "reply_1", { channelId: "c1" })
+ expect(mockLogWarn).not.toHaveBeenCalled()
+ })
+
+ it("out-of-scope replyToId: DROPPED (message stored with replyToId undefined), warn-logged, NOT rejected", async () => {
+ // Target message isn't in this channel's scope → getMessageInScope returns null.
+ mockGetMessageInScope.mockResolvedValue(null)
+ mockGetMessage.mockResolvedValue(messageRow({ replyToId: null }))
+
+ const result = await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "answering across channels", replyToId: "reply_in_other_channel" },
+ })
+
+ // Lenient: the send SUCCEEDS, just as a plain message.
+ expect(result.ok).toBe(true)
+ // The dangling id never reaches the DB — insert carries undefined.
+ expect(mockCreateMessage).toHaveBeenCalledWith(
+ {},
+ expect.objectContaining({ replyToId: undefined }),
+ )
+ // Flagged as a likely client bug.
+ expect(mockLogWarn).toHaveBeenCalledWith(
+ "reply_to_out_of_scope_dropped",
+ expect.objectContaining({
+ authorId: "author_1",
+ channelId: "c1",
+ replyToId: "reply_in_other_channel",
+ }),
+ )
+ })
+
+ it("private source channel the author can't see is indistinguishable from missing (getMessageInScope null → same drop, no leak)", async () => {
+ // getMessageInScope is `WHERE id=? AND channelId=?`; a private channel the
+ // author isn't in resolves to null exactly like a nonexistent id — the
+ // handler can't and doesn't branch on which, so neither content nor the
+ // channel's existence leaks.
+ mockGetMessageInScope.mockResolvedValue(null)
+ mockGetMessage.mockResolvedValue(messageRow({ replyToId: null }))
+
+ const result = await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "peeking", replyToId: "msg_in_private_channel" },
+ })
+
+ expect(result.ok).toBe(true)
+ expect(mockCreateMessage).toHaveBeenCalledWith(
+ {},
+ expect.objectContaining({ replyToId: undefined }),
+ )
+ })
+
+ it("bot author (source cli) hits the SAME drop — the send codepath is shared, so bots can't POST a dangling reply either (#204)", async () => {
+ mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: true, deletedAt: null })
+ mockGetMessageInScope.mockResolvedValue(null)
+ mockGetMessage.mockResolvedValue(messageRow({ replyToId: null }))
+
+ const result = await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "bot cross-scope reply", replyToId: "reply_elsewhere" },
+ source: "cli",
+ })
+
+ expect(result.ok).toBe(true)
+ expect(mockCreateMessage).toHaveBeenCalledWith(
+ {},
+ expect.objectContaining({ replyToId: undefined }),
+ )
+ expect(mockLogWarn).toHaveBeenCalledWith(
+ "reply_to_out_of_scope_dropped",
+ expect.objectContaining({ source: "cli", replyToId: "reply_elsewhere" }),
+ )
+ })
+
+ it("no replyToId: no scope lookup at all (unchanged fast path)", async () => {
+ mockGetMessage.mockResolvedValue(messageRow({ replyToId: null }))
+
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "no reply here" },
+ })
+
+ expect(mockGetMessageInScope).not.toHaveBeenCalled()
+ })
+})
+
describe("createCommunityMessage — CAS race (plans/fix-agent-send-race-condition.md)", () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index 450a6e169..79e178684 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -293,8 +293,41 @@ export async function createCommunityMessage(params: {
}
}
- const replyToId =
+ // A client-supplied `replyToId` must reference a message IN THE TARGET
+ // channel. Validate on the WRITE path (not just the preview path below at
+ // ~:520, which only *skips the preview* for an out-of-scope id while still
+ // persisting the dangling reference). Without this, any client — web, CLI,
+ // or bot (#204, bots ride the same send codepath as users) — could POST a
+ // cross-scope `replyToId`; it would insert, then render as an unresolvable
+ // "unknown" reply because `getMessageInScope` can't resolve it. We drop the
+ // out-of-scope id (store as a plain message) rather than 400 — lenient,
+ // matching the send path's "never fail the send on an edge case" posture —
+ // and warn-log it as a likely client bug. `getMessageInScope` is scoped
+ // `WHERE id = ? AND channelId = ?`, so a private source channel the author
+ // can't otherwise see is denied here too (no leak of its content/existence).
+ const rawReplyToId =
typeof body.replyToId === "string" ? body.replyToId : undefined
+ let replyToId = rawReplyToId
+ // Resolved reply target, in-scope — carried to the preview block below so it
+ // reuses this lookup instead of re-fetching (net: no extra query for the
+ // common in-scope reply; the validation replaces the preview's fetch).
+ let resolvedReplyMsg:
+ | Awaited<ReturnType<typeof queries.communityMessage.getMessageInScope>>
+ | null = null
+ if (rawReplyToId !== undefined) {
+ resolvedReplyMsg = await queries.communityMessage.getMessageInScope(db, rawReplyToId, {
+ channelId: target.channelId,
+ })
+ if (!resolvedReplyMsg) {
+ log.warn("reply_to_out_of_scope_dropped", {
+ authorId,
+ channelId: target.channelId,
+ replyToId: rawReplyToId,
+ source: source ?? "web",
+ })
+ replyToId = undefined
+ }
+ }
const mentionType: MentionType | undefined =
!isDmTarget(target) && isMentionType(body.mentionType)
? body.mentionType
@@ -515,19 +548,20 @@ export async function createCommunityMessage(params: {
// below.
const replyMap = new Map<string, { id: string; authorName: string; content: string | null }>()
const replyTargets = new Set<string>()
- if (!skipMentions && row.replyToId) {
+ // Reuse the in-scope reply target resolved at the write-validation step above
+ // (`resolvedReplyMsg`) — it was fetched with the identical `getMessageInScope`
+ // scope, so re-querying here would be redundant. `row.replyToId` is already
+ // null when the id was out-of-scope (dropped above), so this block only runs
+ // for a genuinely in-scope reply.
+ if (!skipMentions && row.replyToId && resolvedReplyMsg) {
// single-id path — see `dm/[id]/messages/route.ts` / `channels/[id]/messages/route.ts` for the batched N-id path
- const scope = { channelId: target.channelId }
- const replyMsg = await queries.communityMessage.getMessageInScope(db, row.replyToId, scope)
- if (replyMsg) {
- replyMap.set(replyMsg.id, {
- id: replyMsg.id,
- authorName: replyMsg.authorName,
- content: replyMsg.content,
- })
- if (replyMsg.authorId && replyMsg.authorId !== authorId) {
- replyTargets.add(replyMsg.authorId)
- }
+ replyMap.set(resolvedReplyMsg.id, {
+ id: resolvedReplyMsg.id,
+ authorName: resolvedReplyMsg.authorName,
+ content: resolvedReplyMsg.content,
+ })
+ if (resolvedReplyMsg.authorId && resolvedReplyMsg.authorId !== authorId) {
+ replyTargets.add(resolvedReplyMsg.authorId)
}
}