Own sign-in with passkeys, open the entrance, market entry (26.11.2)
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

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
This commit is contained in:
Kai BöhmandClaude Opus 5.5 committed 2026-11-06 19:26:36 +00:00
1 parent a62e48116a
commit f423dd67ce
71 files changed
+3573 -32

No files matched your search

+89
View File
@@ -0,0 +1,89 @@
import "server-only";
import { randomInt } from "node:crypto";
import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { safeEqual } from "./tokens";
// Die Erstinstallation: Wer Lunch zum ersten Mal öffnet, braucht einen Code,
// der nur in den Dateien der Box steht (Data › lunch › lunch-einrichten.txt).
// So kann niemand aus dem Internet die leere App als Erster in Besitz nehmen,
// sobald der Entrance öffentlich ist — Muster Rocket app/einrichtung.py.
const ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // ohne 0/O, 1/I
export const SETUP_FILE = "lunch-einrichten.txt";
function dataDir(): string {
return process.env.APP_DATA_DIR ?? path.join(process.cwd(), ".data");
}
/** Großbuchstaben, ohne Leer- und Bindestriche — so, wie man ihn abtippt. */
export function normalizeCode(input: string): string {
return input.toUpperCase().replace(/[\s\-–]/g, "");
}
function format(raw: string): string {
return raw.match(/.{4}/g)!.join("-");
}
function newCode(): string {
let raw = "";
for (let i = 0; i < 16; i++) raw += ALPHABET[randomInt(ALPHABET.length)];
return format(raw);
}
async function write(file: string, text: string, flag: "wx" | "w"): Promise<void> {
await mkdir(dataDir(), { recursive: true });
await writeFile(path.join(dataDir(), file), text, { mode: 0o600, flag }).catch(() => undefined);
}
async function readCode(file: string, maxAgeMs?: number): Promise<string | null> {
try {
const full = path.join(dataDir(), file);
if (maxAgeMs !== undefined && Date.now() - (await stat(full)).mtimeMs > maxAgeMs) return null;
const text = await readFile(full, "utf8");
const line = text.split("\n").find((l) => /^[A-Z2-9]{4}(-[A-Z2-9]{4}){3}$/.test(l.trim()));
return line ? line.trim() : null;
} catch {
return null;
}
}
async function matches(file: string, input: string, maxAgeMs?: number): Promise<boolean> {
const code = await readCode(file, maxAgeMs);
if (!code || !input) return false;
return safeEqual(normalizeCode(code), normalizeCode(input));
}
/** Legt den Einrichtungscode an, falls er fehlt (16 Zeichen, rund 80 Bit). */
export async function ensureSetupCode(): Promise<void> {
await write(
SETUP_FILE,
`Einrichtungscode für Was gibt's? (lunch)\n\n${newCode()}\n\n` +
"Diesen Code beim ersten Öffnen der App eingeben. Die Datei verschwindet,\n" +
"sobald der Haushalt eingerichtet ist.\n",
"wx",
);
}
export const setupCodeMatches = (input: string) => matches(SETUP_FILE, input);
export const removeSetupCode = () => rm(path.join(dataDir(), SETUP_FILE), { force: true });
// Rückweg, wenn die Person, die eingerichtet hat, keinen Passkey mehr hat
// (Handy verloren). Den Code kann jede anfordern; lesen kann ihn nur, wer an
// die Dateien der Box kommt — dieselbe Wand wie bei der Einrichtung. Er gilt
// eine Stunde, ein neuer ersetzt den alten.
export const RECOVERY_FILE = "lunch-wiederherstellen.txt";
const RECOVERY_MS = 60 * 60 * 1000;
export async function writeRecoveryCode(): Promise<void> {
await write(
RECOVERY_FILE,
`Wiederherstellungscode für Was gibt's? (lunch)\n\n${newCode()}\n\n` +
"Gilt eine Stunde. Damit bekommt die Person, die den Haushalt eingerichtet\n" +
"hat, einen neuen Passkey. Wer diese Datei nicht angefordert hat, kann sie löschen.\n",
"w",
);
}
export const recoveryCodeMatches = (input: string) => matches(RECOVERY_FILE, input, RECOVERY_MS);
export const removeRecoveryCode = () => rm(path.join(dataDir(), RECOVERY_FILE), { force: true });
+33
View File
@@ -0,0 +1,33 @@
import "server-only";
import { browserOrigin } from "./request";
export function json(data: unknown, status = 200): Response {
return Response.json(data, { status, headers: { "cache-control": "no-store" } });
}
/** Fehler als Schlüssel; den Satz dazu kennt die Oberfläche (messages/*.json, auth.errors). */
export function fail(error: string, status: number): Response {
return json({ error }, status);
}
export async function readJson(request: Request): Promise<unknown> {
try {
return await request.json();
} catch {
return null;
}
}
/**
* Schutz vor fremden Seiten (CSRF): Ein POST muss vom Ursprung der App
* kommen. Der Browser setzt den Origin-Kopf selbst; eine fremde Seite kann
* ihn nicht fälschen.
*/
export function sameOrigin(request: Request, expected: string): boolean {
return browserOrigin(request)?.origin === expected;
}
/** Sichere Kekse nur über https — lokal unter http://localhost ginge sonst nichts. */
export function isSecure(origin: string): boolean {
return origin.startsWith("https://");
}
+35
View File
@@ -0,0 +1,35 @@
import "server-only";
import type { PoolClient } from "pg";
import { hashToken } from "./tokens";
export type OpenInvitation = {
id: string;
householdId: string;
householdName: string;
memberId: string | null;
displayName: string | null;
memberName: string | null;
};
/** Die gültige, unbenutzte Einladung zum Link — oder null. In withAuth. */
export async function findInvitation(client: PoolClient, token: string): Promise<OpenInvitation | null> {
const { rows } = await client.query(
`select i.id, i.household_id, h.name as household_name, i.member_id, i.display_name, m.display_name as member_name
from invitations i
join households h on h.id = i.household_id
left join members m on m.id = i.member_id
where i.token_hash = $1 and i.used_at is null and i.expires_at > now()`,
[hashToken(token)],
);
const r = rows[0];
return r
? {
id: r.id,
householdId: r.household_id,
householdName: r.household_name,
memberId: r.member_id,
displayName: r.display_name,
memberName: r.member_name,
}
: null;
}
+28
View File
@@ -0,0 +1,28 @@
import "server-only";
/**
* Die Adresse der App, wie der Browser sie sieht: aus dem Origin-Kopf, den
* der Browser bei jedem POST selbst setzt. Hinter Olares (Envoy, TLS davor)
* ist das verlässlicher als Host und X-Forwarded-*.
*/
export function browserOrigin(request: Request): URL | null {
const origin = request.headers.get("origin");
if (!origin) return null;
try {
const url = new URL(origin);
return url.protocol === "https:" || url.protocol === "http:" ? url : null;
} catch {
return null;
}
}
/**
* Für die Bremse. Envoy hängt die Adresse an; die erste ist die des Geräts —
* aber ein Gerät kann selbst einen Kopf mitschicken. Deshalb hat jede Bremse
* zusätzlich einen gemeinsamen Topf („…:*“), der nicht von der Adresse abhängt.
*/
export function clientIp(request: Request): string {
const forwarded = request.headers.get("x-forwarded-for");
const first = forwarded?.split(",")[0]?.trim();
return first || request.headers.get("x-real-ip") || "unknown";
}
+24
View File
@@ -0,0 +1,24 @@
import { z } from "zod";
const name = z.string().trim().min(1).max(60);
export const setupOptionsBody = z.object({
code: z.string().min(1).max(64),
name,
household: z.string().trim().min(1).max(80),
});
export const challengeBody = z.object({
challengeId: z.string().uuid(),
response: z.object({ id: z.string().min(1).max(1024) }).passthrough(),
});
export const inviteOptionsBody = z.object({
token: z.string().min(20).max(100),
name: name.optional(),
});
export const createInvitationBody = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("person"), name }),
z.object({ kind: z.literal("device") }),
]);
+111
View File
@@ -0,0 +1,111 @@
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);
});
}
+17
View File
@@ -0,0 +1,17 @@
import "server-only";
import type { PoolClient } from "pg";
/**
* Bremse gegen Durchprobieren. Vermerkt einen Versuch unter `key` und sagt,
* ob in den letzten `minutes` Minuten mehr als `limit` waren. Läuft in einer
* withAuth-Transaktion.
*/
export async function tooManyAttempts(client: PoolClient, key: string, limit: number, minutes: number): Promise<boolean> {
await client.query("delete from auth_attempts where at < now() - interval '1 day'");
await client.query("insert into auth_attempts (key) values ($1)", [key]);
const { rows } = await client.query<{ n: number }>(
"select count(*)::int as n from auth_attempts where key = $1 and at > now() - make_interval(mins => $2)",
[key, minutes],
);
return (rows[0]?.n ?? 0) > limit;
}
+17
View File
@@ -0,0 +1,17 @@
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
/** Zufälliges Geheimnis für Keks oder Link: 32 Bytes, base64url. */
export function randomToken(): string {
return randomBytes(32).toString("base64url");
}
/** Gespeichert wird nur der Hash — wer die Datenbank liest, hat keine Sitzung. */
export function hashToken(token: string): Buffer {
return createHash("sha256").update(token, "utf8").digest();
}
export function safeEqual(a: string, b: string): boolean {
const ha = createHash("sha256").update(a).digest();
const hb = createHash("sha256").update(b).digest();
return timingSafeEqual(ha, hb);
}
+135
View File
@@ -0,0 +1,135 @@
import "server-only";
import type { PoolClient } from "pg";
import {
generateAuthenticationOptions,
generateRegistrationOptions,
verifyAuthenticationResponse,
verifyRegistrationResponse,
type AuthenticationResponseJSON,
type AuthenticatorTransportFuture,
type RegistrationResponseJSON,
} from "@simplewebauthn/server";
// Passkeys (WebAuthn). Die Herausforderung liegt in auth_challenges, gilt
// fünf Minuten und wird beim Prüfen verbraucht — ein Mitschnitt lässt sich
// nicht wiederholen. Der Passkey gehört zur Domain, unter der eingerichtet
// wurde (instance.origin, instance.rp_id).
const CHALLENGE_MINUTES = 5;
const RP_NAME = "Was gibt's?";
export type Instance = { origin: string; rpId: string };
type Purpose = "setup" | "invite" | "login" | "recovery";
export async function loadInstance(client: PoolClient): Promise<Instance | null> {
const { rows } = await client.query("select origin, rp_id from instance");
return rows[0] ? { origin: rows[0].origin, rpId: rows[0].rp_id } : null;
}
async function storeChallenge(client: PoolClient, challenge: string, purpose: Purpose, context: object): Promise<string> {
await client.query("delete from auth_challenges where expires_at < now()");
const { rows } = await client.query(
`insert into auth_challenges (challenge, purpose, context, expires_at)
values ($1, $2, $3, now() + make_interval(mins => $4)) returning id`,
[challenge, purpose, JSON.stringify(context), CHALLENGE_MINUTES],
);
return rows[0].id;
}
/** Holt und verbraucht eine Herausforderung. */
export async function takeChallenge<T>(
client: PoolClient,
id: unknown,
purpose: Purpose,
): Promise<{ challenge: string; context: T } | null> {
if (typeof id !== "string" || !/^[0-9a-f-]{36}$/.test(id)) return null;
const { rows } = await client.query(
"delete from auth_challenges where id = $1 and purpose = $2 and expires_at > now() returning challenge, context",
[id, purpose],
);
return rows[0] ? { challenge: rows[0].challenge, context: rows[0].context as T } : null;
}
export async function registrationOptions(
client: PoolClient,
instance: Instance,
user: { id: string; name: string },
purpose: Purpose,
context: object,
exclude: { id: string; transports: string[] }[] = [],
) {
const options = await generateRegistrationOptions({
rpName: RP_NAME,
rpID: instance.rpId,
userName: user.name,
userDisplayName: user.name,
userID: Buffer.from(user.id.replace(/-/g, ""), "hex"),
attestationType: "none",
// Der Passkey ist der einzige Faktor: Besitz allein genügt nicht, das Gerät
// muss die Person prüfen (Gesicht, Finger, Geräte-PIN).
authenticatorSelection: { residentKey: "required", userVerification: "required" },
excludeCredentials: exclude.map((c) => ({ id: c.id, transports: c.transports as AuthenticatorTransportFuture[] })),
});
const challengeId = await storeChallenge(client, options.challenge, purpose, context);
return { challengeId, options };
}
export async function verifyRegistration(instance: Instance, challenge: string, response: RegistrationResponseJSON) {
const result = await verifyRegistrationResponse({
response,
expectedChallenge: challenge,
expectedOrigin: instance.origin,
expectedRPID: instance.rpId,
requireUserVerification: true,
});
if (!result.verified || !result.registrationInfo) return null;
const { credential, credentialDeviceType, credentialBackedUp } = result.registrationInfo;
return {
id: credential.id,
publicKey: Buffer.from(credential.publicKey),
counter: credential.counter,
transports: (response.response.transports ?? []) as string[],
deviceType: credentialDeviceType,
backedUp: credentialBackedUp,
};
}
export async function authenticationOptions(client: PoolClient, instance: Instance) {
const options = await generateAuthenticationOptions({ rpID: instance.rpId, userVerification: "required" });
const challengeId = await storeChallenge(client, options.challenge, "login", {});
return { challengeId, options };
}
export async function verifyAuthentication(
instance: Instance,
challenge: string,
response: AuthenticationResponseJSON,
passkey: { id: string; publicKey: Buffer; counter: number; transports: string[] },
) {
const result = await verifyAuthenticationResponse({
response,
expectedChallenge: challenge,
expectedOrigin: instance.origin,
expectedRPID: instance.rpId,
credential: {
id: passkey.id,
publicKey: new Uint8Array(passkey.publicKey),
counter: passkey.counter,
transports: passkey.transports as AuthenticatorTransportFuture[],
},
requireUserVerification: true,
});
return result.verified ? result.authenticationInfo.newCounter : null;
}
/** Erkennt einen Passkey grob am Gerät, damit die Liste lesbar ist. */
export function deviceLabel(userAgent: string | null): string {
const ua = userAgent ?? "";
if (/iPhone/.test(ua)) return "iPhone";
if (/iPad/.test(ua)) return "iPad";
if (/Android/.test(ua)) return "Android";
if (/Macintosh/.test(ua)) return "Mac";
if (/Windows/.test(ua)) return "Windows";
if (/Linux/.test(ua)) return "Linux";
return "";
}
+21
View File
@@ -45,6 +45,27 @@ export async function withHousehold<T>(householdId: string, fn: (client: PoolCli
}
}
/**
* Für die Anmeldung, bevor der Haushalt bekannt ist: setzt `app.auth = on`.
* Die Policies lassen das nur auf den Tabellen der Anmeldung zu (Migration
* 0002). Außerhalb von lib/auth/ nie benutzen.
*/
export async function withAuth<T>(fn: (client: PoolClient) => Promise<T>): Promise<T> {
const client = await pool.connect();
try {
await client.query("begin");
await client.query("select set_config('app.auth', 'on', true)");
const result = await fn(client);
await client.query("commit");
return result;
} catch (error) {
await client.query("rollback").catch(() => undefined);
throw error;
} finally {
client.release();
}
}
export async function databaseReachable(): Promise<boolean> {
try {
await pool.query("select 1");