Files
accounted/lib/email/invoice-sender.ts
T
Mattsson 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

84 lines
3.2 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { hasCapability } from '@/lib/entitlements/has-capability'
import type { CompanySendingDomain } from '@/types'
import { isReservedSenderDomain, isValidHostname } from '@/lib/email/domain-name'
/**
* Sender identity for invoice email: the From header's display name and
* address. Only used when a company has opted in to its own sending domain;
* otherwise invoice mail keeps the platform sender.
*/
export interface InvoiceSenderIdentity {
name: string
address: string
}
type SenderRow = Pick<
CompanySendingDomain,
'domain' | 'status' | 'enabled' | 'sender_local_part' | 'sender_name'
>
/** `<local>@<domain>`; pure, so the address shape is unit-testable. */
export function buildSenderAddress(localPart: string, domain: string): string {
return `${localPart}@${domain}`
}
/**
* Pure mapping from a sending-domain row to the From identity, or undefined
* when the row must not change the sender (unverified, paused, or missing).
* Falls back to the company name when no explicit sender name is stored.
*/
export function senderFromRow(
row: SenderRow | null | undefined,
companyName: string | null | undefined,
): InvoiceSenderIdentity | undefined {
if (!row || row.status !== 'verified' || !row.enabled) return undefined
// Last line of defense at send time: never send as a platform domain, and
// never trust a row whose domain is not a plain hostname, whatever the DB
// says (the claim/verify paths and the tenant guard trigger enforce this
// earlier; a tampered row must still not reach the From header).
const domain = row.domain.toLowerCase()
if (!isValidHostname(domain) || isReservedSenderDomain(domain)) return undefined
const name = (row.sender_name ?? companyName ?? '').trim()
if (!name) return undefined
return { name, address: buildSenderAddress(row.sender_local_part, row.domain) }
}
/**
* Resolve the From identity for a company's invoice email.
*
* Returns undefined in every case where the platform sender should be used:
* no sending-domain row, not verified, paused, no capability grant (the
* opt-in can lapse), or any read error. Never throws: a sender lookup
* failure must never stop an invoice from going out.
*
* Order matters for cost: most companies have no row, so the table read
* happens first and the two entitlement queries only run for opted-in
* companies.
*/
export async function resolveInvoiceSender(
supabase: SupabaseClient,
companyId: string,
companyName: string | null | undefined,
): Promise<InvoiceSenderIdentity | undefined> {
try {
const { data, error } = await supabase
.from('company_sending_domains')
.select('domain, status, enabled, sender_local_part, sender_name')
.eq('company_id', companyId)
.eq('status', 'verified')
.eq('enabled', true)
.maybeSingle()
if (error || !data) return undefined
const sender = senderFromRow(data as SenderRow, companyName)
if (!sender) return undefined
const entitled = await hasCapability(supabase, companyId, CAPABILITY.custom_sender_domain)
return entitled ? sender : undefined
} catch {
return undefined
}
}