Files
accounted/lib/email/user-text.ts
T
admin e7f0070e84
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s
fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
2026-11-10 09:37:22 +01:00

42 lines
1.5 KiB
TypeScript

/**
* 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, '&')
.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
})
}