Files
accounted/extensions/general/email/index.ts
T
MattssonandClaude Fable 5 0040cadacc feat(invoicing): opt-in invoice email from the company's own sending domain (#1802)
* feat(invoicing): opt-in invoice email from the company's own sending domain

Companies holding the custom_sender_domain capability grant can register
their own domain (Resend sending-only profile), publish DKIM/SPF, and once
verified every invoice email (send, reminders, recurring, payment
confirmation, MCP/v1 sends) leaves as "<name> <faktura@their-domain>"
instead of the platform sender. Reply-To is unchanged.

- New table company_sending_domains (RLS: members read, owner/admin write;
  audit trigger), types, archive-export classification.
- New capability key custom_sender_domain: manually granted per company,
  deliberately outside PAID_CAPABILITIES (never trial-seeded, never written
  by the Stripe sync). Without the grant the settings section is hidden and
  nothing changes.
- Email extension: sending-domain routes (GET/POST/PATCH/DELETE, verify),
  Resend domain lifecycle without orphan adoption, domain.updated handling
  on the delivery webhook, explicit From support in the Resend adapter.
- Core resolveInvoiceSender(): verified + enabled + entitled, else the
  platform sender; never throws.
- Settings -> Invoicing: "Avsändare vid fakturautskick" section (sv/en).
- Unit tests for the resolver, domain helpers, routes, From header; pg-real
  test for RLS and constraints.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(invoicing): harden sending-domain writes, sender fallback, review findings

Skeptic refutations:
- Tenant JWTs could insert/update company_sending_domains with status =
  'verified' and an arbitrary domain through PostgREST (RLS only checked
  membership), then send invoice mail as that domain. New migration
  20260822130000 adds a BEFORE trigger: tenants may only open a pending
  claim and edit sender_local_part/sender_name/enabled; domain and
  verification state are service-role only. claim/verify helpers now take
  a service-role writer for those columns; the route's RLS client still
  does the insert.
- A company domain Resend later rejects made every invoice send fail: the
  Resend adapter retries once as the platform sender when an explicit
  company From is rejected (nothing was sent, so no double send).

Review findings:
- domain.updated webhook: discriminated outcome; DB errors answer 500 so
  Svix retries, unknown domains are acknowledged.
- Display names are RFC 5322-quoted only when they carry specials.
- Sender local part is a strict dot-atom (no trailing/consecutive dots),
  in code and in the CHECK constraint; resend_domain_id index is UNIQUE.
- IME composition guard on the claim input; event bus reset in tests;
  settings section skips its request for non-admins.

Deferred (needs a product call): persisting the effective From address in
the invoice delivery log touches the hardened evidence triggers; recorded
in DECISIONS.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(invoicing): bind sending-domain verification to the claimed domain; fix pg test

Skeptic re-check found a TOCTOU: during the claim's Resend round-trip a
tenant could delete and re-insert its pending row under the same id with a
reserved domain, and the service-role writer updated by id alone. Now:
- the claim's verification-state write filters on (id, company_id, domain,
  resend_domain_id IS NULL) and rolls back on zero rows;
- verify and the domain.updated webhook compare Resend's domain name with
  the row before writing verified;
- resolveInvoiceSender refuses reserved platform domains and non-hostnames
  at send time (reserved-domain logic moved to lib/email/domain-name.ts and
  shared with the claim validator).

pg-real: the case-insensitive uniqueness assertion now expects the
domain_shape CHECK (lowercase enforced) for an uppercase variant and the
unique index for a same-case duplicate.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-23 00:07:30 +02:00

284 lines
11 KiB
TypeScript

import { NextResponse } from 'next/server'
import { z } from 'zod'
import type { SupabaseClient } from '@supabase/supabase-js'
import type { Extension, ExtensionContext } from '@/lib/extensions/types'
import { registerEmailService } from '@/lib/email/service'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { createLogger } from '@/lib/logger'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { requireCapability } from '@/lib/entitlements/has-capability'
import { isSandboxCompany } from '@/lib/sandbox/guard'
import { ResendEmailService } from './lib/resend-service'
import {
ResendDeliverySignatureError,
isDeliveryWebhookConfigured,
toDeliveryReport,
verifyDeliveryWebhook,
} from './lib/delivery-webhook'
import {
applySendingDomainStatusFromWebhook,
checkSendingDomainVerification,
claimSendingDomain,
getSendingDomain,
removeSendingDomain,
updateSendingDomainSettings,
} from './lib/sending-domains'
// Register the Resend implementation immediately when this extension is loaded
registerEmailService(new ResendEmailService())
const log = createLogger('email-delivery-webhook')
// Claim body for POST /sending-domain. Length-capped only: real validation
// (punycode, hostname shape, blocklist) lives in the sending-domains module.
const ClaimSendingDomainSchema = z.object({
domain: z.string().trim().min(1).max(255),
})
const PatchSendingDomainSchema = z
.object({
sender_local_part: z.string().trim().min(1).max(64).optional(),
sender_name: z.string().trim().max(120).nullable().optional(),
enabled: z.boolean().optional(),
})
.strict()
async function isCompanyAdmin(
supabase: SupabaseClient,
userId: string,
companyId: string,
): Promise<boolean> {
const { data } = await supabase
.from('company_members')
.select('role')
.eq('company_id', companyId)
.eq('user_id', userId)
.maybeSingle()
const role = (data as { role?: string } | null)?.role
return role === 'owner' || role === 'admin'
}
/**
* Shared preamble for the sending-domain routes: auth context, the opt-in
* capability grant (403 capability_blocked when missing: the UI hides the
* section on that), and for writes the owner/admin role plus the sandbox
* block (anonymous demo accounts must not register domains in our Resend
* account). Returns the response to send, or null to proceed.
*/
async function guardSendingDomainRoute(
ctx: ExtensionContext | undefined,
opts: { write: boolean },
): Promise<NextResponse | null> {
if (!ctx) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const blocked = await requireCapability(ctx.supabase, ctx.companyId, CAPABILITY.custom_sender_domain)
if (blocked) return blocked
if (!opts.write) return null
if (!(await isCompanyAdmin(ctx.supabase, ctx.userId, ctx.companyId))) {
return NextResponse.json({ error: 'Behörighet saknas.' }, { status: 403 })
}
if (await isSandboxCompany(ctx.supabase, ctx.companyId)) {
return NextResponse.json({ error: 'Egen avsändardomän är inte tillgänglig i sandlådan.' }, { status: 403 })
}
return null
}
export const emailExtension: Extension = {
id: 'email',
name: 'E-post (Resend)',
version: '1.0.0',
apiRoutes: [
// ── Company sending domain: read current state ───────────
{
method: 'GET',
path: '/sending-domain',
handler: async (_request: Request, ctx?: ExtensionContext) => {
const denied = await guardSendingDomainRoute(ctx, { write: false })
if (denied) return denied
try {
// null when the company has no sending domain: the UI renders the
// claim form in that case.
const row = await getSendingDomain(ctx!.supabase, ctx!.companyId)
return NextResponse.json({ data: row })
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to load sending domain' },
{ status: 500 },
)
}
},
},
// ── Company sending domain: claim (owner/admin only) ─────
{
method: 'POST',
path: '/sending-domain',
handler: async (request: Request, ctx?: ExtensionContext) => {
const denied = await guardSendingDomainRoute(ctx, { write: true })
if (denied) return denied
let body: z.infer<typeof ClaimSendingDomainSchema>
try {
body = ClaimSendingDomainSchema.parse(await request.json())
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Invalid request body' },
{ status: 400 },
)
}
// Verification state is service-role only (tenant guard trigger);
// the user client still does the insert, so RLS proves membership.
const result = await claimSendingDomain(
ctx!.supabase,
createServiceClientNoCookies(),
ctx!.companyId,
body.domain,
)
if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })
return NextResponse.json({ data: result.data })
},
},
// ── Company sending domain: re-check verification ────────
{
method: 'POST',
path: '/sending-domain/verify',
handler: async (_request: Request, ctx?: ExtensionContext) => {
const denied = await guardSendingDomainRoute(ctx, { write: true })
if (denied) return denied
const result = await checkSendingDomainVerification(
ctx!.supabase,
createServiceClientNoCookies(),
ctx!.companyId,
)
if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })
return NextResponse.json({ data: result.data })
},
},
// ── Company sending domain: sender address/name, pause ───
{
method: 'PATCH',
path: '/sending-domain',
handler: async (request: Request, ctx?: ExtensionContext) => {
const denied = await guardSendingDomainRoute(ctx, { write: true })
if (denied) return denied
let body: z.infer<typeof PatchSendingDomainSchema>
try {
body = PatchSendingDomainSchema.parse(await request.json())
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Invalid request body' },
{ status: 400 },
)
}
const result = await updateSendingDomainSettings(ctx!.supabase, ctx!.companyId, body)
if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })
return NextResponse.json({ data: result.data })
},
},
// ── Company sending domain: remove (owner/admin only) ────
{
method: 'DELETE',
path: '/sending-domain',
handler: async (_request: Request, ctx?: ExtensionContext) => {
const denied = await guardSendingDomainRoute(ctx, { write: true })
if (denied) return denied
const result = await removeSendingDomain(ctx!.supabase, ctx!.companyId)
if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })
return NextResponse.json({ data: result.data })
},
},
// ── Resend delivery webhook (Svix-signed, no user auth) ──
// Reports whether a sent invoice email actually arrived. Resend pushes
// every event for the account to this endpoint, including mail that is not
// a tracked invoice delivery: unmatched reports are acknowledged and
// dropped so they are not retried forever.
{
method: 'POST',
path: '/delivery-status',
skipAuth: true,
handler: async (request: Request) => {
if (!isDeliveryWebhookConfigured()) {
log.error('RESEND_DELIVERY_WEBHOOK_SECRET is not configured', undefined)
return NextResponse.json({ error: 'Delivery webhook not configured' }, { status: 503 })
}
const rawBody = await request.text()
let event
try {
event = verifyDeliveryWebhook(rawBody, request.headers)
} catch (err) {
if (err instanceof ResendDeliverySignatureError) {
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 })
}
log.error('delivery webhook verification failed', err)
return NextResponse.json({ error: 'Verification failed' }, { status: 500 })
}
// Resend pushes domain.* lifecycle events to the same endpoint. Apply
// domain.updated to company sending-domain rows so verification flips
// without the user pressing "Kontrollera igen" (requires the event
// type to be subscribed on the Resend webhook; harmless when it isn't).
if (event.type === 'domain.updated') {
const outcome = await applySendingDomainStatusFromWebhook(createServiceClientNoCookies(), {
id: event.data.id,
status: event.data.status,
records: event.data.records,
})
// A database error must not be acknowledged: Svix retries non-2xx
// with backoff, which is exactly the recovery wanted for a
// transient failure (same rule as the delivery status below).
if (outcome === 'error') {
log.error('failed to apply domain status', undefined, { domainId: event.data.id })
return NextResponse.json({ error: 'Failed to record domain status' }, { status: 500 })
}
return NextResponse.json({
data: { applied: outcome === 'applied', reason: outcome === 'no_match' ? 'no_matching_domain' : undefined },
})
}
const report = toDeliveryReport(event)
if (!report) {
return NextResponse.json({ data: { applied: false, reason: 'ignored_event' } })
}
const { data, error } = await createServiceClientNoCookies().rpc(
'apply_invoice_delivery_provider_event',
{
p_provider: 'resend',
p_provider_message_id: report.providerMessageId,
p_status: report.status,
p_occurred_at: report.occurredAt,
p_detail: report.detail,
p_recipient_addresses: report.recipients,
},
)
// A failed apply must not be acknowledged: Svix retries non-2xx with
// backoff, which is exactly the recovery wanted for a transient
// database error.
if (error) {
log.error('failed to apply delivery status', error, { status: report.status })
return NextResponse.json({ error: 'Failed to record delivery status' }, { status: 500 })
}
if (!data) {
return NextResponse.json({ data: { applied: false, reason: 'no_matching_delivery' } })
}
log.info('delivery status applied', { deliveryId: data, status: report.status })
return NextResponse.json({ data: { applied: true } })
},
},
],
}