feat(hobbs-organizer): v1.1.0 password-protected LAN-only admin for calendar links
- /admin: first-visit password setup (scrypt), signed 30-day session cookie, calendars add/remove/reorder/rename/color/hide, masked URLs, per-feed test, history (20) with restore; /photo-admin -> /admin#photos placeholder - settings in local /data (settings.json + auth.json + history/), seeded once from the calendar secret; dashboard + health read from settings - start.mjs drops privileges after reading secrets and runs a front proxy that stamps the real client IP; admin refuses non-LAN and proxied requests - deploy: HOBBS_DATA_DIR=/var/lib/hobbs-organizer/data, image 1.1.0 (1.0.0 kept) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01E9NnVEico3WvFxLyjy1iW3
This commit is contained in:
@@ -0,0 +1,167 @@
|
||||
import { createHmac, randomBytes, scrypt as scryptCallback, timingSafeEqual } from "node:crypto";
|
||||
import { promisify } from "node:util";
|
||||
import { readAuth, writeAuth } from "./store";
|
||||
|
||||
const scrypt = promisify(scryptCallback) as (password: string, salt: Buffer, keylen: number, options: object) => Promise<Buffer>;
|
||||
const SCRYPT = { N: 1 << 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
|
||||
const SESSION_COOKIE = "hfo_admin";
|
||||
const SESSION_SECONDS = 30 * 24 * 60 * 60;
|
||||
export const MIN_PASSWORD_LENGTH = 8;
|
||||
|
||||
// ---------- network policy ----------
|
||||
|
||||
function ipv4ToInt(ip: string) {
|
||||
const parts = ip.split(".").map(Number);
|
||||
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return null;
|
||||
return ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0;
|
||||
}
|
||||
|
||||
function inCidr(ip: string, cidr: string) {
|
||||
const [base, bitsText] = cidr.trim().split("/");
|
||||
const address = ipv4ToInt(ip);
|
||||
const network = ipv4ToInt(base);
|
||||
const bits = Number(bitsText ?? 32);
|
||||
if (address === null || network === null || !(bits >= 0 && bits <= 32)) return false;
|
||||
const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
|
||||
return (address & mask) === (network & mask);
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin is reachable only from a direct LAN connection. The container's front proxy
|
||||
* stamps x-hfo-client-ip with the TCP peer and x-hfo-forwarded when the request came
|
||||
* through another proxy (e.g. a future Traefik route), which is always refused.
|
||||
*/
|
||||
export function isAdminNetworkAllowed(headers: Headers) {
|
||||
if (headers.get("x-hfo-forwarded")) return false;
|
||||
const ip = headers.get("x-hfo-client-ip") || "";
|
||||
const allowed = (process.env.ADMIN_ALLOWED_CIDRS || "192.168.86.0/24,127.0.0.1/32").split(",");
|
||||
return allowed.some((cidr) => inCidr(ip, cidr));
|
||||
}
|
||||
|
||||
export function clientIp(headers: Headers) {
|
||||
return headers.get("x-hfo-client-ip") || "unknown";
|
||||
}
|
||||
|
||||
/** Mutating requests must come from this same origin (CSRF guard on top of SameSite=Strict). */
|
||||
export function sameOrigin(request: Request) {
|
||||
const origin = request.headers.get("origin");
|
||||
const host = request.headers.get("host");
|
||||
if (!origin || !host) return false;
|
||||
try {
|
||||
return new URL(origin).host === host;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- passwords ----------
|
||||
|
||||
export async function hashPassword(password: string) {
|
||||
const salt = randomBytes(16);
|
||||
const key = await scrypt(password, salt, 32, SCRYPT);
|
||||
return `scrypt$${SCRYPT.N}$${SCRYPT.r}$${SCRYPT.p}$${salt.toString("base64url")}$${key.toString("base64url")}`;
|
||||
}
|
||||
|
||||
export async function verifyPassword(password: string, stored: string) {
|
||||
const [scheme, n, r, p, saltText, keyText] = stored.split("$");
|
||||
if (scheme !== "scrypt" || !saltText || !keyText) return false;
|
||||
const expected = Buffer.from(keyText, "base64url");
|
||||
const actual = await scrypt(password, Buffer.from(saltText, "base64url"), expected.length, {
|
||||
N: Number(n),
|
||||
r: Number(r),
|
||||
p: Number(p),
|
||||
maxmem: 64 * 1024 * 1024,
|
||||
});
|
||||
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
||||
}
|
||||
|
||||
// ---------- login throttling (in memory, per client IP) ----------
|
||||
|
||||
const failures = new Map<string, { count: number; lockedUntil: number }>();
|
||||
|
||||
export function loginLockedFor(ip: string) {
|
||||
const entry = failures.get(ip);
|
||||
return entry && entry.lockedUntil > Date.now() ? Math.ceil((entry.lockedUntil - Date.now()) / 1000) : 0;
|
||||
}
|
||||
|
||||
export function recordLoginFailure(ip: string) {
|
||||
const entry = failures.get(ip) ?? { count: 0, lockedUntil: 0 };
|
||||
entry.count += 1;
|
||||
if (entry.count >= 5) entry.lockedUntil = Date.now() + Math.min(15 * 60, 30 * 2 ** (entry.count - 5)) * 1000;
|
||||
failures.set(ip, entry);
|
||||
}
|
||||
|
||||
export function clearLoginFailures(ip: string) {
|
||||
failures.delete(ip);
|
||||
}
|
||||
|
||||
// ---------- sessions ----------
|
||||
|
||||
function sign(payload: string, secret: string) {
|
||||
return createHmac("sha256", secret).update(payload).digest("base64url");
|
||||
}
|
||||
|
||||
export function sessionCookie(secret: string) {
|
||||
const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + SESSION_SECONDS })).toString("base64url");
|
||||
const value = `${payload}.${sign(payload, secret)}`;
|
||||
return `${SESSION_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${SESSION_SECONDS}`;
|
||||
}
|
||||
|
||||
export function clearedSessionCookie() {
|
||||
return `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`;
|
||||
}
|
||||
|
||||
function readCookie(headers: Headers, name: string) {
|
||||
for (const part of (headers.get("cookie") || "").split(";")) {
|
||||
const [key, ...rest] = part.trim().split("=");
|
||||
if (key === name) return rest.join("=");
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export async function hasValidSession(headers: Headers) {
|
||||
const value = readCookie(headers, SESSION_COOKIE);
|
||||
const [payload, signature] = value.split(".");
|
||||
if (!payload || !signature) return false;
|
||||
const auth = await readAuth();
|
||||
if (!auth.passwordHash) return false;
|
||||
const expected = Buffer.from(sign(payload, auth.sessionSecret));
|
||||
const actual = Buffer.from(signature);
|
||||
if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return false;
|
||||
try {
|
||||
const { exp } = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as { exp: number };
|
||||
return typeof exp === "number" && exp > Date.now() / 1000;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Sets a new password and rotates the session secret, signing out every other session. */
|
||||
export async function setPassword(password: string) {
|
||||
const sessionSecret = randomBytes(32).toString("base64url");
|
||||
await writeAuth({ passwordHash: await hashPassword(password), sessionSecret });
|
||||
return sessionCookie(sessionSecret);
|
||||
}
|
||||
|
||||
// ---------- route helpers ----------
|
||||
|
||||
export function json(body: unknown, status = 200, extraHeaders: Record<string, string> = {}) {
|
||||
return Response.json(body, { status, headers: { "Cache-Control": "no-store", ...extraHeaders } });
|
||||
}
|
||||
|
||||
/** Returns an error Response when the caller may not use admin APIs, otherwise null. */
|
||||
export async function requireAdmin(request: Request, { mutating = false } = {}) {
|
||||
if (!isAdminNetworkAllowed(request.headers)) return json({ error: "Admin is only available on the home network." }, 403);
|
||||
if (mutating && !sameOrigin(request)) return json({ error: "Cross-origin request refused." }, 403);
|
||||
if (!(await hasValidSession(request.headers))) return json({ error: "Sign in required." }, 401);
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function readJsonBody<T>(request: Request): Promise<T | null> {
|
||||
if (!(request.headers.get("content-type") || "").includes("application/json")) return null;
|
||||
try {
|
||||
return (await request.json()) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import ICAL from "ical.js";
|
||||
|
||||
import type { CalendarTone } from "./store";
|
||||
|
||||
export type CalendarEvent = {
|
||||
id: string;
|
||||
calendar: string;
|
||||
title: string;
|
||||
location?: string;
|
||||
start: string;
|
||||
end: string;
|
||||
allDay: boolean;
|
||||
tone: CalendarTone;
|
||||
};
|
||||
|
||||
const maxFeedBytes = 5 * 1024 * 1024;
|
||||
const maxOccurrencesPerEvent = 10_000;
|
||||
|
||||
function cleanText(value: unknown, fallback: string, maxLength: number) {
|
||||
return String(value ?? fallback).replace(/\s+/g, " ").trim().slice(0, maxLength) || fallback;
|
||||
}
|
||||
|
||||
function calendarDate(value: ICAL.Time) {
|
||||
return `${String(value.year).padStart(4, "0")}-${String(value.month).padStart(2, "0")}-${String(value.day).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function organizerDate(date: Date) {
|
||||
const parts = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: process.env.ORGANIZER_TIMEZONE || "America/Chicago",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
}).formatToParts(date);
|
||||
const value = (part: string) => parts.find((entry) => entry.type === part)?.value ?? "";
|
||||
return `${value("year")}-${value("month")}-${value("day")}`;
|
||||
}
|
||||
|
||||
export function addCalendarDays(isoDate: string, days: number) {
|
||||
const [year, month, day] = isoDate.split("-").map(Number);
|
||||
const value = new Date(Date.UTC(year, month - 1, day + days));
|
||||
return value.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function hashId(value: string) {
|
||||
let hash = 0x811c9dc5;
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
hash ^= value.charCodeAt(index);
|
||||
hash = Math.imul(hash, 0x01000193);
|
||||
}
|
||||
return (hash >>> 0).toString(36);
|
||||
}
|
||||
|
||||
async function readLimitedText(response: Response) {
|
||||
const declaredLength = Number(response.headers.get("content-length") ?? 0);
|
||||
if (declaredLength > maxFeedBytes) throw new Error("Calendar feed is too large");
|
||||
if (!response.body) return "";
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let total = 0;
|
||||
let text = "";
|
||||
|
||||
while (true) {
|
||||
const chunk = await reader.read();
|
||||
if (chunk.done) break;
|
||||
total += chunk.value.byteLength;
|
||||
if (total > maxFeedBytes) {
|
||||
await reader.cancel();
|
||||
throw new Error("Calendar feed is too large");
|
||||
}
|
||||
text += decoder.decode(chunk.value, { stream: true });
|
||||
}
|
||||
|
||||
return text + decoder.decode();
|
||||
}
|
||||
|
||||
function componentString(component: ICAL.Component, name: string) {
|
||||
const value = component.getFirstPropertyValue(name);
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
function isCancelled(event: ICAL.Event) {
|
||||
return componentString(event.component, "status").toUpperCase() === "CANCELLED";
|
||||
}
|
||||
|
||||
function detach(component: ICAL.Component) {
|
||||
return new ICAL.Component(structuredClone(component.toJSON()));
|
||||
}
|
||||
|
||||
function eventIsInWindow(
|
||||
start: ICAL.Time,
|
||||
end: ICAL.Time,
|
||||
windowStart: number,
|
||||
horizon: number,
|
||||
windowStartDate: string,
|
||||
horizonDate: string,
|
||||
) {
|
||||
if (start.isDate) {
|
||||
return calendarDate(end) > windowStartDate && calendarDate(start) <= horizonDate;
|
||||
}
|
||||
return end.toJSDate().getTime() > windowStart && start.toJSDate().getTime() <= horizon;
|
||||
}
|
||||
|
||||
function occurrenceIsPastHorizon(start: ICAL.Time, horizon: number, horizonDate: string) {
|
||||
return start.isDate ? calendarDate(start) > horizonDate : start.toJSDate().getTime() > horizon;
|
||||
}
|
||||
|
||||
function serializeOccurrence(
|
||||
event: ICAL.Event,
|
||||
start: ICAL.Time,
|
||||
end: ICAL.Time,
|
||||
calendar: string,
|
||||
tone: CalendarTone,
|
||||
feedIndex: number,
|
||||
) {
|
||||
const allDay = start.isDate;
|
||||
const startValue = allDay ? calendarDate(start) : start.toJSDate().toISOString();
|
||||
const endValue = allDay ? calendarDate(end) : end.toJSDate().toISOString();
|
||||
const uid = cleanText(event.uid, "event", 180);
|
||||
const location = cleanText(event.location, "", 120);
|
||||
|
||||
return {
|
||||
id: hashId(`${feedIndex}|${uid}|${startValue}`),
|
||||
calendar,
|
||||
title: cleanText(event.summary, "Busy", 140),
|
||||
...(location ? { location } : {}),
|
||||
start: startValue,
|
||||
end: endValue,
|
||||
allDay,
|
||||
tone,
|
||||
} satisfies CalendarEvent;
|
||||
}
|
||||
|
||||
export type FeedOptions = { feedIndex: number; tone: CalendarTone; nameOverride: string };
|
||||
|
||||
function expandCalendar(
|
||||
ics: string,
|
||||
{ feedIndex, tone, nameOverride }: FeedOptions,
|
||||
windowStart: number,
|
||||
horizon: number,
|
||||
windowStartDate: string,
|
||||
horizonDate: string,
|
||||
) {
|
||||
const root = new ICAL.Component(ICAL.parse(ics));
|
||||
for (const timezone of root.getAllSubcomponents("vtimezone")) {
|
||||
try {
|
||||
ICAL.TimezoneService.register(timezone);
|
||||
} catch {
|
||||
// A feed may repeat a timezone that was already registered.
|
||||
}
|
||||
}
|
||||
|
||||
const sourceName = cleanText(root.getFirstPropertyValue("x-wr-calname"), `Calendar ${feedIndex + 1}`, 50);
|
||||
const calendar = nameOverride || (sourceName.includes("@") ? "Personal" : sourceName);
|
||||
const components = root.getAllSubcomponents("vevent");
|
||||
const exceptions = new Map<string, ICAL.Component[]>();
|
||||
|
||||
for (const component of components) {
|
||||
if (!component.hasProperty("recurrence-id")) continue;
|
||||
const uid = componentString(component, "uid");
|
||||
if (!uid) continue;
|
||||
exceptions.set(uid, [...(exceptions.get(uid) ?? []), component]);
|
||||
}
|
||||
|
||||
const items: CalendarEvent[] = [];
|
||||
for (const component of components) {
|
||||
if (component.hasProperty("recurrence-id")) continue;
|
||||
|
||||
try {
|
||||
const event = new ICAL.Event(detach(component));
|
||||
for (const exception of exceptions.get(event.uid) ?? []) {
|
||||
event.relateException(detach(exception));
|
||||
}
|
||||
if (isCancelled(event)) continue;
|
||||
|
||||
if (!event.isRecurring()) {
|
||||
if (eventIsInWindow(event.startDate, event.endDate, windowStart, horizon, windowStartDate, horizonDate)) {
|
||||
items.push(serializeOccurrence(event, event.startDate, event.endDate, calendar, tone, feedIndex));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const iterator = event.iterator();
|
||||
for (let count = 0; count < maxOccurrencesPerEvent; count += 1) {
|
||||
const occurrence = iterator.next();
|
||||
if (!occurrence) break;
|
||||
if (occurrenceIsPastHorizon(occurrence, horizon, horizonDate)) break;
|
||||
|
||||
const details = event.getOccurrenceDetails(occurrence);
|
||||
if (isCancelled(details.item)) continue;
|
||||
if (eventIsInWindow(details.startDate, details.endDate, windowStart, horizon, windowStartDate, horizonDate)) {
|
||||
items.push(serializeOccurrence(details.item, details.startDate, details.endDate, calendar, tone, feedIndex));
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore a malformed event while keeping the rest of the calendar usable.
|
||||
}
|
||||
}
|
||||
|
||||
return { calendar, sourceName, eventCount: components.length, items };
|
||||
}
|
||||
|
||||
export async function readCalendar(
|
||||
url: string,
|
||||
options: FeedOptions,
|
||||
windowStart: number,
|
||||
horizon: number,
|
||||
windowStartDate: string,
|
||||
horizonDate: string,
|
||||
) {
|
||||
let currentUrl = url;
|
||||
let response: Response | undefined;
|
||||
for (let redirectCount = 0; redirectCount <= 3; redirectCount += 1) {
|
||||
const validatedUrl = new URL(currentUrl);
|
||||
if (validatedUrl.protocol !== "https:" || validatedUrl.hostname !== "calendar.google.com" || !validatedUrl.pathname.endsWith("/basic.ics")) {
|
||||
throw new Error("Calendar redirect host is not allowed");
|
||||
}
|
||||
response = await fetch(validatedUrl, {
|
||||
headers: { Accept: "text/calendar" },
|
||||
redirect: "manual",
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
if (![301, 302, 303, 307, 308].includes(response.status)) break;
|
||||
const location = response.headers.get("location");
|
||||
if (!location || redirectCount === 3) throw new Error("Calendar feed redirected too many times");
|
||||
currentUrl = new URL(location, validatedUrl).toString();
|
||||
}
|
||||
if (!response) throw new Error("Calendar feed request failed");
|
||||
if (!response.ok) throw new Error("Calendar feed request failed");
|
||||
return expandCalendar(await readLimitedText(response), options, windowStart, horizon, windowStartDate, horizonDate);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
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<Settings>;
|
||||
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<unknown> = Promise.resolve();
|
||||
function serialized<T>(task: () => Promise<T>) {
|
||||
const run = writeQueue.then(task, task);
|
||||
writeQueue = run.catch(() => undefined);
|
||||
return run;
|
||||
}
|
||||
|
||||
export async function readSettings(): Promise<Settings> {
|
||||
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<HistoryEntry[]> {
|
||||
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<AuthState> {
|
||||
const raw = (await readJson(authPath())) as Partial<AuthState>;
|
||||
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));
|
||||
}
|
||||
Reference in New Issue
Block a user