Files
lunch/lib/auth/session.ts
T
Kai BöhmandClaude Opus 5.5 0602072e04
ci / olares chart · sanity (pull_request) Successful in 5s
ci / app · types + tests + build (pull_request) Successful in 3m10s
ci / oberfläche · Browser am iPhone (pull_request) Successful in 7m49s
release / which version (pull_request) Successful in 5s
release / olares chart · sanity (pull_request) Successful in 4s
markt / eintrag (pull_request) Successful in 29s
release / app (pull_request) Successful in 1m0s
release / tag and release (pull_request) Skipped
Add sign-in by mail link over Resend (26.11.40)
People who confirm their own address under More can sign in with a one-time
link (15 minutes) from their mail. The link opens /anmelden/mail#login=...
and is only redeemed by a POST after a tap, so mail scanners do not use it.
Requests always get the same answer and send in the background. A session
started from a mail link can only sign in: it cannot add or remove devices
or passkeys, create invitations or kid devices, remove people or change the
address or mail settings; it lasts 30 days and ends when the address is
removed or changed. Admins set up sending under More (Resend SMTP preset,
key sealed in the vault). Includes the login security review of the new path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HUc2nv7rJVU2gp3Bgtha3q
2026-11-07 17:58:21 +00:00

142 lines
5.3 KiB
TypeScript

import type { Role } from "./roles";
import "server-only";
import type { PoolClient } from "pg";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { withAuth } from "@/lib/db";
import { LOCALE_COOKIE, isLocale } from "@/lib/locale";
import { KIDS_COOKIE, KITCHEN_COOKIE } from "./kids";
import { hashToken, randomToken } from "./tokens";
// Sitzungen: ein Zufallsgeheimnis im Keks (HttpOnly), in der Datenbank nur
// sein Hash. 180 Tage, gleitend — eine Familien-App auf dem Handy soll nicht
// jede Woche nach dem Passkey fragen. Abmelden löscht die Zeile.
export const SESSION_COOKIE = "lunch_session";
const LIFETIME_DAYS = 180;
/** Per Mail-Link begonnen: kürzer, weil das Postfach der einzige Faktor ist (26.11.40). */
const MAIL_LIFETIME_DAYS = 30;
const lifetime = (via: string) => (via === "mail" ? MAIL_LIFETIME_DAYS : LIFETIME_DAYS);
export type Session = {
sessionId: string;
memberId: string;
householdId: string;
displayName: string;
role: Role;
householdName: string;
/** Womit die Sitzung begann. „mail“ darf nur anmelden: keine Geräte, Passkeys, Einladungen (E-0006). */
via: "passkey" | "mail" | "kid";
};
/** Legt eine Sitzung an und setzt den Keks. Aufruf in einer withAuth-Transaktion. */
export async function startSession(
client: PoolClient,
// Begonnen mit einem Passkey (Erwachsene) oder auf einem Kindergerät (lib/auth/kids.ts).
member: { id: string; householdId: string; passkeyId?: string; kidDeviceId?: string; viaMail?: boolean },
request: Request,
secure: boolean,
): Promise<void> {
const { rows } = await client.query("select locale from members where id = $1", [member.id]);
const token = randomToken();
const via = member.kidDeviceId ? "kid" : member.viaMail ? "mail" : "passkey";
const days = lifetime(via);
await client.query(
`insert into sessions (token_hash, member_id, household_id, passkey_id, kid_device_id, user_agent, expires_at, via)
values ($1, $2, $3, $4, $7, $5, now() + make_interval(days => $6), $8)`,
[
hashToken(token),
member.id,
member.householdId,
member.passkeyId ?? null,
request.headers.get("user-agent")?.slice(0, 300) ?? null,
days,
member.kidDeviceId ?? null,
via,
],
);
(await cookies()).set(SESSION_COOKIE, token, {
httpOnly: true,
secure,
sameSite: "lax",
path: "/",
maxAge: days * 24 * 60 * 60,
});
// Die Sprache gehört der Person: Was sie gewählt hat, gilt auf jedem Gerät.
const locale = rows[0]?.locale;
if (isLocale(locale)) (await cookies()).set(LOCALE_COOKIE, locale, { path: "/", sameSite: "lax", maxAge: 365 * 24 * 60 * 60 });
}
/** Die Sitzung zum Keks, oder null. Verlängert sie höchstens einmal am Tag. */
export async function getSession(): Promise<Session | null> {
const token = (await cookies()).get(SESSION_COOKIE)?.value;
if (!token) return null;
return withAuth(async (client) => {
const { rows } = await client.query(
`select s.id, s.member_id, s.household_id, s.via, s.last_seen_at < now() - interval '1 day' as stale,
m.display_name, m.role, h.name as household_name
from sessions s
join members m on m.id = s.member_id
join households h on h.id = s.household_id
where s.token_hash = $1 and s.expires_at > now()`,
[hashToken(token)],
);
const row = rows[0];
if (!row) return null;
if (row.stale) {
await client.query(
"update sessions set last_seen_at = now(), expires_at = now() + make_interval(days => $2) where id = $1",
[row.id, lifetime(row.via)],
);
}
return {
sessionId: row.id,
memberId: row.member_id,
householdId: row.household_id,
displayName: row.display_name,
role: row.role,
householdName: row.household_name,
via: row.via,
};
});
}
/** Für geschützte Seiten: ohne Sitzung zur Anmeldung — auf einem Kindergerät zur Bildauswahl, auf dem Küchendisplay zu den Rezepten. */
export async function requireSession(): Promise<Session> {
const session = await getSession();
if (!session) {
const jar = await cookies();
redirect(jar.has(KIDS_COOKIE) ? "/kinder" : jar.has(KITCHEN_COOKIE) ? "/kueche" : "/anmelden");
}
return session;
}
/** Für Seiten, die Kinder nicht sehen (Gerichte pflegen, Mehr, Runde): zurück zu „Heute“. */
export async function requireAdult(): Promise<Session> {
const session = await requireSession();
if (session.role === "child") redirect("/");
return session;
}
/** Für Seiten zum Planen (Plan, Runde): nur Erwachsene, sonst zurück zu „Heute“. */
export async function requirePlanner(): Promise<Session> {
const session = await requireSession();
if (session.role !== "admin" && session.role !== "member") redirect("/");
return session;
}
export async function endSession(): Promise<void> {
const jar = await cookies();
const token = jar.get(SESSION_COOKIE)?.value;
if (token) await withAuth((client) => client.query("delete from sessions where token_hash = $1", [hashToken(token)]));
jar.delete(SESSION_COOKIE);
}
/** Gibt es schon einen Haushalt? Sonst führt jeder Weg zur Einrichtung. */
export async function isSetUp(): Promise<boolean> {
return withAuth(async (client) => {
const { rows } = await client.query("select exists (select 1 from instance) as done");
return Boolean(rows[0]?.done);
});
}