import { randomUUID } from "node:crypto"; import { readdir, readFile, rename, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; export const CALENDAR_TONES = ["cyan", "amber", "violet", "emerald", "rose"] as const; export type CalendarTone = (typeof CALENDAR_TONES)[number]; export const MAX_CALENDARS = 10; const HISTORY_LIMIT = 20; export type CalendarSetting = { id: string; /** Display name override; empty means "use the feed's own name". */ name: string; url: string; tone: CalendarTone; enabled: boolean; }; export type Settings = { schema: 1; updatedAt: string; calendars: CalendarSetting[]; }; export type AuthState = { passwordHash: string; sessionSecret: string; }; const dataDir = () => process.env.ORGANIZER_DATA_DIR || "/data"; const settingsPath = () => path.join(dataDir(), "settings.json"); const authPath = () => path.join(dataDir(), "auth.json"); const historyDir = () => path.join(dataDir(), "history"); export function validCalendarUrl(value: unknown) { let url: URL; try { url = new URL(String(value).trim()); } catch { return null; } if (url.protocol !== "https:" || url.hostname !== "calendar.google.com" || !url.pathname.endsWith("/basic.ics")) return null; if (!/^\/calendar\/ical\/[A-Za-z0-9._~%+@-]+\/(private-[A-Za-z0-9._~%+@-]+|public)\/basic\.ics$/.test(url.pathname)) return null; return url.toString(); } /** "…/ical/fam…%40group…/private-••••3854/basic.ics" — enough to tell feeds apart, not enough to use one. */ export function maskCalendarUrl(url: string) { const match = /\/calendar\/ical\/([^/]+)\/(private-[^/]+|public)\/basic\.ics$/.exec(new URL(url).pathname); if (!match) return "calendar.google.com/…"; const owner = decodeURIComponent(match[1]); const shortOwner = owner.length > 18 ? `${owner.slice(0, 8)}…${owner.slice(owner.indexOf("@"))}` : owner; const key = match[2] === "public" ? "public" : `private-••••${match[2].slice(-4)}`; return `${shortOwner} · ${key}`; } function normalizeSettings(raw: unknown): Settings { const value = (raw ?? {}) as Partial; const calendars = Array.isArray(value.calendars) ? value.calendars : []; return { schema: 1, updatedAt: typeof value.updatedAt === "string" ? value.updatedAt : new Date(0).toISOString(), calendars: calendars .map((entry) => { const url = validCalendarUrl(entry?.url); if (!url) return null; return { id: typeof entry.id === "string" && entry.id ? entry.id : randomUUID(), name: typeof entry.name === "string" ? entry.name.trim().slice(0, 50) : "", url, tone: CALENDAR_TONES.includes(entry.tone as CalendarTone) ? (entry.tone as CalendarTone) : "cyan", enabled: entry.enabled !== false, } satisfies CalendarSetting; }) .filter((entry): entry is CalendarSetting => entry !== null) .slice(0, MAX_CALENDARS), }; } async function readJson(file: string) { return JSON.parse(await readFile(file, "utf8")) as unknown; } async function writeJsonAtomic(file: string, value: unknown) { const temporary = `${file}.${process.pid}.${Date.now()}.tmp`; await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 }); await rename(temporary, file); } // All writes go through one queue so concurrent saves cannot interleave. let writeQueue: Promise = Promise.resolve(); function serialized(task: () => Promise) { const run = writeQueue.then(task, task); writeQueue = run.catch(() => undefined); return run; } export async function readSettings(): Promise { try { return normalizeSettings(await readJson(settingsPath())); } catch { return normalizeSettings({}); } } export type HistoryEntry = { id: string; savedAt: string; calendarCount: number; note: string }; async function pruneHistory() { const files = (await readdir(historyDir())).filter((name) => name.endsWith(".json")).sort(); for (const name of files.slice(0, Math.max(0, files.length - HISTORY_LIMIT))) { await unlink(path.join(historyDir(), name)).catch(() => undefined); } } /** Saves new settings, first snapshotting the current ones into history. */ export function saveSettings(calendars: CalendarSetting[], note: string) { return serialized(async () => { const current = await readSettings(); const stamp = new Date().toISOString(); const snapshotId = `${stamp.replace(/[:.]/g, "-")}`; await writeJsonAtomic(path.join(historyDir(), `${snapshotId}.json`), { ...current, note }); await pruneHistory(); const next = normalizeSettings({ schema: 1, updatedAt: stamp, calendars }); await writeJsonAtomic(settingsPath(), next); return next; }); } export async function listHistory(): Promise { const files = (await readdir(historyDir()).catch(() => [] as string[])).filter((name) => name.endsWith(".json")).sort().reverse(); const entries: HistoryEntry[] = []; for (const name of files) { try { const raw = (await readJson(path.join(historyDir(), name))) as Settings & { note?: string }; entries.push({ id: name.slice(0, -5), savedAt: raw.updatedAt, calendarCount: Array.isArray(raw.calendars) ? raw.calendars.length : 0, note: typeof raw.note === "string" ? raw.note : "", }); } catch { // Skip an unreadable snapshot. } } return entries; } export async function readHistorySnapshot(id: string) { if (!/^[0-9TZ-]+$/.test(id)) return null; try { return normalizeSettings(await readJson(path.join(historyDir(), `${id}.json`))); } catch { return null; } } export async function readAuth(): Promise { const raw = (await readJson(authPath())) as Partial; if (typeof raw.sessionSecret !== "string" || raw.sessionSecret.length < 32) throw new Error("auth.json is missing a session secret"); return { passwordHash: typeof raw.passwordHash === "string" ? raw.passwordHash : "", sessionSecret: raw.sessionSecret }; } export function writeAuth(next: AuthState) { return serialized(() => writeJsonAtomic(authPath(), next)); }