diff --git a/apps/discord-bot/src/__tests__/commands.test.ts b/apps/discord-bot/src/__tests__/commands.test.ts index 7393bd76..7c3d0353 100644 --- a/apps/discord-bot/src/__tests__/commands.test.ts +++ b/apps/discord-bot/src/__tests__/commands.test.ts @@ -21,20 +21,42 @@ const TICKET = { sourceId: 'thread-123', }; -function makeInteraction(options: { - commandName?: string; - optionValues?: Record; - channelType?: ChannelType; - channelId?: string; -} = {}) { +function makeInteraction( + options: { + commandName?: string; + optionValues?: Record; + channelType?: ChannelType; + channelId?: string; + guildId?: string; + /** What `client.channels.fetch` resolves for the ticket's thread. */ + threadGuildId?: string | null; + /** What `client.channels.fetch` rejects with, when set. */ + fetchError?: Error; + } = {}, +) { const { optionValues = {}, channelType = ChannelType.PublicThread, channelId = 'thread-123', + guildId = 'guild-1', + threadGuildId = guildId, + fetchError, } = options; return { user: { tag: 'Admin#0001', id: 'admin-1' }, + guildId, + client: { + channels: { + fetch: fetchError + ? vi.fn().mockRejectedValue(fetchError) + : vi + .fn() + .mockResolvedValue( + threadGuildId === null ? null : { guildId: threadGuildId }, + ), + }, + }, channel: { type: channelType, id: channelId, @@ -51,10 +73,30 @@ function makeInteraction(options: { describe('handleAssign', () => { beforeEach(() => { - vi.mocked(prisma.ticket.findFirst).mockResolvedValue(TICKET as ReturnType extends Promise ? T : never); - vi.mocked(prisma.ticket.update).mockResolvedValue(TICKET as ReturnType extends Promise ? T : never); - vi.mocked(prisma.note.create).mockResolvedValue({ id: 'note-1' } as ReturnType extends Promise ? T : never); - vi.mocked(prisma.user.findFirst).mockResolvedValue(null); + vi.mocked(prisma.ticket.findFirst).mockResolvedValue( + TICKET as ReturnType extends Promise + ? T + : never, + ); + vi.mocked(prisma.ticket.update).mockResolvedValue( + TICKET as ReturnType extends Promise ? T : never, + ); + vi.mocked(prisma.note.create).mockResolvedValue({ id: 'note-1' } as ReturnType< + typeof prisma.note.create + > extends Promise + ? T + : never); + // The invoker maps to a team member; the assignee lookup finds nobody. + vi.mocked(prisma.user.findFirst).mockImplementation(((args: { + where?: { externalId?: string }; + }) => + Promise.resolve( + args?.where?.externalId === 'admin-1' ? { email: 'admin@example.com' } : null, + )) as never); + vi.mocked(prisma.teamMember.findUnique).mockResolvedValue({ + id: 'tm-1', + status: 'ACTIVE', + } as ReturnType extends Promise ? T : never); }); it('assigns a ticket to a user via thread context', async () => { @@ -81,7 +123,11 @@ describe('handleAssign', () => { }); it('assigns by explicit ticket ID', async () => { - vi.mocked(prisma.ticket.findUnique).mockResolvedValue(TICKET as ReturnType extends Promise ? T : never); + vi.mocked(prisma.ticket.findUnique).mockResolvedValue( + TICKET as ReturnType extends Promise + ? T + : never, + ); const interaction = makeInteraction({ optionValues: { @@ -98,6 +144,175 @@ describe('handleAssign', () => { expect(prisma.ticket.update).toHaveBeenCalled(); }); + it('rejects invokers who are not team members', async () => { + vi.mocked(prisma.user.findFirst).mockResolvedValue(null); + + const interaction = makeInteraction({ + optionValues: { + user: { tag: 'Engineer#1234', id: 'eng-1' }, + ticket: 'TKT-AB12', + }, + }); + + await handleAssign(interaction); + + expect(interaction.reply).toHaveBeenCalledWith( + expect.objectContaining({ + content: expect.stringContaining('Only team members'), + ephemeral: true, + }), + ); + expect(prisma.ticket.findUnique).not.toHaveBeenCalled(); + expect(prisma.ticket.update).not.toHaveBeenCalled(); + }); + + it('rejects an explicit ticket ID from another source', async () => { + vi.mocked(prisma.ticket.findUnique).mockResolvedValue({ + ...TICKET, + source: 'GITHUB_ISSUE', + sourceId: '42', + } as ReturnType extends Promise ? T : never); + + const interaction = makeInteraction({ + optionValues: { + user: { tag: 'Engineer#1234', id: 'eng-1' }, + ticket: 'TKT-AB12', + }, + }); + + await handleAssign(interaction); + + expect(interaction.reply).toHaveBeenCalledWith( + expect.objectContaining({ + content: expect.stringContaining('No ticket found'), + ephemeral: true, + }), + ); + expect(prisma.ticket.update).not.toHaveBeenCalled(); + }); + + it('rejects an explicit ticket ID whose thread is in another guild', async () => { + vi.mocked(prisma.ticket.findUnique).mockResolvedValue( + TICKET as ReturnType extends Promise + ? T + : never, + ); + + const interaction = makeInteraction({ + optionValues: { + user: { tag: 'Engineer#1234', id: 'eng-1' }, + ticket: 'TKT-AB12', + }, + threadGuildId: 'other-guild', + }); + + await handleAssign(interaction); + + expect(interaction.reply).toHaveBeenCalledWith( + expect.objectContaining({ + content: expect.stringContaining('No ticket found'), + ephemeral: true, + }), + ); + expect(prisma.ticket.update).not.toHaveBeenCalled(); + }); + + it('rejects an explicit ticket ID whose thread is gone', async () => { + vi.mocked(prisma.ticket.findUnique).mockResolvedValue( + TICKET as ReturnType extends Promise + ? T + : never, + ); + + const interaction = makeInteraction({ + optionValues: { + user: { tag: 'Engineer#1234', id: 'eng-1' }, + ticket: 'TKT-AB12', + }, + // DiscordAPIError 10003: Unknown Channel. + fetchError: Object.assign(new Error('Unknown Channel'), { code: 10003 }), + }); + + await handleAssign(interaction); + + expect(interaction.reply).toHaveBeenCalledWith( + expect.objectContaining({ + content: expect.stringContaining('No ticket found'), + ephemeral: true, + }), + ); + expect(prisma.ticket.update).not.toHaveBeenCalled(); + }); + + it('rejects an explicit ticket ID when the thread fetch resolves null', async () => { + vi.mocked(prisma.ticket.findUnique).mockResolvedValue( + TICKET as ReturnType extends Promise + ? T + : never, + ); + + const interaction = makeInteraction({ + optionValues: { + user: { tag: 'Engineer#1234', id: 'eng-1' }, + ticket: 'TKT-AB12', + }, + threadGuildId: null, + }); + + await handleAssign(interaction); + + expect(interaction.reply).toHaveBeenCalledWith( + expect.objectContaining({ + content: expect.stringContaining('No ticket found'), + ephemeral: true, + }), + ); + expect(prisma.ticket.update).not.toHaveBeenCalled(); + }); + + it('surfaces transient Discord API failures instead of claiming no ticket', async () => { + vi.mocked(prisma.ticket.findUnique).mockResolvedValue( + TICKET as ReturnType extends Promise + ? T + : never, + ); + + const interaction = makeInteraction({ + optionValues: { + user: { tag: 'Engineer#1234', id: 'eng-1' }, + ticket: 'TKT-AB12', + }, + fetchError: new Error('rate limited'), + }); + + await expect(handleAssign(interaction)).rejects.toThrow('rate limited'); + expect(prisma.ticket.update).not.toHaveBeenCalled(); + }); + + it('rejects invokers whose team membership is disabled', async () => { + vi.mocked(prisma.teamMember.findUnique).mockResolvedValue({ + id: 'tm-1', + status: 'DISABLED', + } as ReturnType extends Promise ? T : never); + + const interaction = makeInteraction({ + optionValues: { + user: { tag: 'Engineer#1234', id: 'eng-1' }, + ticket: 'TKT-AB12', + }, + }); + + await handleAssign(interaction); + + expect(interaction.reply).toHaveBeenCalledWith( + expect.objectContaining({ + content: expect.stringContaining('Only team members'), + ephemeral: true, + }), + ); + expect(prisma.ticket.update).not.toHaveBeenCalled(); + }); + it('errors when used outside a thread without a ticket ID', async () => { const interaction = makeInteraction({ optionValues: { @@ -119,9 +334,19 @@ describe('handleAssign', () => { describe('handleClose', () => { beforeEach(() => { - vi.mocked(prisma.ticket.findFirst).mockResolvedValue(TICKET as ReturnType extends Promise ? T : never); - vi.mocked(prisma.ticket.update).mockResolvedValue(TICKET as ReturnType extends Promise ? T : never); - vi.mocked(prisma.note.create).mockResolvedValue({ id: 'note-1' } as ReturnType extends Promise ? T : never); + vi.mocked(prisma.ticket.findFirst).mockResolvedValue( + TICKET as ReturnType extends Promise + ? T + : never, + ); + vi.mocked(prisma.ticket.update).mockResolvedValue( + TICKET as ReturnType extends Promise ? T : never, + ); + vi.mocked(prisma.note.create).mockResolvedValue({ id: 'note-1' } as ReturnType< + typeof prisma.note.create + > extends Promise + ? T + : never); }); it('closes the ticket with a reason', async () => { @@ -177,9 +402,19 @@ describe('handleClose', () => { describe('handleEscalate', () => { beforeEach(() => { - vi.mocked(prisma.ticket.findFirst).mockResolvedValue(TICKET as ReturnType extends Promise ? T : never); - vi.mocked(prisma.ticket.update).mockResolvedValue(TICKET as ReturnType extends Promise ? T : never); - vi.mocked(prisma.note.create).mockResolvedValue({ id: 'note-1' } as ReturnType extends Promise ? T : never); + vi.mocked(prisma.ticket.findFirst).mockResolvedValue( + TICKET as ReturnType extends Promise + ? T + : never, + ); + vi.mocked(prisma.ticket.update).mockResolvedValue( + TICKET as ReturnType extends Promise ? T : never, + ); + vi.mocked(prisma.note.create).mockResolvedValue({ id: 'note-1' } as ReturnType< + typeof prisma.note.create + > extends Promise + ? T + : never); }); it('escalates the ticket to HIGH priority', async () => { @@ -241,9 +476,19 @@ describe('handleEscalate', () => { describe('handlePriority', () => { beforeEach(() => { - vi.mocked(prisma.ticket.findFirst).mockResolvedValue(TICKET as ReturnType extends Promise ? T : never); - vi.mocked(prisma.ticket.update).mockResolvedValue(TICKET as ReturnType extends Promise ? T : never); - vi.mocked(prisma.note.create).mockResolvedValue({ id: 'note-1' } as ReturnType extends Promise ? T : never); + vi.mocked(prisma.ticket.findFirst).mockResolvedValue( + TICKET as ReturnType extends Promise + ? T + : never, + ); + vi.mocked(prisma.ticket.update).mockResolvedValue( + TICKET as ReturnType extends Promise ? T : never, + ); + vi.mocked(prisma.note.create).mockResolvedValue({ id: 'note-1' } as ReturnType< + typeof prisma.note.create + > extends Promise + ? T + : never); }); it('updates ticket priority to the specified level', async () => { diff --git a/apps/discord-bot/src/__tests__/tickets.test.ts b/apps/discord-bot/src/__tests__/tickets.test.ts index eaacc0fb..067ff7ca 100644 --- a/apps/discord-bot/src/__tests__/tickets.test.ts +++ b/apps/discord-bot/src/__tests__/tickets.test.ts @@ -33,7 +33,9 @@ describe('findTicketByThreadId', () => { it('returns the ticket when found', async () => { const ticket = { id: 'ticket-1', source: 'DISCORD', sourceId: 'thread-123' }; vi.mocked(prisma.ticket.findFirst).mockResolvedValue( - ticket as ReturnType extends Promise ? T : never, + ticket as ReturnType extends Promise + ? T + : never, ); expect(await findTicketByThreadId('thread-123')).toEqual(ticket); @@ -61,13 +63,14 @@ describe('isTeamMember', () => { vi.clearAllMocks(); }); - it('returns true when the user maps to a TeamMember', async () => { + it('returns true when the user maps to an active TeamMember', async () => { vi.mocked(prisma.user.findFirst).mockResolvedValue({ id: 'u-1', email: 'team@copilotkit.ai', } as ReturnType extends Promise ? T : never); vi.mocked(prisma.teamMember.findUnique).mockResolvedValue({ id: 'tm-1', + status: 'ACTIVE', } as ReturnType extends Promise ? T : never); expect(await isTeamMember('discord-user-1')).toBe(true); @@ -76,6 +79,29 @@ describe('isTeamMember', () => { }); }); + it.each(['DISABLED', 'INVITED'] as const)('returns false for a %s member', async (status) => { + vi.mocked(prisma.user.findFirst).mockResolvedValue({ + id: 'u-1', + email: 'team@copilotkit.ai', + } as ReturnType extends Promise ? T : never); + vi.mocked(prisma.teamMember.findUnique).mockResolvedValue({ + id: 'tm-1', + status, + } as ReturnType extends Promise ? T : never); + + expect(await isTeamMember('discord-user-1')).toBe(false); + }); + + it('returns false when no TeamMember row exists', async () => { + vi.mocked(prisma.user.findFirst).mockResolvedValue({ + id: 'u-1', + email: 'team@copilotkit.ai', + } as ReturnType extends Promise ? T : never); + vi.mocked(prisma.teamMember.findUnique).mockResolvedValue(null); + + expect(await isTeamMember('discord-user-1')).toBe(false); + }); + it('returns false when no User row exists', async () => { vi.mocked(prisma.user.findFirst).mockResolvedValue(null); diff --git a/apps/discord-bot/src/commands/assign.ts b/apps/discord-bot/src/commands/assign.ts index c6dd2ca3..ab1bc97e 100644 --- a/apps/discord-bot/src/commands/assign.ts +++ b/apps/discord-bot/src/commands/assign.ts @@ -1,18 +1,57 @@ import { ChannelType, type ChatInputCommandInteraction } from 'discord.js'; import { prisma } from '@copilotkit/outpost/db'; -import { findTicketByThreadId } from '../lib/tickets.js'; +import { findTicketByThreadId, isTeamMember } from '../lib/tickets.js'; + +/** + * Whether the ticket is a Discord ticket whose thread lives in the guild this + * command was invoked in. Tickets from other sources have no Discord thread + * to check, so they are out of reach here by definition. + */ +async function ticketInThisGuild( + interaction: ChatInputCommandInteraction, + ticket: { source: string; sourceId: string | null }, +): Promise { + if (ticket.source !== 'DISCORD' || !ticket.sourceId) return false; + + try { + const thread = await interaction.client.channels.fetch(ticket.sourceId); + return thread !== null && 'guildId' in thread && thread.guildId === interaction.guildId; + } catch (error) { + // Only "the channel is gone" (10003 Unknown Channel, 10004 Unknown + // Guild) means the ticket is unreachable. A rate limit or API failure + // is transient — let it surface as an error rather than claim the + // ticket does not exist. + const code = (error as { code?: number } | null)?.code; + if (code === 10003 || code === 10004) return false; + throw error; + } +} export async function handleAssign(interaction: ChatInputCommandInteraction): Promise { + // Display ids are public — they get pasted into community threads — so the + // id alone is not evidence that the invoker may touch the ticket. Only + // team members may reassign. + if (!(await isTeamMember(interaction.user.id))) { + await interaction.reply({ + content: 'Only team members can assign tickets.', + ephemeral: true, + }); + return; + } + const user = interaction.options.getUser('user', true); const ticketIdOption = interaction.options.getString('ticket'); let ticket; if (ticketIdOption) { - // Look up by explicit ticket ID - ticket = await prisma.ticket.findUnique({ + // Look up by explicit ticket ID, then check the ticket is one this + // command can reach. Anything else gets the same reply as a bad id, + // so the answer never reveals that the ticket exists elsewhere. + const found = await prisma.ticket.findUnique({ where: { displayId: ticketIdOption }, }); + ticket = found && (await ticketInThisGuild(interaction, found)) ? found : null; } else { // Look up by current thread const channel = interaction.channel; @@ -32,7 +71,8 @@ export async function handleAssign(interaction: ChatInputCommandInteraction): Pr if (!ticket) { await interaction.reply({ - content: 'No ticket found. Make sure you are in a tracked thread or provide a valid ticket ID.', + content: + 'No ticket found. Make sure you are in a tracked thread or provide a valid ticket ID.', ephemeral: true, }); return; diff --git a/apps/discord-bot/src/lib/tickets.ts b/apps/discord-bot/src/lib/tickets.ts index cd19dcf6..b5c5b49f 100644 --- a/apps/discord-bot/src/lib/tickets.ts +++ b/apps/discord-bot/src/lib/tickets.ts @@ -45,5 +45,7 @@ export async function isTeamMember(discordUserId: string): Promise { where: { email: user.email }, }); - return member !== null; + // Only an active member counts: a disabled member keeps their Discord link + // and email, and an invited one has not accepted yet — neither may act. + return member?.status === 'ACTIVE'; }