diff --git a/CHANGELOG.md b/CHANGELOG.md index cef0ac4ec..48f71cb91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,11 @@ This project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Packages without a separate changelog are covered by the cross-package notes below. -## [Unreleased] +## [Unreleased - Patch] + +### Fixed + +- DM and group DM participant rules now apply consistently for agent tokens across the channel, message, search and console routes, matching the `/v1/dm/…` routes. Workspace keys and observer tokens are unchanged. ## [12.13.0] - 2026-11-17 diff --git a/packages/engine/CHANGELOG.md b/packages/engine/CHANGELOG.md index febc85558..ec314558a 100644 --- a/packages/engine/CHANGELOG.md +++ b/packages/engine/CHANGELOG.md @@ -7,7 +7,11 @@ See the [root changelog](../../CHANGELOG.md) for cross-package release highlight The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [Unreleased - Patch] + +### Fixed + +- DM participant rules are applied consistently for agent tokens. For an agent that is not an active participant of a DM or group DM, `/v1/channels/:name` (detail, messages, members, read-status, update, topic, archive, leave, mute, unmute) and `/v1/messages/:id` (get, replies, reactions, readers) answer `404`, as does posting to the channel, including a node token posting as a non-participant `from`. `join` and `invite` are refused on DM-backed channels for every agent; add group DM members through `/v1/dm/:conversation_id/participants`. `GET /v1/search` and `GET /v1/console/messages` drop DM rows the agent does not participate in. ## [12.13.0] - 2026-11-17 diff --git a/packages/engine/src/__tests__/conformance/dmChannelRouteAccess.test.ts b/packages/engine/src/__tests__/conformance/dmChannelRouteAccess.test.ts new file mode 100644 index 000000000..fdd78d2f7 --- /dev/null +++ b/packages/engine/src/__tests__/conformance/dmChannelRouteAccess.test.ts @@ -0,0 +1,248 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + createWorkspace, + D1_MAX_BOUND_PARAMETERS, + enforceD1ParameterLimit, + makeNodeStack, + registerAgent, + type TestStack, +} from './harness.js'; +import { conformancePgDb } from './pgMode.js'; + +// DM and group-DM conversations live on ordinary channel rows, so the +// channel/message/search/console routes reach them. An agent that is not a +// participant must see none of it, and must not be able to write into it. + +interface Envelope { ok: boolean; data: T; error?: { code: string } } + +describe('DM content through channel and message routes', () => { + let stack: TestStack; + + beforeEach(() => { stack = makeNodeStack(); }); + afterEach(() => stack.close()); + + async function call(method: string, path: string, token: string, body?: unknown) { + const res = await stack.app.request(`/v1${path}`, { + method, + headers: { + authorization: `Bearer ${token}`, + ...(body === undefined ? {} : { 'content-type': 'application/json' }), + }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const text = await res.text(); + const json = (text ? JSON.parse(text) : {}) as Envelope; + return { status: res.status, data: json.data, text }; + } + + async function setup() { + const ws = await createWorkspace(stack.app, 'dm-route-access-ws'); + const alice = await registerAgent(stack.app, ws.workspaceKey, 'alice'); + const bob = await registerAgent(stack.app, ws.workspaceKey, 'bob'); + const carol = await registerAgent(stack.app, ws.workspaceKey, 'carol'); + const dave = await registerAgent(stack.app, ws.workspaceKey, 'dave'); + + const dm = await call<{ id: string; conversation_id: string }>( + 'POST', '/dm', alice.token, { to: 'bob', text: 'pairsecret one' }, + ); + expect(dm.status).toBe(201); + const group = await call<{ id: string }>( + 'POST', '/dm/group', alice.token, { participants: ['bob', 'dave'], name: 'private' }, + ); + expect(group.status).toBe(201); + const groupMessage = await call<{ id: string }>( + 'POST', `/dm/${group.data.id}/messages`, alice.token, { text: 'groupsecret two' }, + ); + expect(groupMessage.status).toBe(201); + + // The workspace key is the admin view; use it to learn the backing channel names. + const all = await call>('GET', '/dm/conversations/all', ws.workspaceKey); + const pairConversationId = all.data.find((conversation) => conversation.type === '1:1')!.id; + const pairChannel = `dm-${pairConversationId.replace(/^dm_/, '')}`; + const groupChannel = `group-dm-${group.data.id}`; + + return { + ws, alice, bob, carol, dave, + pair: { channel: pairChannel, conversationId: pairConversationId, messageId: String(dm.data.id) }, + group: { channel: groupChannel, conversationId: group.data.id, messageId: String(groupMessage.data.id) }, + }; + } + + it('hides DM-backed channels and their messages from a non-participant agent', async () => { + const { carol, pair, group } = await setup(); + + for (const target of [pair, group]) { + for (const path of [ + `/channels/${target.channel}`, + `/channels/${target.channel}/messages`, + `/channels/${target.channel}/members`, + `/channels/${target.channel}/read-status`, + `/messages/${target.messageId}`, + `/messages/${target.messageId}/replies`, + `/messages/${target.messageId}/reactions`, + `/messages/${target.messageId}/readers`, + ]) { + const res = await call('GET', path, carol.token); + expect(res.status, `GET ${path}`).toBe(404); + expect(res.text).not.toContain('secret'); + } + } + }); + + it('keeps DM content out of search and console logs for a non-participant agent', async () => { + const { carol, bob, alice } = await setup(); + const publicPost = await call('POST', '/channels/general/messages', alice.token, { text: 'pairsecret in public' }); + expect(publicPost.status).toBe(201); + + for (const q of ['pairsecret', 'groupsecret']) { + const outsider = await call>( + 'GET', `/search?q=${q}`, carol.token, + ); + expect(outsider.status).toBe(200); + expect(outsider.data.every((hit) => !hit.conversation_id)).toBe(true); + expect(outsider.text).not.toContain('one'); + expect(outsider.text).not.toContain('two'); + } + // Regular channel hits are unaffected. + const publicHits = await call>('GET', '/search?q=pairsecret', carol.token); + expect(publicHits.data.map((hit) => hit.text)).toEqual(['pairsecret in public']); + + const participant = await call>('GET', '/search?q=groupsecret', bob.token); + expect(participant.data.map((hit) => hit.text)).toContain('groupsecret two'); + + const outsiderLogs = await call>( + 'GET', '/console/messages', carol.token, + ); + expect(outsiderLogs.status).toBe(200); + expect(outsiderLogs.data.length).toBeGreaterThan(0); + expect(outsiderLogs.data.every((log) => !log.conversation_id)).toBe(true); + const dmOnly = await call('GET', '/console/messages?delivery_kind=dm', carol.token); + expect(dmOnly.data).toHaveLength(0); + + const participantLogs = await call>( + 'GET', '/console/messages?delivery_kind=dm', bob.token, + ); + expect(participantLogs.data.length).toBeGreaterThan(0); + }); + + it('refuses writes into a DM by a non-participant agent', async () => { + const { bob, carol, pair, group } = await setup(); + + for (const target of [pair, group]) { + const writes: Array<[string, string, unknown?]> = [ + ['POST', `/channels/${target.channel}/messages`, { text: 'injected' }], + ['POST', `/channels/${target.channel}/join`], + ['POST', `/channels/${target.channel}/leave`], + ['POST', `/channels/${target.channel}/invite`, { agent_name: 'carol' }], + ['POST', `/channels/${target.channel}/mute`], + ['PATCH', `/channels/${target.channel}`, { topic: 'x' }], + ['DELETE', `/channels/${target.channel}`], + ['POST', `/messages/${target.messageId}/replies`, { text: 'injected' }], + ['POST', `/messages/${target.messageId}/reactions`, { emoji: 'eyes' }], + ['POST', `/messages/${target.messageId}/read`], + ]; + for (const [method, path, body] of writes) { + const res = await call(method, path, carol.token, body); + expect(res.status, `${method} ${path}`).toBe(404); + } + + const history = await call('GET', `/dm/${target.conversationId}/messages`, bob.token); + expect(history.status).toBe(200); + expect(history.text).not.toContain('injected'); + } + }); + + it('does not let a participant pull an outsider in through channel membership', async () => { + const { alice, carol, pair, group } = await setup(); + + for (const target of [pair, group]) { + const join = await call('POST', `/channels/${target.channel}/join`, alice.token); + expect(join.status).toBe(404); + const invite = await call('POST', `/channels/${target.channel}/invite`, alice.token, { agent_name: 'carol' }); + expect(invite.status).toBe(404); + const stillHidden = await call('GET', `/channels/${target.channel}/messages`, carol.token); + expect(stillHidden.status).toBe(404); + } + }); + + it('refuses a channel leave on a DM-backed channel and keeps the participant in the DM', async () => { + const { alice, pair, group } = await setup(); + + for (const target of [pair, group]) { + const leave = await call('POST', `/channels/${target.channel}/leave`, alice.token); + expect(leave.status).toBe(404); + const history = await call('GET', `/channels/${target.channel}/messages`, alice.token); + expect(history.status).toBe(200); + } + }); + + it('leaves participants and the workspace key able to read by channel name and message id', async () => { + const { ws, bob, pair, group } = await setup(); + + for (const token of [bob.token, ws.workspaceKey]) { + for (const target of [pair, group]) { + const history = await call('GET', `/channels/${target.channel}/messages`, token); + expect(history.status).toBe(200); + expect(history.text).toContain('secret'); + const message = await call('GET', `/messages/${target.messageId}`, token); + expect(message.status).toBe(200); + } + } + }); + + it('stops applying once a participant has left a group DM', async () => { + const { dave, group } = await setup(); + const before = await call('GET', `/messages/${group.messageId}`, dave.token); + expect(before.status).toBe(200); + + const leave = await call('DELETE', `/dm/${group.conversationId}/participants/dave`, dave.token); + expect(leave.status).toBeLessThan(300); + + const after = await call('GET', `/messages/${group.messageId}`, dave.token); + expect(after.status).toBe(404); + }); + + it('keeps a DM posted through the channel route in its participants\' console logs', async () => { + const { alice, bob, carol, pair } = await setup(); + const post = await call('POST', `/channels/${pair.channel}/messages`, alice.token, { text: 'viachannel three' }); + expect(post.status).toBe(201); + + for (const participant of [alice, bob]) { + const logs = await call>('GET', '/console/messages?limit=100', participant.token); + expect(logs.status).toBe(200); + expect(logs.data.map((log) => log.text)).toContain('viachannel three'); + } + const outsider = await call('GET', '/console/messages?limit=100', carol.token); + expect(outsider.status).toBe(200); + expect(outsider.text).not.toContain('viachannel'); + }); + + it('filters a full page of distinct DM conversations inside the D1 parameter limit', async () => { + const ws = await createWorkspace(stack.app, 'dm-route-access-d1-ws'); + const hub = await registerAgent(stack.app, ws.workspaceKey, 'hub'); + const outsider = await registerAgent(stack.app, ws.workspaceKey, 'outsider'); + const PEERS = 100; + for (let index = 0; index < PEERS; index += 1) { + const peer = await registerAgent(stack.app, ws.workspaceKey, `peer-${index}`); + const dm = await call('POST', '/dm', peer.token, { to: 'hub', text: `fanword ${index}` }); + expect(dm.status).toBe(201); + } + + // The guard patches the SQLite handle, which PostgreSQL mode does not have; + // the result checks below still run there. + const guard = conformancePgDb() ? undefined : enforceD1ParameterLimit(stack); + try { + for (const path of ['/search?q=fanword&limit=100', '/console/messages?limit=100&delivery_kind=dm']) { + const mine = await call('GET', path, hub.token); + expect(mine.status, path).toBe(200); + expect(mine.data, path).toHaveLength(PEERS); + const theirs = await call('GET', path, outsider.token); + expect(theirs.status, path).toBe(200); + expect(theirs.data, path).toHaveLength(0); + } + if (guard) expect(guard.maxObserved()).toBeLessThanOrEqual(D1_MAX_BOUND_PARAMETERS); + } finally { + guard?.restore(); + } + }); +}); diff --git a/packages/engine/src/engine/dmAccess.ts b/packages/engine/src/engine/dmAccess.ts new file mode 100644 index 000000000..5d97a3c71 --- /dev/null +++ b/packages/engine/src/engine/dmAccess.ts @@ -0,0 +1,129 @@ +import { and, eq, inArray, isNull } from 'drizzle-orm'; +import type { getDb } from '../db/index.js'; +import { channels, dmConversations, dmParticipants, messages } from '../db/tables.js'; +import { queryInChunks } from '../lib/queryChunks.js'; + +type Db = ReturnType; + +/** + * DM and group-DM conversations are stored on ordinary `channels` rows + * (`channel_type` 1 and 2). Routes that address a channel by name or a message + * by id therefore reach DM content too, and must apply the same rule the `/dm` + * routes do: an agent sees a conversation only while it is a participant. + * + * These helpers answer that question for an *agent* principal. Workspace keys + * keep full access, and observer tokens are scoped by their own filters. + */ + +/** channel_type 0 is a regular channel; anything else backs a DM conversation. */ +export function isDmBackedChannelType(channelType: number | null | undefined): boolean { + return channelType != null && channelType !== 0; +} + +async function isActiveParticipantOfChannel(db: Db, channelId: string, agentId: string): Promise { + const [row] = await db + .select({ agentId: dmParticipants.agentId }) + .from(dmConversations) + .innerJoin(dmParticipants, eq(dmParticipants.conversationId, dmConversations.id)) + .where(and( + eq(dmConversations.channelId, channelId), + eq(dmParticipants.agentId, agentId), + isNull(dmParticipants.leftAt), + )); + return Boolean(row); +} + +export type DmChannelAccess = + /** No such channel, or a regular channel: the DM rule does not apply. */ + | 'not_dm' + | 'participant' + | 'outsider'; + +/** Classifies a channel name against the DM participant rule for one agent. */ +export async function agentDmAccessForChannelName( + db: Db, + workspaceId: string, + agentId: string, + channelName: string, +): Promise { + const [channel] = await db + .select({ id: channels.id, channelType: channels.channelType }) + .from(channels) + .where(and(eq(channels.workspaceId, workspaceId), eq(channels.name, channelName))); + if (!channel || !isDmBackedChannelType(channel.channelType)) return 'not_dm'; + return (await isActiveParticipantOfChannel(db, channel.id, agentId)) ? 'participant' : 'outsider'; +} + +/** Classifies a message id against the DM participant rule for one agent. */ +export async function agentDmAccessForMessage( + db: Db, + workspaceId: string, + agentId: string, + messageId: string, +): Promise { + const [row] = await db + .select({ channelId: channels.id, channelType: channels.channelType }) + .from(messages) + .innerJoin(channels, eq(messages.channelId, channels.id)) + .where(and(eq(messages.id, messageId), eq(messages.workspaceId, workspaceId))); + if (!row || !isDmBackedChannelType(row.channelType)) return 'not_dm'; + return (await isActiveParticipantOfChannel(db, row.channelId, agentId)) ? 'participant' : 'outsider'; +} + +/** + * Drops DM rows the agent is not a participant in from a mixed result list + * (search hits, console message logs). A row is treated as DM content when it + * carries a conversation id or a non-zero channel type. + * + * Rows are attributed by their backing channel, because a message posted to a + * DM through the channel route is logged without a conversation id; the + * conversation id is the fallback for a row with no channel id. A DM row with + * neither cannot be attributed and is dropped. + */ +export async function filterAgentVisibleDmResults( + db: Db, + agentId: string | undefined, + results: T[], +): Promise { + if (!agentId || results.length === 0) return results; + const isDm = (result: T) => Boolean(result.conversation_id) || isDmBackedChannelType(result.channel_type); + const dmRows = results.filter(isDm); + if (dmRows.length === 0) return results; + + const distinct = (values: Array) => + [...new Set(values.filter((value): value is string => Boolean(value)))]; + const channelIds = distinct(dmRows.map((row) => row.channel_id)); + const conversationIds = distinct(dmRows.filter((row) => !row.channel_id).map((row) => row.conversation_id)); + + // A page can hold up to 100 distinct conversations; chunk to stay inside + // D1's bound-parameter ceiling. + const byChannel = await queryInChunks(channelIds, (ids) => db + .select({ channelId: dmConversations.channelId }) + .from(dmConversations) + .innerJoin(dmParticipants, eq(dmParticipants.conversationId, dmConversations.id)) + .where(and( + eq(dmParticipants.agentId, agentId), + isNull(dmParticipants.leftAt), + inArray(dmConversations.channelId, ids), + ))); + const byConversation = await queryInChunks(conversationIds, (ids) => db + .select({ conversationId: dmParticipants.conversationId }) + .from(dmParticipants) + .where(and( + eq(dmParticipants.agentId, agentId), + isNull(dmParticipants.leftAt), + inArray(dmParticipants.conversationId, ids), + ))); + const allowedChannels = new Set(byChannel.map((row) => row.channelId)); + const allowedConversations = new Set(byConversation.map((row) => row.conversationId)); + + return results.filter((result) => { + if (!isDm(result)) return true; + if (result.channel_id) return allowedChannels.has(result.channel_id); + return Boolean(result.conversation_id && allowedConversations.has(result.conversation_id)); + }); +} diff --git a/packages/engine/src/middleware/dmAccess.ts b/packages/engine/src/middleware/dmAccess.ts new file mode 100644 index 000000000..5a0dec78e --- /dev/null +++ b/packages/engine/src/middleware/dmAccess.ts @@ -0,0 +1,56 @@ +import { createMiddleware } from 'hono/factory'; +import type { AppEnv } from '../env.js'; +import { agentDmAccessForChannelName, agentDmAccessForMessage } from '../engine/dmAccess.js'; +import { jsonNotFound } from '../lib/httpResponse.js'; + +/** + * Guards for routes that reach a conversation by channel name or message id. + * DM and group-DM conversations live on ordinary channel rows, so without + * these any agent token in the workspace could read or write another pair's + * DM through the channel/message routes. + * + * Both run after the route's auth middleware and only constrain an agent + * principal: a workspace key keeps full access and an observer token is + * scoped by its own filters. An outsider gets the same 404 as a missing + * resource so the routes do not confirm that a conversation exists. + */ + +interface DmChannelGuardOptions { + /** + * Channel-membership operations (join, invite, leave) have no meaning on a + * DM's backing channel: DM participants hold no `channel_members` row, so + * join and invite would add one for a non-participant and leave would report + * a departure that did not happen. They are refused for every agent, + * participants included. Group DMs manage members through + * `/dm/group/:id/participants`. + */ + refuseParticipants?: boolean; +} + +/** For `/channels/:name…` routes. */ +export function hideDmChannelFromOutsiders(options: DmChannelGuardOptions = {}) { + return createMiddleware(async (c, next) => { + const agent = c.get('agent'); + const name = c.req.param('name'); + if (agent && name) { + const access = await agentDmAccessForChannelName(c.get('db'), c.get('workspace').id, agent.id, name); + if (access === 'outsider' || (access === 'participant' && options.refuseParticipants)) { + return jsonNotFound(c, 'channel_not_found', `Channel "${name}" not found`); + } + } + await next(); + }); +} + +/** For `/messages/:id…` routes. */ +export const hideDmMessageFromOutsiders = createMiddleware(async (c, next) => { + const agent = c.get('agent'); + const messageId = c.req.param('id'); + if (agent && messageId) { + const access = await agentDmAccessForMessage(c.get('db'), c.get('workspace').id, agent.id, messageId); + if (access === 'outsider') { + return jsonNotFound(c, 'message_not_found', 'Message not found'); + } + } + await next(); +}); diff --git a/packages/engine/src/routes/channel.ts b/packages/engine/src/routes/channel.ts index a2e584a1d..1952f5eb7 100644 --- a/packages/engine/src/routes/channel.ts +++ b/packages/engine/src/routes/channel.ts @@ -2,6 +2,7 @@ import { Hono } from 'hono'; import { z } from 'zod'; import type { AppEnv } from '../env.js'; import { requireAuth, requireAgentToken, requireWorkspaceRead, requireWorkspaceKey } from '../middleware/auth.js'; +import { hideDmChannelFromOutsiders } from '../middleware/dmAccess.js'; import { rateLimit } from '../middleware/rateLimit.js'; import * as channelEngine from '../engine/channel.js'; import { fanoutToChannel, fanoutToWorkspace } from './fanout.js'; @@ -128,6 +129,7 @@ channelRoutes.get( channelRoutes.get( '/channels/:name', requireWorkspaceRead('channels:read'), + hideDmChannelFromOutsiders(), rateLimit, async (c) => { try { @@ -158,6 +160,7 @@ channelRoutes.get( channelRoutes.patch( '/channels/:name', requireAuth, + hideDmChannelFromOutsiders(), rateLimit, async (c) => { try { @@ -203,6 +206,7 @@ channelRoutes.patch( channelRoutes.patch( '/channels/:name/topic', requireAuth, + hideDmChannelFromOutsiders(), rateLimit, async (c) => { try { @@ -248,6 +252,7 @@ channelRoutes.patch( channelRoutes.delete( '/channels/:name', requireAuth, + hideDmChannelFromOutsiders(), rateLimit, async (c) => { try { @@ -288,6 +293,7 @@ channelRoutes.delete( channelRoutes.post( '/channels/:name/join', requireAgentToken, + hideDmChannelFromOutsiders({ refuseParticipants: true }), rateLimit, async (c) => { try { @@ -333,6 +339,7 @@ channelRoutes.post( channelRoutes.post( '/channels/:name/leave', requireAgentToken, + hideDmChannelFromOutsiders({ refuseParticipants: true }), rateLimit, async (c) => { try { @@ -379,6 +386,7 @@ channelRoutes.post( channelRoutes.get( '/channels/:name/members', requireWorkspaceRead('channels:read'), + hideDmChannelFromOutsiders(), rateLimit, async (c) => { try { @@ -411,6 +419,7 @@ channelRoutes.get( channelRoutes.post( '/channels/:name/invite', requireAuth, + hideDmChannelFromOutsiders({ refuseParticipants: true }), rateLimit, async (c) => { try { @@ -471,6 +480,7 @@ channelRoutes.post( channelRoutes.post( '/channels/:name/mute', requireAgentToken, + hideDmChannelFromOutsiders(), rateLimit, async (c) => { try { @@ -516,6 +526,7 @@ channelRoutes.post( channelRoutes.post( '/channels/:name/unmute', requireAgentToken, + hideDmChannelFromOutsiders(), rateLimit, async (c) => { try { diff --git a/packages/engine/src/routes/console.ts b/packages/engine/src/routes/console.ts index 4b4823472..c451ca258 100644 --- a/packages/engine/src/routes/console.ts +++ b/packages/engine/src/routes/console.ts @@ -4,6 +4,7 @@ import type { AppEnv } from '../env.js'; import { requireWorkspaceRead } from '../middleware/auth.js'; import { rateLimit } from '../middleware/rateLimit.js'; import * as consoleEngine from '../engine/console.js'; +import { filterAgentVisibleDmResults } from '../engine/dmAccess.js'; import { filterObserverSearchResults, getObserverTokenFromContext, @@ -75,11 +76,13 @@ consoleRoutes.get('/console/messages', requireWorkspaceRead('messages:read'), ra deliveryKind: parsed.data.delivery_kind, }); + // An agent token sees DM logs only for conversations it participates in. + const agentVisible = await filterAgentVisibleDmResults(db, c.get('agent')?.id, data); const visible = await filterObserverSearchResults( db, workspace.id, getObserverTokenFromContext(c), - data.map((item) => ({ + agentVisible.map((item) => ({ ...item, channel_name: item.channel_name ?? undefined, })), diff --git a/packages/engine/src/routes/message.ts b/packages/engine/src/routes/message.ts index 20dfa54c5..dab15f7b7 100644 --- a/packages/engine/src/routes/message.ts +++ b/packages/engine/src/routes/message.ts @@ -4,11 +4,13 @@ import { and, eq } from 'drizzle-orm'; import { agents } from '../db/tables.js'; import type { AppEnv } from '../env.js'; import { requireSender, requireWorkspaceKey, requireWorkspaceRead } from '../middleware/auth.js'; +import { hideDmChannelFromOutsiders, hideDmMessageFromOutsiders } from '../middleware/dmAccess.js'; import { rateLimit } from '../middleware/rateLimit.js'; import { admitMessage, assertMessageAdmitted } from '../middleware/admission.js'; import { jsonIdempotentOk, parseIdempotencyKey, runIdempotent } from '../middleware/idempotency.js'; import * as messageEngine from '../engine/message.js'; import * as channelEngine from '../engine/channel.js'; +import { agentDmAccessForChannelName } from '../engine/dmAccess.js'; import * as triggerEngine from '../engine/trigger.js'; import { resolveMailboxConfig } from '../engine/mailboxConfig.js'; import { resolveWorkspaceDeliveryPolicyFor } from '../engine/workspaceDeliveryPolicy.js'; @@ -136,6 +138,12 @@ messageRoutes.post( return jsonError(c, 'agent_token_required', 'Agent or node token required to post messages', 403); } const senderAgentId = sender.id; + // A DM lives on an ordinary channel row; only its participants may post + // to it by channel name. Checked on the resolved sender so a node token + // posting as `from` is held to the same rule. + if ((await agentDmAccessForChannelName(db, workspace.id, senderAgentId, channelName)) === 'outsider') { + return jsonNotFound(c, 'channel_not_found', `Channel "${channelName}" not found`); + } const senderAgentName = sender.name; const mailbox = resolveMailboxConfig(c.get('engine').config, workspace.id); @@ -289,6 +297,7 @@ messageRoutes.get( messageRoutes.get( '/channels/:name/messages', requireWorkspaceRead('messages:read'), + hideDmChannelFromOutsiders(), rateLimit, async (c) => { try { @@ -330,6 +339,7 @@ messageRoutes.get( messageRoutes.get( '/messages/:id', requireWorkspaceRead(['messages:read', 'dms:read']), + hideDmMessageFromOutsiders, rateLimit, async (c) => { try { diff --git a/packages/engine/src/routes/reaction.ts b/packages/engine/src/routes/reaction.ts index 90585ac48..188211745 100644 --- a/packages/engine/src/routes/reaction.ts +++ b/packages/engine/src/routes/reaction.ts @@ -2,6 +2,7 @@ import { Hono } from 'hono'; import { z } from 'zod'; import type { AppEnv } from '../env.js'; import { requireAgentToken, requireWorkspaceRead } from '../middleware/auth.js'; +import { hideDmMessageFromOutsiders } from '../middleware/dmAccess.js'; import { rateLimit } from '../middleware/rateLimit.js'; import * as reactionEngine from '../engine/reaction.js'; import { and, eq } from 'drizzle-orm'; @@ -36,6 +37,7 @@ const addReactionSchema = z.object({ reactionRoutes.post( '/messages/:id/reactions', requireAgentToken, + hideDmMessageFromOutsiders, rateLimit, async (c) => { try { @@ -133,6 +135,7 @@ reactionRoutes.post( reactionRoutes.delete( '/messages/:id/reactions/:emoji', requireAgentToken, + hideDmMessageFromOutsiders, rateLimit, async (c) => { try { @@ -229,6 +232,7 @@ reactionRoutes.delete( reactionRoutes.get( '/messages/:id/reactions', requireWorkspaceRead('reactions:read'), + hideDmMessageFromOutsiders, rateLimit, async (c) => { try { diff --git a/packages/engine/src/routes/receipt.ts b/packages/engine/src/routes/receipt.ts index edd7481d3..3a65e9890 100644 --- a/packages/engine/src/routes/receipt.ts +++ b/packages/engine/src/routes/receipt.ts @@ -1,6 +1,7 @@ import { Hono } from 'hono'; import type { AppEnv } from '../env.js'; import { requireAuth, requireAgentToken } from '../middleware/auth.js'; +import { hideDmChannelFromOutsiders, hideDmMessageFromOutsiders } from '../middleware/dmAccess.js'; import { rateLimit } from '../middleware/rateLimit.js'; import * as receiptEngine from '../engine/receipt.js'; import { notifySenderDeliveryReceipts } from '../engine/deliveryReceipts.js'; @@ -21,6 +22,7 @@ export const receiptRoutes = new Hono(); receiptRoutes.post( '/messages/:id/read', requireAgentToken, + hideDmMessageFromOutsiders, rateLimit, async (c) => { try { @@ -109,6 +111,7 @@ receiptRoutes.post( receiptRoutes.get( '/messages/:id/readers', requireAuth, + hideDmMessageFromOutsiders, rateLimit, async (c) => { try { @@ -134,6 +137,7 @@ receiptRoutes.get( receiptRoutes.get( '/channels/:name/read-status', requireAuth, + hideDmChannelFromOutsiders(), rateLimit, async (c) => { try { diff --git a/packages/engine/src/routes/search.ts b/packages/engine/src/routes/search.ts index 983c9e0e4..b2227b5e9 100644 --- a/packages/engine/src/routes/search.ts +++ b/packages/engine/src/routes/search.ts @@ -4,6 +4,7 @@ import type { AppEnv } from '../env.js'; import { requireWorkspaceRead } from '../middleware/auth.js'; import { rateLimit } from '../middleware/rateLimit.js'; import * as searchEngine from '../engine/search.js'; +import { filterAgentVisibleDmResults } from '../engine/dmAccess.js'; import { filterObserverSearchResults, getObserverTokenFromContext, @@ -48,11 +49,13 @@ searchRoutes.get( before, after, }, c.get('engine').search); + // An agent token sees DM hits only for conversations it participates in. + const agentVisibleResults = await filterAgentVisibleDmResults(db, c.get('agent')?.id, results); const visibleResults = await filterObserverSearchResults( db, workspace.id, getObserverTokenFromContext(c), - results, + agentVisibleResults, ); // Adapters may carry additional internal metadata. Only publish the // established response fields, after observer visibility filtering. diff --git a/packages/engine/src/routes/thread.ts b/packages/engine/src/routes/thread.ts index 9cd4f7789..c991bbbea 100644 --- a/packages/engine/src/routes/thread.ts +++ b/packages/engine/src/routes/thread.ts @@ -2,6 +2,7 @@ import { Hono } from 'hono'; import { z } from 'zod'; import type { AppEnv } from '../env.js'; import { requireAuth, requireWorkspaceRead } from '../middleware/auth.js'; +import { hideDmMessageFromOutsiders } from '../middleware/dmAccess.js'; import { rateLimit } from '../middleware/rateLimit.js'; import { admitMessage, assertMessageAdmitted } from '../middleware/admission.js'; import { jsonIdempotentOk, parseIdempotencyKey, runIdempotent } from '../middleware/idempotency.js'; @@ -36,6 +37,7 @@ const postReplySchema = z.object({ threadRoutes.post( '/messages/:id/replies', requireAuth, + hideDmMessageFromOutsiders, rateLimit, admitMessage, async (c) => { @@ -153,6 +155,7 @@ threadRoutes.post( threadRoutes.get( '/messages/:id/replies', requireWorkspaceRead('threads:read'), + hideDmMessageFromOutsiders, rateLimit, async (c) => { try {