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,60 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { json, readJsonBody, requireAdmin } from "../../../_lib/auth";
|
||||
import {
|
||||
CALENDAR_TONES,
|
||||
type CalendarSetting,
|
||||
type CalendarTone,
|
||||
MAX_CALENDARS,
|
||||
maskCalendarUrl,
|
||||
readSettings,
|
||||
saveSettings,
|
||||
validCalendarUrl,
|
||||
} from "../../../_lib/store";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
function publicView(calendars: CalendarSetting[]) {
|
||||
return calendars.map(({ id, name, tone, enabled, url }) => ({ id, name, tone, enabled, masked: maskCalendarUrl(url) }));
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const denied = await requireAdmin(request);
|
||||
if (denied) return denied;
|
||||
const settings = await readSettings();
|
||||
return json({ calendars: publicView(settings.calendars), updatedAt: settings.updatedAt, tones: CALENDAR_TONES });
|
||||
}
|
||||
|
||||
type IncomingCalendar = { id?: string; name?: string; tone?: string; enabled?: boolean; url?: string };
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
const denied = await requireAdmin(request, { mutating: true });
|
||||
if (denied) return denied;
|
||||
const body = await readJsonBody<{ calendars?: IncomingCalendar[] }>(request);
|
||||
if (!body || !Array.isArray(body.calendars)) return json({ error: "Expected a calendars list." }, 400);
|
||||
if (body.calendars.length > MAX_CALENDARS) return json({ error: `At most ${MAX_CALENDARS} calendars.` }, 400);
|
||||
|
||||
const existing = new Map((await readSettings()).calendars.map((calendar) => [calendar.id, calendar]));
|
||||
const next: CalendarSetting[] = [];
|
||||
for (const [index, entry] of body.calendars.entries()) {
|
||||
const label = entry.name?.trim() || `Calendar ${index + 1}`;
|
||||
const previous = entry.id ? existing.get(entry.id) : undefined;
|
||||
if (entry.id && !previous) return json({ error: `${label}: unknown calendar; reload the page.` }, 409);
|
||||
const suppliedUrl = typeof entry.url === "string" && entry.url.trim() ? entry.url : "";
|
||||
const url = suppliedUrl ? validCalendarUrl(suppliedUrl) : previous?.url;
|
||||
if (!url) {
|
||||
return json({ error: `${label}: paste a Google Calendar "Secret address in iCal format" (https://calendar.google.com/…/basic.ics).` }, 400);
|
||||
}
|
||||
next.push({
|
||||
id: previous?.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,
|
||||
});
|
||||
}
|
||||
if (new Set(next.map((calendar) => calendar.url)).size !== next.length) return json({ error: "The same calendar is listed twice." }, 400);
|
||||
|
||||
const saved = await saveSettings(next, `Saved ${next.length} calendar(s)`);
|
||||
console.log(`[admin] calendars saved (${saved.calendars.length})`);
|
||||
return json({ calendars: publicView(saved.calendars), updatedAt: saved.updatedAt });
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import { json, readJsonBody, requireAdmin } from "../../../../_lib/auth";
|
||||
import { addCalendarDays, organizerDate, readCalendar } from "../../../../_lib/calendar-feed";
|
||||
import { readSettings, validCalendarUrl } from "../../../../_lib/store";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Fetches one feed (saved by id, or a not-yet-saved URL) and reports what it found. */
|
||||
export async function POST(request: Request) {
|
||||
const denied = await requireAdmin(request, { mutating: true });
|
||||
if (denied) return denied;
|
||||
const body = await readJsonBody<{ id?: string; url?: string }>(request);
|
||||
let url: string | null = null;
|
||||
if (body?.url) url = validCalendarUrl(body.url);
|
||||
else if (body?.id) url = (await readSettings()).calendars.find((calendar) => calendar.id === body.id)?.url ?? null;
|
||||
if (!url) return json({ ok: false, error: "Not a Google Calendar basic.ics address." }, 400);
|
||||
|
||||
const now = Date.now();
|
||||
const today = organizerDate(new Date(now));
|
||||
try {
|
||||
const result = await readCalendar(
|
||||
url,
|
||||
{ feedIndex: 0, tone: "cyan", nameOverride: "" },
|
||||
now,
|
||||
now + 60 * 24 * 60 * 60 * 1_000,
|
||||
today,
|
||||
addCalendarDays(today, 60),
|
||||
);
|
||||
return json({ ok: true, sourceName: result.sourceName, eventCount: result.eventCount, upcoming: result.items.length });
|
||||
} catch (error) {
|
||||
return json({ ok: false, error: error instanceof Error ? error.message : "Fetch failed" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { json, readJsonBody, requireAdmin } from "../../../_lib/auth";
|
||||
import { listHistory, readHistorySnapshot, saveSettings } from "../../../_lib/store";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const denied = await requireAdmin(request);
|
||||
if (denied) return denied;
|
||||
return json({ history: await listHistory() });
|
||||
}
|
||||
|
||||
/** Reverts calendars to a snapshot. The current state is itself snapshotted first, so a revert can be undone. */
|
||||
export async function POST(request: Request) {
|
||||
const denied = await requireAdmin(request, { mutating: true });
|
||||
if (denied) return denied;
|
||||
const body = await readJsonBody<{ id?: string }>(request);
|
||||
const snapshot = body?.id ? await readHistorySnapshot(body.id) : null;
|
||||
if (!snapshot) return json({ error: "That version no longer exists." }, 404);
|
||||
const saved = await saveSettings(snapshot.calendars, `Reverted to version from ${snapshot.updatedAt}`);
|
||||
console.log(`[admin] calendars reverted to ${body?.id}`);
|
||||
return json({ ok: true, updatedAt: saved.updatedAt });
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import {
|
||||
clearLoginFailures,
|
||||
clientIp,
|
||||
isAdminNetworkAllowed,
|
||||
json,
|
||||
loginLockedFor,
|
||||
readJsonBody,
|
||||
recordLoginFailure,
|
||||
sameOrigin,
|
||||
sessionCookie,
|
||||
verifyPassword,
|
||||
} from "../../../_lib/auth";
|
||||
import { readAuth } from "../../../_lib/store";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (!isAdminNetworkAllowed(request.headers)) return json({ error: "Admin is only available on the home network." }, 403);
|
||||
if (!sameOrigin(request)) return json({ error: "Cross-origin request refused." }, 403);
|
||||
const ip = clientIp(request.headers);
|
||||
const locked = loginLockedFor(ip);
|
||||
if (locked) return json({ error: `Too many attempts. Try again in ${locked} seconds.` }, 429);
|
||||
|
||||
const auth = await readAuth();
|
||||
if (!auth.passwordHash) return json({ error: "No password is set yet." }, 409);
|
||||
const body = await readJsonBody<{ password?: string }>(request);
|
||||
const password = typeof body?.password === "string" ? body.password : "";
|
||||
if (!password || !(await verifyPassword(password, auth.passwordHash))) {
|
||||
recordLoginFailure(ip);
|
||||
console.warn(`[admin] failed login from ${ip}`);
|
||||
return json({ error: "Wrong password." }, 401);
|
||||
}
|
||||
clearLoginFailures(ip);
|
||||
console.log(`[admin] login from ${ip}`);
|
||||
return json({ ok: true }, 200, { "Set-Cookie": sessionCookie(auth.sessionSecret) });
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { clearedSessionCookie, json } from "../../../_lib/auth";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST() {
|
||||
return json({ ok: true }, 200, { "Set-Cookie": clearedSessionCookie() });
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { json, MIN_PASSWORD_LENGTH, readJsonBody, requireAdmin, setPassword, verifyPassword } from "../../../_lib/auth";
|
||||
import { readAuth } from "../../../_lib/store";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Changes the password; signs out every other session. */
|
||||
export async function POST(request: Request) {
|
||||
const denied = await requireAdmin(request, { mutating: true });
|
||||
if (denied) return denied;
|
||||
const body = await readJsonBody<{ currentPassword?: string; newPassword?: string }>(request);
|
||||
const current = typeof body?.currentPassword === "string" ? body.currentPassword : "";
|
||||
const next = typeof body?.newPassword === "string" ? body.newPassword : "";
|
||||
if (!(await verifyPassword(current, (await readAuth()).passwordHash))) return json({ error: "Current password is wrong." }, 401);
|
||||
if (next.length < MIN_PASSWORD_LENGTH || next.length > 256) return json({ error: `Use at least ${MIN_PASSWORD_LENGTH} characters.` }, 400);
|
||||
return json({ ok: true }, 200, { "Set-Cookie": await setPassword(next) });
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { isAdminNetworkAllowed, json, MIN_PASSWORD_LENGTH, readJsonBody, sameOrigin, setPassword } from "../../../_lib/auth";
|
||||
import { readAuth } from "../../../_lib/store";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** First-run only: sets the admin password when none exists yet. */
|
||||
export async function POST(request: Request) {
|
||||
if (!isAdminNetworkAllowed(request.headers)) return json({ error: "Admin is only available on the home network." }, 403);
|
||||
if (!sameOrigin(request)) return json({ error: "Cross-origin request refused." }, 403);
|
||||
if ((await readAuth()).passwordHash) return json({ error: "A password is already set. Sign in instead." }, 409);
|
||||
const body = await readJsonBody<{ password?: string }>(request);
|
||||
const password = typeof body?.password === "string" ? body.password : "";
|
||||
if (password.length < MIN_PASSWORD_LENGTH || password.length > 256) {
|
||||
return json({ error: `Use at least ${MIN_PASSWORD_LENGTH} characters.` }, 400);
|
||||
}
|
||||
return json({ ok: true }, 200, { "Set-Cookie": await setPassword(password) });
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { hasValidSession, isAdminNetworkAllowed, json } from "../../../_lib/auth";
|
||||
import { readAuth } from "../../../_lib/store";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
if (!isAdminNetworkAllowed(request.headers)) return json({ error: "Admin is only available on the home network." }, 403);
|
||||
const { passwordHash } = await readAuth();
|
||||
return json({ setupRequired: !passwordHash, authenticated: passwordHash ? await hasValidSession(request.headers) : false });
|
||||
}
|
||||
@@ -1,297 +1,47 @@
|
||||
import ICAL from "ical.js";
|
||||
|
||||
type CalendarTone = "cyan" | "amber" | "violet" | "emerald" | "rose";
|
||||
|
||||
type CalendarEvent = {
|
||||
id: string;
|
||||
calendar: string;
|
||||
title: string;
|
||||
location?: string;
|
||||
start: string;
|
||||
end: string;
|
||||
allDay: boolean;
|
||||
tone: CalendarTone;
|
||||
};
|
||||
|
||||
const tones: CalendarTone[] = ["cyan", "amber", "violet", "emerald", "rose"];
|
||||
const maxFeedBytes = 5 * 1024 * 1024;
|
||||
const maxOccurrencesPerEvent = 10_000;
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
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")}`;
|
||||
}
|
||||
|
||||
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")}`;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
function parseFeedUrls() {
|
||||
const raw = process.env.CALENDAR_ICAL_URLS;
|
||||
if (!raw) return [];
|
||||
|
||||
const values = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(values) || values.length < 1 || values.length > 10) {
|
||||
throw new Error("Calendar feed configuration is invalid");
|
||||
}
|
||||
|
||||
return values.map((value) => {
|
||||
const url = new URL(String(value));
|
||||
if (url.protocol !== "https:" || url.hostname !== "calendar.google.com" || !url.pathname.endsWith("/basic.ics")) {
|
||||
throw new Error("Calendar feed host is not allowed");
|
||||
}
|
||||
return url.toString();
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
function expandCalendar(
|
||||
ics: string,
|
||||
feedIndex: number,
|
||||
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 = sourceName.includes("@") ? "Personal" : sourceName;
|
||||
const tone = tones[feedIndex % tones.length];
|
||||
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, items };
|
||||
}
|
||||
|
||||
async function readCalendar(
|
||||
url: string,
|
||||
feedIndex: number,
|
||||
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), feedIndex, windowStart, horizon, windowStartDate, horizonDate);
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
let urls: string[];
|
||||
try {
|
||||
urls = parseFeedUrls();
|
||||
} catch {
|
||||
return Response.json({ items: [], calendarsAvailable: 0, calendarsTotal: 0, updatedAt: new Date().toISOString() }, { status: 503 });
|
||||
}
|
||||
|
||||
if (!urls.length) {
|
||||
return Response.json({ items: [], calendarsAvailable: 0, calendarsTotal: 0, updatedAt: new Date().toISOString() }, { status: 503 });
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const windowStart = now - 45 * 24 * 60 * 60 * 1_000;
|
||||
const horizon = now + 60 * 24 * 60 * 60 * 1_000;
|
||||
const today = organizerDate(new Date(now));
|
||||
const windowStartDate = addCalendarDays(today, -45);
|
||||
const horizonDate = addCalendarDays(today, 60);
|
||||
const results = await Promise.allSettled(
|
||||
urls.map((url, index) => readCalendar(url, index, windowStart, horizon, windowStartDate, horizonDate)),
|
||||
);
|
||||
const successful = results.filter((result): result is PromiseFulfilledResult<Awaited<ReturnType<typeof readCalendar>>> => result.status === "fulfilled");
|
||||
const items = successful
|
||||
.flatMap((result) => result.value.items)
|
||||
.filter((item, index, all) => all.findIndex((candidate) => candidate.id === item.id) === index)
|
||||
.sort((left, right) => {
|
||||
const leftValue = left.allDay ? `${left.start}T00:00:00` : left.start;
|
||||
const rightValue = right.allDay ? `${right.start}T00:00:00` : right.start;
|
||||
return leftValue.localeCompare(rightValue);
|
||||
})
|
||||
.slice(0, 160);
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
items,
|
||||
calendarsAvailable: successful.length,
|
||||
calendarsTotal: urls.length,
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
status: successful.length ? 200 : 503,
|
||||
headers: { "Cache-Control": "private, max-age=60, stale-while-revalidate=240" },
|
||||
},
|
||||
);
|
||||
}
|
||||
import { addCalendarDays, organizerDate, readCalendar } from "../../_lib/calendar-feed";
|
||||
import { readSettings } from "../../_lib/store";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET() {
|
||||
const { calendars } = await readSettings();
|
||||
const feeds = calendars.filter((calendar) => calendar.enabled);
|
||||
if (!feeds.length) {
|
||||
return Response.json({ items: [], calendarsAvailable: 0, calendarsTotal: 0, updatedAt: new Date().toISOString() }, { status: 503 });
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const windowStart = now - 45 * 24 * 60 * 60 * 1_000;
|
||||
const horizon = now + 60 * 24 * 60 * 60 * 1_000;
|
||||
const today = organizerDate(new Date(now));
|
||||
const windowStartDate = addCalendarDays(today, -45);
|
||||
const horizonDate = addCalendarDays(today, 60);
|
||||
const results = await Promise.allSettled(
|
||||
feeds.map((feed, feedIndex) =>
|
||||
readCalendar(feed.url, { feedIndex, tone: feed.tone, nameOverride: feed.name }, windowStart, horizon, windowStartDate, horizonDate),
|
||||
),
|
||||
);
|
||||
const successful = results.filter((result): result is PromiseFulfilledResult<Awaited<ReturnType<typeof readCalendar>>> => result.status === "fulfilled");
|
||||
const items = successful
|
||||
.flatMap((result) => result.value.items)
|
||||
.filter((item, index, all) => all.findIndex((candidate) => candidate.id === item.id) === index)
|
||||
.sort((left, right) => {
|
||||
const leftValue = left.allDay ? `${left.start}T00:00:00` : left.start;
|
||||
const rightValue = right.allDay ? `${right.start}T00:00:00` : right.start;
|
||||
return leftValue.localeCompare(rightValue);
|
||||
})
|
||||
.slice(0, 160);
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
items,
|
||||
calendarsAvailable: successful.length,
|
||||
calendarsTotal: feeds.length,
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
status: successful.length ? 200 : 503,
|
||||
headers: { "Cache-Control": "private, max-age=60, stale-while-revalidate=240" },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,20 +1,24 @@
|
||||
import { readAuth, readSettings } from "../../_lib/store";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET() {
|
||||
let calendarConfigurationValid = false;
|
||||
const { calendars } = await readSettings();
|
||||
let adminConfigured = false;
|
||||
try {
|
||||
const parsed = JSON.parse(process.env.CALENDAR_ICAL_URLS || "[]") as unknown;
|
||||
calendarConfigurationValid = Array.isArray(parsed) && parsed.length > 0;
|
||||
adminConfigured = Boolean((await readAuth()).passwordHash);
|
||||
} catch {
|
||||
calendarConfigurationValid = false;
|
||||
adminConfigured = false;
|
||||
}
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
status: "ok",
|
||||
service: "hobbs-family-organizer",
|
||||
version: "1.0.0",
|
||||
calendarConfigurationValid,
|
||||
version: "1.1.0",
|
||||
calendarConfigurationValid: calendars.some((calendar) => calendar.enabled),
|
||||
calendarsEnabled: calendars.filter((calendar) => calendar.enabled).length,
|
||||
adminConfigured,
|
||||
authenticationEnabled: Boolean(process.env.ORGANIZER_ACCESS_TOKEN),
|
||||
checkedAt: new Date().toISOString(),
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user