Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
149 changes: 149 additions & 0 deletions apps/web/src/__tests__/team-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const mockInviteTokenCreate = vi.fn();
const mockInviteTokenUpdate = vi.fn();
const mockInviteTokenDeleteMany = vi.fn();
const mockOrganizationFindFirst = vi.fn();
const mockTemplateOverrideFindUnique = vi.fn();
const mockTransaction = vi.fn();

vi.mock('@copilotkit/outpost/db', () => ({
Expand All @@ -36,6 +37,9 @@ vi.mock('@copilotkit/outpost/db', () => ({
organization: {
findFirst: (...args: unknown[]) => mockOrganizationFindFirst(...args),
},
templateOverride: {
findUnique: (...args: unknown[]) => mockTemplateOverrideFindUnique(...args),
},
$transaction: (...args: unknown[]) => mockTransaction(...args),
},
}));
Expand All @@ -60,6 +64,7 @@ vi.mock('next-auth', () => ({

// ─── Import route handlers ─────────────────────────────────────────────────

import { sendEmail } from '@copilotkit/outpost/shared/server';
import { POST as invitePost } from '@/app/api/team/invite/route';
import { GET as teamGet } from '@/app/api/team/route';
import { PATCH as memberPatch, DELETE as memberDelete } from '@/app/api/team/[id]/route';
Expand Down Expand Up @@ -116,6 +121,150 @@ describe('Team API', () => {
vi.clearAllMocks();
});

it('uses a saved invite template for new and resent invitations, then falls back after removal', async () => {
const actual = await vi.importActual<typeof import('@copilotkit/outpost/shared/server')>(
'@copilotkit/outpost/shared/server',
);
const delivered = vi.fn().mockResolvedValue({ id: 'mail-1' });
vi.mocked(sendEmail).mockImplementation((options) =>
actual.sendEmail({ ...options, transport: { send: delivered } }),
);
mockGetServerSession.mockResolvedValue(adminSession());
mockOrganizationFindFirst.mockResolvedValue({
name: 'Example Org',
email: 'org@example.test',
});
mockTeamMemberCreate.mockResolvedValue({
id: 'm1',
email: 'person@example.test',
role: 'MEMBER',
status: 'INVITED',
});
mockInviteTokenDeleteMany.mockResolvedValue({ count: 1 });
mockInviteTokenCreate.mockResolvedValue({ token: 'token' });

try {
for (const saved of [true, false]) {
// Clear per pass: toHaveBeenCalledWith is satisfied by any
// earlier call, so without this the second pass would pass on
// the first pass's lookups alone.
mockTemplateOverrideFindUnique.mockClear();
mockTemplateOverrideFindUnique.mockResolvedValue(
saved
? {
subject: 'Custom {{org.name}}',
body: 'Hello {{member.name}} — accept at {{invite.url}}',
}
: null,
);
const deliveriesBefore = delivered.mock.calls.length;
mockTeamMemberFindUnique
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ name: 'Admin' });
expect(
(
await invitePost(
jsonRequest('http://localhost:3000/api/team/invite', {
email: 'person@example.test',
}),
)
).status,
).toBe(200);
mockTeamMemberFindUnique.mockResolvedValueOnce({
id: 'm1',
name: 'person',
email: 'person@example.test',
role: 'MEMBER',
status: 'INVITED',
});
expect(
(
await resendInvite(
jsonRequest('http://localhost:3000/api/team/invite/resend', {
memberId: 'm1',
}),
)
).status,
).toBe(200);
expect(delivered.mock.calls.length).toBe(deliveriesBefore + 2);
expect(mockTemplateOverrideFindUnique).toHaveBeenCalledWith({
where: { slug: 'invite' },
});
const messages = delivered.mock.calls.slice(-2).map(([message]) => message);
for (const message of messages) {
if (saved) {
expect(message.subject).toBe('Custom Example Org');
expect(message.text).toContain('Hello person');
// The saved override carries the accept link, so the
// delivered email must contain the real invite URL.
expect(message.text).toContain('/invite/accept?token=');
} else {
expect(message.subject).toBe("You've been invited to join Example Org");
expect(message.text).toContain("You've been invited to join");
expect(message.text).toContain('/invite/accept?token=');
}
}
}
} finally {
vi.mocked(sendEmail)
.mockReset()
.mockResolvedValue({ success: true, method: 'console' });
}
});

it('falls back to the on-disk invite template when the saved override lacks the accept link', async () => {
const actual = await vi.importActual<typeof import('@copilotkit/outpost/shared/server')>(
'@copilotkit/outpost/shared/server',
);
const delivered = vi.fn().mockResolvedValue({ id: 'mail-1' });
vi.mocked(sendEmail).mockImplementation((options) =>
actual.sendEmail({ ...options, transport: { send: delivered } }),
);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
mockGetServerSession.mockResolvedValue(adminSession());
mockOrganizationFindFirst.mockResolvedValue({
name: 'Example Org',
email: 'org@example.test',
});
mockTeamMemberCreate.mockResolvedValue({
id: 'm1',
email: 'person@example.test',
role: 'MEMBER',
status: 'INVITED',
});
mockTeamMemberFindUnique
.mockResolvedValueOnce(null) // no existing member with this email
.mockResolvedValueOnce({ name: 'Admin' }); // inviter lookup
// A row saved before the PUT check existed never went through it, so
// it can lack the accept link the send path requires.
mockTemplateOverrideFindUnique.mockResolvedValue({
subject: 'Custom {{org.name}}',
body: 'Hello {{member.name}}',
});

try {
const res = await invitePost(
jsonRequest('http://localhost:3000/api/team/invite', {
email: 'person@example.test',
}),
);

expect(res.status).toBe(200);
expect(delivered).toHaveBeenCalledTimes(1);
const message = delivered.mock.calls[0][0];
// The link-less override is skipped, so the on-disk template —
// which carries the accept link — is what actually goes out.
expect(message.subject).toBe("You've been invited to join Example Org");
expect(message.text).toContain('/invite/accept?token=');
expect(warn).toHaveBeenCalledWith(expect.stringContaining('{{invite.url}}'));
} finally {
vi.mocked(sendEmail)
.mockReset()
.mockResolvedValue({ success: true, method: 'console' });
warn.mockRestore();
}
});

// ── Invite creates member + token ──────────────────────────────────────

describe('POST /api/team/invite', () => {
Expand Down
62 changes: 62 additions & 0 deletions apps/web/src/__tests__/templates-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,40 @@ describe('template persistence and preview (outpost#226)', () => {
expect(mockOverrideUpsert).not.toHaveBeenCalled();
});

it('requires the accept link in invitation templates', async () => {
const res = await putTemplate(
jsonRequest({ subject: 'Invitation', body: 'You are invited' }),
routeParams('invite'),
);

expect(res.status).toBe(400);
expect((await res.json()).error).toMatch(/accept link.*required/i);
expect(mockOverrideUpsert).not.toHaveBeenCalled();
});

it('accepts an invitation template containing the accept link', async () => {
const res = await putTemplate(
jsonRequest({ subject: 'Invitation', body: 'Accept: {{invite.url}}' }),
routeParams('invite'),
);

expect(res.status).toBe(200);
expect(mockOverrideUpsert).toHaveBeenCalledTimes(1);
});

it('accepts the spaced spelling of the accept link', async () => {
// `interpolate` trims whitespace inside the braces, so this body
// renders a working link — rejecting it on save would 400 a
// template that is actually fine.
const res = await putTemplate(
jsonRequest({ subject: 'Invitation', body: 'Accept: {{ invite.url }}' }),
routeParams('invite'),
);

expect(res.status).toBe(200);
expect(mockOverrideUpsert).toHaveBeenCalledTimes(1);
});

it('rejects an oversized body', async () => {
const res = await putTemplate(
jsonRequest({ subject: 's', body: 'x'.repeat(100_001) }),
Expand All @@ -221,6 +255,16 @@ describe('template persistence and preview (outpost#226)', () => {
expect(mockOverrideUpsert).not.toHaveBeenCalled();
});

it('rejects control characters in the subject', async () => {
const res = await putTemplate(
jsonRequest({ subject: 'Hi\r\nBcc: attacker@example.com', body: 'b' }),
routeParams(REAL_SLUG),
);

expect(res.status).toBe(400);
expect(mockOverrideUpsert).not.toHaveBeenCalled();
});

it('rejects a body that is not valid JSON', async () => {
const badRequest = {
json: async () => {
Expand Down Expand Up @@ -489,6 +533,24 @@ describe('template persistence and preview (outpost#226)', () => {
expect(data.html).toContain('Jane Smith');
expect(data.html).not.toContain('{{member.name}}');
});

it('previews invite templates with the context invitation emails receive', async () => {
const res = await previewTemplate(
jsonRequest({
draft: {
subject: 'Invite expires in {{invite.expiresIn}}',
body: 'app={{app.url}} ticket={{ticket.displayId}} expires={{invite.expiresIn}}',
},
}),
routeParams('invite'),
);
const data = await res.json();

expect(data.subject).toBe('Invite expires in 1 hour');
expect(data.html).toContain('app= ticket= expires=1 hour');
expect(data.html).not.toContain('app.outpost.dev');
expect(data.html).not.toContain('TKT-0042');
});
});
});

Expand Down
29 changes: 22 additions & 7 deletions apps/web/src/__tests__/templates-page.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,13 +181,8 @@ describe('the editor reports what the server actually said (outpost#226)', () =>
});
});

// A save writes the override and every read surface honours it, but outgoing email
// does not — `sendEmail` consults an override only when handed a `dbLookup`, and
// neither invite call site passes one, so the invitee gets the on-disk copy.
// "Template saved successfully" was true about the row and false about the thing
// the author cared about. These pin the honest copy, because the dishonest version
// is the shorter and more natural string to write.
describe('the editor does not claim more than a save delivers (outpost#226)', () => {
// Invitation delivery uses overrides; other templates remain preview-only.
describe('the editor describes which saved templates are used', () => {
beforeEach(() => {
mockApiFetch.mockReset();
});
Expand All @@ -210,6 +205,26 @@ describe('the editor does not claim more than a save delivers (outpost#226)', ()
expect(screen.queryByText('Template saved successfully')).toBeNull();
});

it('marks a saved invitation as active and says it will be used', async () => {
const invite = {
...TEMPLATE_LIST[0],
slug: 'invite',
name: 'Invitation',
isOverride: true,
};
mockApiFetch.mockImplementation(async (url: string) => {
if (url === '/api/templates') return jsonOk([invite]);
return jsonOk({ ...TEMPLATE_DETAIL, slug: 'invite', name: 'Invitation' });
});
render(<TemplatesPage />);
fireEvent.click(await screen.findByRole('button', { name: /invitation/i }));
expect(await screen.findByText('Custom')).toBeTruthy();
fireEvent.click(await screen.findByRole('button', { name: /save/i }));
expect(
await screen.findByText('Saved. New invitation emails will use this template.'),
).toBeTruthy();
});

it('marks an overridden template as preview-only in the list', async () => {
// The shared fixture is un-overridden, so this test supplies its own — the
// badge only appears for a template that actually has a stored override.
Expand Down
11 changes: 9 additions & 2 deletions apps/web/src/app/api/team/invite/resend/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { NextResponse } from 'next/server';
import { prisma } from '@copilotkit/outpost/db';
import { requireAdmin } from '@/lib/require-admin';
import { sendEmail } from '@copilotkit/outpost/shared/server';
import { findSendableTemplateOverride } from '@/lib/template-override';

export async function POST(request: Request) {
const { error } = await requireAdmin();
Expand All @@ -27,7 +28,10 @@ export async function POST(request: Request) {
});

if (!member || member.status !== 'INVITED') {
return NextResponse.json({ error: 'No pending invitation found for this member' }, { status: 404 });
return NextResponse.json(
{ error: 'No pending invitation found for this member' },
{ status: 404 },
);
}

const token = randomBytes(32).toString('hex');
Expand All @@ -52,6 +56,7 @@ export async function POST(request: Request) {
const emailResult = await sendEmail({
to: member.email,
template: 'invite',
dbLookup: findSendableTemplateOverride,
context: {
org: {
name: org?.name || 'Outpost',
Expand All @@ -71,7 +76,9 @@ export async function POST(request: Request) {
});

if (!emailResult.success) {
console.warn(`[INVITE] Failed to resend invite email to ${member.email}: ${emailResult.error}`);
console.warn(
`[INVITE] Failed to resend invite email to ${member.email}: ${emailResult.error}`,
);
return NextResponse.json({ ...responseData, emailSent: false });
}
} catch (emailError) {
Expand Down
19 changes: 15 additions & 4 deletions apps/web/src/app/api/team/invite/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { NextResponse } from 'next/server';
import { prisma } from '@copilotkit/outpost/db';
import { requireAdmin } from '@/lib/require-admin';
import { sendEmail } from '@copilotkit/outpost/shared/server';
import { findSendableTemplateOverride } from '@/lib/template-override';

export async function POST(request: Request) {
const { error, session } = await requireAdmin();
Expand All @@ -21,13 +22,20 @@ export async function POST(request: Request) {
return NextResponse.json({ error: 'Valid email is required' }, { status: 400 });
}

const validRole = (role && ['ADMIN', 'MEMBER'].includes(role) ? role : 'MEMBER') as 'ADMIN' | 'MEMBER';
const validRole = (role && ['ADMIN', 'MEMBER'].includes(role) ? role : 'MEMBER') as
| 'ADMIN'
| 'MEMBER';

try {
// Check for existing member with this email
const existing = await prisma.teamMember.findUnique({ where: { email: email.trim().toLowerCase() } });
const existing = await prisma.teamMember.findUnique({
where: { email: email.trim().toLowerCase() },
});
if (existing) {
return NextResponse.json({ error: 'A team member with this email already exists' }, { status: 409 });
return NextResponse.json(
{ error: 'A team member with this email already exists' },
{ status: 409 },
);
}

const inviterId = (session!.user as Record<string, unknown>).memberId as string;
Expand Down Expand Up @@ -72,6 +80,7 @@ export async function POST(request: Request) {
const emailResult = await sendEmail({
to: email.trim().toLowerCase(),
template: 'invite',
dbLookup: findSendableTemplateOverride,
context: {
org: {
name: org?.name || 'Outpost',
Expand All @@ -91,7 +100,9 @@ export async function POST(request: Request) {
});

if (!emailResult.success) {
console.warn(`[INVITE] Failed to send invite email to ${email}: ${emailResult.error}`);
console.warn(
`[INVITE] Failed to send invite email to ${email}: ${emailResult.error}`,
);
return NextResponse.json({ ...responseData, emailSent: false });
}
} catch (emailError) {
Expand Down
Loading
Loading