Files
lunch/lib/auth/session.ts
T
Kai BöhmandClaude Opus 5.5 f423dd67ce
ci / olares chart · sanity (pull_request) Successful in 3s
ci / app · types + tests + build (pull_request) Successful in 3m7s
markt / eintrag (pull_request) Successful in 29s
release / which version (pull_request) Successful in 3s
release / olares chart · sanity (pull_request) Successful in 4s
release / app (pull_request) Successful in 59s
release / tag and release (pull_request) Skipped
Own sign-in with passkeys, open the entrance, market entry (26.11.2)
Setup with a code from /app/data, passkeys with required user
verification, sessions as hashed cookies bound to the passkey they
started with, single-use invitation and device links, removing a
passkey or a member, and a recovery code for the owner. Cross-household
lookups before sign-in run in withAuth() (app.auth), allowed only on the
sign-in tables; a test pins that list. State-changing routes check the
session and the Origin header.

Security check with the login-sicherheit skill before the first
invitation: docs/sicherheit/login-2026-11-06.md (no open findings above
low). Entrance goes public now that the own sign-in exists; markt.yml
creates the Lunch entry in aimighty-market and proves it with wrangler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HUc2nv7rJVU2gp3Bgtha3q
2026-11-06 19:26:36 +00:00

112 lines
3.8 KiB
TypeScript

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 { 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;
export type Session = {
sessionId: string;
memberId: string;
householdId: string;
displayName: string;
role: "owner" | "adult" | "child";
householdName: string;
};
/** Legt eine Sitzung an und setzt den Keks. Aufruf in einer withAuth-Transaktion. */
export async function startSession(
client: PoolClient,
member: { id: string; householdId: string; passkeyId: string },
request: Request,
secure: boolean,
): Promise<void> {
const { rows } = await client.query("select locale from members where id = $1", [member.id]);
const token = randomToken();
await client.query(
`insert into sessions (token_hash, member_id, household_id, passkey_id, user_agent, expires_at)
values ($1, $2, $3, $4, $5, now() + make_interval(days => $6))`,
[
hashToken(token),
member.id,
member.householdId,
member.passkeyId,
request.headers.get("user-agent")?.slice(0, 300) ?? null,
LIFETIME_DAYS,
],
);
(await cookies()).set(SESSION_COOKIE, token, {
httpOnly: true,
secure,
sameSite: "lax",
path: "/",
maxAge: LIFETIME_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.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_DAYS],
);
}
return {
sessionId: row.id,
memberId: row.member_id,
householdId: row.household_id,
displayName: row.display_name,
role: row.role,
householdName: row.household_name,
};
});
}
/** Für geschützte Seiten: ohne Sitzung zur Anmeldung. */
export async function requireSession(): Promise<Session> {
const session = await getSession();
if (!session) redirect("/anmelden");
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);
});
}