Files
accounted/supabase/migrations/20260822120000_company_sending_domains.sql
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

126 lines
5.9 KiB
SQL

-- Custom outbound sending domains for invoice email (opt-in per company).
--
-- Today every invoice email leaves from the platform's shared sender
-- ("<Company> via <App> <noreply@platform>"). This table lets a company verify
-- its own domain via Resend's domain API (sending capability only) and, once
-- status = 'verified' AND enabled, send invoice mail as
-- "<sender_name> <sender_local_part@domain>" so DKIM/DMARC align with the
-- company's own domain at the recipient's filter.
--
-- Design notes:
-- * Mirrors company_inbound_domains (20260701090000): same lifecycle
-- (claim -> DNS -> verified), same RLS shape, same audit trigger. Kept as
-- a separate table because the two are different Resend domain profiles
-- (sending-only vs receiving-only) with different failure consequences.
-- * No user_id column: the row is company configuration that must outlive
-- the user who created it.
-- * Global unique on lower(domain): one company owns a sending domain
-- across all tenants. One sending domain per company (v1).
-- * Only rows with status = 'verified' AND enabled = true ever change the
-- From header. Everything else falls back to the platform sender, so a
-- DNS blip can never stop invoice mail.
-- * The feature itself is gated behind a per-company capability grant
-- (CAPABILITY.custom_sender_domain) resolved application-side; the table
-- carries no opinion about who may use it.
-- =============================================================================
-- 1. Table
-- =============================================================================
CREATE TABLE IF NOT EXISTS public.company_sending_domains (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
-- Lowercased, punycoded hostname (validated app-side before insert).
domain text NOT NULL,
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'verified', 'failed')),
-- Local part of the From address: <sender_local_part>@<domain>.
sender_local_part text NOT NULL DEFAULT 'faktura'
CHECK (sender_local_part ~ '^[a-z0-9][a-z0-9._-]{0,63}$'),
-- Optional display name; NULL means "use the company name".
sender_name text
CHECK (sender_name IS NULL OR (length(sender_name) BETWEEN 1 AND 120)),
-- Pause without removing the domain (DNS stays verified in Resend).
enabled boolean NOT NULL DEFAULT true,
-- Resend's domain id + the DNS records the user must publish (records[]
-- from the Resend API response, rendered verbatim in the UI).
resend_domain_id text,
dns_records jsonb,
verified_at timestamptz,
last_checked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
-- A domain belongs to exactly one company, across all tenants.
CREATE UNIQUE INDEX IF NOT EXISTS idx_company_sending_domains_domain
ON public.company_sending_domains (lower(domain));
-- One sending domain per company (v1).
CREATE UNIQUE INDEX IF NOT EXISTS idx_company_sending_domains_company
ON public.company_sending_domains (company_id);
-- Webhook lookups resolve rows by Resend's domain id.
CREATE INDEX IF NOT EXISTS idx_company_sending_domains_resend_id
ON public.company_sending_domains (resend_domain_id)
WHERE resend_domain_id IS NOT NULL;
-- =============================================================================
-- 2. RLS: SELECT for members, writes for owner/admin only
-- (same shape as company_inbound_domains)
-- =============================================================================
ALTER TABLE public.company_sending_domains ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "company_sending_domains_select" ON public.company_sending_domains;
CREATE POLICY "company_sending_domains_select" ON public.company_sending_domains
FOR SELECT USING (company_id IN (SELECT public.user_company_ids()));
DROP POLICY IF EXISTS "company_sending_domains_insert" ON public.company_sending_domains;
CREATE POLICY "company_sending_domains_insert" ON public.company_sending_domains
FOR INSERT WITH CHECK (
company_id IN (
SELECT cm.company_id FROM public.company_members cm
WHERE cm.user_id = auth.uid()
AND cm.role IN ('owner', 'admin')
)
);
DROP POLICY IF EXISTS "company_sending_domains_update" ON public.company_sending_domains;
CREATE POLICY "company_sending_domains_update" ON public.company_sending_domains
FOR UPDATE USING (
company_id IN (
SELECT cm.company_id FROM public.company_members cm
WHERE cm.user_id = auth.uid()
AND cm.role IN ('owner', 'admin')
)
);
DROP POLICY IF EXISTS "company_sending_domains_delete" ON public.company_sending_domains;
CREATE POLICY "company_sending_domains_delete" ON public.company_sending_domains
FOR DELETE USING (
company_id IN (
SELECT cm.company_id FROM public.company_members cm
WHERE cm.user_id = auth.uid()
AND cm.role IN ('owner', 'admin')
)
);
-- =============================================================================
-- 3. Triggers
-- =============================================================================
DROP TRIGGER IF EXISTS company_sending_domains_updated_at ON public.company_sending_domains;
CREATE TRIGGER company_sending_domains_updated_at
BEFORE UPDATE ON public.company_sending_domains
FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();
-- Sending-domain changes alter who a company's invoice mail claims to come
-- from: audit them.
DROP TRIGGER IF EXISTS audit_company_sending_domains ON public.company_sending_domains;
CREATE TRIGGER audit_company_sending_domains
AFTER INSERT OR UPDATE OR DELETE ON public.company_sending_domains
FOR EACH ROW EXECUTE FUNCTION public.write_audit_log();
NOTIFY pgrst, 'reload schema';