Files
accounted/lib/email/domain-name.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 { domainToASCII } from 'node:url'
/**
* Hostname normalization for user-entered email domains.
*
* Accepts what users actually paste ("Faktura.Hansbolag.SE.", a full URL, or
* an email address) and reduces it to a lowercased, punycoded hostname.
* Returns null when no valid hostname can be extracted. Dependency-free so
* both core and extensions can share one definition of "a valid domain".
*/
export function normalizeDomainName(raw: string): string | null {
let value = String(raw ?? '').trim().toLowerCase()
value = value.replace(/^[a-z][a-z0-9+.-]*:\/\//, '') // strip scheme
value = value.split('/')[0].split('?')[0]
const atIndex = value.lastIndexOf('@')
if (atIndex !== -1) value = value.slice(atIndex + 1)
value = value.replace(/^\.+|\.+$/g, '')
if (!value) return null
// IDN -> punycode (blåbär.se -> xn--blbr-noab.se). Returns '' when the
// input is not a valid domain.
const ascii = domainToASCII(value)
if (!ascii) return null
return isValidHostname(ascii) ? ascii : null
}
export function isValidHostname(domain: string): boolean {
if (domain.length < 4 || domain.length > 253) return false
const labels = domain.split('.')
if (labels.length < 2) return false
if (!labels.every((l) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(l))) return false
// TLD must contain a letter: rejects IP addresses and all-numeric TLDs.
return /[a-z]/.test(labels[labels.length - 1])
}
function hostnameOf(value: string | undefined): string | null {
if (!value) return null
try {
return new URL(value).hostname.toLowerCase() || null
} catch {
return null
}
}
/**
* Domains no tenant may ever send as: the platform's own sender domain
* (RESEND_FROM_EMAIL), the shared inbound domain, and the app host, plus
* their subdomains. Read from env on every call (cheap, and tests flip env).
*/
export function reservedSenderDomains(): string[] {
const reserved: string[] = []
const fromDomain = process.env.RESEND_FROM_EMAIL
? normalizeDomainName(process.env.RESEND_FROM_EMAIL)
: null
if (fromDomain) reserved.push(fromDomain)
const inbound = process.env.RESEND_INBOUND_DOMAIN?.toLowerCase()
if (inbound) reserved.push(inbound)
const appHost = hostnameOf(process.env.NEXT_PUBLIC_APP_URL)
if (appHost) reserved.push(appHost)
return reserved
}
/** True when `domain` is a reserved platform domain or a subdomain of one. */
export function isReservedSenderDomain(domain: string): boolean {
const d = domain.toLowerCase()
return reservedSenderDomains().some((r) => d === r || d.endsWith(`.${r}`))
}
/**
* Local part of a sender address: conservative dot-atom subset, lowercase.
* Dots may only separate atoms (RFC 5322 dot-atom): no leading, trailing or
* consecutive dots. Mirrored by the CHECK constraint in
* 20260822130000_company_sending_domains_tenant_guard.sql.
*/
export const SENDER_LOCAL_PART_PATTERN = /^[a-z0-9_-]+(\.[a-z0-9_-]+)*$/
const SENDER_LOCAL_PART_MAX_LENGTH = 64
export function normalizeSenderLocalPart(raw: string): string | null {
const value = String(raw ?? '').trim().toLowerCase()
if (value.length === 0 || value.length > SENDER_LOCAL_PART_MAX_LENGTH) return null
return SENDER_LOCAL_PART_PATTERN.test(value) ? value : null
}