feat: e-mail, password reset and shareable links for images and collections
Mail goes out through the account's own mailbox (SMTP) rather than a sending service: the domain lives there anyway, so SPF and DKIM line up by themselves and no third party gets to see the messages. Credentials are AES-256-GCM encrypted in settings like every other secret, never in the repo. nodemailer has zero dependencies and no native postinstall -- checked before adding it, given the history. Password reset: single-use token, only its hash is stored, one hour, and the request endpoint answers identically whether or not the address exists so it cannot be used to enumerate accounts. Rate limited per address. Share links (/s/<slug>) let someone without an account see the pictures and download them at full resolution. These are photos of children, so the defaults lean safe: every link expires by itself (30 days), can be revoked, optionally carries a passphrase, and the page and files are noindex. Access is bound to the link, not the image -- swapping in another item id on a valid link returns 404. Private-session results can never be shared at all. Tracking records when and with what, never who: IP addresses are only stored salted-and-hashed, so repeat visitors can be counted but nobody identified. Sharing goes out by mail (several recipients at once, no attachment -- a link can be withdrawn later, an attachment cannot) or via wa.me, which opens WhatsApp with the text prepared. The WhatsApp Business API would need a Meta account, approved templates and per-conversation fees; this works today for free and the API can slot in behind it later. Verified end to end against a local SMTP server: reset issues and consumes its token exactly once, the old password stops working, an unknown address gives the same answer, share mail reaches several recipients. Link behaviour checked for expiry (410), revocation (410), wrong passphrase (401) and download lock (403). Outbound SMTP is blocked in the sandbox, so the real mailbox still needs one test from the live server. Also fixes a regression this introduced: the seventh nav item pushed the logout button off screen at 820px. The bar now shrinks and scrolls, logout never does. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BNhLunz586g6DeYMa7Qsd1
This commit is contained in:
27 files changed
+1946
-13
No files matched your search
@@ -0,0 +1,88 @@
|
||||
import type { APIRoute } from 'astro';
|
||||
import { randomBytes, createHash } from 'node:crypto';
|
||||
import { one, query } from '../../../lib/db';
|
||||
import { hashPassword } from '../../../lib/auth';
|
||||
import { sendMail, mailLayout, mailReady, istMail } from '../../../lib/mail';
|
||||
|
||||
export const prerender = false;
|
||||
const json = (b: unknown, s = 200) =>
|
||||
new Response(JSON.stringify(b), { status: s, headers: { 'Content-Type': 'application/json' } });
|
||||
|
||||
const GUELTIG_MINUTEN = 60;
|
||||
const hashToken = (t: string) => createHash('sha256').update(t).digest('hex');
|
||||
const basis = () => (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
|
||||
|
||||
// Ein Zähler je Adresse, damit niemand über diese Route Mails verschicken kann.
|
||||
const versuche = new Map<string, { n: number; bis: number }>();
|
||||
function zuOft(schluessel: string, max = 5, fensterMs = 15 * 60_000): boolean {
|
||||
const jetzt = Date.now();
|
||||
const e = versuche.get(schluessel);
|
||||
if (!e || e.bis < jetzt) { versuche.set(schluessel, { n: 1, bis: jetzt + fensterMs }); return false; }
|
||||
e.n++;
|
||||
if (versuche.size > 5000) versuche.clear(); // simpler Schutz gegen Zuwachs
|
||||
return e.n > max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rücksetz-Link anfordern (`{ email }`) oder neues Passwort setzen
|
||||
* (`{ token, password }`).
|
||||
*
|
||||
* Wichtig: Beim Anfordern antwortet die Route **immer gleich**, egal ob es die
|
||||
* Adresse gibt. Sonst ließe sich hier ablesen, wer ein Konto hat.
|
||||
*/
|
||||
export const POST: APIRoute = async ({ request, clientAddress }) => {
|
||||
const b = await request.json().catch(() => ({}));
|
||||
|
||||
// --- Neues Passwort setzen -------------------------------------------------
|
||||
if (b.token) {
|
||||
const token = String(b.token);
|
||||
const pw = String(b.password || '');
|
||||
if (pw.length < 10) return json({ error: 'Das Passwort muss mindestens 10 Zeichen haben.' }, 400);
|
||||
if (zuOft('einloesen:' + clientAddress, 20)) return json({ error: 'Zu viele Versuche. Bitte später erneut.' }, 429);
|
||||
|
||||
const r = await one<{ user_id: string }>(
|
||||
`SELECT user_id FROM password_resets
|
||||
WHERE token_hash = $1 AND used_at IS NULL AND expires_at > now()`, [hashToken(token)]);
|
||||
if (!r) return json({ error: 'Dieser Link ist abgelaufen oder wurde schon benutzt.' }, 400);
|
||||
|
||||
await query('UPDATE users SET password_hash=$2 WHERE id=$1', [r.user_id, await hashPassword(pw)]);
|
||||
// Einmalnutzung, und alle anderen offenen Links desselben Kontos verfallen mit.
|
||||
await query('UPDATE password_resets SET used_at = now() WHERE user_id=$1 AND used_at IS NULL', [r.user_id]);
|
||||
return json({ ok: true });
|
||||
}
|
||||
|
||||
// --- Rücksetz-Link anfordern ----------------------------------------------
|
||||
const email = String(b.email || '').trim().toLowerCase();
|
||||
if (!istMail(email)) return json({ error: 'Bitte eine gültige E-Mail-Adresse eingeben.' }, 400);
|
||||
if (zuOft('anfordern:' + clientAddress)) return json({ ok: true }); // still schlucken
|
||||
if (!(await mailReady())) return json({ error: 'Auf diesem Server ist kein E-Mail-Versand eingerichtet.' }, 503);
|
||||
|
||||
const u = await one<{ id: string; display_name: string | null; username: string }>(
|
||||
'SELECT id, display_name, username FROM users WHERE lower(email) = $1', [email]);
|
||||
|
||||
if (u) {
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
await query(
|
||||
`INSERT INTO password_resets (token_hash, user_id, expires_at)
|
||||
VALUES ($1, $2, now() + ($3 || ' minutes')::interval)`,
|
||||
[hashToken(token), u.id, String(GUELTIG_MINUTEN)]);
|
||||
|
||||
const url = `${basis()}/passwort?token=${token}`;
|
||||
const name = u.display_name || u.username;
|
||||
await sendMail({
|
||||
to: email,
|
||||
subject: 'Passwort für Klarbild zurücksetzen',
|
||||
text: `Hallo ${name},\n\nüber den folgenden Link kannst du dir ein neues Passwort für Klarbild setzen. `
|
||||
+ `Der Link gilt ${GUELTIG_MINUTEN} Minuten und lässt sich nur einmal verwenden.\n\n${url}\n\n`
|
||||
+ `Wenn du das nicht angefordert hast, kannst du diese Nachricht ignorieren — es ändert sich dann nichts.`,
|
||||
html: mailLayout('Neues Passwort setzen', [
|
||||
`Hallo ${name},`,
|
||||
`über den Knopf unten setzt du dir ein neues Passwort für Klarbild. Der Link gilt <b>${GUELTIG_MINUTEN} Minuten</b> und lässt sich nur <b>einmal</b> verwenden.`,
|
||||
`Wenn du das nicht angefordert hast, kannst du diese Nachricht ignorieren — es ändert sich dann nichts.`,
|
||||
], { text: 'Neues Passwort setzen', url }),
|
||||
}).catch((e) => console.error('[reset] Mail fehlgeschlagen:', e?.message || e));
|
||||
}
|
||||
|
||||
// Immer dieselbe Antwort — sonst verrät sie, welche Adressen ein Konto haben.
|
||||
return json({ ok: true });
|
||||
};
|
||||
Reference in new issue
Block a user