Files
kai 6f43b81f9b
release / which version (push) Successful in 2s
release / olares chart · sanity (push) Successful in 3s
release / app (push) Successful in 1m5s
release / tag and release (push) Successful in 2s
26.11.45: Runde beenden, Tage, Kalender-Abo (#46)
2026-11-08 05:23:22 +00:00

39 lines
1.8 KiB
TypeScript

import "server-only";
import type { PoolClient } from "pg";
import { withAuth } from "@/lib/db";
import { hashToken, randomToken } from "./tokens";
import { tooManyAttempts } from "./throttle";
// Kalender-Abo (26.11.45): ein Link je Haushalt. Gespeichert wird nur der Hash;
// den Link sieht die Person einmal, danach nur „Neuen Link erzeugen“.
/** Neuen Link erzeugen; ein alter verliert damit seine Gültigkeit. */
export async function newCalendarToken(client: PoolClient, householdId: string, locale: string): Promise<string> {
const token = randomToken();
await client.query("update households set calendar_token_hash = $2, calendar_locale = $3 where id = $1", [householdId, hashToken(token), locale]);
return token;
}
export async function removeCalendarToken(client: PoolClient, householdId: string): Promise<void> {
await client.query("update households set calendar_token_hash = null where id = $1", [householdId]);
}
/**
* Haushalt zum Link, oder null. Fehlversuche bremsen je Adresse und gemeinsam,
* damit niemand Links durchprobiert; gültige Abrufe zählen nicht (Kalender
* fragen stündlich nach).
*/
export async function householdForCalendar(token: string, ip: string): Promise<{ id: string } | "tooMany" | null> {
return withAuth(async (c) => {
const blocked = await c.query<{ n: number }>(
"select count(*)::int as n from auth_attempts where key = any($1) and at > now() - interval '15 minutes'",
[[`cal:${ip}`]],
);
if ((blocked.rows[0]?.n ?? 0) > 20) return "tooMany";
const { rows } = await c.query<{ id: string }>("select id from households where calendar_token_hash = $1", [hashToken(token)]);
if (rows[0]) return rows[0];
if ((await tooManyAttempts(c, `cal:${ip}`, 20, 15)) || (await tooManyAttempts(c, "cal:*", 200, 15))) return "tooMany";
return null;
});
}