Files
accounted/lib/email/__tests__/domain-name.test.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

93 lines
3.6 KiB
TypeScript

import { describe, it, expect } from 'vitest'
import {
normalizeDomainName,
isValidHostname,
isReservedSenderDomain,
normalizeSenderLocalPart,
} from '@/lib/email/domain-name'
describe('normalizeDomainName', () => {
it('lowercases and strips trailing dots', () => {
expect(normalizeDomainName('Faktura.HansBolag.SE.')).toBe('faktura.hansbolag.se')
})
it('accepts a pasted URL', () => {
expect(normalizeDomainName('https://hansbolag.se/kontakt?x=1')).toBe('hansbolag.se')
})
it('accepts a pasted email address', () => {
expect(normalizeDomainName('faktura@hansbolag.se')).toBe('hansbolag.se')
})
it('punycodes Swedish IDN domains', () => {
const result = normalizeDomainName('blåbär.se')
expect(result).not.toBeNull()
expect(result!.startsWith('xn--')).toBe(true)
expect(result!.endsWith('.se')).toBe(true)
})
it('rejects hostnames without a dot, empty input, and IP addresses', () => {
expect(normalizeDomainName('nodots')).toBeNull()
expect(normalizeDomainName('')).toBeNull()
expect(normalizeDomainName(' ')).toBeNull()
expect(normalizeDomainName('192.168.0.1')).toBeNull()
})
})
describe('isReservedSenderDomain', () => {
it("flags the platform sender domain, the inbound domain, the app host and their subdomains", () => {
const saved = {
from: process.env.RESEND_FROM_EMAIL,
inbound: process.env.RESEND_INBOUND_DOMAIN,
app: process.env.NEXT_PUBLIC_APP_URL,
}
process.env.RESEND_FROM_EMAIL = 'noreply@platform.example'
process.env.RESEND_INBOUND_DOMAIN = 'inbox.platform.example'
process.env.NEXT_PUBLIC_APP_URL = 'https://app.other.example'
try {
expect(isReservedSenderDomain('platform.example')).toBe(true)
expect(isReservedSenderDomain('mail.platform.example')).toBe(true)
expect(isReservedSenderDomain('inbox.platform.example')).toBe(true)
expect(isReservedSenderDomain('app.other.example')).toBe(true)
expect(isReservedSenderDomain('APP.OTHER.EXAMPLE')).toBe(true)
expect(isReservedSenderDomain('hansbolag.example')).toBe(false)
expect(isReservedSenderDomain('notplatform.example')).toBe(false)
} finally {
process.env.RESEND_FROM_EMAIL = saved.from
process.env.RESEND_INBOUND_DOMAIN = saved.inbound
process.env.NEXT_PUBLIC_APP_URL = saved.app
}
})
})
describe('isValidHostname', () => {
it('accepts ordinary hostnames and rejects malformed labels', () => {
expect(isValidHostname('hansbolag.se')).toBe(true)
expect(isValidHostname('-bad.se')).toBe(false)
expect(isValidHostname('bad-.se')).toBe(false)
expect(isValidHostname('a.b')).toBe(false) // too short
})
})
describe('normalizeSenderLocalPart', () => {
it('lowercases and accepts dot, hyphen, underscore', () => {
expect(normalizeSenderLocalPart('Faktura')).toBe('faktura')
expect(normalizeSenderLocalPart('ekonomi.ab_1-x')).toBe('ekonomi.ab_1-x')
})
it('rejects trailing and consecutive dots (dot-atom rule)', () => {
expect(normalizeSenderLocalPart('faktura.')).toBeNull()
expect(normalizeSenderLocalPart('fak..tura')).toBeNull()
expect(normalizeSenderLocalPart('fak.tura')).toBe('fak.tura')
})
it('rejects header-breaking or out-of-alphabet input', () => {
expect(normalizeSenderLocalPart('')).toBeNull()
expect(normalizeSenderLocalPart('.faktura')).toBeNull()
expect(normalizeSenderLocalPart('fak tura')).toBeNull()
expect(normalizeSenderLocalPart('fak<tura>')).toBeNull()
expect(normalizeSenderLocalPart('faktura@x')).toBeNull()
expect(normalizeSenderLocalPart('a'.repeat(65))).toBeNull()
})
})