v1.5: Selbst gehostete Auth (Passwort + Passkeys), Postgres statt Supabase
Fundament: db/migrations/0001_init.sql (users/sessions/passkey_credentials/ webauthn_challenges + Inhaltstabellen ohne RLS), db/migrate.mjs (idempotenter Migrationsrunner), lib/db (pg-Pool + query-Wrapper), lib/auth/password.ts (Node-crypto.scrypt, keine neue Abhängigkeit), lib/auth/session.ts (opake DB-Session-Tokens, Sliding-Refresh in proxy.ts). Passkeys: @simplewebauthn/server + /browser ersetzen Supabase's experimentelles WebAuthn-API (dafür gab es bisher kein eigenes Credential-Schema); RP-Konfiguration kommt jetzt direkt aus APP_URL statt über scripts/configure-passkeys.mjs und die Supabase-Management-API. scripts/bootstrap-admin.mjs legt bei leerer users-Tabelle automatisch einen Admin mit zufälligem Passwort an und hängt die Zugangsdaten an ZUGANGSDATEN.md an (idempotent, via predev/prestart-Hooks aufgerufen). Bugfix im Zuge des Umbaus: "mind. 1 Passkey nötig, um Passwort-Login zu deaktivieren" wurde bisher nur clientseitig geprüft – jetzt zusätzlich serverseitig in PATCH /api/account. E-Mail-Änderung im eigenen Konto läuft jetzt direkt nach Passwort-Bestätigung statt über eine Supabase-Bestätigungsmail (kein SMTP-Server vorhanden). Rest der Anwendung (Gerichte/Essenszeiten/Kennzeichnung/Vorschläge/ Benutzerverwaltung/Branding) nutzt noch den alten Supabase-Client – folgt in weiteren Commits.
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import "server-only";
|
||||
import { randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
|
||||
|
||||
// scrypt-Parameter fest verankert statt "der aktuelle Node-Default" zu
|
||||
// nutzen, damit ein künftiges Node-Upgrade die Hash-Stärke nicht
|
||||
// stillschweigend ändert. Speicherbedarf = 128 * N * r = 16 MiB.
|
||||
const N = 16384;
|
||||
const r = 8;
|
||||
const p = 1;
|
||||
const KEY_LEN = 64;
|
||||
const MAX_MEM = 32 * 1024 * 1024;
|
||||
|
||||
// Selbstbeschreibendes Format "scrypt$N$r$p$salt$hash" (hex), damit die
|
||||
// Parameter später erhöht werden können, ohne bestehende Hashes zu
|
||||
// invalidieren.
|
||||
export function hashPassword(plain: string): string {
|
||||
const salt = randomBytes(16);
|
||||
const hash = scryptSync(plain, salt, KEY_LEN, { N, r, p, maxmem: MAX_MEM });
|
||||
return `scrypt$${N}$${r}$${p}$${salt.toString("hex")}$${hash.toString("hex")}`;
|
||||
}
|
||||
|
||||
export function verifyPassword(plain: string, stored: string): boolean {
|
||||
const parts = stored.split("$");
|
||||
if (parts.length !== 6 || parts[0] !== "scrypt") return false;
|
||||
const [, nStr, rStr, pStr, saltHex, hashHex] = parts;
|
||||
const salt = Buffer.from(saltHex, "hex");
|
||||
const expected = Buffer.from(hashHex, "hex");
|
||||
const actual = scryptSync(plain, salt, expected.length, {
|
||||
N: Number(nStr),
|
||||
r: Number(rStr),
|
||||
p: Number(pStr),
|
||||
maxmem: MAX_MEM,
|
||||
});
|
||||
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import "server-only";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { cookies } from "next/headers";
|
||||
import { query, queryOne } from "@/lib/db";
|
||||
import type { Role } from "@/lib/types";
|
||||
|
||||
export const SESSION_COOKIE = "session";
|
||||
const SESSION_LIFETIME_MS = 30 * 24 * 60 * 60 * 1000; // 30 Tage
|
||||
const REFRESH_THRESHOLD_MS = 7 * 24 * 60 * 60 * 1000; // unter 7 Tage Restlaufzeit verlängern
|
||||
|
||||
export interface SessionUser {
|
||||
id: string;
|
||||
email: string;
|
||||
full_name: string;
|
||||
role: Role;
|
||||
password_auth_enabled: boolean;
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
user: SessionUser;
|
||||
expiresAt: Date;
|
||||
}
|
||||
|
||||
function hashToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
function isSecureCookie(): boolean {
|
||||
return (process.env.APP_URL ?? "").startsWith("https://");
|
||||
}
|
||||
|
||||
/** Nur lesend – sicher in Server Components, Route Handlern und Server Actions. */
|
||||
export async function getSession(): Promise<Session | null> {
|
||||
const token = (await cookies()).get(SESSION_COOKIE)?.value;
|
||||
if (!token) return null;
|
||||
|
||||
const row = await queryOne<{
|
||||
expires_at: Date;
|
||||
id: string;
|
||||
email: string;
|
||||
full_name: string;
|
||||
role: Role;
|
||||
password_auth_enabled: boolean;
|
||||
}>(
|
||||
`select s.expires_at, u.id, u.email, u.full_name, u.role, u.password_auth_enabled
|
||||
from sessions s join users u on u.id = s.user_id
|
||||
where s.token_hash = $1 and s.expires_at > now()`,
|
||||
[hashToken(token)]
|
||||
);
|
||||
if (!row) return null;
|
||||
|
||||
return {
|
||||
expiresAt: row.expires_at,
|
||||
user: {
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
full_name: row.full_name,
|
||||
role: row.role,
|
||||
password_auth_enabled: row.password_auth_enabled,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export class UnauthorizedError extends Error {}
|
||||
export class ForbiddenError extends Error {}
|
||||
|
||||
export async function requireSession(): Promise<Session> {
|
||||
const session = await getSession();
|
||||
if (!session) throw new UnauthorizedError();
|
||||
return session;
|
||||
}
|
||||
|
||||
export async function requireRole(roles: Role[]): Promise<Session> {
|
||||
const session = await requireSession();
|
||||
if (!roles.includes(session.user.role)) throw new ForbiddenError();
|
||||
return session;
|
||||
}
|
||||
|
||||
/** Legt eine neue Sitzung an und setzt das Session-Cookie. Nur in Route
|
||||
* Handlern/Server Actions aufrufbar (dort ist cookies().set() erlaubt). */
|
||||
export async function createSession(userId: string): Promise<void> {
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
const expiresAt = new Date(Date.now() + SESSION_LIFETIME_MS);
|
||||
|
||||
await query(
|
||||
"insert into sessions (token_hash, user_id, expires_at) values ($1, $2, $3)",
|
||||
[hashToken(token), userId, expiresAt]
|
||||
);
|
||||
|
||||
(await cookies()).set(SESSION_COOKIE, token, {
|
||||
httpOnly: true,
|
||||
secure: isSecureCookie(),
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
expires: expiresAt,
|
||||
});
|
||||
}
|
||||
|
||||
/** Löscht die Sitzung serverseitig (nicht nur das Cookie), damit ein
|
||||
* abgefangener Token nicht mehr verwendbar ist. */
|
||||
export async function destroySession(): Promise<void> {
|
||||
const store = await cookies();
|
||||
const token = store.get(SESSION_COOKIE)?.value;
|
||||
if (token) {
|
||||
await query("delete from sessions where token_hash = $1", [hashToken(token)]);
|
||||
}
|
||||
store.delete(SESSION_COOKIE);
|
||||
}
|
||||
|
||||
export { REFRESH_THRESHOLD_MS, hashToken, isSecureCookie };
|
||||
@@ -0,0 +1,34 @@
|
||||
import "server-only";
|
||||
import { query, queryOne } from "@/lib/db";
|
||||
|
||||
const CHALLENGE_TTL_MS = 5 * 60 * 1000;
|
||||
|
||||
export type ChallengeType = "registration" | "authentication";
|
||||
|
||||
export async function storeChallenge(
|
||||
challenge: string,
|
||||
type: ChallengeType,
|
||||
userId: string | null
|
||||
): Promise<void> {
|
||||
// Kein Cron nötig: abgelaufene Zeilen bei jeder neuen Challenge
|
||||
// gleich mit aufräumen.
|
||||
await query("delete from webauthn_challenges where expires_at < now()");
|
||||
await query(
|
||||
"insert into webauthn_challenges (user_id, challenge, type, expires_at) values ($1, $2, $3, $4)",
|
||||
[userId, challenge, type, new Date(Date.now() + CHALLENGE_TTL_MS)]
|
||||
);
|
||||
}
|
||||
|
||||
/** Einmalig verwendbar: die Zeile wird beim Abruf sofort gelöscht. */
|
||||
export async function consumeChallenge(
|
||||
challenge: string,
|
||||
type: ChallengeType
|
||||
): Promise<{ userId: string | null } | null> {
|
||||
const row = await queryOne<{ user_id: string | null }>(
|
||||
`delete from webauthn_challenges
|
||||
where challenge = $1 and type = $2 and expires_at > now()
|
||||
returning user_id`,
|
||||
[challenge, type]
|
||||
);
|
||||
return row ? { userId: row.user_id } : null;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import "server-only";
|
||||
|
||||
// RP-Konfiguration wird direkt aus APP_URL/SITE_TITLE abgeleitet – kein
|
||||
// externer Konfigurationsschritt mehr nötig (ersetzt das bisherige
|
||||
// scripts/configure-passkeys.mjs, das die Supabase-Management-API
|
||||
// aufrief).
|
||||
function appUrl(): URL {
|
||||
return new URL(process.env.APP_URL ?? "http://localhost:3000");
|
||||
}
|
||||
|
||||
export function rpID(): string {
|
||||
return appUrl().hostname;
|
||||
}
|
||||
|
||||
export function origin(): string {
|
||||
return appUrl().origin;
|
||||
}
|
||||
|
||||
export function rpName(): string {
|
||||
return process.env.SITE_TITLE?.trim() || "Canteen Menu";
|
||||
}
|
||||
Reference in New Issue
Block a user