Files
wekan/tests/emailLocalizationPreparation.test.cjs
T
Lauri Ojansivu 058677e078 E-mails in the clear HTML layout by default: notifications and account mail.
Notification e-mail now defaults to the clearly arranged layout of #5171 -
board first, board, actor and card in bold and linked, with a plain-text
alternative. One sentence (classic) is still one choice away at the
Admin Panel, board and member levels, and the tray keeps the classic line.

Account e-mails - reset password, verify e-mail, enroll account, and the
board and registration invitations - get an HTML part in the same style,
built from the same translated text, which is still sent as the text
part: no translation changes. Every piece of text is escaped first, the
link paragraph becomes a button, and only an http(s) address is linked. A
caller's own HTML and texts that are not WeKan's e-mail strings are left
as they were, and a failure to build the HTML leaves the text alone.

models/lib/accountEmailHtml.js renders it; tests/accountEmailHtml.test.cjs
lays out the real English texts and checks that markup in a name, a board
title or the site name stays text and only http(s) is linked.
notificationDelivery's default assertions now expect clear for e-mail,
and emailLocalizationPreparation's harness allows the new module, checks
the HTML part, and checks the absent-HTML case with literal text.

Thanks to Meeques and xet7 !

Fixes #4434.
2026-10-14 14:33:10 +03:00

100 lines
6.3 KiB
JavaScript

'use strict';
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(require.resolve('../server/lib/emailLocalization.js'), 'utf8')
.replace(/^import .*;\n/gm, '').replace('export default EmailLocalization;', 'globalThis.localization = EmailLocalization;');
function fixture() {
const events = [], sent = [];
const context = { structuredClone, require: name => {
// #4434: a WeKan e-mail string without HTML of its own gets the clear layout.
if (name === '/models/lib/accountEmailHtml') return require('../models/lib/accountEmailHtml');
assert.equal(name, './ruleEmailAttachments'); return require('../server/lib/ruleEmailAttachments'); }, Accounts: { emailTemplates: { from: 'default@example.org' } },
ReactiveCache: { getUser: async id => { events.push(`user:${id}`); return { getLanguage: () => 'fi' }; } },
TAPi18n: { getLanguage: () => 'en', ensureLanguageLoaded: async lang => { events.push(`load:${lang}`); },
__: (key, params, lang) => { events.push(`translate:${key}`); return `${lang}:${key}:${params.name || ''}`; } },
Email: { sendAsync: async mail => { sent.push(mail); return 'transport-result'; } } };
vm.createContext(context); vm.runInContext(source, context);
return { ...context, events, sent };
}
const options = { to: 'person@example.org', subject: 'email-subject', text: 'email-body', params: { name: 'Person' },
userId: 'recipient', replyTo: 'reply@example.org', html: '<p>Body</p>' };
test('preparation resolves language and freezes translated transport content without sending', async () => {
const f = fixture(), mail = await f.localization.prepareEmail(options);
assert.deepEqual(JSON.parse(JSON.stringify(mail)), { to: options.to, from: 'default@example.org',
subject: 'fi:email-subject:Person', text: 'fi:email-body:Person', html: options.html, replyTo: options.replyTo });
assert.deepEqual(f.events, ['user:recipient', 'load:fi', 'translate:email-subject', 'translate:email-body']);
assert.equal(f.sent.length, 0);
// The already prepared message is unaffected by later locale/template changes.
f.TAPi18n.__ = () => 'changed'; f.Accounts.emailTemplates.from = 'changed@example.org';
assert.equal(mail.subject, 'fi:email-subject:Person');
assert.equal(mail.from, 'default@example.org');
});
test('explicit locale and sender win; literal body and optional reply header retain semantics', async () => {
const f = fixture();
const mail = await f.localization.prepareEmail({ ...options, language: 'sv', from: 'sender@example.org', text: 'Literal body', replyTo: undefined });
assert.equal(mail.text, 'Literal body'); assert.equal(mail.from, 'sender@example.org');
assert.equal(Object.hasOwn(mail, 'replyTo'), false);
assert.deepEqual(f.events, ['load:sv', 'translate:email-subject']);
});
test('missing recipient falls back to site language', async () => {
const f = fixture(); f.ReactiveCache.getUser = async () => null;
const mail = await f.localization.prepareEmail(options);
assert.equal(mail.subject, 'en:email-subject:Person');
});
test('sendEmail uses the same prepared content and awaits the transport receipt', async () => {
const f = fixture(), expected = await f.localization.prepareEmail(options);
let release, entered, done = false;
const started = new Promise(resolve => { entered = resolve; });
f.Email.sendAsync = async mail => { assert.deepEqual(mail, expected); entered(); return new Promise(resolve => { release = resolve; }); };
const execution = f.localization.sendEmail(options).then(result => { done = true; return result; });
await started;
assert.equal(done, false); release('receipt');
assert.equal(await execution, 'receipt');
});
test('locale loading failure prevents translation and any send', async () => {
const f = fixture(), error = new Error('language load failed');
f.TAPi18n.ensureLanguageLoaded = async () => { throw error; };
await assert.rejects(f.localization.sendEmail(options), value => value === error);
assert.equal(f.events.some(event => event.startsWith('translate:')), false);
assert.equal(f.sent.length, 0);
});
test('transport failure remains visible to the rule caller', async () => {
const f = fixture(), error = new Error('send failed');
f.Email.sendAsync = async () => { throw error; };
await assert.rejects(f.localization.sendEmail(options), value => value === error);
});
test('plain text preparation omits absent HTML before BSON serialization', async () => {
const f = fixture();
// #4434: a WeKan `email-` string now gets a real HTML part (tested below),
// so absence is checked with literal text, which has none - the point is
// still that no `html: undefined` key reaches BSON.
const mail = await f.localization.prepareEmail({ ...options, html: undefined, text: 'Literal body' });
assert.equal(Object.hasOwn(mail, 'html'), false);
const { EJSON } = require('bson');
assert.equal(Object.hasOwn(EJSON.parse(EJSON.stringify(mail)), 'html'), false);
});
test('attachment snapshots survive preparation and reach the transport unchanged', async () => {
const f = fixture();
const attachments = [{ filename: 'file.bin', contentType: 'application/octet-stream', encoding: 'base64', content: 'AP8=' }];
const mail = await f.localization.prepareEmail({ ...options, attachments });
attachments[0].content = 'YQ==';
assert.equal(mail.attachments[0].content, 'AP8=');
await f.localization.sendEmail({ ...options, attachments });
assert.deepEqual(f.sent[0].attachments, attachments);
await assert.rejects(f.localization.sendEmail({ ...options, attachments: [{ path: '/private/file' }] }), /invalid/);
assert.equal(f.sent.length, 1);
});
test('#4434: a WeKan e-mail string without HTML of its own also gets the clear HTML layout', async () => {
const f = fixture();
const mail = await f.localization.prepareEmail({ ...options, html: undefined });
assert.equal(mail.text, 'fi:email-body:Person', 'the text part is unchanged');
assert.match(mail.html, /^<div style="font-family:[\s\S]*<p style="margin:0 0 16px 0">fi:email-body:Person<\/p>/);
const literal = await f.localization.prepareEmail({ ...options, html: undefined, text: 'Literal body' });
assert.equal(Object.hasOwn(literal, 'html'), false, 'text that is not a WeKan e-mail string gets no HTML');
});