docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
@@ -1,97 +0,0 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`buildAuthEmail > renders the branded recovery mail (snapshot) 1`] = `
"
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Återställ ditt lösenord</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f5f5f5;">
<div style="max-width: 520px; margin: 0 auto; padding: 40px 20px;">
<div style="background: #ffffff; border-radius: 12px; padding: 40px 32px; border: 1px solid #e5e5e5;">
<!-- Header -->
<div style="margin-bottom: 28px;">
<p style="margin: 0 0 4px 0; font-size: 13px; color: #888; letter-spacing: 0.05em;">SIFFRA</p>
<h1 style="margin: 0 0 8px 0; font-size: 22px; font-weight: 600; color: #111;">
Återställ ditt lösenord
</h1>
<p style="margin: 0; color: #666; font-size: 15px;">
Vi har tagit emot en begäran om att återställa lösenordet för ditt konto hos Siffra. Klicka på knappen nedan för att välja ett nytt lösenord.
</p>
</div>
<div style="margin: 28px 0;">
<a href="https://app.siffra.se/auth/callback?token_hash=abc&amp;type=recovery" style="display: inline-block; background: #111; color: #fff; text-decoration: none; padding: 12px 28px; border-radius: 8px; font-size: 14px; font-weight: 500;">
Återställ lösenord
</a>
</div>
<!-- Info -->
<p style="margin: 0; color: #999; font-size: 13px;">
Om du inte begärde detta kan du bortse från det här meddelandet.
</p>
</div>
</div>
</body>
</html>"
`;
exports[`buildAuthEmail > renders the branded recovery mail (snapshot) 2`] = `
"Återställ ditt lösenord
Vi har tagit emot en begäran om att återställa lösenordet för ditt konto hos Siffra. Klicka på knappen nedan för att välja ett nytt lösenord.
Återställ lösenord: https://app.siffra.se/auth/callback?token_hash=abc&type=recovery
Om du inte begärde detta kan du bortse från det här meddelandet."
`;
exports[`buildAuthEmail > renders the platform default without a brand 1`] = `
"
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Återställ ditt lösenord</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f5f5f5;">
<div style="max-width: 520px; margin: 0 auto; padding: 40px 20px;">
<div style="background: #ffffff; border-radius: 12px; padding: 40px 32px; border: 1px solid #e5e5e5;">
<!-- Header -->
<div style="margin-bottom: 28px;">
<p style="margin: 0 0 4px 0; font-size: 13px; color: #888; letter-spacing: 0.05em;">ACCOUNTED</p>
<h1 style="margin: 0 0 8px 0; font-size: 22px; font-weight: 600; color: #111;">
Återställ ditt lösenord
</h1>
<p style="margin: 0; color: #666; font-size: 15px;">
Vi har tagit emot en begäran om att återställa lösenordet för ditt konto hos Accounted. Klicka på knappen nedan för att välja ett nytt lösenord.
</p>
</div>
<div style="margin: 28px 0;">
<a href="https://app.gnubok.se/auth/callback?token_hash=abc&amp;type=recovery" style="display: inline-block; background: #111; color: #fff; text-decoration: none; padding: 12px 28px; border-radius: 8px; font-size: 14px; font-weight: 500;">
Återställ lösenord
</a>
</div>
<!-- Info -->
<p style="margin: 0; color: #999; font-size: 13px;">
Om du inte begärde detta kan du bortse från det här meddelandet.
</p>
</div>
</div>
</body>
</html>"
`;
exports[`buildAuthEmail > renders the platform default without a brand 2`] = `
"Återställ ditt lösenord
Vi har tagit emot en begäran om att återställa lösenordet för ditt konto hos Accounted. Klicka på knappen nedan för att välja ett nytt lösenord.
Återställ lösenord: https://app.gnubok.se/auth/callback?token_hash=abc&type=recovery
Om du inte begärde detta kan du bortse från det här meddelandet."
`;
@@ -1,331 +0,0 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`invite mail (template class: invite) > branded: brand sender, brand-domain link, no Accounted leakage 1`] = `
"
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inbjudan till Kund AB</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f5f5f5;">
<div style="max-width: 520px; margin: 0 auto; padding: 40px 20px;">
<div style="background: #ffffff; border-radius: 12px; padding: 40px 32px; border: 1px solid #e5e5e5;">
<!-- Header -->
<div style="margin-bottom: 28px;">
<p style="margin: 0 0 4px 0; font-size: 13px; color: #888; letter-spacing: 0.05em;">SIFFRA</p>
<h1 style="margin: 0 0 8px 0; font-size: 22px; font-weight: 600; color: #111;">
Du har blivit inbjuden
</h1>
<p style="margin: 0; color: #666; font-size: 15px;">
<strong>[email protected]</strong> har bjudit in dig till <strong>Kund AB</strong> på siffra.
</p>
</div>
<!-- CTA -->
<div style="margin: 28px 0;">
<a href="https://app.siffra.se/invite/tok-1" style="display: inline-block; background: #111; color: #fff; text-decoration: none; padding: 12px 28px; border-radius: 8px; font-size: 14px; font-weight: 500;">
Acceptera inbjudan
</a>
</div>
<!-- Info -->
<p style="margin: 0; color: #999; font-size: 13px;">
Länken är giltig i 7 dagar. Om du inte förväntade dig denna inbjudan kan du ignorera detta meddelande.
</p>
</div>
</div>
</body>
</html>"
`;
exports[`invite mail (template class: invite) > unbranded: byte-identical to the un-overridden template on the canonical URL 1`] = `
"
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inbjudan till Kund AB</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f5f5f5;">
<div style="max-width: 520px; margin: 0 auto; padding: 40px 20px;">
<div style="background: #ffffff; border-radius: 12px; padding: 40px 32px; border: 1px solid #e5e5e5;">
<!-- Header -->
<div style="margin-bottom: 28px;">
<p style="margin: 0 0 4px 0; font-size: 13px; color: #888; letter-spacing: 0.05em;">ACCOUNTED</p>
<h1 style="margin: 0 0 8px 0; font-size: 22px; font-weight: 600; color: #111;">
Du har blivit inbjuden
</h1>
<p style="margin: 0; color: #666; font-size: 15px;">
<strong>[email protected]</strong> har bjudit in dig till <strong>Kund AB</strong> på accounted.
</p>
</div>
<!-- CTA -->
<div style="margin: 28px 0;">
<a href="https://app.gnubok.se/invite/tok-1" style="display: inline-block; background: #111; color: #fff; text-decoration: none; padding: 12px 28px; border-radius: 8px; font-size: 14px; font-weight: 500;">
Acceptera inbjudan
</a>
</div>
<!-- Info -->
<p style="margin: 0; color: #999; font-size: 13px;">
Länken är giltig i 7 dagar. Om du inte förväntade dig denna inbjudan kan du ignorera detta meddelande.
</p>
</div>
</div>
</body>
</html>"
`;
exports[`invoice mail (template class: invoice) > unbranded: template output unchanged and platform-free 1`] = `
"
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Faktura F-1001</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333;">
<div style="max-width: 600px; margin: 0 auto; padding: 40px 20px;">
<!-- Header -->
<div style="margin-bottom: 30px; border-bottom: 2px solid #1a1a1a; padding-bottom: 16px;">
<h1 style="margin: 0 0 10px 0; font-size: 24px; font-weight: 600; color: #1a1a1a;">
Faktura från Kund AB
</h1>
<p style="margin: 0; color: #666; font-size: 14px;">
Fakturanummer: F-1001
</p>
</div>
<!-- Greeting -->
<div style="margin-bottom: 30px;">
<p style="margin: 0 0 15px 0;">
Hej Erik,
</p>
<p style="margin: 0;">
Tack för ditt förtroende! Bifogat hittar du din faktura.
</p>
</div>
<!-- Summary Box -->
<div style="background: #f8f9fa; border-radius: 8px; padding: 25px; margin-bottom: 30px;">
<table style="width: 100%; border-collapse: collapse;">
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Fakturanummer:</td>
<td style="padding: 8px 0; text-align: right; font-weight: 500;">F-1001</td>
</tr>
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Fakturadatum:</td>
<td style="padding: 8px 0; text-align: right;">2026-07-01</td>
</tr>
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Förfallodatum:</td>
<td style="padding: 8px 0; text-align: right; font-weight: 500; color: #e11d48;">
2026-07-31
</td>
</tr>
<tr>
<td colspan="2" style="padding: 15px 0 8px 0; border-top: 1px solid #e5e7eb;"></td>
</tr>
<tr>
<td style="padding: 8px 0; font-size: 18px; font-weight: 600;">Att betala:</td>
<td style="padding: 8px 0; text-align: right; font-size: 18px; font-weight: 600; color: #1a1a1a;">
1 250,00 SEK
</td>
</tr>
</table>
</div>
<!-- Pay-online button: only when the user pasted a payment link on this
invoice. The URL is schema-validated (https-only) but still escaped
for the attribute context: a URL may legally contain quotes. -->
<!-- Payment Details -->
<div style="margin-bottom: 30px;">
<h2 style="margin: 0 0 15px 0; font-size: 16px; font-weight: 600; color: #1a1a1a;">
Betalningsinformation
</h2>
<table style="width: 100%; border-collapse: collapse;">
<tr>
<td style="padding: 6px 0; color: #666; font-size: 14px;">Meddelande:</td>
<td style="padding: 6px 0; font-weight: 500;">F-1001</td>
</tr>
</table>
</div>
<!-- Footer -->
<div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #e5e7eb;">
<p style="margin: 0 0 10px 0; color: #666; font-size: 14px;">
Har du frågor om fakturan? Svara direkt på detta mejl så hjälper vi dig.
</p>
<p style="margin: 0; color: #666; font-size: 14px;">
Med vänliga hälsningar,<br>
<strong style="color: #1a1a1a;">Kund AB</strong>
</p>
<p style="margin: 10px 0 0 0; color: #999; font-size: 12px;">
Org.nr: 556000-0000
| VAT: SE556012579001
| Innehar F-skattsedel
</p>
</div>
</div>
</body>
</html>
"
`;
exports[`payslip mail (template class: payslip) > branded: brand sender and brand-domain link 1`] = `
"<p>Hej Anna,</p>
<p>Din lönespecifikation för juni 2026 finns att hämta via länken nedan.</p>
<p><a href="https://app.siffra.se/payslip/tok-1">Visa lönespecifikation</a></p>
<p>Utbetalningsdag: 2026-06-25<br>
Länken är personlig och giltig i 90 dagar.</p>
<p>Med vänliga hälsningar,<br>Kund AB</p>"
`;
exports[`payslip mail (template class: payslip) > unbranded: canonical link, platform sender, unchanged body 1`] = `
"<p>Hej Anna,</p>
<p>Din lönespecifikation för juni 2026 finns att hämta via länken nedan.</p>
<p><a href="https://app.gnubok.se/payslip/tok-1">Visa lönespecifikation</a></p>
<p>Utbetalningsdag: 2026-06-25<br>
Länken är personlig och giltig i 90 dagar.</p>
<p>Med vänliga hälsningar,<br>Kund AB</p>"
`;
exports[`reminder mail (template class: reminder) > unbranded: canonical action link and unchanged output 1`] = `
"
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vänlig påminnelse - Faktura F-1001</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f9fafb;">
<div style="max-width: 600px; margin: 0 auto; padding: 40px 20px;">
<div style="background: white; border-radius: 12px; padding: 40px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
<!-- Header -->
<div style="text-align: center; margin-bottom: 30px;">
<div style="display: inline-block; background: #2563eb15; color: #2563eb; padding: 8px 16px; border-radius: 20px; font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">
Vänlig påminnelse
</div>
</div>
<!-- Title -->
<h1 style="margin: 0 0 20px 0; font-size: 22px; font-weight: 600; color: #111; text-align: center;">
Faktura F-1001 förföll för 20 dagar sedan
</h1>
<!-- Greeting and Message -->
<div style="margin-bottom: 30px;">
<p style="margin: 0 0 15px 0;">
Hej Erik,
</p>
<p style="margin: 0 0 15px 0;">Vi vill påminna dig om att faktura F-1001 förföll till betalning den 2026-06-01. Om du redan har betalat kan du bortse från denna påminnelse.</p>
</div>
<!-- Invoice Summary Box -->
<div style="background: #f8f9fa; border-radius: 8px; padding: 25px; margin-bottom: 30px; border-left: 4px solid #2563eb;">
<table style="width: 100%; border-collapse: collapse;">
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Fakturanummer:</td>
<td style="padding: 8px 0; text-align: right; font-weight: 500;">F-1001</td>
</tr>
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Fakturadatum:</td>
<td style="padding: 8px 0; text-align: right;">2026-05-01</td>
</tr>
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Förfallodatum:</td>
<td style="padding: 8px 0; text-align: right; color: #dc2626; font-weight: 500;">
2026-06-01
</td>
</tr>
<tr>
<td colspan="2" style="padding: 15px 0 8px 0; border-top: 1px solid #e5e7eb;"></td>
</tr>
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Ursprungligt belopp:</td>
<td style="padding: 8px 0; text-align: right; font-weight: 500;">1 250 kr</td>
</tr>
<tr>
<td style="padding: 8px 0; font-size: 18px; font-weight: 600;">Att betala:</td>
<td style="padding: 8px 0; text-align: right; font-size: 18px; font-weight: 600; color: #2563eb;">
1 250 kr
</td>
</tr>
</table>
</div>
<!-- Payment Details -->
<div style="margin-bottom: 30px;">
<h2 style="margin: 0 0 15px 0; font-size: 16px; font-weight: 600; color: #111;">
Betalningsinformation
</h2>
<table style="width: 100%; border-collapse: collapse;">
<tr>
<td style="padding: 6px 0; color: #666; font-size: 14px;">Meddelande:</td>
<td style="padding: 6px 0; font-weight: 500;">F-1001</td>
</tr>
</table>
</div>
<!-- Action Buttons -->
<div style="text-align: center; margin-bottom: 30px;">
<p style="margin: 0 0 20px 0; color: #666; font-size: 14px;">
Har du redan betalat eller har frågor om fakturan?
</p>
<a href="https://app.gnubok.se/invoice-action/tok-1" style="display: inline-block; background: #2563eb; color: white; padding: 14px 28px; border-radius: 8px; text-decoration: none; font-weight: 500; font-size: 14px;">
Hantera faktura
</a>
</div>
<!-- Footer -->
<div style="padding-top: 20px; border-top: 1px solid #e5e7eb;">
<p style="margin: 0 0 10px 0; color: #666; font-size: 14px;">
Har du frågor? Svara direkt på detta mejl så hjälper vi dig.
</p>
<p style="margin: 0; color: #666; font-size: 14px;">
Med vänliga hälsningar,<br>
<strong>Kund AB</strong>
</p>
<p style="margin: 10px 0 0 0; color: #999; font-size: 12px;">
Org.nr: 199001011234
| VAT: SE556012579001
</p>
</div>
</div>
<!-- Unsubscribe note -->
<p style="text-align: center; margin-top: 20px; color: #999; font-size: 12px;">
Detta är ett automatiskt meddelande angående en obetald faktura.
</p>
</div>
</body>
</html>
"
`;
-114
View File
@@ -1,114 +0,0 @@
import { describe, it, expect } from 'vitest'
import { buildAuthEmail } from '../auth-templates'
const URL_EXAMPLE = 'https://app.siffra.se/auth/callback?token_hash=abc&type=recovery'
// In HTML the URL lands in an attribute and is entity-escaped.
const URL_EXAMPLE_HTML = URL_EXAMPLE.replace(/&/g, '&amp;')
describe('buildAuthEmail', () => {
it.each([
['signup', 'Bekräfta din e-postadress'],
['recovery', 'Återställ ditt lösenord'],
['magiclink', 'Din inloggningslänk'],
['invite', 'Du har blivit inbjuden'],
['email_change', 'Bekräfta din nya e-postadress'],
['email_change_current', 'Godkänn ändrad e-postadress'],
] as const)('renders %s with the brand app name and action link', (actionType, subject) => {
const mail = buildAuthEmail({
actionType,
appName: 'Siffra',
actionUrl: URL_EXAMPLE,
})
expect(mail.subject).toBe(subject)
expect(mail.html).toContain('Siffra')
expect(mail.html).toContain(URL_EXAMPLE_HTML)
expect(mail.html).not.toMatch(/accounted/i)
expect(mail.text).toContain(URL_EXAMPLE)
expect(mail.text).not.toMatch(/accounted/i)
})
it('renders the platform default without a brand', () => {
const mail = buildAuthEmail({
actionType: 'recovery',
appName: 'Accounted',
actionUrl: 'https://app.gnubok.se/auth/callback?token_hash=abc&type=recovery',
})
expect(mail.html).toContain('ACCOUNTED')
expect(mail.html).toContain('https://app.gnubok.se/auth/callback')
expect(mail.html).toMatchSnapshot()
expect(mail.text).toMatchSnapshot()
})
it('renders the branded recovery mail (snapshot)', () => {
const mail = buildAuthEmail({
actionType: 'recovery',
appName: 'Siffra',
actionUrl: URL_EXAMPLE,
})
expect(mail.html).toMatchSnapshot()
expect(mail.text).toMatchSnapshot()
})
it('tells the user both mails must be clicked for an email change', () => {
for (const actionType of ['email_change', 'email_change_current'] as const) {
const mail = buildAuthEmail({
actionType,
appName: 'Siffra',
actionUrl: URL_EXAMPLE,
})
expect(mail.text).toContain('två mail')
expect(mail.text).toContain('länken i båda')
}
})
it('renders the reauthentication code without a link', () => {
const mail = buildAuthEmail({
actionType: 'reauthentication',
appName: 'Siffra',
otpCode: '123456',
})
expect(mail.subject).toBe('Din verifieringskod')
expect(mail.html).toContain('123456')
expect(mail.html).not.toContain('<a href')
expect(mail.text).toContain('Kod: 123456')
})
it('renders the BankID signup confirmation with the ignore-and-stay-inactive note', () => {
// Sent to whatever address the BankID holder typed, so the copy must say
// the account was opened with BankID and that ignoring the mail leaves it
// inactive: a stranger must not be nudged into activating it.
const mail = buildAuthEmail({
actionType: 'bankid_signup',
appName: 'Siffra',
actionUrl: 'https://app.siffra.se/auth/callback?token_hash=abc&type=magiclink',
})
expect(mail.subject).toBe('Bekräfta din e-postadress')
expect(mail.text).toContain('BankID')
expect(mail.text).toContain('Siffra')
expect(mail.text).toContain('förblir inaktivt')
expect(mail.text).toContain(
'Bekräfta e-postadress: https://app.siffra.se/auth/callback?token_hash=abc&type=magiclink',
)
expect(mail.html).toContain('type=magiclink')
expect(mail.html).not.toMatch(/accounted/i)
})
it('falls back to a generic mail for unknown action types', () => {
const mail = buildAuthEmail({
actionType: 'some_future_type',
appName: 'Siffra',
actionUrl: URL_EXAMPLE,
})
expect(mail.subject).toBe('Bekräfta din åtgärd')
expect(mail.html).toContain(URL_EXAMPLE_HTML)
})
it('escapes HTML in the app name', () => {
const mail = buildAuthEmail({
actionType: 'recovery',
appName: '<script>x</script>',
actionUrl: URL_EXAMPLE,
})
expect(mail.html).not.toContain('<script>')
})
})
@@ -1,265 +0,0 @@
/**
* WL-13 brand-mail snapshot suite: for every template class (invite, payslip,
* invoice, reminder) assert the three sender states:
*
* - branded company -> brand sender + brand-domain links + no platform
* ("Accounted") leakage in the mail body
* - unbranded company-> today's output, unchanged
* - unverified sender domain -> platform-address fallback (fromName set,
* no fromAddress; the Resend service renders the brand
* name alone over the platform address)
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { Brand } from '@/lib/branding/resolve'
import { makeCustomer, makeInvoice, makeCompanySettings } from '@/tests/helpers'
const resolveBrandForCompanyMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandForCompany: resolveBrandForCompanyMock,
}))
vi.mock('@/lib/branding/service', () => ({
getBranding: () => ({ appName: 'Accounted', appUrl: 'https://app.gnubok.se' }),
}))
import { getSenderForCompany, getBaseUrlForBrand } from '../brand-sender'
import {
generateInviteEmailSubject,
generateInviteEmailHtml,
generateInviteEmailText,
} from '../invite-templates'
import {
generateReminderEmailHtml,
generateReminderEmailText,
type ReminderEmailData,
} from '../reminder-templates'
import { generateInvoiceEmailHtml } from '../invoice-templates'
import { buildPayslipLinkEmail } from '@/lib/salary/payslips/email-template'
function makeBrand(overrides: Partial<Brand> = {}): Brand {
return {
id: 'brand-1',
teamId: 'team-1',
domain: 'app.siffra.se',
appName: 'Siffra',
logoUrl: null,
brandColor: '#123456',
chromeColor: null,
fontKey: 'default',
supportEmail: '[email protected]',
authEmailFrom: '[email protected]',
senderDomain: 'post.siffra.se',
senderDomainStatus: 'verified',
resendDomainId: 'rd-1',
signupMode: 'open',
...overrides,
}
}
const VERIFIED = makeBrand()
const UNVERIFIED = makeBrand({ senderDomainStatus: 'pending' })
beforeEach(() => {
vi.clearAllMocks()
resolveBrandForCompanyMock.mockResolvedValue(null)
})
describe('invite mail (template class: invite)', () => {
async function composeInvite() {
const sender = await getSenderForCompany('company-1')
const baseUrl = getBaseUrlForBrand(sender.brand)
const data = {
companyName: 'Kund AB',
inviterEmail: '[email protected]',
inviteUrl: `${baseUrl}/invite/tok-1`,
appName: sender.brand?.appName,
}
return {
sender,
subject: generateInviteEmailSubject(data),
html: generateInviteEmailHtml(data),
text: generateInviteEmailText(data),
}
}
it('branded: brand sender, brand-domain link, no Accounted leakage', async () => {
resolveBrandForCompanyMock.mockResolvedValue(VERIFIED)
const mail = await composeInvite()
expect(mail.sender).toMatchObject({
fromName: 'Siffra',
fromAddress: '[email protected]',
replyTo: '[email protected]',
})
expect(mail.html).toContain('https://app.siffra.se/invite/tok-1')
expect(mail.subject).toContain('siffra')
expect(mail.html).not.toMatch(/accounted/i)
expect(mail.text).not.toMatch(/accounted/i)
expect(mail.html).toMatchSnapshot()
})
it('unbranded: byte-identical to the un-overridden template on the canonical URL', async () => {
const mail = await composeInvite()
expect(mail.sender).toEqual({ fromName: null, fromAddress: null, replyTo: null, brand: null })
expect(mail.html).toContain('https://app.gnubok.se/invite/tok-1')
const todays = generateInviteEmailHtml({
companyName: 'Kund AB',
inviterEmail: '[email protected]',
inviteUrl: 'https://app.gnubok.se/invite/tok-1',
})
expect(mail.html).toBe(todays)
expect(mail.html).toMatchSnapshot()
})
it('unverified sender domain: via-Accounted fallback (fromName without fromAddress)', async () => {
resolveBrandForCompanyMock.mockResolvedValue(UNVERIFIED)
const mail = await composeInvite()
expect(mail.sender.fromName).toBe('Siffra')
expect(mail.sender.fromAddress).toBeNull()
// Links and body still carry the brand even in the fallback.
expect(mail.html).toContain('https://app.siffra.se/invite/tok-1')
expect(mail.html).not.toMatch(/accounted/i)
})
})
describe('payslip mail (template class: payslip)', () => {
async function composePayslip() {
const sender = await getSenderForCompany('company-1')
const baseUrl = getBaseUrlForBrand(sender.brand)
return {
sender,
...buildPayslipLinkEmail({
employeeFirstName: 'Anna',
companyName: 'Kund AB',
periodYear: 2026,
periodMonth: 6,
paymentDate: '2026-06-25',
url: `${baseUrl}/payslip/tok-1`,
}),
}
}
it('branded: brand sender and brand-domain link', async () => {
resolveBrandForCompanyMock.mockResolvedValue(VERIFIED)
const mail = await composePayslip()
expect(mail.sender).toMatchObject({
fromName: 'Siffra',
fromAddress: '[email protected]',
})
expect(mail.html).toContain('https://app.siffra.se/payslip/tok-1')
expect(mail.html).not.toMatch(/accounted/i)
expect(mail.html).toMatchSnapshot()
})
it('unbranded: canonical link, platform sender, unchanged body', async () => {
const mail = await composePayslip()
expect(mail.sender.fromName).toBeNull()
expect(mail.sender.fromAddress).toBeNull()
expect(mail.html).toContain('https://app.gnubok.se/payslip/tok-1')
expect(mail.html).toMatchSnapshot()
})
it('unverified sender domain: via-Accounted fallback', async () => {
resolveBrandForCompanyMock.mockResolvedValue(UNVERIFIED)
const mail = await composePayslip()
expect(mail.sender.fromName).toBe('Siffra')
expect(mail.sender.fromAddress).toBeNull()
})
})
describe('invoice mail (template class: invoice)', () => {
const company = makeCompanySettings({
company_name: 'Kund AB',
org_number: '556000-0000',
})
const customer = makeCustomer({ name: 'Erik Andersson', email: '[email protected]', language: 'sv' })
const invoice = makeInvoice({
invoice_number: 'F-1001',
invoice_date: '2026-07-01',
due_date: '2026-07-31',
total: 1250,
currency: 'SEK',
})
it('branded: mail rides the brand sender domain, COMPANY stays the display sender', async () => {
resolveBrandForCompanyMock.mockResolvedValue(VERIFIED)
const sender = await getSenderForCompany('company-1')
// The call site (sendTrackedInvoiceEmail) keeps fromName = company name
// and only picks up fromAddress from the brand.
expect(sender.fromAddress).toBe('[email protected]')
const html = generateInvoiceEmailHtml({ invoice, customer, company })
// Template content is company-branded and platform-free by design;
// the brand must not inject itself into the customer-facing body.
expect(html).not.toMatch(/accounted/i)
expect(html).not.toContain('Siffra')
expect(html).toContain('Kund AB')
})
it('unbranded: template output unchanged and platform-free', async () => {
const sender = await getSenderForCompany('company-1')
expect(sender.fromAddress).toBeNull()
const html = generateInvoiceEmailHtml({ invoice, customer, company })
expect(html).not.toMatch(/accounted/i)
expect(html).toMatchSnapshot()
})
it('unverified sender domain: no fromAddress, so the From header stays byte-identical', async () => {
resolveBrandForCompanyMock.mockResolvedValue(UNVERIFIED)
const sender = await getSenderForCompany('company-1')
expect(sender.fromAddress).toBeNull()
})
})
describe('reminder mail (template class: reminder)', () => {
function makeReminderData(actionUrl: string): ReminderEmailData {
return {
invoice: makeInvoice({
invoice_number: 'F-1001',
invoice_date: '2026-05-01',
due_date: '2026-06-01',
total: 1250,
currency: 'SEK',
}),
customer: makeCustomer({ name: 'Erik Andersson', email: '[email protected]' }),
company: makeCompanySettings({ company_name: 'Kund AB' }),
reminderLevel: 1,
daysOverdue: 20,
actionUrl,
interestAmount: 0,
interestRate: 0,
interestFromDate: '2026-06-02',
interestDays: 0,
reminderFee: 0,
}
}
it('branded: action link on the brand home domain, no Accounted leakage', async () => {
resolveBrandForCompanyMock.mockResolvedValue(VERIFIED)
const sender = await getSenderForCompany('company-1')
const baseUrl = getBaseUrlForBrand(sender.brand)
const data = makeReminderData(`${baseUrl}/invoice-action/tok-1`)
const html = generateReminderEmailHtml(data)
const text = generateReminderEmailText(data)
expect(sender.fromAddress).toBe('[email protected]')
expect(html).toContain('https://app.siffra.se/invoice-action/tok-1')
expect(html).not.toMatch(/accounted/i)
expect(text).toContain('https://app.siffra.se/invoice-action/tok-1')
})
it('unbranded: canonical action link and unchanged output', async () => {
const sender = await getSenderForCompany('company-1')
const baseUrl = getBaseUrlForBrand(sender.brand)
const data = makeReminderData(`${baseUrl}/invoice-action/tok-1`)
const html = generateReminderEmailHtml(data)
expect(sender.fromAddress).toBeNull()
expect(html).toContain('https://app.gnubok.se/invoice-action/tok-1')
expect(html).not.toMatch(/accounted/i)
expect(html).toMatchSnapshot()
})
it('unverified sender domain: brand link but platform From address', async () => {
resolveBrandForCompanyMock.mockResolvedValue(UNVERIFIED)
const sender = await getSenderForCompany('company-1')
expect(sender.fromAddress).toBeNull()
expect(getBaseUrlForBrand(sender.brand)).toBe('https://app.siffra.se')
})
})
-113
View File
@@ -1,113 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { Brand } from '@/lib/branding/resolve'
const resolveBrandForCompanyMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandForCompany: resolveBrandForCompanyMock,
}))
vi.mock('@/lib/branding/service', () => ({
getBranding: () => ({ appName: 'Accounted', appUrl: 'https://app.gnubok.se' }),
}))
import {
getSenderForBrand,
getSenderForCompany,
getBaseUrlForBrand,
getBaseUrlForCompany,
} from '../brand-sender'
function makeBrand(overrides: Partial<Brand> = {}): Brand {
return {
id: 'brand-1',
teamId: 'team-1',
domain: 'app.siffra.se',
appName: 'Siffra',
logoUrl: null,
brandColor: '#123456',
chromeColor: null,
fontKey: 'default',
supportEmail: '[email protected]',
authEmailFrom: '[email protected]',
senderDomain: 'post.siffra.se',
senderDomainStatus: 'verified',
resendDomainId: 'rd-1',
signupMode: 'open',
...overrides,
}
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('getSenderForBrand', () => {
it('returns platform defaults (all null) for no brand', () => {
expect(getSenderForBrand(null)).toEqual({
fromName: null,
fromAddress: null,
replyTo: null,
brand: null,
})
})
it('sends from the brand address when the sender domain is verified', () => {
const brand = makeBrand()
expect(getSenderForBrand(brand)).toEqual({
fromName: 'Siffra',
fromAddress: '[email protected]',
replyTo: '[email protected]',
brand,
})
})
it('falls back to the via-platform pattern when the domain is unverified', () => {
const brand = makeBrand({ senderDomainStatus: 'pending' })
expect(getSenderForBrand(brand)).toEqual({
fromName: 'Siffra',
fromAddress: null,
replyTo: '[email protected]',
brand,
})
})
it('falls back when the domain is verified but authEmailFrom is missing', () => {
const brand = makeBrand({ authEmailFrom: null })
const sender = getSenderForBrand(brand)
expect(sender.fromAddress).toBeNull()
expect(sender.fromName).toBe('Siffra')
})
})
describe('getSenderForCompany', () => {
it('resolves through resolveBrandForCompany', async () => {
const brand = makeBrand()
resolveBrandForCompanyMock.mockResolvedValue(brand)
const sender = await getSenderForCompany('company-1')
expect(resolveBrandForCompanyMock).toHaveBeenCalledWith('company-1')
expect(sender.fromAddress).toBe('[email protected]')
})
it('returns platform defaults for a brandless company', async () => {
resolveBrandForCompanyMock.mockResolvedValue(null)
const sender = await getSenderForCompany('company-1')
expect(sender).toEqual({ fromName: null, fromAddress: null, replyTo: null, brand: null })
})
})
describe('base URLs', () => {
it('uses the brand home domain when a brand exists', () => {
expect(getBaseUrlForBrand(makeBrand())).toBe('https://app.siffra.se')
})
it('uses the canonical app URL without a brand', () => {
expect(getBaseUrlForBrand(null)).toBe('https://app.gnubok.se')
})
it('getBaseUrlForCompany resolves the brand by company', async () => {
resolveBrandForCompanyMock.mockResolvedValue(makeBrand())
await expect(getBaseUrlForCompany('company-1')).resolves.toBe('https://app.siffra.se')
resolveBrandForCompanyMock.mockResolvedValue(null)
await expect(getBaseUrlForCompany('company-2')).resolves.toBe('https://app.gnubok.se')
})
})
@@ -1,90 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
generateConsentExpiryEmailHtml,
generateConsentExpiryEmailText,
generateConsentExpiryEmailSubject,
} from '@/lib/email/consent-notification-templates'
import { getBranding } from '@/lib/branding/service'
const expired = {
bankName: 'SEB',
daysUntilExpiry: 0,
renewalUrl: 'https://app.gnubok.se/settings/banking',
companyName: 'Glimworks AB',
isExpired: true,
}
const expiringSoon = {
...expired,
daysUntilExpiry: 3,
isExpired: false,
}
describe('consent expiry email templates', () => {
it('signs off as the app, never as the recipient company', () => {
const html = generateConsentExpiryEmailHtml(expired)
const text = generateConsentExpiryEmailText(expired)
const { appName } = getBranding()
expect(html).toContain(`Med vänliga hälsningar,<br>\n <strong>${appName}</strong>`)
expect(text).toContain(`Med vänliga hälsningar,\n${appName}`)
expect(html).not.toContain('Med vänliga hälsningar,<br>\n <strong>Glimworks')
})
it('uses no alarm colors in the chrome', () => {
for (const data of [expired, expiringSoon]) {
const html = generateConsentExpiryEmailHtml(data)
expect(html).not.toMatch(/#dc2626|#ea580c|#ef4444|#b91c1c/i)
expect(html).not.toContain('Åtgärd krävs')
}
})
it('names the bank, the company, and the destination URL', () => {
const html = generateConsentExpiryEmailHtml(expired)
expect(html).toContain('SEB')
expect(html).toContain('Glimworks AB')
// The URL is shown as plain text next to the button so the recipient can
// verify where it leads before clicking.
const urlMentions = html.split(expired.renewalUrl).length - 1
expect(urlMentions).toBeGreaterThanOrEqual(2)
})
it('explains why the recipient got the email', () => {
const html = generateConsentExpiryEmailHtml(expired)
const text = generateConsentExpiryEmailText(expired)
const { supportEmail } = getBranding()
expect(html).toContain('Du får det här mejlet eftersom')
expect(html).toContain(supportEmail)
expect(text).toContain('Du får det här mejlet eftersom')
expect(text).toContain(supportEmail)
})
it('omits the company row cleanly when no company name is available', () => {
const data = { ...expired, companyName: '' }
const html = generateConsentExpiryEmailHtml(data)
const text = generateConsentExpiryEmailText(data)
expect(html).not.toContain('Företag')
expect(html).not.toContain('för </')
expect(text).not.toContain('Företag:')
expect(generateConsentExpiryEmailSubject(data)).toBe('Förnya bankkopplingen till SEB')
})
it('generates calm, specific subjects', () => {
expect(generateConsentExpiryEmailSubject(expired)).toBe(
'Förnya bankkopplingen till SEB - Glimworks AB'
)
expect(generateConsentExpiryEmailSubject(expiringSoon)).toBe(
'Bankkopplingen till SEB löper ut om 3 dagar - Glimworks AB'
)
expect(generateConsentExpiryEmailSubject({ ...expiringSoon, daysUntilExpiry: 1 })).toBe(
'Bankkopplingen till SEB löper ut om 1 dag - Glimworks AB'
)
})
it('pluralizes days in the expiring-soon body', () => {
const html = generateConsentExpiryEmailHtml({ ...expiringSoon, daysUntilExpiry: 1 })
expect(html).toContain('löper ut om 1 dag')
const html3 = generateConsentExpiryEmailHtml(expiringSoon)
expect(html3).toContain('löper ut om 3 dagar')
})
})
-92
View File
@@ -1,92 +0,0 @@
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('[email protected]')).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 = '[email protected]'
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()
})
})
-115
View File
@@ -1,115 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
buildSenderAddress,
senderFromRow,
resolveInvoiceSender,
} from '@/lib/email/invoice-sender'
import { createQueuedMockSupabase } from '@/tests/helpers'
import type { SupabaseClient } from '@supabase/supabase-js'
const hasCapabilityMock = vi.fn()
vi.mock('@/lib/entitlements/has-capability', () => ({
hasCapability: (...args: unknown[]) => hasCapabilityMock(...args),
}))
const VERIFIED_ROW = {
domain: 'hansbolag.example',
status: 'verified' as const,
enabled: true,
sender_local_part: 'faktura',
sender_name: null,
}
describe('buildSenderAddress', () => {
it('joins local part and domain', () => {
expect(buildSenderAddress('faktura', 'hansbolag.example')).toBe('[email protected]')
})
})
describe('senderFromRow', () => {
it('uses the company name when no sender name is stored', () => {
expect(senderFromRow(VERIFIED_ROW, 'Hans Bolag AB')).toEqual({
name: 'Hans Bolag AB',
address: '[email protected]',
})
})
it('prefers an explicit sender name', () => {
expect(senderFromRow({ ...VERIFIED_ROW, sender_name: 'Hans Bolag Ekonomi' }, 'Hans Bolag AB')).toEqual({
name: 'Hans Bolag Ekonomi',
address: '[email protected]',
})
})
it('never sends as a reserved platform domain or a malformed domain, even from a verified row', () => {
const previous = process.env.RESEND_FROM_EMAIL
process.env.RESEND_FROM_EMAIL = '[email protected]'
try {
expect(senderFromRow({ ...VERIFIED_ROW, domain: 'platform.example' }, 'X')).toBeUndefined()
expect(senderFromRow({ ...VERIFIED_ROW, domain: 'mail.platform.example' }, 'X')).toBeUndefined()
expect(senderFromRow({ ...VERIFIED_ROW, domain: 'not a host' }, 'X')).toBeUndefined()
expect(senderFromRow(VERIFIED_ROW, 'X')).toEqual({ name: 'X', address: '[email protected]' })
} finally {
if (previous === undefined) delete process.env.RESEND_FROM_EMAIL
else process.env.RESEND_FROM_EMAIL = previous
}
})
it('returns undefined for missing, unverified, paused, or nameless rows', () => {
expect(senderFromRow(null, 'X')).toBeUndefined()
expect(senderFromRow({ ...VERIFIED_ROW, status: 'pending' }, 'X')).toBeUndefined()
expect(senderFromRow({ ...VERIFIED_ROW, status: 'failed' }, 'X')).toBeUndefined()
expect(senderFromRow({ ...VERIFIED_ROW, enabled: false }, 'X')).toBeUndefined()
expect(senderFromRow(VERIFIED_ROW, ' ')).toBeUndefined()
expect(senderFromRow(VERIFIED_ROW, null)).toBeUndefined()
})
})
describe('resolveInvoiceSender', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns undefined and skips the entitlement check when the company has no verified row', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueue({ data: null })
const result = await resolveInvoiceSender(supabase as unknown as SupabaseClient, 'company-1', 'Hans Bolag AB')
expect(result).toBeUndefined()
expect(hasCapabilityMock).not.toHaveBeenCalled()
// Only verified + enabled rows are ever read.
const eqArgs = findCall('company_sending_domains', 'eq')
expect(eqArgs).toEqual(['company_id', 'company-1'])
})
it('returns the sender when the row is verified and the company holds the grant', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: VERIFIED_ROW })
hasCapabilityMock.mockResolvedValue(true)
const result = await resolveInvoiceSender(supabase as unknown as SupabaseClient, 'company-1', 'Hans Bolag AB')
expect(result).toEqual({ name: 'Hans Bolag AB', address: '[email protected]' })
expect(hasCapabilityMock).toHaveBeenCalledWith(expect.anything(), 'company-1', 'custom_sender_domain')
})
it('falls back to the platform sender when the grant has lapsed', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: VERIFIED_ROW })
hasCapabilityMock.mockResolvedValue(false)
const result = await resolveInvoiceSender(supabase as unknown as SupabaseClient, 'company-1', 'Hans Bolag AB')
expect(result).toBeUndefined()
})
it('never throws: a read error or a thrown entitlement check yields undefined', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: null, error: { message: 'boom' } })
await expect(
resolveInvoiceSender(supabase as unknown as SupabaseClient, 'company-1', 'X'),
).resolves.toBeUndefined()
const second = createQueuedMockSupabase()
second.enqueue({ data: VERIFIED_ROW })
hasCapabilityMock.mockRejectedValue(new Error('network'))
await expect(
resolveInvoiceSender(second.supabase as unknown as SupabaseClient, 'company-1', 'X'),
).resolves.toBeUndefined()
})
})
File diff suppressed because it is too large Load Diff
@@ -1,468 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
generateReminderEmailHtml,
generateReminderEmailText,
generateReminderEmailSubject,
calculateReminderAmounts,
formatReminderTotalDue,
REMINDER_FEE_CURRENCY,
reminderPrincipal,
} from '../reminder-templates'
import { formatCurrency } from '@/lib/utils'
import { makeCustomer, makeInvoice, makeCompanySettings } from '@/tests/helpers'
import type { CompanySettings } from '@/types'
const company = makeCompanySettings({ company_name: 'Acme AB' })
const customer = makeCustomer({ name: 'Erik Andersson', email: '[email protected]' })
const invoice = makeInvoice({
invoice_number: 'F2026010',
invoice_date: '2026-04-15',
due_date: '2026-05-01',
currency: 'SEK',
total: 10_000,
})
const eurInvoice = makeInvoice({
invoice_number: 'F2026011',
invoice_date: '2026-04-15',
due_date: '2026-05-01',
currency: 'EUR',
total: 1_000,
})
const baseData = {
invoice,
customer,
company,
reminderLevel: 1 as const,
daysOverdue: 25,
actionUrl: 'https://example.com/invoice-action/abc',
}
const eurBaseData = { ...baseData, invoice: eurInvoice }
describe('reminder email templates: surcharges', () => {
it('renders dröjsmålsränta + påminnelseavgift in HTML when set', () => {
const html = generateReminderEmailHtml({
...baseData,
interestAmount: 86.3,
interestRate: 0.105,
interestFromDate: '2026-05-01',
interestDays: 30,
reminderFee: 60,
})
expect(html).toContain('Ursprungligt belopp:')
expect(html).toContain('Dröjsmålsränta')
expect(html).toContain('Påminnelseavgift:')
expect(html).toContain('Att betala:')
expect(html).toContain('10,5%') // rate display (sv-SE format)
expect(html).toContain('30 dagar')
})
it('omits surcharge rows when both are zero', () => {
const html = generateReminderEmailHtml({
...baseData,
interestAmount: 0,
interestRate: 0.105,
interestFromDate: '2026-05-01',
interestDays: 0,
reminderFee: 0,
})
expect(html).not.toContain('Dröjsmålsränta')
expect(html).not.toContain('Påminnelseavgift:')
expect(html).toContain('Att betala:')
})
it('renders surcharges in plain text', () => {
const text = generateReminderEmailText({
...baseData,
interestAmount: 86.3,
interestRate: 0.105,
interestFromDate: '2026-05-01',
interestDays: 30,
reminderFee: 60,
})
expect(text).toContain('Ursprungligt belopp')
expect(text).toContain('Dröjsmålsränta')
expect(text).toContain('Påminnelseavgift')
expect(text).toContain('Att betala')
})
it('subject includes surcharge note when surcharges apply', () => {
const subject = generateReminderEmailSubject({
...baseData,
interestAmount: 86.3,
interestRate: 0.105,
interestFromDate: '2026-05-01',
interestDays: 30,
reminderFee: 60,
})
expect(subject).toContain('F2026010')
expect(subject).toContain('inkl. dröjsmålsränta')
})
it('subject is unchanged when no surcharges apply', () => {
const subject = generateReminderEmailSubject({
...baseData,
interestAmount: 0,
interestRate: 0,
interestFromDate: '2026-05-01',
interestDays: 0,
reminderFee: 0,
})
expect(subject).not.toContain('inkl. dröjsmålsränta')
expect(subject).toContain('F2026010')
})
})
describe('calculateReminderAmounts', () => {
it('folds the fee into the total for a SEK invoice', () => {
expect(
calculateReminderAmounts({
invoiceTotal: 10_000,
interestAmount: 86.3,
reminderFee: 60,
currency: 'SEK',
}),
).toEqual({ currency: 'SEK', totalDue: 10_146.3, feeDueSeparately: 0 })
})
it('keeps the SEK fee out of a foreign-currency total', () => {
expect(
calculateReminderAmounts({
invoiceTotal: 1_000,
interestAmount: 10,
reminderFee: 60,
currency: 'EUR',
}),
).toEqual({ currency: 'EUR', totalDue: 1_010, feeDueSeparately: 60 })
})
it('treats a missing currency as SEK', () => {
expect(
calculateReminderAmounts({
invoiceTotal: 100,
interestAmount: 0,
reminderFee: 60,
currency: null,
}),
).toEqual({ currency: 'SEK', totalDue: 160, feeDueSeparately: 0 })
})
it('rounds with Math.round(x * 100) / 100, not toFixed', () => {
const amounts = calculateReminderAmounts({
invoiceTotal: 1_000.005,
interestAmount: 0.011,
reminderFee: 0,
currency: 'SEK',
})
expect(amounts.totalDue).toBe(1_000.02)
})
it('renders a split total as two amounts, never one mixed scalar', () => {
const amounts = calculateReminderAmounts({
invoiceTotal: 1_000,
interestAmount: 10,
reminderFee: 60,
currency: 'EUR',
})
expect(formatReminderTotalDue(amounts)).toBe(
`${formatCurrency(1_010, 'EUR')} + ${formatCurrency(60, 'SEK')}`,
)
})
})
describe('reminder email templates: statutory fee currency (Lag 1981:739)', () => {
const eurSurcharges = {
interestAmount: 10,
interestRate: 0.105,
interestFromDate: '2026-05-01',
interestDays: 30,
reminderFee: 60,
}
it('the fee is a SEK statute, not the invoice currency', () => {
expect(REMINDER_FEE_CURRENCY).toBe('SEK')
})
it('never labels the 60 kr fee with the invoice currency in HTML', () => {
const html = generateReminderEmailHtml({ ...eurBaseData, ...eurSurcharges })
expect(
html,
'the påminnelseavgift is capped at 60 kr by Lag 1981:739; rendering it as 60 EUR demands roughly 690 kr',
).not.toContain(formatCurrency(60, 'EUR'))
expect(html).toContain(formatCurrency(60, 'SEK'))
})
it('never sums a SEK fee into a EUR total in HTML', () => {
const html = generateReminderEmailHtml({ ...eurBaseData, ...eurSurcharges })
// 1000 EUR invoice + 10 EUR interest = 1010 EUR, plus 60 kr alongside.
expect(html).toContain(formatCurrency(1_010, 'EUR'))
expect(html).not.toContain(formatCurrency(1_070, 'EUR'))
expect(html).toContain('Lag 1981:739')
})
it('never labels the fee with the invoice currency in plain text', () => {
const text = generateReminderEmailText({ ...eurBaseData, ...eurSurcharges })
expect(text).toContain(`Påminnelseavgift: ${formatCurrency(60, 'SEK')}`)
expect(text).not.toContain(formatCurrency(60, 'EUR'))
expect(text).toContain(
`Att betala: ${formatCurrency(1_010, 'EUR')} + ${formatCurrency(60, 'SEK')}`,
)
})
it('never quotes a mixed-currency amount in the subject', () => {
const subject = generateReminderEmailSubject({ ...eurBaseData, ...eurSurcharges })
expect(subject).not.toContain(formatCurrency(1_070, 'EUR'))
expect(subject).toContain(
`${formatCurrency(1_010, 'EUR')} + ${formatCurrency(60, 'SEK')}`,
)
})
it('leaves a SEK invoice untouched: one currency, one total, no split note', () => {
const data = {
...baseData,
interestAmount: 86.3,
interestRate: 0.105,
interestFromDate: '2026-05-01',
interestDays: 30,
reminderFee: 60,
}
const html = generateReminderEmailHtml(data)
const text = generateReminderEmailText(data)
const subject = generateReminderEmailSubject(data)
expect(html).toContain(formatCurrency(60, 'SEK'))
expect(html).toContain(formatCurrency(10_146.3, 'SEK'))
expect(html).not.toContain('Lag 1981:739')
expect(text).toContain(`Påminnelseavgift: ${formatCurrency(60, 'SEK')}`)
expect(text).toContain(`Att betala: ${formatCurrency(10_146.3, 'SEK')}`)
expect(text).not.toContain(' + ')
expect(subject).toContain(formatCurrency(10_146.3, 'SEK'))
})
it('does not append a SEK note when the fee is disabled on a EUR invoice', () => {
const html = generateReminderEmailHtml({
...eurBaseData,
...eurSurcharges,
reminderFee: 0,
})
expect(html).not.toContain('Lag 1981:739')
expect(html).toContain(formatCurrency(1_010, 'EUR'))
})
})
describe('reminder email templates: ROT/RUT-avdrag (fakturamodellen)', () => {
// 12 500 total with a 3 750 ROT deduction: the customer was asked for
// 8 750; the 3 750 is a claim on Skatteverket and must never be dunned.
const rotInvoice = makeInvoice({
invoice_number: 'F2026012',
invoice_date: '2026-04-15',
due_date: '2026-05-01',
currency: 'SEK',
total: 12_500,
deduction_total: 3_750,
} as Parameters<typeof makeInvoice>[0])
const rotData = { ...baseData, invoice: rotInvoice, interestAmount: 0, interestRate: 0, interestFromDate: '2026-05-02', interestDays: 0, reminderFee: 0 }
it('reminderPrincipal is the customer share', () => {
expect(reminderPrincipal(rotInvoice, company)).toBe(8_750)
expect(reminderPrincipal(invoice, company)).toBe(10_000)
})
it('HTML, text and subject never quote the pre-deduction total', () => {
const html = generateReminderEmailHtml(rotData)
const text = generateReminderEmailText(rotData)
const subject = generateReminderEmailSubject({ ...rotData, reminderFee: 60 })
for (const out of [html, text]) {
expect(out).toContain(formatCurrency(8_750, 'SEK'))
expect(out).not.toContain(formatCurrency(12_500, 'SEK'))
}
expect(subject).not.toContain(formatCurrency(12_500, 'SEK'))
})
it('folds interest and fee onto the customer share', () => {
const amounts = calculateReminderAmounts({
invoiceTotal: reminderPrincipal(rotInvoice, company),
interestAmount: 12.5,
reminderFee: 60,
currency: 'SEK',
})
expect(amounts.totalDue).toBe(8_822.5)
})
})
describe('payment details follow the invoice currency', () => {
const multiCurrencyCompany = makeCompanySettings({
company_name: 'Acme AB',
bank_name: 'Svenska Banken',
iban: 'SE4550000000058398257466',
bic: 'ESSESESS',
invoice_payment_accounts: {
SEK: { bank_name: 'Svenska Banken', iban: 'SE4550000000058398257466', bic: 'ESSESESS' },
EUR: { bank_name: 'Deutsche Bank', iban: 'DE89370400440532013000', bic: 'DEUTDEFF' },
} as CompanySettings['invoice_payment_accounts'],
})
it('prints the EUR account on a EUR reminder, never the SEK IBAN', () => {
const data = { ...baseData, company: multiCurrencyCompany, invoice: eurInvoice }
const html = generateReminderEmailHtml(data)
const text = generateReminderEmailText(data)
for (const out of [html, text]) {
expect(out).toContain('DE89370400440532013000')
expect(out).toContain('DEUTDEFF')
expect(out).toContain('Deutsche Bank')
expect(out).not.toContain('SE4550000000058398257466')
expect(out).not.toContain('ESSESESS')
}
})
it('keeps the SEK account on a SEK reminder', () => {
const data = { ...baseData, company: multiCurrencyCompany, invoice }
const html = generateReminderEmailHtml(data)
const text = generateReminderEmailText(data)
for (const out of [html, text]) {
expect(out).toContain('SE4550000000058398257466')
expect(out).not.toContain('DE89370400440532013000')
}
})
it('never falls back to the legacy SEK fields for a EUR reminder when no EUR account exists', () => {
const sekOnly = makeCompanySettings({
company_name: 'Acme AB',
bank_name: 'Svenska Banken',
iban: 'SE4550000000058398257466',
bic: 'ESSESESS',
})
const data = { ...baseData, company: sekOnly, invoice: eurInvoice }
for (const out of [generateReminderEmailHtml(data), generateReminderEmailText(data)]) {
expect(out).not.toContain('SE4550000000058398257466')
expect(out).not.toContain('Svenska Banken')
}
})
})
describe('reminder email texts: per-company overrides', () => {
const zeroSurcharges = {
interestAmount: 0,
interestRate: 0,
interestFromDate: '2026-05-02',
interestDays: 0,
reminderFee: 0,
}
const withOverrides = (overrides: CompanySettings['reminder_text_overrides']) => ({
...baseData,
...zeroSurcharges,
company: makeCompanySettings({ company_name: 'Acme AB', reminder_text_overrides: overrides }),
})
it('renders the stock texts when no overrides are stored', () => {
const data = withOverrides(null)
const text = generateReminderEmailText(data)
const html = generateReminderEmailHtml(data)
const subject = generateReminderEmailSubject(data)
expect(text).toContain(
'Vi vill påminna dig om att faktura F2026010 förföll till betalning den 2026-05-01.',
)
expect(html).toContain('Om du redan har betalat kan du bortse från denna påminnelse.')
expect(subject).toBe(
`Vänlig påminnelse: Faktura F2026010 - ${formatCurrency(10_000, 'SEK')}`,
)
})
it('the stock final level is an inkassovarning, never fee math', () => {
const data = { ...withOverrides(null), reminderLevel: 3 as const }
const text = generateReminderEmailText(data)
const html = generateReminderEmailHtml(data)
for (const out of [text, html]) {
expect(out).toContain('inkassovarning')
expect(out).toContain('överlämnas fordran till inkasso')
expect(out).toContain('lag (1981:739)')
expect(out).toContain('inom 8 dagar')
// Text only: no fee amount is promised or invented by the template.
expect(out).not.toContain('450')
}
// The opening inkassovarning paragraph keeps the red emphasis.
expect(html).toContain('color: #dc2626; font-weight: 500;')
})
it('a body override wins in HTML and text; the subject stays stock', () => {
const data = withOverrides({ level_1: { body: 'Vår helt egna påminnelsetext.' } })
const text = generateReminderEmailText(data)
const html = generateReminderEmailHtml(data)
for (const out of [text, html]) {
expect(out).toContain('Vår helt egna påminnelsetext.')
expect(out).not.toContain('Vi vill påminna dig om att faktura')
}
expect(generateReminderEmailSubject(data)).toContain('Vänlig påminnelse: Faktura F2026010')
})
it('a subject override wins and owns the whole line: no automatic suffix', () => {
const data = {
...withOverrides({ level_1: { subject: 'Obetald faktura {fakturanummer}' } }),
interestAmount: 86.3,
interestRate: 0.105,
interestDays: 30,
reminderFee: 60,
}
const subject = generateReminderEmailSubject(data)
expect(subject).toBe('Obetald faktura F2026010')
expect(subject).not.toContain('inkl. dröjsmålsränta')
// The body is untouched by a subject-only override.
expect(generateReminderEmailText(data)).toContain('Vi vill påminna dig om att faktura')
})
it('substitutes the documented placeholders in overrides', () => {
const data = withOverrides({
level_1: {
body: 'Faktura {fakturanummer} till {kundnamn} ({förnamn}) från {företag} förföll {förfallodatum} ({dagar} dagar sedan). Att betala: {belopp}. Skickad {fakturadatum}.',
},
})
const text = generateReminderEmailText(data)
expect(text).toContain(
`Faktura F2026010 till Erik Andersson (Erik) från Acme AB förföll 2026-05-01 (25 dagar sedan). Att betala: ${formatCurrency(10_000, 'SEK')}. Skickad 2026-04-15.`,
)
})
it('leaves unknown placeholders as literal text', () => {
const data = withOverrides({ level_1: { body: 'Hej {okänd} värld' } })
expect(generateReminderEmailText(data)).toContain('Hej {okänd} värld')
})
it('falls back to the default for whitespace-only override fields', () => {
const data = withOverrides({ level_1: { subject: ' ', body: '\n' } })
expect(generateReminderEmailSubject(data)).toContain('Vänlig påminnelse: Faktura F2026010')
expect(generateReminderEmailText(data)).toContain('Vi vill påminna dig om att faktura')
})
it('escapes override content in HTML and keeps paragraph breaks', () => {
const data = withOverrides({
level_1: { body: 'Första stycket <script>alert(1)</script>\n\nAndra stycket\nmed radbrytning' },
})
const html = generateReminderEmailHtml(data)
expect(html).not.toContain('<script>')
expect(html).toContain('&lt;script&gt;alert(1)&lt;/script&gt;')
expect(html).toContain('Andra stycket<br>med radbrytning')
// Two paragraphs -> two <p> blocks.
expect(html.match(/Första stycket/g)).toHaveLength(1)
expect(html).toContain('<p style="margin: 0 0 15px 0;">Andra stycket<br>med radbrytning</p>')
})
it('applies an override only to its own level', () => {
const overrides = { level_2: { body: 'Egen text för nivå två.' } }
const level1 = generateReminderEmailText(withOverrides(overrides))
const level2 = generateReminderEmailText({
...withOverrides(overrides),
reminderLevel: 2 as const,
})
expect(level1).not.toContain('Egen text för nivå två.')
expect(level1).toContain('Vi vill påminna dig')
expect(level2).toContain('Egen text för nivå två.')
expect(level2).not.toContain('Trots vår tidigare påminnelse')
})
})
@@ -1,128 +0,0 @@
import { describe, it, expect } from 'vitest'
import { createHmac, randomBytes } from 'node:crypto'
import { verifyStandardWebhookSignature } from '../standard-webhook'
const KEY = randomBytes(24)
const SECRET = `v1,whsec_${KEY.toString('base64')}`
function sign(id: string, timestamp: string, payload: string, key: Buffer = KEY): string {
const sig = createHmac('sha256', key)
.update(`${id}.${timestamp}.${payload}`)
.digest('base64')
return `v1,${sig}`
}
const NOW_MS = 1_754_000_000_000
const NOW_SECONDS = String(Math.floor(NOW_MS / 1000))
describe('verifyStandardWebhookSignature', () => {
const payload = JSON.stringify({ hello: 'world' })
it('accepts a valid v1 signature', () => {
expect(
verifyStandardWebhookSignature({
secret: SECRET,
payload,
id: 'msg_1',
timestamp: NOW_SECONDS,
signature: sign('msg_1', NOW_SECONDS, payload),
nowMs: NOW_MS,
}),
).toBe(true)
})
it('accepts the whsec_-only secret format', () => {
expect(
verifyStandardWebhookSignature({
secret: `whsec_${KEY.toString('base64')}`,
payload,
id: 'msg_1',
timestamp: NOW_SECONDS,
signature: sign('msg_1', NOW_SECONDS, payload),
nowMs: NOW_MS,
}),
).toBe(true)
})
it('accepts a space-separated signature list with one matching entry', () => {
const other = sign('msg_1', NOW_SECONDS, payload, randomBytes(24))
const good = sign('msg_1', NOW_SECONDS, payload)
expect(
verifyStandardWebhookSignature({
secret: SECRET,
payload,
id: 'msg_1',
timestamp: NOW_SECONDS,
signature: `${other} ${good}`,
nowMs: NOW_MS,
}),
).toBe(true)
})
it('rejects a signature computed with a different key', () => {
expect(
verifyStandardWebhookSignature({
secret: SECRET,
payload,
id: 'msg_1',
timestamp: NOW_SECONDS,
signature: sign('msg_1', NOW_SECONDS, payload, randomBytes(24)),
nowMs: NOW_MS,
}),
).toBe(false)
})
it('rejects a tampered payload', () => {
expect(
verifyStandardWebhookSignature({
secret: SECRET,
payload: payload + 'x',
id: 'msg_1',
timestamp: NOW_SECONDS,
signature: sign('msg_1', NOW_SECONDS, payload),
nowMs: NOW_MS,
}),
).toBe(false)
})
it('rejects missing headers', () => {
expect(
verifyStandardWebhookSignature({
secret: SECRET,
payload,
id: null,
timestamp: NOW_SECONDS,
signature: sign('msg_1', NOW_SECONDS, payload),
nowMs: NOW_MS,
}),
).toBe(false)
})
it('rejects a timestamp outside the replay tolerance', () => {
const stale = String(Math.floor(NOW_MS / 1000) - 3600)
expect(
verifyStandardWebhookSignature({
secret: SECRET,
payload,
id: 'msg_1',
timestamp: stale,
signature: sign('msg_1', stale, payload),
nowMs: NOW_MS,
}),
).toBe(false)
})
it('ignores non-v1 signature versions', () => {
const sig = sign('msg_1', NOW_SECONDS, payload).slice(3)
expect(
verifyStandardWebhookSignature({
secret: SECRET,
payload,
id: 'msg_1',
timestamp: NOW_SECONDS,
signature: `v1a,${sig}`,
nowMs: NOW_MS,
}),
).toBe(false)
})
})
-63
View File
@@ -1,63 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
escapeHtml,
userTextToHtml,
sanitizeSubjectLine,
applyPlaceholders,
} from '../user-text'
describe('escapeHtml', () => {
it('escapes all five special characters', () => {
expect(escapeHtml(`&<>"'`)).toBe('&amp;&lt;&gt;&quot;&#39;')
})
it('leaves normal text untouched', () => {
expect(escapeHtml('Hej Erik, här är fakturan.')).toBe('Hej Erik, här är fakturan.')
})
})
describe('userTextToHtml', () => {
it('escapes before converting newlines so user-typed <br> stays escaped', () => {
expect(userTextToHtml('a<br>b\nc')).toBe('a&lt;br&gt;b<br>c')
})
it('converts \\r\\n, \\r and \\n to <br>', () => {
expect(userTextToHtml('a\r\nb\rc\nd')).toBe('a<br>b<br>c<br>d')
})
})
describe('sanitizeSubjectLine', () => {
it('flattens newlines to spaces and trims', () => {
expect(sanitizeSubjectLine(' Faktura\r\n1042\n ')).toBe('Faktura 1042')
})
it('leaves a normal subject untouched', () => {
expect(sanitizeSubjectLine('Faktura 1042 från Acme AB')).toBe('Faktura 1042 från Acme AB')
})
})
describe('applyPlaceholders', () => {
const values = { fakturanummer: '1042', förnamn: 'Erik' }
it('substitutes known keys', () => {
expect(applyPlaceholders('Faktura {fakturanummer} till {förnamn}', values)).toBe(
'Faktura 1042 till Erik',
)
})
it('leaves unknown keys literal', () => {
expect(applyPlaceholders('{fakturanumer}', values)).toBe('{fakturanumer}')
})
it('is forgiving about case and inner whitespace', () => {
expect(applyPlaceholders('{ Förnamn }', values)).toBe('Erik')
})
it('leaves empty braces literal', () => {
expect(applyPlaceholders('a {} b', values)).toBe('a {} b')
})
it('does not re-substitute values (single pass)', () => {
expect(applyPlaceholders('{namn}', { namn: '{fakturanummer}' })).toBe('{fakturanummer}')
})
})
-191
View File
@@ -1,191 +0,0 @@
/**
* Auth mail templates for the Supabase Send Email hook (WL-05, WL-13).
*
* Swedish-only, like the other user-facing mail templates in lib/email/
* (see .claude/rules/i18n.md): these are transactional mails, not UI chrome,
* so they deliberately do not go through next-intl.
*
* The appName parameter carries the brand of the requesting host (resolved
* via resolveBrandByHost from the redirect_to origin); the default is the
* platform name, so unbranded hosts render canonical mail.
*/
import { escapeHtml, sanitizeSubjectLine } from './user-text'
export type AuthEmailActionType =
| 'signup'
| 'recovery'
| 'magiclink'
| 'invite'
| 'email_change'
| 'email_change_current'
| 'reauthentication'
| 'bankid_signup'
interface AuthEmailContent {
subject: string
heading: string
body: (appName: string) => string
cta: string
}
const CONTENT: Record<AuthEmailActionType, AuthEmailContent> = {
signup: {
subject: 'Bekräfta din e-postadress',
heading: 'Bekräfta din e-postadress',
body: (appName) =>
`Klicka på knappen nedan för att bekräfta din e-postadress och slutföra din registrering hos ${appName}.`,
cta: 'Bekräfta e-postadress',
},
recovery: {
subject: 'Återställ ditt lösenord',
heading: 'Återställ ditt lösenord',
body: (appName) =>
`Vi har tagit emot en begäran om att återställa lösenordet för ditt konto hos ${appName}. Klicka på knappen nedan för att välja ett nytt lösenord.`,
cta: 'Återställ lösenord',
},
magiclink: {
subject: 'Din inloggningslänk',
heading: 'Logga in',
body: (appName) => `Klicka på knappen nedan för att logga in hos ${appName}.`,
cta: 'Logga in',
},
invite: {
subject: 'Du har blivit inbjuden',
heading: 'Du har blivit inbjuden',
body: (appName) =>
`Du har blivit inbjuden till ${appName}. Klicka på knappen nedan för att skapa ditt konto.`,
cta: 'Acceptera inbjudan',
},
email_change: {
subject: 'Bekräfta din nya e-postadress',
heading: 'Bekräfta din nya e-postadress',
body: (appName) =>
`Klicka på knappen nedan för att bekräfta din nya e-postadress hos ${appName}. Av säkerhetsskäl skickas två mail, ett till din nya adress och ett till din nuvarande. Bytet slutförs först när du klickat på länken i båda.`,
cta: 'Bekräfta ny e-postadress',
},
email_change_current: {
subject: 'Godkänn ändrad e-postadress',
heading: 'Godkänn ändrad e-postadress',
body: (appName) =>
`En ändring av e-postadressen för ditt konto hos ${appName} har begärts. Klicka på knappen nedan för att godkänna ändringen från din nuvarande adress. Av säkerhetsskäl skickas två mail, ett till din nuvarande adress och ett till din nya. Bytet slutförs först när du klickat på länken i båda.`,
cta: 'Godkänn ändringen',
},
reauthentication: {
subject: 'Din verifieringskod',
heading: 'Din verifieringskod',
body: (appName) => `Ange koden nedan för att bekräfta din identitet hos ${appName}.`,
cta: '',
},
// Sent by the BankID signup (extensions/general/tic) to the address the
// person typed, and again when a still-unconfirmed identity tries to log
// in. Not a Supabase hook type: the link is minted by generateLink and only
// ever travels by mail. The copy says plainly that the account was opened
// with BankID and that ignoring the mail leaves it inactive, so a stranger
// whose address was typed by mistake (or on purpose) is not nudged into
// activating someone else's BankID login.
bankid_signup: {
subject: 'Bekräfta din e-postadress',
heading: 'Bekräfta din e-postadress',
body: (appName) =>
`Ett konto hos ${appName} har skapats med BankID och den här e-postadressen. Klicka på knappen nedan för att bekräfta att adressen är din och aktivera kontot. Om det inte var du som skapade kontot kan du bortse från det här meddelandet: kontot förblir inaktivt och kan inte användas för att logga in.`,
cta: 'Bekräfta e-postadress',
},
}
// Availability first: an action type this module does not know (Supabase can
// add new mail classes) still produces a usable mail with the verify link
// rather than dropping the send.
const FALLBACK_CONTENT: AuthEmailContent = {
subject: 'Bekräfta din åtgärd',
heading: 'Bekräfta din åtgärd',
body: (appName) => `Klicka på knappen nedan för att fortsätta hos ${appName}.`,
cta: 'Fortsätt',
}
const IGNORE_NOTE = 'Om du inte begärde detta kan du bortse från det här meddelandet.'
export interface AuthEmailInput {
actionType: string
appName: string
/** Verify URL on the originating host (token_hash flow). */
actionUrl?: string
/** One-time code, for reauthentication mail (no link). */
otpCode?: string
}
export interface AuthEmail {
subject: string
html: string
text: string
}
function contentFor(actionType: string): AuthEmailContent {
return (CONTENT as Record<string, AuthEmailContent>)[actionType] ?? FALLBACK_CONTENT
}
export function buildAuthEmail(input: AuthEmailInput): AuthEmail {
const content = contentFor(input.actionType)
const appName = input.appName
const safeAppName = escapeHtml(appName)
const body = content.body(appName)
const action = input.otpCode
? `
<div style="margin: 28px 0;">
<span style="display: inline-block; background: #f5f5f5; border: 1px solid #e5e5e5; border-radius: 8px; padding: 12px 28px; font-size: 22px; font-weight: 600; letter-spacing: 0.3em; color: #111;">${escapeHtml(input.otpCode)}</span>
</div>`
: input.actionUrl
? `
<div style="margin: 28px 0;">
<a href="${escapeHtml(input.actionUrl)}" style="display: inline-block; background: #111; color: #fff; text-decoration: none; padding: 12px 28px; border-radius: 8px; font-size: 14px; font-weight: 500;">
${escapeHtml(content.cta)}
</a>
</div>`
: ''
const html = `
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${escapeHtml(content.subject)}</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f5f5f5;">
<div style="max-width: 520px; margin: 0 auto; padding: 40px 20px;">
<div style="background: #ffffff; border-radius: 12px; padding: 40px 32px; border: 1px solid #e5e5e5;">
<!-- Header -->
<div style="margin-bottom: 28px;">
<p style="margin: 0 0 4px 0; font-size: 13px; color: #888; letter-spacing: 0.05em;">${safeAppName.toUpperCase()}</p>
<h1 style="margin: 0 0 8px 0; font-size: 22px; font-weight: 600; color: #111;">
${escapeHtml(content.heading)}
</h1>
<p style="margin: 0; color: #666; font-size: 15px;">
${escapeHtml(body)}
</p>
</div>
${action}
<!-- Info -->
<p style="margin: 0; color: #999; font-size: 13px;">
${IGNORE_NOTE}
</p>
</div>
</div>
</body>
</html>`
let text = `${content.heading}\n\n${body}\n\n`
if (input.otpCode) {
text += `Kod: ${input.otpCode}\n\n`
} else if (input.actionUrl) {
text += `${content.cta}: ${input.actionUrl}\n\n`
}
text += IGNORE_NOTE
return {
subject: sanitizeSubjectLine(content.subject),
html,
text,
}
}
-79
View File
@@ -1,79 +0,0 @@
/**
* Brand-aware outbound mail identity (WL-13).
*
* THE RULE: every outbound mail is sent in the brand of the COMPANY it
* concerns, resolved via resolveBrandForCompany (WL-12). These helpers are
* the ONLY entry points call sites use for sender identity and link base
* URLs; a company without a brand gets exactly today's values, byte for byte.
*
* Sender chain (WL-04):
* 1. Brand with a VERIFIED Resend sender domain and an authEmailFrom
* address: send from the brand address with the brand app name.
* 2. Brand without a verified sender domain: ride the platform default
* address with the brand name alone as the display name (fromName set,
* no fromAddress; no "via <platform>", founder call 2026-08-05).
* DMARC-clean: the From domain stays ours.
* 3. No brand: platform defaults (fromName/fromAddress/replyTo all null,
* the email service renders "<Platform> <RESEND_FROM_EMAIL>").
*/
import { getBranding } from '@/lib/branding/service'
import { resolveBrandForCompany, type Brand } from '@/lib/branding/resolve'
export interface BrandSender {
/** Display name for the From header; null = platform default. */
fromName: string | null
/**
* Explicit From address; only set when the brand's sender domain is
* verified in Resend. Null = platform default address.
*/
fromAddress: string | null
/** Reply-To; the brand's support address when a brand exists, else null. */
replyTo: string | null
/** The resolved brand, for callers that also need appName/domain/logo. */
brand: Brand | null
}
/** Pure mapping from a resolved brand to sender identity. */
export function getSenderForBrand(brand: Brand | null): BrandSender {
if (!brand) {
return { fromName: null, fromAddress: null, replyTo: null, brand: null }
}
if (brand.senderDomainStatus === 'verified' && brand.authEmailFrom) {
return {
fromName: brand.appName,
fromAddress: brand.authEmailFrom,
replyTo: brand.supportEmail || null,
brand,
}
}
// Unverified/pending/failed sender domain: "via Accounted" fallback.
return {
fromName: brand.appName,
fromAddress: null,
replyTo: brand.supportEmail || null,
brand,
}
}
/**
* Sender identity for mail concerning `companyId`. Host-independent and
* cron-safe: resolution goes company -> team -> brand.
*/
export async function getSenderForCompany(companyId: string): Promise<BrandSender> {
return getSenderForBrand(await resolveBrandForCompany(companyId))
}
/** Base URL mailed links should point at, given an already-resolved brand. */
export function getBaseUrlForBrand(brand: Brand | null): string {
return brand ? `https://${brand.domain}` : getBranding().appUrl
}
/**
* Base URL for links in mail concerning `companyId`: the brand's home domain
* when the company's team has a brand, else the canonical app URL
* (NEXT_PUBLIC_APP_URL via getBranding().appUrl).
*/
export async function getBaseUrlForCompany(companyId: string): Promise<string> {
return getBaseUrlForBrand(await resolveBrandForCompany(companyId))
}
-162
View File
@@ -1,162 +0,0 @@
import { getBranding } from '@/lib/branding/service'
export interface ConsentExpiryEmailData {
bankName: string
daysUntilExpiry: number
renewalUrl: string
/** The company the bank connection belongs to. Shown so the recipient knows
* which of their companies the email concerns; never used as the sender. */
companyName: string
isExpired: boolean
}
/**
* Consent expiry notification emails.
*
* Tone and layout are deliberately calm: a PSD2 consent running out is
* routine, not an incident. No red, no urgency chrome; the email is signed
* by the app (never the recipient's own company), states plainly why the
* recipient got it, and shows the destination URL in plain text next to the
* button so it does not pattern-match phishing.
*/
const SERIF = `Georgia, 'Times New Roman', serif`
const SANS = `-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`
function dagar(n: number): string {
return `${n} ${n === 1 ? 'dag' : 'dagar'}`
}
/**
* Generate HTML email for consent expiry notification
*/
export function generateConsentExpiryEmailHtml(data: ConsentExpiryEmailData): string {
const { bankName, daysUntilExpiry, renewalUrl, companyName, isExpired } = data
const { appName, supportEmail } = getBranding()
const title = isExpired
? 'Bankkopplingen behöver förnyas'
: `Bankkopplingen löper ut om ${dagar(daysUntilExpiry)}`
const intro = isExpired
? `Banksamtycket för <strong>${bankName}</strong> har löpt ut och den automatiska hämtningen av nya transaktioner är pausad.`
: `Banksamtycket för <strong>${bankName}</strong> löper ut om ${dagar(daysUntilExpiry)}.`
const explanation =
'Det här är väntat: av säkerhetsskäl gäller ett banksamtycke (PSD2) bara en begränsad tid, och därefter behöver det godkännas på nytt hos banken.'
const consequence = isExpired
? 'Ingenting har försvunnit. Redan hämtade transaktioner och din bokföring påverkas inte, och när kopplingen är förnyad hämtas mellanliggande transaktioner ikapp.'
: 'Förnya gärna i förväg så fortsätter transaktionerna att hämtas utan avbrott. Din bokföring påverkas inte.'
return `
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${title}</title>
</head>
<body style="margin: 0; padding: 0; font-family: ${SANS}; line-height: 1.6; color: #374151; background-color: #f5f4f1;">
<div style="max-width: 560px; margin: 0 auto; padding: 40px 20px;">
<div style="background: #ffffff; border: 1px solid #e7e5e0; border-radius: 12px; padding: 40px;">
<div style="font-family: ${SERIF}; font-size: 19px; color: #111111; margin-bottom: 28px;">
${appName}
</div>
<h1 style="margin: 0 0 16px 0; font-family: ${SERIF}; font-size: 23px; font-weight: 400; color: #111111; line-height: 1.3;">
${title}
</h1>
<p style="margin: 0 0 14px 0; font-size: 15px;">${intro}</p>
<p style="margin: 0 0 14px 0; font-size: 15px;">${explanation}</p>
<p style="margin: 0 0 28px 0; font-size: 15px;">${consequence}</p>
<table role="presentation" style="width: 100%; border-collapse: collapse; margin-bottom: 28px; font-size: 14px;">
<tr>
<td style="padding: 8px 0; border-top: 1px solid #ececea; color: #9ca3af; width: 90px;">Bank</td>
<td style="padding: 8px 0; border-top: 1px solid #ececea; color: #111111;">${bankName}</td>
</tr>
${companyName ? `
<tr>
<td style="padding: 8px 0; border-top: 1px solid #ececea; border-bottom: 1px solid #ececea; color: #9ca3af;">Företag</td>
<td style="padding: 8px 0; border-top: 1px solid #ececea; border-bottom: 1px solid #ececea; color: #111111;">${companyName}</td>
</tr>
` : ''}
</table>
<div style="margin-bottom: 12px;">
<a href="${renewalUrl}" style="display: inline-block; background: #1a1a1a; color: #ffffff; padding: 12px 26px; border-radius: 99px; text-decoration: none; font-weight: 500; font-size: 14px;">
Förnya bankkopplingen
</a>
</div>
<p style="margin: 0 0 32px 0; font-size: 13px; color: #9ca3af;">
Knappen leder till ${renewalUrl}.<br>
Du kan också logga in som vanligt och gå till Inställningar och sedan Bank.
</p>
<div style="padding-top: 20px; border-top: 1px solid #ececea;">
<p style="margin: 0 0 12px 0; font-size: 14px; color: #374151;">
Med vänliga hälsningar,<br>
<strong>${appName}</strong>
</p>
<p style="margin: 0; font-size: 12.5px; color: #9ca3af;">
Du får det här mejlet eftersom det finns en bankkoppling i ${appName}${companyName ? ` för ${companyName}` : ''}.
Undrar du något? Mejla <a href="mailto:${supportEmail}" style="color: #6b7280;">${supportEmail}</a>.
</p>
</div>
</div>
</div>
</body>
</html>
`
}
/**
* Generate plain text email for consent expiry notification
*/
export function generateConsentExpiryEmailText(data: ConsentExpiryEmailData): string {
const { bankName, daysUntilExpiry, renewalUrl, companyName, isExpired } = data
const { appName, supportEmail } = getBranding()
let text = ''
if (isExpired) {
text += `Bankkopplingen behöver förnyas\n\n`
text += `Banksamtycket för ${bankName} har löpt ut och den automatiska hämtningen av nya transaktioner är pausad.\n\n`
} else {
text += `Bankkopplingen löper ut om ${dagar(daysUntilExpiry)}\n\n`
text += `Banksamtycket för ${bankName} löper ut om ${dagar(daysUntilExpiry)}.\n\n`
}
text += `Det här är väntat: av säkerhetsskäl gäller ett banksamtycke (PSD2) bara en begränsad tid, och därefter behöver det godkännas på nytt hos banken.\n\n`
if (isExpired) {
text += `Ingenting har försvunnit. Redan hämtade transaktioner och din bokföring påverkas inte, och när kopplingen är förnyad hämtas mellanliggande transaktioner ikapp.\n\n`
} else {
text += `Förnya gärna i förväg så fortsätter transaktionerna att hämtas utan avbrott. Din bokföring påverkas inte.\n\n`
}
text += `Bank: ${bankName}\n`
if (companyName) text += `Företag: ${companyName}\n`
text += `\nFörnya bankkopplingen: ${renewalUrl}\n`
text += `Du kan också logga in som vanligt och gå till Inställningar och sedan Bank.\n\n`
text += `Med vänliga hälsningar,\n`
text += `${appName}\n\n`
text += `Du får det här mejlet eftersom det finns en bankkoppling i ${appName}${companyName ? ` för ${companyName}` : ''}. Undrar du något? Mejla ${supportEmail}.\n`
return text
}
/**
* Generate email subject for consent expiry notification
*/
export function generateConsentExpiryEmailSubject(data: ConsentExpiryEmailData): string {
const suffix = data.companyName ? ` - ${data.companyName}` : ''
if (data.isExpired) {
return `Förnya bankkopplingen till ${data.bankName}${suffix}`
}
return `Bankkopplingen till ${data.bankName} löper ut om ${dagar(data.daysUntilExpiry)}${suffix}`
}
-83
View File
@@ -1,83 +0,0 @@
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
}
-161
View File
@@ -1,161 +0,0 @@
import { getBranding } from '@/lib/branding/service'
export interface InviteEmailData {
companyName: string
inviterEmail: string
inviteUrl: string
/**
* Brand override (WL-13): the app name of the brand of the company the
* invite concerns. Absent = platform default from getBranding(), which
* keeps unbranded companies byte-identical to before.
*/
appName?: string
}
export function generateInviteEmailSubject(data: InviteEmailData): string {
const appName = data.appName ?? getBranding().appName
return `Du har bjudits in till ${data.companyName} på ${appName.toLowerCase()}`
}
export function generateInviteEmailHtml(data: InviteEmailData): string {
const { companyName, inviterEmail, inviteUrl } = data
const appName = data.appName ?? getBranding().appName
return `
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inbjudan till ${companyName}</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f5f5f5;">
<div style="max-width: 520px; margin: 0 auto; padding: 40px 20px;">
<div style="background: #ffffff; border-radius: 12px; padding: 40px 32px; border: 1px solid #e5e5e5;">
<!-- Header -->
<div style="margin-bottom: 28px;">
<p style="margin: 0 0 4px 0; font-size: 13px; color: #888; letter-spacing: 0.05em;">${appName.toUpperCase()}</p>
<h1 style="margin: 0 0 8px 0; font-size: 22px; font-weight: 600; color: #111;">
Du har blivit inbjuden
</h1>
<p style="margin: 0; color: #666; font-size: 15px;">
<strong>${inviterEmail}</strong> har bjudit in dig till <strong>${companyName}</strong> på ${appName.toLowerCase()}.
</p>
</div>
<!-- CTA -->
<div style="margin: 28px 0;">
<a href="${inviteUrl}" style="display: inline-block; background: #111; color: #fff; text-decoration: none; padding: 12px 28px; border-radius: 8px; font-size: 14px; font-weight: 500;">
Acceptera inbjudan
</a>
</div>
<!-- Info -->
<p style="margin: 0; color: #999; font-size: 13px;">
Länken är giltig i 7 dagar. Om du inte förväntade dig denna inbjudan kan du ignorera detta meddelande.
</p>
</div>
</div>
</body>
</html>`
}
export function generateInviteEmailText(data: InviteEmailData): string {
const appName = data.appName ?? getBranding().appName
return `Du har bjudits in till ${data.companyName} på ${appName.toLowerCase()} av ${data.inviterEmail}.
Acceptera inbjudan: ${data.inviteUrl}
Länken är giltig i 7 dagar.`
}
// =============================================================================
// Team invite email templates
// =============================================================================
export interface TeamInviteEmailData {
inviterEmail: string
inviteUrl: string
/**
* Brand override (WL-13): the app name of the byrå team's brand. Absent =
* platform default from getBranding(), which keeps brandless teams
* byte-identical to before.
*/
appName?: string
}
export function generateTeamInviteEmailSubject(data?: Pick<TeamInviteEmailData, 'appName'>): string {
// Branded byrå: the invite is to THE BYRÅ, by name and in its own casing
// ("Du har blivit inbjuden till Willem"), no platform wording. Brandless
// teams keep the platform phrasing byte-identical.
if (data?.appName) {
return `Du har blivit inbjuden till ${data.appName}`
}
return `Du har bjudits in till ett team på ${getBranding().appName.toLowerCase()}`
}
export function generateTeamInviteEmailHtml(data: TeamInviteEmailData): string {
const { inviterEmail, inviteUrl } = data
const appName = data.appName ?? getBranding().appName
// Branded byrå: headline and body name the byrå itself; brandless teams
// keep the generic team wording.
const headline = data.appName
? `Du har blivit inbjuden till ${data.appName}`
: 'Du har blivit inbjuden till ett team'
const bodyLine = data.appName
? `<strong>${inviterEmail}</strong> har bjudit in dig till <strong>${data.appName}</strong>. Du får tillgång till alla företag i teamet.`
: `<strong>${inviterEmail}</strong> har bjudit in dig som konsult. Du får tillgång till alla företag i teamet.`
return `
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inbjudan till team</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f5f5f5;">
<div style="max-width: 520px; margin: 0 auto; padding: 40px 20px;">
<div style="background: #ffffff; border-radius: 12px; padding: 40px 32px; border: 1px solid #e5e5e5;">
<!-- Header -->
<div style="margin-bottom: 28px;">
<p style="margin: 0 0 4px 0; font-size: 13px; color: #888; letter-spacing: 0.05em;">${appName.toUpperCase()}</p>
<h1 style="margin: 0 0 8px 0; font-size: 22px; font-weight: 600; color: #111;">
${headline}
</h1>
<p style="margin: 0; color: #666; font-size: 15px;">
${bodyLine}
</p>
</div>
<!-- CTA -->
<div style="margin: 28px 0;">
<a href="${inviteUrl}" style="display: inline-block; background: #111; color: #fff; text-decoration: none; padding: 12px 28px; border-radius: 8px; font-size: 14px; font-weight: 500;">
Acceptera inbjudan
</a>
</div>
<!-- Info -->
<p style="margin: 0; color: #999; font-size: 13px;">
Länken är giltig i 7 dagar. Om du inte förväntade dig denna inbjudan kan du ignorera detta meddelande.
</p>
</div>
</div>
</body>
</html>`
}
export function generateTeamInviteEmailText(data: TeamInviteEmailData): string {
if (data.appName) {
return `Du har blivit inbjuden till ${data.appName} av ${data.inviterEmail}. Du får tillgång till alla företag i teamet.
Acceptera inbjudan: ${data.inviteUrl}
Länken är giltig i 7 dagar.`
}
return `Du har bjudits in som konsult till ett team på ${getBranding().appName.toLowerCase()} av ${data.inviterEmail}. Du får tillgång till alla företag i teamet.
Acceptera inbjudan: ${data.inviteUrl}
Länken är giltig i 7 dagar.`
}
-83
View File
@@ -1,83 +0,0 @@
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
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-73
View File
@@ -1,73 +0,0 @@
import { getEmailService } from '@/lib/email/service'
import { getSenderForBrand, getBaseUrlForBrand } from '@/lib/email/brand-sender'
import { resolveBrandForTeam } from '@/lib/branding/resolve'
import {
generateTeamInviteEmailSubject,
generateTeamInviteEmailHtml,
generateTeamInviteEmailText,
} from '@/lib/email/invite-templates'
import { createLogger } from '@/lib/logger'
const log = createLogger('team-invite-mail')
export interface TeamInviteMailResult {
/** The accept link, always produced so the inviter can share it directly. */
inviteUrl: string
/** False when the service is unconfigured or the provider send failed. */
emailSent: boolean
}
/**
* Send a byrå-team invitation mail in the team's brand (WL-13): sender
* identity via getSenderForBrand(resolveBrandForTeam(teamId)) and the accept
* link on the brand's home domain, canonical for brandless teams.
*
* Shared by invite creation and re-send so the two paths cannot drift. A send
* failure never throws: the invitation stays valid and the caller surfaces
* emailSent: false together with the link.
*/
export async function sendTeamInviteMail(params: {
teamId: string
email: string
inviterEmail: string
token: string
}): Promise<TeamInviteMailResult> {
const { teamId, email, inviterEmail, token } = params
const brand = await resolveBrandForTeam(teamId)
const sender = getSenderForBrand(brand)
const appUrl = getBaseUrlForBrand(brand)
const inviteUrl = `${appUrl}/invite/${token}`
let emailSent = false
const emailService = getEmailService()
if (emailService.isConfigured()) {
const emailData = {
inviterEmail,
inviteUrl,
appName: sender.brand?.appName,
}
const result = await emailService.sendEmail({
to: email,
subject: generateTeamInviteEmailSubject(emailData),
html: generateTeamInviteEmailHtml(emailData),
text: generateTeamInviteEmailText(emailData),
fromName: sender.fromName ?? undefined,
fromAddress: sender.fromAddress ?? undefined,
replyTo: sender.replyTo ?? undefined,
})
if (result.success) {
emailSent = true
log.info('team invite email sent', { to: email, teamId, messageId: result.messageId })
} else {
log.error('team invite email send failed', new Error(result.error ?? 'unknown'), {
to: email,
teamId,
})
}
} else {
log.warn('email service not configured: team invite email skipped', { to: email, teamId })
}
return { inviteUrl, emailSent }
}
-68
View File
@@ -1,68 +0,0 @@
/**
* Email Service Interface
*
* Core defines the contract. The email extension registers a real
* implementation (Resend). Without the extension, a no-op service
* is used: email-dependent features degrade gracefully.
*/
export interface SendEmailOptions {
to: string | string[]
cc?: string | string[]
bcc?: string | string[]
subject: string
html: string
text?: string
replyTo?: string
fromName?: string
/**
* Explicit From address. Only ever set by lib/email/brand-sender.ts for
* brands whose Resend sender domain is VERIFIED. When absent, the provider
* sends from its default address (RESEND_FROM_EMAIL) with fromName as the
* display name.
*/
fromAddress?: string
/**
* Explicit From identity (company's own verified sending domain). When
* set, the provider sends as "<name> <address>" instead of the platform
* sender; `fromName` is ignored. Callers obtain it from
* resolveInvoiceSender(): never build one from raw user input.
*/
from?: { name: string; address: string }
attachments?: Array<{
filename: string
content: Buffer | string
contentType?: string
}>
}
export interface SendEmailResult {
success: boolean
provider?: string
messageId?: string
error?: string
}
export interface EmailService {
sendEmail(options: SendEmailOptions): Promise<SendEmailResult>
isConfigured(): boolean
}
class NoopEmailService implements EmailService {
async sendEmail(): Promise<SendEmailResult> {
return { success: false, error: 'Email service not configured' }
}
isConfigured(): boolean {
return false
}
}
let emailService: EmailService = new NoopEmailService()
export function getEmailService(): EmailService {
return emailService
}
export function registerEmailService(svc: EmailService): void {
emailService = svc
}
-78
View File
@@ -1,78 +0,0 @@
/**
* Standard Webhooks signature verification (https://www.standardwebhooks.com/),
* implemented with node:crypto only: the Supabase Send Email hook signs its
* requests in this format and the endpoint must stay dependency-free.
*
* Scheme: the secret is base64 material, presented as "v1,whsec_<base64>"
* (Supabase dashboard) or "whsec_<base64>". The signed content is
* "<msg-id>.<timestamp>.<raw-body>", HMAC-SHA256 over the decoded secret,
* base64-encoded. The webhook-signature header carries a space-separated
* list of "<version>,<signature>" entries; only symmetric v1 entries are
* considered.
*/
import { createHmac, timingSafeEqual } from 'node:crypto'
const DEFAULT_TOLERANCE_SECONDS = 300
export interface StandardWebhookVerificationInput {
/** Raw secret ("v1,whsec_...", "whsec_..." or bare base64). */
secret: string
/** Raw request body, byte-identical to what was signed. */
payload: string
/** webhook-id header. */
id: string | null
/** webhook-timestamp header (unix seconds). */
timestamp: string | null
/** webhook-signature header. */
signature: string | null
/** Replay window in seconds; default 300. */
toleranceSeconds?: number
/** Test hook: current time in ms. */
nowMs?: number
}
function decodeSecret(secret: string): Buffer {
let s = secret.trim()
if (s.startsWith('v1,')) s = s.slice(3)
if (s.startsWith('whsec_')) s = s.slice(6)
return Buffer.from(s, 'base64')
}
/**
* True only when the signature verifies and the timestamp is within the
* replay tolerance. Never throws: any malformed input is a failed
* verification.
*/
export function verifyStandardWebhookSignature(
input: StandardWebhookVerificationInput,
): boolean {
const { secret, payload, id, timestamp, signature } = input
if (!secret || !id || !timestamp || !signature) return false
const ts = Number(timestamp)
if (!Number.isFinite(ts)) return false
const nowSeconds = (input.nowMs ?? Date.now()) / 1000
const tolerance = input.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS
if (Math.abs(nowSeconds - ts) > tolerance) return false
const key = decodeSecret(secret)
if (key.length === 0) return false
const expected = createHmac('sha256', key)
.update(`${id}.${timestamp}.${payload}`)
.digest()
for (const part of signature.split(/\s+/)) {
const commaIndex = part.indexOf(',')
if (commaIndex === -1) continue
const version = part.slice(0, commaIndex)
const candidateBase64 = part.slice(commaIndex + 1)
if (version !== 'v1' || !candidateBase64) continue
const candidate = Buffer.from(candidateBase64, 'base64')
if (candidate.length === expected.length && timingSafeEqual(candidate, expected)) {
return true
}
}
return false
}
-41
View File
@@ -1,41 +0,0 @@
/**
* Utilities for safely rendering user-authored text in outgoing emails.
*
* Company-editable email texts (see company_settings.invoice_email_texts)
* are untrusted input: they must be escaped before interpolation into HTML
* templates and kept single-line when used as mail headers.
*/
export function escapeHtml(input: string): string {
return input
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
}
// Escape FIRST, then convert newlines, order matters: a '<br>' typed by the
// user must arrive escaped; only OUR <br> survives.
export function userTextToHtml(input: string): string {
return escapeHtml(input).replace(/\r\n|\r|\n/g, '<br>')
}
// Mail-header hygiene: a subject must be a single line (header injection).
export function sanitizeSubjectLine(input: string): string {
return input.replace(/[\r\n]+/g, ' ').trim()
}
// Fixed-set {x} substitution. Single pass: substituted VALUES are never
// re-scanned, so a customer named '{belopp}' stays literal. Unknown keys are
// left as-is so the user sees and fixes typos. Keys are matched after
// trim + toLowerCase (forgiving of '{ Förnamn }').
export function applyPlaceholders(
template: string,
values: Record<string, string>,
): string {
return template.replace(/\{([^{}]*)\}/g, (match, rawKey: string) => {
const value = values[rawKey.trim().toLowerCase()]
return value !== undefined ? value : match
})
}