43 lines
2.1 KiB
TypeScript
43 lines
2.1 KiB
TypeScript
import { z } from "zod";
|
|
import { withAuth } from "@/lib/db";
|
|
import { fail, json, readJson, sameOrigin } from "@/lib/auth/http";
|
|
import { createMailToken, findMailMember, linkMail, normalizeEmail, sendInBackground } from "@/lib/auth/mail-login";
|
|
import { clientIp } from "@/lib/auth/request";
|
|
import { tooManyAttempts } from "@/lib/auth/throttle";
|
|
import { loadInstance } from "@/lib/auth/webauthn";
|
|
|
|
export const dynamic = "force-dynamic";
|
|
|
|
const body = z.object({ email: z.string().trim().max(200).email() });
|
|
|
|
// Link per Mail anfordern (26.11.40). Die Antwort ist immer dieselbe — ob es die
|
|
// Adresse gibt, verrät sie nicht, auch nicht durch ihre Dauer (Versand im Hintergrund).
|
|
export async function POST(request: Request) {
|
|
const parsed = body.safeParse(await readJson(request));
|
|
const result = await withAuth(async (client) => {
|
|
const instance = await loadInstance(client);
|
|
if (!instance) return fail("notSetUp", 409);
|
|
if (!sameOrigin(request, instance.origin)) return fail("origin", 403);
|
|
if (!parsed.success) return fail("invalid", 400);
|
|
const email = normalizeEmail(parsed.data.email);
|
|
if (
|
|
(await tooManyAttempts(client, `mail:${clientIp(request)}`, 10, 15)) ||
|
|
(await tooManyAttempts(client, `mail-to:${email}`, 3, 15)) ||
|
|
(await tooManyAttempts(client, `mail-to-day:${email}`, 10, 24 * 60)) ||
|
|
// Gemeinsamer Topf: hält Resend-Kontingent und Absender-Ruf, auch wenn jemand Adressen variiert.
|
|
(await tooManyAttempts(client, "mail:*", 30, 60))
|
|
) {
|
|
return fail("tooMany", 429);
|
|
}
|
|
const member = await findMailMember(client, email);
|
|
if (!member) return null;
|
|
const token = await createMailToken(client, { householdId: member.householdId, memberId: member.id, purpose: "login", email });
|
|
return { member, token, email, origin: instance.origin };
|
|
});
|
|
if (result instanceof Response) return result;
|
|
if (result) {
|
|
sendInBackground(result.member.householdId, linkMail({ purpose: "login", to: result.email, token: result.token, origin: result.origin, locale: result.member.locale }));
|
|
}
|
|
return json({ ok: true });
|
|
}
|