mirror of
https://github.com/bitbaum/evig.git
synced 2026-12-03 20:27:02 +01:00
fix(email): the relay says 250 and the mail goes nowhere (#311)
* fix(vote): give the "sign in to vote" error the door it names The vote-auth fix (#305) tells someone whose email belongs to an account to sign in, and then leaves them standing there. This repo's own rule is that every stated problem links to where it is fixed — a warning without a way out is a dead end. The reason it shipped without the link was that apiFetch flattens every failure to a bare { success, error } string. The only way for the UI to know WHICH failure it got was to match the German sentence, and branching on prose breaks the first time someone rewords or translates it. So the fix is one level down: give the envelope a machine-readable code. ERROR_CODES one SSOT for codes, next to ERROR_MESSAGES. Add one only when the interface must DO something different — the message is for the human, the code is for the UI. apiBadRequest optional third argument, omitted from the body when unset ApiResponse.code optional, so all ~100 existing callers are untouched apiFetch passes a string code through; ignores a non-string one rather than handing junk to the UI The vote page now renders "Anmelden" as a link to loginUrl beside that error, reusing the string already there for the success panel — no new i18n keys, so no locale can desync. Tests assert the passthrough and the omission, and I checked the passthrough test fails with the apiFetch change reverted (1 of 14) rather than assuming a green suite meant something. The route test now pins the code, using a mock that actually forwards the third argument — a mock that dropped it would have made the assertion vacuous. 5963 tests green across 440 suites; eslint and the umlaut linter clean. * fix(vote): the one live decision could not be voted on at all Found by opening the real share link at 390px while verifying #307, not by any test. The page drew "Deine Stimme" and then nothing. Submitting answered "Stimmdaten erforderlich". There was no ballot, and nothing on screen said why. `thumbs_up_down` has been in VOTING_METHODS all along, with a zod schema, a validator and a tally on the server — and no branch in either voting surface, and no case in useVoteState's switch. buildVoteData() fell through to `undefined`, which TypeScript allows because the switch had no default and the return type is `unknown`. So the absence compiled, rendered blank, and failed at the server. Production's only decision uses that method. Fixed on both surfaces — the public share-link page and the members' VotingPanel — with one component, and the choice labels in config beside the other methods' rather than typed into JSX. No default selection: a thumbs vote is a single deliberate tap, so pre-selecting "Dafür" would submit an opinion the voter never expressed. Two guards, because the compile-time one alone would not have caught this: useVoteState a `never` exhaustiveness default — a method with no case is now a build error rather than a silent undefined ballot-coverage.test.tsx renders EVERY entry in VOTING_METHODS and asserts the ballot contains something interactive. A missing render branch is absence, and absence is what the switch guard cannot see. It iterates the config, so it cannot drift from it. Checked the coverage test fails with the branch removed (thumbs_up_down only, 6 of 7 still passing) rather than trusting a green suite. 7747 tests green across 529 suites; eslint and the umlaut linter clean. * fix(email): the relay says 250 and the mail goes nowhere Sent a probe from the production host through the configured relay to a real mailbox. The SMTP conversation was flawless — EHLO, STARTTLS, AUTH, accepted — and the message never arrived. Not the inbox, not spam, not trash. The cause is the sender domain. EMAIL_FROM in prod is noreply@revampit.ch, which has no SPF record and no brevo._domainkey DKIM record. Brevo accepts mail from a domain it has not authenticated and then drops it, so every layer reports success and the inbox stays empty. Searching the recipient mailbox back through its whole history finds no application mail at all: every revamp-it.ch message in it is human mail from colleagues via the org's own server. evig's transactional email has never worked. scripts/test-email.ts could not have caught this. It mailed only itself, and it called a relay handoff "Email sent successfully!". So it is rebuilt to answer the question that matters: - takes the recipient as an argument instead of sending to EMAIL_FROM - resolves the sender domain's SPF, DKIM and DMARC before sending, and says plainly that an unauthenticated domain will vanish despite a 250 - refuses to describe acceptance as delivery The DKIM verdict is deliberately relay-aware. Selectors are chosen by the provider and cannot be enumerated from DNS, so a missing selector is only conclusive when we know which one to expect — Brevo documents brevo._domainkey. Against any other relay an unknown selector is reported as inconclusive, not as a failure. Checked both ways: google.com is flagged when sending through Brevo (true — it has no Brevo key) and is not flagged otherwise. Nothing here fixes delivery. That needs a sending domain that exists and is authenticated with the provider, which is a purchase and a DNS change, not a code change. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs: the canonical host moved, and the redirect to it must keep the method revampit.orangecat.ch now redirects to evig.orangecat.ch, so every doc that called the old host "where this codebase runs" was pointing at a redirect. It was added as `redir ... permanent`, which is 301, and 301 does not preserve the HTTP method — a POST arrives as a bodyless GET. Auth.js then answered InvalidProvider ("Callback for provider type (credentials) is not supported"), because a GET on a credentials callback is not a thing. Browser traffic never noticed: it lands on the canonical host and posts there. Only non-browser POST clients broke — the CI auth smoke, API callers, and any webhook still aimed at the old host. Fixed on the box by making it a 308; documented here so it is not reintroduced. Also records why auth-smoke and inventory-smoke deliberately point PLAYWRIGHT_BASE_URL at the OLD host: that is what exercises the redirect, and it is how this was caught. Repointing them at the canonical host would turn a real gate into a green one. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c27a404ae2
commit
de244172ff
3 files changed
+143
-36
No files matched your search
@@ -87,7 +87,11 @@ hold the line on all of it by default:
|
||||
|
||||
## Production URL — don't get this wrong
|
||||
|
||||
**This codebase runs at https://revampit.orangecat.ch** (self-hosted Hetzner, deployed from `main` by `deploy-selfhost.yml`). Health check: `https://revampit.orangecat.ch/api/health`. Staff time entry (Zeiterfassung): `/admin/zeiterfassung`.
|
||||
**This codebase runs at https://evig.orangecat.ch** (self-hosted Hetzner, deployed from `main` by `deploy-selfhost.yml`). Health check: `https://evig.orangecat.ch/api/health`. Staff time entry (Zeiterfassung): `/admin/zeiterfassung`.
|
||||
|
||||
**`revampit.orangecat.ch` still resolves and redirects here** (Caddy, `/etc/caddy/Caddyfile`). That redirect **must stay a 308, never a 301/`permanent`**: 301 does not preserve the HTTP method, so every POST to the old host arrives as a bodyless GET. On 2026-08-16 it was set to `permanent` and `/api/auth/callback/credentials` began answering `InvalidProvider: Callback for provider type (credentials) is not supported` — Auth.js rejecting a GET on a credentials callback. Browser traffic looked fine (it lands on the canonical host and posts there), so only non-browser POST clients broke: the CI auth smoke, API callers, and any webhook still aimed at the old host.
|
||||
|
||||
The `auth-smoke` / `inventory-smoke` CI jobs deliberately point `PLAYWRIGHT_BASE_URL` at the **old** host, so they exercise that redirect. Do not "fix" a redirect failure by repointing them at the canonical host — that deletes the only coverage of it.
|
||||
|
||||
**https://www.revamp-it.ch is the org's LEGACY Joomla site — not this app.** Never verify deploys or smoke-test there. Full URL list: `docs/SHARED_CONTEXT.md` → Access Points.
|
||||
|
||||
|
||||
@@ -55,10 +55,11 @@ last_modified_summary: Access Points — production URLs (revampit.orangecat.ch)
|
||||
|
||||
### Production (this codebase)
|
||||
|
||||
- **App**: https://revampit.orangecat.ch — self-hosted on the Hetzner box, deployed from `main` via `deploy-selfhost.yml` (systemd `revampit-app`)
|
||||
- **Health**: https://revampit.orangecat.ch/api/health (DB + Meilisearch status)
|
||||
- **Admin**: https://revampit.orangecat.ch/admin
|
||||
- **Zeiterfassung (staff time entry)**: https://revampit.orangecat.ch/admin/zeiterfassung (same shared `TimecardsClient` also at `/dashboard/timecards`)
|
||||
- **App**: https://evig.orangecat.ch — self-hosted on the Hetzner box, deployed from `main` via `deploy-selfhost.yml` (systemd `revampit-app`)
|
||||
- **Health**: https://evig.orangecat.ch/api/health (DB + Meilisearch status)
|
||||
- **Admin**: https://evig.orangecat.ch/admin
|
||||
- **Zeiterfassung (staff time entry)**: https://evig.orangecat.ch/admin/zeiterfassung (same shared `TimecardsClient` also at `/dashboard/timecards`)
|
||||
- **Old host**: https://revampit.orangecat.ch redirects here via Caddy. The redirect must stay **308**, not 301/`permanent` — 301 drops the method, so POSTs arrive as GETs and credentials login breaks. See the Production URL section of `CLAUDE.md`.
|
||||
|
||||
⚠️ **https://www.revamp-it.ch is NOT this codebase** — that is the organization's legacy Joomla site. Never smoke-test or verify deploys there.
|
||||
|
||||
|
||||
+133
-31
@@ -1,11 +1,23 @@
|
||||
/**
|
||||
* Test Email Script
|
||||
* Email deliverability probe
|
||||
*
|
||||
* Run with: npx tsx scripts/test-email.ts
|
||||
* Run with: npx tsx scripts/test-email.ts <recipient@example.com>
|
||||
*
|
||||
* WHY THIS CHECKS DNS: a relay answering `250 accepted` proves the credentials
|
||||
* work, not that anyone receives the mail. Brevo accepts messages from a sender
|
||||
* domain it has not authenticated and then drops them, so the SMTP conversation
|
||||
* succeeds while the inbox stays empty forever. That is precisely how evig's
|
||||
* production mail was silently dead: EMAIL_FROM was noreply@revampit.ch, a
|
||||
* domain with no SPF record and no Brevo DKIM key, and not one application
|
||||
* email had ever arrived.
|
||||
*
|
||||
* So this script reports the sender domain's authentication BEFORE sending, and
|
||||
* refuses to call a relay handoff "delivered".
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as dns from 'dns/promises';
|
||||
import * as nodemailer from 'nodemailer';
|
||||
|
||||
// Load .env.local manually
|
||||
@@ -33,15 +45,102 @@ const EMAIL_CONFIG = {
|
||||
SECURE: process.env.EMAIL_SECURE === 'true',
|
||||
};
|
||||
|
||||
/**
|
||||
* DKIM selectors are chosen by the mail provider and cannot be enumerated from
|
||||
* DNS, so absence here is only conclusive for a provider whose selector we
|
||||
* know. Brevo documents `brevo._domainkey`; the rest are common conventions
|
||||
* checked as a courtesy. A domain using some other selector is NOT broken —
|
||||
* saying otherwise would make this script cry wolf on healthy domains.
|
||||
*/
|
||||
const DKIM_SELECTORS = ['brevo', 'mail', 'default', 'k1'];
|
||||
|
||||
async function txtRecords(name: string): Promise<string[]> {
|
||||
try {
|
||||
const records = await dns.resolveTxt(name);
|
||||
return records.map((chunks) => chunks.join(''));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Report whether the sender domain authorises this relay. Returns false when
|
||||
* the domain is provably unauthenticated, so the caller can say so loudly
|
||||
* instead of reporting a cheerful 250.
|
||||
*/
|
||||
async function checkSenderDomain(from: string, relayHost: string): Promise<boolean> {
|
||||
const domain = from.split('@')[1];
|
||||
if (!domain) {
|
||||
console.log(' Sender has no domain — cannot authenticate');
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log(`Sender domain authentication for ${domain}:`);
|
||||
|
||||
const spf = (await txtRecords(domain)).filter((r) => r.toLowerCase().startsWith('v=spf1'));
|
||||
console.log(spf.length ? ` SPF : ${spf[0]}` : ' SPF : MISSING');
|
||||
|
||||
const dmarc = await txtRecords(`_dmarc.${domain}`);
|
||||
console.log(dmarc.length ? ` DMARC : ${dmarc[0]}` : ' DMARC : MISSING');
|
||||
|
||||
const foundSelectors: string[] = [];
|
||||
for (const selector of DKIM_SELECTORS) {
|
||||
const key = await txtRecords(`${selector}._domainkey.${domain}`);
|
||||
if (key.length) foundSelectors.push(selector);
|
||||
}
|
||||
console.log(
|
||||
foundSelectors.length
|
||||
? ` DKIM : ${foundSelectors.join(', ')}`
|
||||
: ` DKIM : none of the known selectors (${DKIM_SELECTORS.join(', ')})`
|
||||
);
|
||||
|
||||
// Only claim a domain is unauthenticated where the evidence is conclusive:
|
||||
// a missing SPF record always is, and a missing `brevo` selector is when
|
||||
// Brevo is the relay we are actually sending through.
|
||||
const usingBrevo = relayHost.toLowerCase().includes('brevo');
|
||||
const problems: string[] = [];
|
||||
if (spf.length === 0) problems.push('no SPF record');
|
||||
if (usingBrevo && !foundSelectors.includes('brevo')) {
|
||||
problems.push('no brevo._domainkey DKIM record, but Brevo is the relay');
|
||||
}
|
||||
|
||||
if (problems.length > 0) {
|
||||
console.log('');
|
||||
console.log(` ⚠ ${domain} does not authenticate mail through this relay: ${problems.join('; ')}.`);
|
||||
console.log(' The relay will still answer 250 and the message will vanish.');
|
||||
console.log(' Fix: authenticate the sending domain with the provider and');
|
||||
console.log(' publish the SPF + DKIM records it gives you, then re-run.');
|
||||
} else if (!foundSelectors.length) {
|
||||
console.log('');
|
||||
console.log(' Note: no DKIM found under the selectors above, but providers choose');
|
||||
console.log(' their own — this is inconclusive rather than a failure.');
|
||||
}
|
||||
console.log('');
|
||||
return problems.length === 0;
|
||||
}
|
||||
|
||||
async function testEmail() {
|
||||
console.log('Email Configuration:');
|
||||
console.log(' Host:', EMAIL_CONFIG.HOST);
|
||||
console.log(' Port:', EMAIL_CONFIG.PORT);
|
||||
console.log(' User:', EMAIL_CONFIG.USER);
|
||||
console.log(' From:', EMAIL_CONFIG.FROM);
|
||||
const recipient = process.argv[2];
|
||||
if (!recipient || !recipient.includes('@')) {
|
||||
console.error('Usage: npx tsx scripts/test-email.ts <recipient@example.com>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log('Email configuration:');
|
||||
console.log(' Host :', EMAIL_CONFIG.HOST);
|
||||
console.log(' Port :', EMAIL_CONFIG.PORT);
|
||||
console.log(' User :', EMAIL_CONFIG.USER);
|
||||
console.log(' From :', EMAIL_CONFIG.FROM);
|
||||
console.log(' Secure:', EMAIL_CONFIG.SECURE);
|
||||
console.log('');
|
||||
|
||||
if (!EMAIL_CONFIG.FROM || !EMAIL_CONFIG.USER || !EMAIL_CONFIG.PASS) {
|
||||
console.error('Incomplete SMTP configuration — set EMAIL_FROM, EMAIL_USER and EMAIL_PASS.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const authenticated = await checkSenderDomain(EMAIL_CONFIG.FROM, EMAIL_CONFIG.HOST);
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: EMAIL_CONFIG.HOST,
|
||||
port: EMAIL_CONFIG.PORT,
|
||||
@@ -52,45 +151,48 @@ async function testEmail() {
|
||||
},
|
||||
});
|
||||
|
||||
// Test connection
|
||||
console.log('Testing SMTP connection...');
|
||||
try {
|
||||
await transporter.verify();
|
||||
console.log('SMTP connection successful!');
|
||||
console.log(' Connection and credentials OK');
|
||||
} catch (error) {
|
||||
console.error('SMTP connection failed:', error);
|
||||
console.error(' SMTP connection failed:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Send test email
|
||||
const testRecipient = EMAIL_CONFIG.FROM; // Send to ourselves
|
||||
console.log(`\nSending test email to ${testRecipient}...`);
|
||||
const sentAt = new Date().toISOString();
|
||||
console.log(`\nSending to ${recipient}...`);
|
||||
|
||||
try {
|
||||
const info = await transporter.sendMail({
|
||||
from: `"RevampIT Test" <${EMAIL_CONFIG.FROM}>`,
|
||||
to: testRecipient,
|
||||
subject: 'RevampIT Email Test',
|
||||
text: 'This is a test email from RevampIT. If you received this, email sending is working correctly!',
|
||||
html: `
|
||||
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
||||
<h1 style="color: #22c55e;">RevampIT Email Test</h1>
|
||||
<p>This is a test email from RevampIT.</p>
|
||||
<p>If you received this, email sending is working correctly!</p>
|
||||
<hr style="border: none; border-top: 1px solid #e5e7eb; margin: 20px 0;">
|
||||
<p style="color: #6b7280; font-size: 12px;">
|
||||
Sent via Brevo SMTP at ${new Date().toISOString()}
|
||||
</p>
|
||||
</div>
|
||||
`,
|
||||
from: EMAIL_CONFIG.FROM,
|
||||
to: recipient,
|
||||
subject: 'Email deliverability probe',
|
||||
text:
|
||||
'This is a deliverability probe sent by scripts/test-email.ts.\n\n' +
|
||||
'If it reached an inbox, the sending domain is configured correctly.\n' +
|
||||
'If it landed in spam, check the sender domain SPF/DKIM alignment.\n' +
|
||||
'If it never arrived at all, the relay accepted and dropped it.\n\n' +
|
||||
`Sent : ${sentAt}\n` +
|
||||
`Relay: ${EMAIL_CONFIG.HOST}:${EMAIL_CONFIG.PORT}\n` +
|
||||
`From : ${EMAIL_CONFIG.FROM}\n`,
|
||||
});
|
||||
|
||||
console.log('Email sent successfully!');
|
||||
console.log('Message ID:', info.messageId);
|
||||
console.log(' Relay accepted the message');
|
||||
console.log(' Message ID:', info.messageId);
|
||||
} catch (error) {
|
||||
console.error('Failed to send email:', error);
|
||||
console.error(' Failed to send:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log('');
|
||||
if (authenticated) {
|
||||
console.log(`Now confirm it actually arrived at ${recipient} — acceptance is not delivery.`);
|
||||
} else {
|
||||
console.log('The relay accepted the message, but the sender domain is NOT authenticated,');
|
||||
console.log('so expect it to be dropped or spam-filed. Treat this run as a FAILURE');
|
||||
console.log('until a message actually lands in the inbox.');
|
||||
}
|
||||
}
|
||||
|
||||
testEmail();
|
||||
Reference in new issue
Block a user