diff --git a/apps/web/src/__tests__/team-api.test.ts b/apps/web/src/__tests__/team-api.test.ts index 11e870a1..a162e062 100644 --- a/apps/web/src/__tests__/team-api.test.ts +++ b/apps/web/src/__tests__/team-api.test.ts @@ -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', () => ({ @@ -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), }, })); @@ -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'; @@ -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( + '@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( + '@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', () => { diff --git a/apps/web/src/__tests__/templates-api.test.ts b/apps/web/src/__tests__/templates-api.test.ts index 49ed0c54..5ccc37fc 100644 --- a/apps/web/src/__tests__/templates-api.test.ts +++ b/apps/web/src/__tests__/templates-api.test.ts @@ -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) }), @@ -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 () => { @@ -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'); + }); }); }); diff --git a/apps/web/src/__tests__/templates-page.test.tsx b/apps/web/src/__tests__/templates-page.test.tsx index bab8d3fe..7c010c89 100644 --- a/apps/web/src/__tests__/templates-page.test.tsx +++ b/apps/web/src/__tests__/templates-page.test.tsx @@ -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(); }); @@ -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(); + 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. diff --git a/apps/web/src/app/api/team/invite/resend/route.ts b/apps/web/src/app/api/team/invite/resend/route.ts index 623ca6b8..3378c6bf 100644 --- a/apps/web/src/app/api/team/invite/resend/route.ts +++ b/apps/web/src/app/api/team/invite/resend/route.ts @@ -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(); @@ -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'); @@ -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', @@ -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) { diff --git a/apps/web/src/app/api/team/invite/route.ts b/apps/web/src/app/api/team/invite/route.ts index 8bb3b8f8..1602e7f7 100644 --- a/apps/web/src/app/api/team/invite/route.ts +++ b/apps/web/src/app/api/team/invite/route.ts @@ -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(); @@ -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).memberId as string; @@ -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', @@ -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) { diff --git a/apps/web/src/app/api/templates/[slug]/preview/route.ts b/apps/web/src/app/api/templates/[slug]/preview/route.ts index 2d183495..b1d169f3 100644 --- a/apps/web/src/app/api/templates/[slug]/preview/route.ts +++ b/apps/web/src/app/api/templates/[slug]/preview/route.ts @@ -1,7 +1,7 @@ import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth/next'; import { authOptions } from '@/lib/auth'; -import { prisma } from '@copilotkit/outpost/db'; +import { findTemplateOverride } from '@/lib/template-override'; import { isKnownTemplateSlug, renderTemplate } from '@copilotkit/outpost/shared/server'; import type { TemplateContext } from '@copilotkit/outpost/shared/server'; @@ -48,6 +48,18 @@ const SAMPLE_CONTEXT: TemplateContext = { }, }; +/** Invite previews use the same context shape the invite routes send. */ +const INVITE_SAMPLE_CONTEXT: TemplateContext = { + org: { name: 'Acme Corp', email: 'support@example.com' }, + member: { + name: 'Alex Member', + email: 'alex@example.com', + invitedBy: 'John Admin', + role: 'Engineer', + }, + invite: { url: 'https://app.outpost.dev/invite/sample-token', expiresIn: '1 hour' }, +}; + /** * POST /api/templates/[slug]/preview * @@ -107,9 +119,10 @@ export async function POST( const body = (parsed ?? {}) as Record; - let context = SAMPLE_CONTEXT; + const sampleContext = slug === 'invite' ? INVITE_SAMPLE_CONTEXT : SAMPLE_CONTEXT; + let context = sampleContext; if (body.context && typeof body.context === 'object') { - context = { ...SAMPLE_CONTEXT, ...(body.context as object) }; + context = { ...sampleContext, ...(body.context as object) }; } // A draft that is present but unusable is a client bug, not a request to preview @@ -136,10 +149,7 @@ export async function POST( // wins over the stored row, which is the whole point of previewing edits. const lookup = useDraft ? async () => ({ subject: draft!.subject as string, body: draft!.body as string }) - : async (s: string) => { - const override = await prisma.templateOverride.findUnique({ where: { slug: s } }); - return override ? { subject: override.subject, body: override.body } : null; - }; + : findTemplateOverride; const result = await renderTemplate(slug, context, lookup); if (!result) { diff --git a/apps/web/src/app/api/templates/[slug]/route.ts b/apps/web/src/app/api/templates/[slug]/route.ts index c45fbc6f..4f958c72 100644 --- a/apps/web/src/app/api/templates/[slug]/route.ts +++ b/apps/web/src/app/api/templates/[slug]/route.ts @@ -2,23 +2,12 @@ import { NextRequest, NextResponse } from 'next/server'; import { requireSession, requireAdmin } from '@/lib/require-admin'; import { prisma } from '@copilotkit/outpost/db'; import { isKnownTemplateSlug, loadTemplate } from '@copilotkit/outpost/shared/server'; +import { findTemplateOverride, hasInviteUrl } from '@/lib/template-override'; /** Bounds on stored template content. The subject becomes an email header downstream. */ const SUBJECT_MAX = 500; const BODY_MAX = 100_000; -/** - * Look up a stored override for a slug. - * - * Passed into `loadTemplate` so the shared loader stays free of a Prisma - * dependency — it takes the lookup as an argument. - */ -async function findOverride(slug: string): Promise<{ subject: string; body: string } | null> { - const override = await prisma.templateOverride.findUnique({ where: { slug } }); - if (!override) return null; - return { subject: override.subject, body: override.body }; -} - /** * GET /api/templates/[slug] * @@ -43,7 +32,7 @@ export async function GET( return NextResponse.json({ error: 'Template not found' }, { status: 404 }); } - const loaded = await loadTemplate(slug, findOverride); + const loaded = await loadTemplate(slug, findTemplateOverride); if (!loaded) { return NextResponse.json({ error: 'Template not found' }, { status: 404 }); @@ -93,6 +82,15 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{ ); } + // The subject becomes an email header downstream; control characters can + // split it into extra headers at the provider. + if (/[\x00-\x1f\x7f]/.test(subject)) { + return NextResponse.json( + { error: 'subject must not contain control characters' }, + { status: 400 }, + ); + } + // Both columns are unbounded in the schema, and the subject becomes an email header // downstream, so the bound belongs here. if (subject.length > SUBJECT_MAX || templateBody.length > BODY_MAX) { @@ -115,6 +113,16 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{ return NextResponse.json({ error: 'Template not found' }, { status: 404 }); } + // The renderer trims whitespace inside the braces, so `{{ invite.url }}` + // produces a working link — the check has to accept every spelling + // `interpolate` does, which is what hasInviteUrl shares with the send path. + if (slug === 'invite' && !hasInviteUrl(templateBody)) { + return NextResponse.json( + { error: 'The invitation accept link {{invite.url}} is required in the body' }, + { status: 400 }, + ); + } + // Falls back to the member id: the session callback always sets one, so an absent // email should not cost us the audit trail on a security-relevant screen. const user = session.user as Record | undefined; diff --git a/apps/web/src/app/settings/templates/page.tsx b/apps/web/src/app/settings/templates/page.tsx index 2b233427..fbedc051 100644 --- a/apps/web/src/app/settings/templates/page.tsx +++ b/apps/web/src/app/settings/templates/page.tsx @@ -123,19 +123,11 @@ export default function TemplatesPage() { }); if (!res.ok) throw new Error(await describeFailure(res, 'Save failed')); await fetchTemplates(); - // Says what actually happened. The override is written and every read - // surface honours it — this list, GET, the preview — but outgoing email - // does not: `sendEmail` consults an override only when handed a - // `dbLookup` (shared/src/email/sender.ts:166), and neither - // api/team/invite/route.ts:72 nor invite/resend/route.ts:52 passes one. - // So an invitee receives the on-disk copy. - // - // "Template saved successfully" was true about the row and false about - // the thing the author cared about, which is the same silent-success - // shape as the rest of this screen's history. Wiring the lookup is - // tracked separately, and per outpost#253 would not make an edited - // template reach an invitee today either. - setSuccess('Saved. Not yet used for outgoing email — see outpost#226.'); + setSuccess( + selected.slug === 'invite' + ? 'Saved. New invitation emails will use this template.' + : 'Saved for preview. This template is not yet used for outgoing email.', + ); } catch (err) { setError(err instanceof Error ? err.message : 'Save failed'); } finally { @@ -174,7 +166,7 @@ export default function TemplatesPage() {
@@ -218,7 +210,11 @@ export default function TemplatesPage() { : 'bg-muted text-muted-foreground' }`} > - {t.isOverride ? 'Custom (preview only)' : 'Default'} + {t.isOverride + ? t.slug === 'invite' + ? 'Custom' + : 'Custom (preview only)' + : 'Default'}

diff --git a/apps/web/src/lib/template-override.ts b/apps/web/src/lib/template-override.ts new file mode 100644 index 00000000..aa3724b0 --- /dev/null +++ b/apps/web/src/lib/template-override.ts @@ -0,0 +1,55 @@ +import { prisma } from '@copilotkit/outpost/db'; + +/** + * Look up a stored override for a slug. + * + * Passed into `loadTemplate` so the shared loader stays free of a Prisma + * dependency — it takes the lookup as an argument. The editor, the preview and + * the email send path all read the same row, so they agree on what an author + * saved. + */ +export async function findTemplateOverride( + slug: string, +): Promise<{ subject: string; body: string } | null> { + const override = await prisma.templateOverride.findUnique({ where: { slug } }); + if (!override) return null; + return { subject: override.subject, body: override.body }; +} + +/** + * Matches the invite accept-link placeholder in every spelling the renderer + * accepts: `interpolate` trims whitespace inside the braces, so + * `{{ invite.url }}` produces a working link exactly like `{{invite.url}}`. + * The save check and the send-side fallback share this one pattern so the two + * cannot disagree about what counts as carrying the link. + */ +export const INVITE_URL_PLACEHOLDER = /\{\{\s*invite\.url\s*\}\}/; + +/** Whether a template body carries the invite accept link. */ +export function hasInviteUrl(body: string): boolean { + return INVITE_URL_PLACEHOLDER.test(body); +} + +/** + * The dbLookup for the invite send path. Same row as findTemplateOverride, + * except an invite override whose body lacks the accept link is treated as + * absent: rows saved before the PUT check existed never went through it, and + * sending one mails the invitee an email they cannot accept while the route + * still reports success. Treating the row as missing makes the loader fall + * back to the on-disk template, so the accept link always renders; the + * warning records why the saved copy was skipped. The editor and preview keep + * using findTemplateOverride — they must still show the stored row so an + * admin can fix it. + */ +export async function findSendableTemplateOverride( + slug: string, +): Promise<{ subject: string; body: string } | null> { + const override = await findTemplateOverride(slug); + if (slug === 'invite' && override !== null && !hasInviteUrl(override.body)) { + console.warn( + '[TEMPLATES] Ignoring the saved invite template: its body has no {{invite.url}} accept link, so the on-disk template is sent instead.', + ); + return null; + } + return override; +}