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 });
|
||||
}
|
||||
Reference in New Issue
Block a user