From 5671a55a2e4f8ac9cf8b0c1e1e57a78b501dae3d Mon Sep 17 00:00:00 2001 From: Michael Zhou Date: Tue, 1 Dec 2026 15:38:25 +0800 Subject: [PATCH 1/4] Use saved template overrides for outgoing invitation emails Co-Authored-By: Claude Code --- apps/web/src/__tests__/team-api.test.ts | 85 +++++++++++++++++++ apps/web/src/__tests__/templates-api.test.ts | 28 ++++++ .../web/src/__tests__/templates-page.test.tsx | 29 +++++-- .../src/app/api/team/invite/resend/route.ts | 2 + apps/web/src/app/api/team/invite/route.ts | 2 + .../app/api/templates/[slug]/preview/route.ts | 24 ++++-- .../web/src/app/api/templates/[slug]/route.ts | 24 +++--- apps/web/src/app/settings/templates/page.tsx | 26 +++--- apps/web/src/lib/template-override.ts | 17 ++++ 9 files changed, 195 insertions(+), 42 deletions(-) create mode 100644 apps/web/src/lib/template-override.ts diff --git a/apps/web/src/__tests__/team-api.test.ts b/apps/web/src/__tests__/team-api.test.ts index 11e870a1..1e0ad1eb 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,86 @@ 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]) { + mockTemplateOverrideFindUnique.mockResolvedValue( + saved + ? { subject: 'Custom {{org.name}}', body: 'Hello {{member.name}}' } + : 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'); + } else { + expect(message.subject).toBe("You've been invited to join Example Org"); + expect(message.text).toContain("You've been invited to join"); + } + } + } + } finally { + vi.mocked(sendEmail) + .mockReset() + .mockResolvedValue({ success: true, method: 'console' }); + } + }); + // ── 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..8a4ebf3e 100644 --- a/apps/web/src/__tests__/templates-api.test.ts +++ b/apps/web/src/__tests__/templates-api.test.ts @@ -221,6 +221,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 +499,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..8ac97f05 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 { findTemplateOverride } from '@/lib/template-override'; export async function POST(request: Request) { const { error } = await requireAdmin(); @@ -52,6 +53,7 @@ export async function POST(request: Request) { const emailResult = await sendEmail({ to: member.email, template: 'invite', + dbLookup: findTemplateOverride, context: { org: { name: org?.name || 'Outpost', diff --git a/apps/web/src/app/api/team/invite/route.ts b/apps/web/src/app/api/team/invite/route.ts index 8bb3b8f8..12f71117 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 { findTemplateOverride } from '@/lib/template-override'; export async function POST(request: Request) { const { error, session } = await requireAdmin(); @@ -72,6 +73,7 @@ export async function POST(request: Request) { const emailResult = await sendEmail({ to: email.trim().toLowerCase(), template: 'invite', + dbLookup: findTemplateOverride, context: { org: { name: org?.name || 'Outpost', 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..061a13ce 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 } 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) { 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..0814a5f1 --- /dev/null +++ b/apps/web/src/lib/template-override.ts @@ -0,0 +1,17 @@ +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 }; +} From 44e65951954df08701b466051138e339b8226dbc Mon Sep 17 00:00:00 2001 From: Michael Zhou Date: Wed, 2 Dec 2026 07:08:33 +0800 Subject: [PATCH 2/4] Fix Prettier formatting in invite routes Co-Authored-By: Claude Code --- .../web/src/app/api/team/invite/resend/route.ts | 9 +++++++-- apps/web/src/app/api/team/invite/route.ts | 17 +++++++++++++---- 2 files changed, 20 insertions(+), 6 deletions(-) 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 8ac97f05..f513c7e6 100644 --- a/apps/web/src/app/api/team/invite/resend/route.ts +++ b/apps/web/src/app/api/team/invite/resend/route.ts @@ -28,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'); @@ -73,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 12f71117..d88e18ef 100644 --- a/apps/web/src/app/api/team/invite/route.ts +++ b/apps/web/src/app/api/team/invite/route.ts @@ -22,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; @@ -93,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) { From 06e1ecde9ca0b38711b863262be97db120eaff06 Mon Sep 17 00:00:00 2001 From: Michael Zhou Date: Wed, 2 Dec 2026 08:37:42 +0800 Subject: [PATCH 3/4] Require invite URL in saved templates Co-Authored-By: Claude Code --- apps/web/src/__tests__/templates-api.test.ts | 21 +++++++++++++++++++ .../web/src/app/api/templates/[slug]/route.ts | 7 +++++++ 2 files changed, 28 insertions(+) diff --git a/apps/web/src/__tests__/templates-api.test.ts b/apps/web/src/__tests__/templates-api.test.ts index 8a4ebf3e..ef1032c6 100644 --- a/apps/web/src/__tests__/templates-api.test.ts +++ b/apps/web/src/__tests__/templates-api.test.ts @@ -211,6 +211,27 @@ 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('rejects an oversized body', async () => { const res = await putTemplate( jsonRequest({ subject: 's', body: 'x'.repeat(100_001) }), diff --git a/apps/web/src/app/api/templates/[slug]/route.ts b/apps/web/src/app/api/templates/[slug]/route.ts index 061a13ce..b24a08ba 100644 --- a/apps/web/src/app/api/templates/[slug]/route.ts +++ b/apps/web/src/app/api/templates/[slug]/route.ts @@ -113,6 +113,13 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{ return NextResponse.json({ error: 'Template not found' }, { status: 404 }); } + if (slug === 'invite' && !templateBody.includes('{{invite.url}}')) { + 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; From a516c69caa25c60ce9e1ae77aa0b8ca2deacbf54 Mon Sep 17 00:00:00 2001 From: Michael Zhou Date: Thu, 3 Dec 2026 19:59:26 +0800 Subject: [PATCH 4/4] Check the accept link on the invite send path too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rows saved before the PUT check existed never went through it, so an invite override can still lack {{invite.url}} — and sending it mails the invitee an email they cannot accept while the route reports success. The send path now treats such an override as absent, falling back to the on-disk template and logging a warning; the editor and preview still read the stored row so an admin can fix it. The required-link check also moves to a shared pattern: interpolate trims whitespace inside the braces, so {{ invite.url }} renders a working link and the save check must accept it. The spaced spelling now saves, and the send-side fallback uses the same pattern. Co-Authored-By: Claude Code --- apps/web/src/__tests__/team-api.test.ts | 66 ++++++++++++++++++- apps/web/src/__tests__/templates-api.test.ts | 13 ++++ .../src/app/api/team/invite/resend/route.ts | 4 +- apps/web/src/app/api/team/invite/route.ts | 4 +- .../web/src/app/api/templates/[slug]/route.ts | 7 +- apps/web/src/lib/template-override.ts | 38 +++++++++++ 6 files changed, 125 insertions(+), 7 deletions(-) diff --git a/apps/web/src/__tests__/team-api.test.ts b/apps/web/src/__tests__/team-api.test.ts index 1e0ad1eb..a162e062 100644 --- a/apps/web/src/__tests__/team-api.test.ts +++ b/apps/web/src/__tests__/team-api.test.ts @@ -145,9 +145,16 @@ describe('Team API', () => { 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}}' } + ? { + subject: 'Custom {{org.name}}', + body: 'Hello {{member.name}} — accept at {{invite.url}}', + } : null, ); const deliveriesBefore = delivered.mock.calls.length; @@ -188,9 +195,13 @@ describe('Team API', () => { 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='); } } } @@ -201,6 +212,59 @@ describe('Team API', () => { } }); + 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 ef1032c6..5ccc37fc 100644 --- a/apps/web/src/__tests__/templates-api.test.ts +++ b/apps/web/src/__tests__/templates-api.test.ts @@ -232,6 +232,19 @@ describe('template persistence and preview (outpost#226)', () => { 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) }), 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 f513c7e6..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,7 +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 { findTemplateOverride } from '@/lib/template-override'; +import { findSendableTemplateOverride } from '@/lib/template-override'; export async function POST(request: Request) { const { error } = await requireAdmin(); @@ -56,7 +56,7 @@ export async function POST(request: Request) { const emailResult = await sendEmail({ to: member.email, template: 'invite', - dbLookup: findTemplateOverride, + dbLookup: findSendableTemplateOverride, context: { org: { name: org?.name || 'Outpost', diff --git a/apps/web/src/app/api/team/invite/route.ts b/apps/web/src/app/api/team/invite/route.ts index d88e18ef..1602e7f7 100644 --- a/apps/web/src/app/api/team/invite/route.ts +++ b/apps/web/src/app/api/team/invite/route.ts @@ -3,7 +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 { findTemplateOverride } from '@/lib/template-override'; +import { findSendableTemplateOverride } from '@/lib/template-override'; export async function POST(request: Request) { const { error, session } = await requireAdmin(); @@ -80,7 +80,7 @@ export async function POST(request: Request) { const emailResult = await sendEmail({ to: email.trim().toLowerCase(), template: 'invite', - dbLookup: findTemplateOverride, + dbLookup: findSendableTemplateOverride, context: { org: { name: org?.name || 'Outpost', diff --git a/apps/web/src/app/api/templates/[slug]/route.ts b/apps/web/src/app/api/templates/[slug]/route.ts index b24a08ba..4f958c72 100644 --- a/apps/web/src/app/api/templates/[slug]/route.ts +++ b/apps/web/src/app/api/templates/[slug]/route.ts @@ -2,7 +2,7 @@ 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 } from '@/lib/template-override'; +import { findTemplateOverride, hasInviteUrl } from '@/lib/template-override'; /** Bounds on stored template content. The subject becomes an email header downstream. */ const SUBJECT_MAX = 500; @@ -113,7 +113,10 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{ return NextResponse.json({ error: 'Template not found' }, { status: 404 }); } - if (slug === 'invite' && !templateBody.includes('{{invite.url}}')) { + // 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 }, diff --git a/apps/web/src/lib/template-override.ts b/apps/web/src/lib/template-override.ts index 0814a5f1..aa3724b0 100644 --- a/apps/web/src/lib/template-override.ts +++ b/apps/web/src/lib/template-override.ts @@ -15,3 +15,41 @@ export async function findTemplateOverride( 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; +}