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

+46
View File
@@ -0,0 +1,46 @@
import { randomUUID } from "node:crypto";
import { withAuth } from "@/lib/db";
import { fail, json, readJson, sameOrigin } from "@/lib/auth/http";
import { findInvitation } from "@/lib/auth/invitations";
import { clientIp } from "@/lib/auth/request";
import { inviteOptionsBody } from "@/lib/auth/schemas";
import { tooManyAttempts } from "@/lib/auth/throttle";
import { loadInstance, registrationOptions } from "@/lib/auth/webauthn";
export const dynamic = "force-dynamic";
// Einladung annehmen, Schritt 1: Passkey-Optionen für die neue Person oder
// das neue Gerät einer vorhandenen.
export async function POST(request: Request) {
const body = inviteOptionsBody.safeParse(await readJson(request));
return withAuth(async (client) => {
const instance = await loadInstance(client);
if (!instance) return fail("notSetUp", 409);
if (!sameOrigin(request, instance.origin)) return fail("origin", 403);
if (
(await tooManyAttempts(client, `invite:${clientIp(request)}`, 20, 15)) ||
(await tooManyAttempts(client, "invite:*", 200, 15))
) {
return fail("tooMany", 429);
}
if (!body.success) return fail("invalid", 400);
const invitation = await findInvitation(client, body.data.token);
if (!invitation) return fail("invitation", 410);
let memberId: string;
let name: string;
let exclude: { id: string; transports: string[] }[] = [];
if (invitation.memberId) {
memberId = invitation.memberId;
name = invitation.memberName ?? "";
const { rows } = await client.query("select id, transports from passkeys where member_id = $1", [memberId]);
exclude = rows;
} else {
memberId = randomUUID();
name = body.data.name ?? invitation.displayName ?? "";
}
if (!name) return fail("invalid", 400);
const context = { invitationId: invitation.id, memberId, isNew: !invitation.memberId, name, householdId: invitation.householdId };
return json(await registrationOptions(client, instance, { id: memberId, name }, "invite", context, exclude));
});
}
+64
View File
@@ -0,0 +1,64 @@
import type { RegistrationResponseJSON } from "@simplewebauthn/server";
import { withAuth } from "@/lib/db";
import { fail, isSecure, json, readJson, sameOrigin } from "@/lib/auth/http";
import { challengeBody } from "@/lib/auth/schemas";
import { startSession } from "@/lib/auth/session";
import { deviceLabel, loadInstance, takeChallenge, verifyRegistration } from "@/lib/auth/webauthn";
import { cookies } from "next/headers";
import { LOCALE_COOKIE, resolveLocale } from "@/lib/locale";
export const dynamic = "force-dynamic";
type InviteContext = { invitationId: string; memberId: string; isNew: boolean; name: string; householdId: string };
// Einladung annehmen, Schritt 2: Passkey prüfen, die Einladung verbrauchen
// (genau einmal), Person anlegen, falls neu, Sitzung beginnen.
export async function POST(request: Request) {
const body = challengeBody.safeParse(await readJson(request));
if (!body.success) return fail("invalid", 400);
return withAuth(async (client) => {
const instance = await loadInstance(client);
if (!instance) return fail("notSetUp", 409);
if (!sameOrigin(request, instance.origin)) return fail("origin", 403);
const taken = await takeChallenge<InviteContext>(client, body.data.challengeId, "invite");
if (!taken) return fail("expired", 400);
const ctx = taken.context;
const passkey = await verifyRegistration(instance, taken.challenge, body.data.response as unknown as RegistrationResponseJSON).catch(
() => null,
);
if (!passkey) return fail("passkey", 400);
const used = await client.query(
"update invitations set used_at = now() where id = $1 and used_at is null and expires_at > now() returning id",
[ctx.invitationId],
);
if (used.rowCount !== 1) return fail("invitation", 410);
if (ctx.isNew) {
await client.query("insert into members (id, household_id, display_name, role, locale) values ($1, $2, $3, 'adult', $4)", [
ctx.memberId,
ctx.householdId,
ctx.name,
resolveLocale((await cookies()).get(LOCALE_COOKIE)?.value, request.headers.get("accept-language")),
]);
}
await client.query(
`insert into passkeys (id, member_id, household_id, public_key, counter, transports, device_type, backed_up, label)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
[
passkey.id,
ctx.memberId,
ctx.householdId,
passkey.publicKey,
passkey.counter,
passkey.transports,
passkey.deviceType,
passkey.backedUp,
deviceLabel(request.headers.get("user-agent")),
],
);
await startSession(client, { id: ctx.memberId, householdId: ctx.householdId, passkeyId: passkey.id }, request, isSecure(instance.origin));
return json({ ok: true });
});
}
+24
View File
@@ -0,0 +1,24 @@
import { withAuth } from "@/lib/db";
import { fail, json, sameOrigin } from "@/lib/auth/http";
import { clientIp } from "@/lib/auth/request";
import { tooManyAttempts } from "@/lib/auth/throttle";
import { authenticationOptions, loadInstance } from "@/lib/auth/webauthn";
export const dynamic = "force-dynamic";
// Anmelden mit Passkey, Schritt 1. Ohne Namen: Der Passkey auf dem Gerät
// weiß selbst, wem er gehört (discoverable credential).
export async function POST(request: Request) {
return withAuth(async (client) => {
const instance = await loadInstance(client);
if (!instance) return fail("notSetUp", 409);
if (!sameOrigin(request, instance.origin)) return fail("origin", 403);
if (
(await tooManyAttempts(client, `login:${clientIp(request)}`, 30, 15)) ||
(await tooManyAttempts(client, "login:*", 600, 15))
) {
return fail("tooMany", 429);
}
return json(await authenticationOptions(client, instance));
});
}
+41
View File
@@ -0,0 +1,41 @@
import type { AuthenticationResponseJSON } from "@simplewebauthn/server";
import { withAuth } from "@/lib/db";
import { fail, isSecure, json, readJson, sameOrigin } from "@/lib/auth/http";
import { challengeBody } from "@/lib/auth/schemas";
import { startSession } from "@/lib/auth/session";
import { loadInstance, takeChallenge, verifyAuthentication } from "@/lib/auth/webauthn";
export const dynamic = "force-dynamic";
// Anmelden mit Passkey, Schritt 2: Signatur prüfen, Zähler fortschreiben,
// Sitzung anlegen. Ein unbekannter Passkey und eine falsche Signatur geben
// dieselbe Antwort.
export async function POST(request: Request) {
const body = challengeBody.safeParse(await readJson(request));
if (!body.success) return fail("invalid", 400);
return withAuth(async (client) => {
const instance = await loadInstance(client);
if (!instance) return fail("notSetUp", 409);
if (!sameOrigin(request, instance.origin)) return fail("origin", 403);
const taken = await takeChallenge(client, body.data.challengeId, "login");
if (!taken) return fail("expired", 400);
const { rows } = await client.query(
"select id, member_id, household_id, public_key, counter, transports from passkeys where id = $1",
[body.data.response.id],
);
const row = rows[0];
if (!row) return fail("passkey", 401);
const newCounter = await verifyAuthentication(instance, taken.challenge, body.data.response as unknown as AuthenticationResponseJSON, {
id: row.id,
publicKey: row.public_key,
counter: Number(row.counter),
transports: row.transports,
}).catch(() => null);
if (newCounter === null) return fail("passkey", 401);
await client.query("update passkeys set counter = $2, last_used_at = now() where id = $1", [row.id, newCounter]);
await startSession(client, { id: row.member_id, householdId: row.household_id, passkeyId: row.id }, request, isSecure(instance.origin));
return json({ ok: true });
});
}
+8
View File
@@ -0,0 +1,8 @@
import { endSession } from "@/lib/auth/session";
export const dynamic = "force-dynamic";
export async function POST() {
await endSession();
return new Response(null, { status: 204 });
}
+44
View File
@@ -0,0 +1,44 @@
import { z } from "zod";
import { withAuth } from "@/lib/db";
import { recoveryCodeMatches } from "@/lib/auth/codes";
import { fail, json, readJson, sameOrigin } from "@/lib/auth/http";
import { clientIp } from "@/lib/auth/request";
import { tooManyAttempts } from "@/lib/auth/throttle";
import { loadInstance, registrationOptions } from "@/lib/auth/webauthn";
export const dynamic = "force-dynamic";
// Rückweg, Schritt 1: Code prüfen, Passkey-Optionen für die Person, die den
// Haushalt eingerichtet hat. Sie kann danach unter „Mehr“ verlorene Geräte
// entfernen und andere neu einladen.
export async function POST(request: Request) {
const body = z.object({ code: z.string().min(1).max(64) }).safeParse(await readJson(request));
return withAuth(async (client) => {
const instance = await loadInstance(client);
if (!instance) return fail("notSetUp", 409);
if (!sameOrigin(request, instance.origin)) return fail("origin", 403);
if (
(await tooManyAttempts(client, `recovery-code:${clientIp(request)}`, 10, 15)) ||
(await tooManyAttempts(client, "recovery-code:*", 100, 60))
) {
return fail("tooMany", 429);
}
if (!body.success) return fail("invalid", 400);
if (!(await recoveryCodeMatches(body.data.code))) return fail("code", 401);
const { rows } = await client.query("select id, household_id, display_name from members where role = 'owner' order by created_at limit 1");
const owner = rows[0];
if (!owner) return fail("unknown", 500);
const existing = await client.query("select id, transports from passkeys where member_id = $1", [owner.id]);
return json(
await registrationOptions(
client,
instance,
{ id: owner.id, name: owner.display_name },
"recovery",
{ memberId: owner.id, householdId: owner.household_id },
existing.rows,
),
);
});
}
+28
View File
@@ -0,0 +1,28 @@
import { withAuth } from "@/lib/db";
import { writeRecoveryCode } from "@/lib/auth/codes";
import { fail, sameOrigin } from "@/lib/auth/http";
import { clientIp } from "@/lib/auth/request";
import { tooManyAttempts } from "@/lib/auth/throttle";
import { loadInstance } from "@/lib/auth/webauthn";
export const dynamic = "force-dynamic";
// Rückweg, Schritt 0: einen Code in die Dateien der Box legen. Verrät nichts
// und gibt niemandem Zugang, der nicht an die Box kommt.
export async function POST(request: Request) {
const allowed = 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 (
(await tooManyAttempts(client, `recovery:${clientIp(request)}`, 5, 60)) ||
(await tooManyAttempts(client, "recovery:*", 20, 60))
) {
return fail("tooMany", 429);
}
return null;
});
if (allowed) return allowed;
await writeRecoveryCode();
return new Response(null, { status: 204 });
}
+49
View File
@@ -0,0 +1,49 @@
import type { RegistrationResponseJSON } from "@simplewebauthn/server";
import { withAuth } from "@/lib/db";
import { removeRecoveryCode } from "@/lib/auth/codes";
import { fail, isSecure, json, readJson, sameOrigin } from "@/lib/auth/http";
import { challengeBody } from "@/lib/auth/schemas";
import { startSession } from "@/lib/auth/session";
import { deviceLabel, loadInstance, takeChallenge, verifyRegistration } from "@/lib/auth/webauthn";
export const dynamic = "force-dynamic";
type RecoveryContext = { memberId: string; householdId: string };
export async function POST(request: Request) {
const body = challengeBody.safeParse(await readJson(request));
if (!body.success) return fail("invalid", 400);
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);
const taken = await takeChallenge<RecoveryContext>(client, body.data.challengeId, "recovery");
if (!taken) return fail("expired", 400);
const passkey = await verifyRegistration(instance, taken.challenge, body.data.response as unknown as RegistrationResponseJSON).catch(
() => null,
);
if (!passkey) return fail("passkey", 400);
const { memberId, householdId } = taken.context;
await client.query(
`insert into passkeys (id, member_id, household_id, public_key, counter, transports, device_type, backed_up, label)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
[
passkey.id,
memberId,
householdId,
passkey.publicKey,
passkey.counter,
passkey.transports,
passkey.deviceType,
passkey.backedUp,
deviceLabel(request.headers.get("user-agent")),
],
);
await startSession(client, { id: memberId, householdId, passkeyId: passkey.id }, request, isSecure(instance.origin));
return null;
});
if (result) return result;
// Einmal benutzt, dann weg.
await removeRecoveryCode();
return json({ ok: true });
}
+40
View File
@@ -0,0 +1,40 @@
import { randomUUID } from "node:crypto";
import { withAuth } from "@/lib/db";
import { fail, json, readJson } from "@/lib/auth/http";
import { browserOrigin, clientIp } from "@/lib/auth/request";
import { setupOptionsBody } from "@/lib/auth/schemas";
import { setupCodeMatches } from "@/lib/auth/codes";
import { tooManyAttempts } from "@/lib/auth/throttle";
import { loadInstance, registrationOptions } from "@/lib/auth/webauthn";
export const dynamic = "force-dynamic";
// Einrichtung, Schritt 1: Code prüfen, Passkey-Optionen für die erste Person.
export async function POST(request: Request) {
const body = setupOptionsBody.safeParse(await readJson(request));
const origin = browserOrigin(request);
return withAuth(async (client) => {
if (await loadInstance(client)) return fail("alreadySetUp", 409);
if (
(await tooManyAttempts(client, `setup:${clientIp(request)}`, 10, 15)) ||
(await tooManyAttempts(client, "setup:*", 100, 60))
) {
return fail("tooMany", 429);
}
if (!body.success) return fail("invalid", 400);
if (!origin) return fail("origin", 400);
if (!(await setupCodeMatches(body.data.code))) return fail("code", 401);
const memberId = randomUUID();
const householdId = randomUUID();
const instance = { origin: origin.origin, rpId: origin.hostname };
const { challengeId, options } = await registrationOptions(
client,
instance,
{ id: memberId, name: body.data.name },
"setup",
{ memberId, householdId, name: body.data.name, household: body.data.household, ...instance },
);
return json({ challengeId, options });
});
}
+62
View File
@@ -0,0 +1,62 @@
import type { RegistrationResponseJSON } from "@simplewebauthn/server";
import { withAuth } from "@/lib/db";
import { fail, isSecure, json, readJson } from "@/lib/auth/http";
import { challengeBody } from "@/lib/auth/schemas";
import { startSession } from "@/lib/auth/session";
import { removeSetupCode } from "@/lib/auth/codes";
import { deviceLabel, loadInstance, takeChallenge, verifyRegistration } from "@/lib/auth/webauthn";
import { cookies } from "next/headers";
import { resolveLocale, LOCALE_COOKIE } from "@/lib/locale";
export const dynamic = "force-dynamic";
type SetupContext = { memberId: string; householdId: string; name: string; household: string; origin: string; rpId: string };
// Einrichtung, Schritt 2: Passkey prüfen, dann Box, Haushalt, erste Person,
// Passkey und Sitzung in einer Transaktion anlegen.
export async function POST(request: Request) {
const body = challengeBody.safeParse(await readJson(request));
if (!body.success) return fail("invalid", 400);
const result = await withAuth(async (client) => {
if (await loadInstance(client)) return fail("alreadySetUp", 409);
const taken = await takeChallenge<SetupContext>(client, body.data.challengeId, "setup");
if (!taken) return fail("expired", 400);
const ctx = taken.context;
const instance = { origin: ctx.origin, rpId: ctx.rpId };
const passkey = await verifyRegistration(instance, taken.challenge, body.data.response as unknown as RegistrationResponseJSON).catch(
() => null,
);
if (!passkey) return fail("passkey", 400);
const locale = resolveLocale((await cookies()).get(LOCALE_COOKIE)?.value, request.headers.get("accept-language"));
await client.query("select set_config('app.household_id', $1, true)", [ctx.householdId]);
await client.query("insert into instance (origin, rp_id) values ($1, $2)", [instance.origin, instance.rpId]);
await client.query("insert into households (id, name) values ($1, $2)", [ctx.householdId, ctx.household]);
await client.query("insert into members (id, household_id, display_name, role, locale) values ($1, $2, $3, 'owner', $4)", [
ctx.memberId,
ctx.householdId,
ctx.name,
locale,
]);
await client.query(
`insert into passkeys (id, member_id, household_id, public_key, counter, transports, device_type, backed_up, label)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
[
passkey.id,
ctx.memberId,
ctx.householdId,
passkey.publicKey,
passkey.counter,
passkey.transports,
passkey.deviceType,
passkey.backedUp,
deviceLabel(request.headers.get("user-agent")),
],
);
await startSession(client, { id: ctx.memberId, householdId: ctx.householdId, passkeyId: passkey.id }, request, isSecure(instance.origin));
return null;
});
if (result) return result;
await removeSetupCode();
return json({ ok: true });
}
+42
View File
@@ -0,0 +1,42 @@
import { withAuth, withHousehold } from "@/lib/db";
import { fail, json, readJson, sameOrigin } from "@/lib/auth/http";
import { createInvitationBody } from "@/lib/auth/schemas";
import { getSession } from "@/lib/auth/session";
import { hashToken, randomToken } from "@/lib/auth/tokens";
import { loadInstance } from "@/lib/auth/webauthn";
export const dynamic = "force-dynamic";
// Einladungslink: eine neue Person (nur wer eingerichtet hat) oder ein
// weiteres eigenes Gerät (jede erwachsene Person). Der Link wird einmal
// gezeigt; gespeichert ist nur sein Hash.
const DAYS = { person: 7, device: 1 } as const;
export async function POST(request: Request) {
const session = await getSession();
if (!session) return fail("signedOut", 401);
const instance = await withAuth(loadInstance);
if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403);
const body = createInvitationBody.safeParse(await readJson(request));
if (!body.success) return fail("invalid", 400);
if (body.data.kind === "person" && session.role !== "owner") return fail("forbidden", 403);
if (session.role === "child") return fail("forbidden", 403);
const token = randomToken();
const data = body.data;
await withHousehold(session.householdId, (client) =>
client.query(
`insert into invitations (household_id, token_hash, member_id, display_name, created_by, expires_at)
values ($1, $2, $3, $4, $5, now() + make_interval(days => $6))`,
[
session.householdId,
hashToken(token),
data.kind === "device" ? session.memberId : null,
data.kind === "person" ? data.name : null,
session.memberId,
DAYS[data.kind],
],
),
);
return json({ url: `${instance.origin}/einladung/${token}`, days: DAYS[data.kind] });
}
+23
View File
@@ -0,0 +1,23 @@
import { z } from "zod";
import { withAuth, withHousehold } from "@/lib/db";
import { fail, readJson, sameOrigin } from "@/lib/auth/http";
import { getSession } from "@/lib/auth/session";
import { loadInstance } from "@/lib/auth/webauthn";
export const dynamic = "force-dynamic";
// Eine Person aus dem Haushalt nehmen — nur wer eingerichtet hat, nie sich
// selbst. Passkeys, Sitzungen und offene Einladungen gehen mit (on delete cascade).
export async function POST(request: Request) {
const session = await getSession();
if (!session) return fail("signedOut", 401);
const instance = await withAuth(loadInstance);
if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403);
if (session.role !== "owner") return fail("forbidden", 403);
const body = z.object({ id: z.string().uuid() }).safeParse(await readJson(request));
if (!body.success || body.data.id === session.memberId) return fail("invalid", 400);
return withHousehold(session.householdId, async (client) => {
const removed = await client.query("delete from members where id = $1 and role <> 'owner'", [body.data.id]);
return removed.rowCount === 1 ? new Response(null, { status: 204 }) : fail("invalid", 404);
});
}
+25
View File
@@ -0,0 +1,25 @@
import { cookies } from "next/headers";
import { z } from "zod";
import { withAuth, withHousehold } from "@/lib/db";
import { fail, readJson, sameOrigin } from "@/lib/auth/http";
import { getSession } from "@/lib/auth/session";
import { loadInstance } from "@/lib/auth/webauthn";
import { LOCALE_COOKIE, LOCALES } from "@/lib/locale";
export const dynamic = "force-dynamic";
// Die Sprache gehört der Person: gespeichert am Mitglied, damit sie auf
// jedem Gerät gilt, und als Keks für dieses Gerät.
export async function POST(request: Request) {
const session = await getSession();
if (!session) return fail("signedOut", 401);
const instance = await withAuth(loadInstance);
if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403);
const body = z.object({ locale: z.enum(LOCALES) }).safeParse(await readJson(request));
if (!body.success) return fail("invalid", 400);
await withHousehold(session.householdId, (client) =>
client.query("update members set locale = $2 where id = $1", [session.memberId, body.data.locale]),
);
(await cookies()).set(LOCALE_COOKIE, body.data.locale, { path: "/", sameSite: "lax", maxAge: 365 * 24 * 60 * 60 });
return new Response(null, { status: 204 });
}
+25
View File
@@ -0,0 +1,25 @@
import { z } from "zod";
import { withAuth, withHousehold } from "@/lib/db";
import { fail, readJson, sameOrigin } from "@/lib/auth/http";
import { getSession } from "@/lib/auth/session";
import { loadInstance } from "@/lib/auth/webauthn";
export const dynamic = "force-dynamic";
// Einen eigenen Passkey entfernen (Gerät verloren oder verkauft). Jede
// Sitzung, die mit ihm begann, endet mit ihm. Der letzte bleibt — sonst
// sperrt man sich selbst aus.
export async function POST(request: Request) {
const session = await getSession();
if (!session) return fail("signedOut", 401);
const instance = await withAuth(loadInstance);
if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403);
const body = z.object({ id: z.string().min(1).max(1024) }).safeParse(await readJson(request));
if (!body.success) return fail("invalid", 400);
return withHousehold(session.householdId, async (client) => {
const { rows } = await client.query("select count(*)::int as n from passkeys where member_id = $1", [session.memberId]);
if ((rows[0]?.n ?? 0) <= 1) return fail("lastPasskey", 409);
const removed = await client.query("delete from passkeys where id = $1 and member_id = $2", [body.data.id, session.memberId]);
return removed.rowCount === 1 ? new Response(null, { status: 204 }) : fail("invalid", 404);
});
}