Files
wibosim/server/src/mailer.test.js
T
db9979andClaude Opus 5.5 ca7ecd6b89 Mein Tag: Aufgabenübersicht mit Zählern, Ausblenden und Morgenmail-Block
- Neue Ansicht „Mein Tag“ (erster Menüpunkt, auch in der Handy-Leiste) mit
  Gruppen Sofort handeln / Heute fällig / Abholen / Im Blick behalten /
  Erste Schritte, Fristen, Countdown und Sprungknöpfen
- Server-Registry todo.js mit Providern (g, p) → items, Push nur bei
  Änderung (Hash je Spieler), REST-Fallback, Ausblenden je Spieler und Tag
- Zähler „N zu tun“ neben der Glocke, Badges an Menü, Mehr-Knopf und
  Mehr-Menü; ersetzt die alten Battle-/Clan-Punkte
- Leiste „Nächster Schritt“ entfernt, Einführung angepasst
- Morgenmail: Block „Heute für dich zu tun“ (max. 8 Einträge)
- Tests für Registry und Mail-Block, Doku in docs/API.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
2026-12-04 08:46:31 +00:00

135 lines
8.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import net from 'node:net';
import os from 'node:os';
import fs from 'node:fs';
import path from 'node:path';
process.env.NODE_ENV = 'test';
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-mail-'));
const { settings } = await import('./settings.js');
const { tlsOptions, fromAddress, explainMailError, testMail } = await import('./mailer.js');
/** Winziger SMTP-Server ohne Verschlüsselung (AUTH PLAIN/LOGIN, Passwort „richtig“) */
function fakeSmtp() {
const mails = [];
const srv = net.createServer((c) => {
let buf = '', data = false, body = '', authLogin = 0, user = '';
const say = (s) => c.write(`${s}\r\n`);
say('220 fake ESMTP');
c.on('data', (d) => {
buf += d;
let i;
while ((i = buf.indexOf('\r\n')) >= 0) {
const line = buf.slice(0, i); buf = buf.slice(i + 2);
if (data) { if (line === '.') { data = false; mails.push(body); say('250 ok'); } else body += `${line}\n`; continue; }
if (authLogin === 1) { user = Buffer.from(line, 'base64').toString(); authLogin = 2; say('334 UGFzc3dvcmQ6'); continue; }
if (authLogin === 2) { authLogin = 0; say(Buffer.from(line, 'base64').toString() === 'richtig' ? '235 ok' : '535 5.7.8 Authentication failed'); continue; }
const cmd = line.slice(0, 4).toUpperCase();
if (cmd === 'EHLO') { c.write('250-fake\r\n250 AUTH PLAIN LOGIN\r\n'); }
else if (cmd === 'AUTH') {
const [, mech, arg] = line.split(' ');
if (mech === 'PLAIN') { const parts = Buffer.from(arg, 'base64').toString().split('\0'); user = parts[1]; say(parts[2] === 'richtig' ? '235 ok' : '535 5.7.8 Authentication failed'); }
else { authLogin = 1; say('334 VXNlcm5hbWU6'); }
}
else if (cmd === 'MAIL') say(/@fremd\.de/.test(line) ? '553 5.7.1 Sender address not owned by user' : '250 ok');
else if (cmd === 'RCPT') say('250 ok');
else if (cmd === 'DATA') { data = true; body = ''; say('354 go'); }
else if (cmd === 'QUIT') { say('221 bye'); c.end(); }
else if (cmd === 'RSET' || cmd === 'NOOP') say('250 ok');
else say('502 nope');
}
});
});
return new Promise((r) => srv.listen(0, '127.0.0.1', () => r({ srv, port: srv.address().port, mails })));
}
test('E-Mail: Verschlüsselung, Absender und verständliche Fehler', () => {
assert.deepEqual(tlsOptions({ tls: 'starttls', port: 587 }), { secure: false, requireTLS: true });
assert.deepEqual(tlsOptions({ tls: 'auto', port: 465 }), { secure: true });
assert.deepEqual(tlsOptions({ tls: 'ssl', port: 465 }), { secure: true });
assert.deepEqual(tlsOptions({ tls: 'none', port: 25 }), { secure: false, ignoreTLS: true });
assert.equal(fromAddress({ from: '', user: 'ich@icloud.com' }), 'WiBoSim <ich@icloud.com>');
assert.equal(fromAddress({ from: 'WiBoSim <noreply@wibosim.local>', user: 'ich@icloud.com' }), 'WiBoSim <ich@icloud.com>');
assert.equal(fromAddress({ from: 'Spiel <spiel@icloud.com>', user: 'ich@icloud.com' }), 'Spiel <spiel@icloud.com>');
assert.match(explainMailError({ code: 'EAUTH', responseCode: 535 }).hint, /app-spezifisches Passwort/);
assert.match(explainMailError({ code: 'ESOCKET', message: 'routines:ssl3_get_record:wrong version number' }).hint, /Port 587 = STARTTLS/);
assert.match(explainMailError({ code: 'ETIMEDOUT' }).hint, /nicht erreichbar/);
assert.match(explainMailError({ code: 'EENVELOPE', responseCode: 553, response: '553 Sender address not owned' }).hint, /Absender/);
});
test('E-Mail: Testmail prüft Anmeldung und Versand gegen einen SMTP-Server', async () => {
const { srv, port, mails } = await fakeSmtp();
try {
Object.assign(settings.smtp, { host: '127.0.0.1', port, tls: 'none', user: 'ich@icloud.com', pass: 'falsch', from: '' });
const bad = await testMail('du@example.com');
assert.equal(bad.ok, undefined);
assert.match(bad.hint, /Anmeldung abgelehnt/);
assert.ok(!bad.detail.includes('falsch'), 'Passwort taucht nicht in der Meldung auf');
settings.smtp.pass = 'richtig';
const good = await testMail('du@example.com');
assert.equal(good.ok, true, JSON.stringify(good));
assert.equal(good.from, 'WiBoSim <ich@icloud.com>');
assert.ok(mails.some((m) => /Testmail/.test(m) && /From: WiBoSim <ich@icloud\.com>/.test(m) && /text\/html/.test(m)), 'HTML-Mail mit Textfassung');
settings.smtp.from = 'X <x@fremd.de>';
const rej = await testMail('du@example.com');
assert.match(rej.error, /Versand wurde abgelehnt/);
assert.match(rej.hint, /Absender/);
settings.smtp.port = 1; // niemand hört zu
const off = await testMail('du@example.com');
assert.match(off.hint, /nicht erreichbar/);
} finally {
srv.close();
Object.assign(settings.smtp, { host: '', pass: '', user: '', from: '' });
}
});
test('E-Mail: Börsenbrief-Vorlage – HTML sicher, Textfassung vollständig, Berichte gestaltet', async () => {
const { renderMail } = await import('./mailtpl.js');
const r = renderMail({ subject: 'Test', kicker: 'Tagesbericht', title: 'Kurs <b>steigt</b>', baseUrl: 'javascript:alert(1)',
ticker: [{ symbol: 'WIBO-10', last: 10123.4, change: -0.5 }],
blocks: [{ type: 'kpis', items: [{ label: 'Depot', value: '1.000 €', dir: 1 }] }, { type: 'list', title: 'Termine', items: [{ text: '<script>x</script>', meta: '08:00' }] },
{ type: 'table', title: 'Positionen', rows: [['NVLT', { html: '<b>ok</b>', text: 'ok' }]] }, { type: 'note', tone: 'bad', text: 'Achtung' }],
cta: { label: 'Öffnen', url: 'http://example.com/' } });
assert.ok(!r.html.includes('<script>x') && r.html.includes('&lt;script&gt;'), 'Inhalte werden maskiert');
assert.ok(!r.html.includes('javascript:'), 'nur http(s)-Links');
assert.match(r.html, /WIBO-10/);
assert.match(r.html, /−0,50 %/);
for (const s of ['TAGESBERICHT', 'Kurs <b>steigt</b>', 'Depot: 1.000 €', '<script>x</script> (08:00)', 'NVLT ok', 'Achtung', 'Öffnen: http://example.com/']) assert.ok(r.text.includes(s), `Text enthält ${s}`);
const { Store } = await import('./store.js');
const { Game } = await import('./game.js');
const { morningMail, dailyMail } = await import('./reports.js');
const clock = { t: Date.now() };
const g = new Game({ store: new Store(fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-mailg-'))), now: () => clock.t });
for (let i = 0; i < 3; i++) { clock.t += 1000; g.tick(); }
const p = (await g.register({ name: 'Anna', password: 'geheim123' })).player;
p.positions.NVLT = { qty: 10, avgCost: 100 };
// „Heute für dich zu tun“: dieselben Einträge wie „Mein Tag“ (offene Abstimmung mit Frist)
g.pol.pipeline = [];
g.pol.newBill();
const e = g.pol.pipeline[0];
e.stage = 'abstimmung'; e.votes = {};
e.endsAt = e.stageEndsAt = g.clock.now() + 3_600_000; e.secretFrom = e.endsAt - 60_000;
const mm = renderMail({ subject: 'x', ...morningMail(g, p) });
assert.match(mm.text, /Guten Morgen Anna/);
assert.match(mm.text, /NVLT/);
assert.match(mm.text, /HEUTE FÜR DICH ZU TUN/);
assert.ok(mm.text.includes(`Abstimmung im Parlament: ${e.bill.title} (Heute fällig · bis `), 'Eintrag mit Gruppe und Frist');
assert.match(mm.html, /Heute für dich zu tun/);
const { registerTodo } = await import('./todo.js');
const { todoBlock } = await import('./reports.js');
registerTodo('mailtest', () => Array.from({ length: 12 }, (_, i) => ({ id: `m${i}`, group: 'watch', icon: '•', title: `Eintrag ${i}`, target: { view: 'markt' } })));
try {
const blk = todoBlock(g, p);
assert.equal(blk.type, 'list');
assert.equal(blk.items.length, 8, 'höchstens 8 Einträge');
assert.ok(blk.items[0].text.startsWith('Abstimmung im Parlament'), 'Dringlicheres zuerst');
assert.ok(blk.items.every((x) => x.dot && x.meta), 'Farbpunkt und Gruppe/Frist je Eintrag');
} finally { registerTodo('mailtest', () => []); }
g.pol.vote(p, e.id, true);
assert.ok(!renderMail({ subject: 'x', ...morningMail(g, p) }).text.includes('Abstimmung im Parlament'), 'erledigt → nicht mehr in der Mail');
const dm = renderMail({ subject: 'x', ...dailyMail(g, p) });
assert.match(dm.text, /WIBO-10 schließt/);
assert.match(dm.html, /Deine Positionen/);
});