Your favorite shift management application!
feat: Block requests when system is unhealthy (#108)
panteL1695eb2ae1a6
diff --git a/app/api/admin/stats/route.ts b/app/api/admin/stats/route.tsindex ff38a2a..0ee1ee0 100644--- a/app/api/admin/stats/route.ts+++ b/app/api/admin/stats/route.ts@@ -125,18 +125,13 @@ export async function GET(request: NextRequest) {const totalShifts = Number(totalShiftsResult?.count || 0);- // 6. Recent activity count (last 7 days) - user-visible audit logs only+ // 6. Recent activity count (last 7 days)const [recentActivityResult] = await db.select({count: sql<number>`COUNT(*)`,}).from(auditLogs)- .where(- and(- eq(auditLogs.isUserVisible, true),- gte(auditLogs.timestamp, sevenDaysAgo)- )- );+ .where(and(gte(auditLogs.timestamp, sevenDaysAgo)));const recentActivity = Number(recentActivityResult?.count || 0);diff --git a/app/api/health/route.ts b/app/api/health/route.tsindex 9513b2a..8f3ea99 100644--- a/app/api/health/route.ts+++ b/app/api/health/route.ts@@ -1,11 +1,13 @@-import { NextRequest, NextResponse } from "next/server";+import { NextResponse } from "next/server";import { db } from "@/lib/db";import { sql } from "drizzle-orm";-import { readFile } from "fs/promises";-import { join } from "path";+import { user } from "@/lib/db/schema";+import { getCurrentVersion } from "@/lib/version";export const dynamic = "force-dynamic";+const HEALTH_CHECK_TIMEOUT = 5000; // 5 seconds for health endpoint+interface HealthStatus {status: "healthy" | "unhealthy";timestamp: string;@@ -22,12 +24,12 @@ interface HealthStatus {};}-export async function GET(request: NextRequest) {+export async function GET() {const startTime = Date.now();const health: HealthStatus = {status: "healthy",timestamp: new Date().toISOString(),- version: "unknown",+ version: await getCurrentVersion(),checks: {database: {status: "ok",@@ -39,25 +41,47 @@ export async function GET(request: NextRequest) {},};- // Check version+ // Check database connection and schema+ let timeoutId: NodeJS.Timeout | null = null;try {- const versionPath = join(process.cwd(), ".version");- const version = await readFile(versionPath, "utf-8");- health.version = version.trim();- } catch (error) {- // Version file might not exist in dev mode- health.version = process.env.NODE_ENV === "production" ? "unknown" : "dev";- }+ // Create a timeout promise that rejects after HEALTH_CHECK_TIMEOUT+ const timeoutPromise = new Promise<never>((_, reject) => {+ timeoutId = setTimeout(() => {+ reject(new Error("Database health check timeout"));+ }, HEALTH_CHECK_TIMEOUT);+ });- // Check database connection- try {- db.run(sql`SELECT 1`);+ // Create the database query promise+ const dbPromise = db+ .select({ count: sql<number>`count(*)` })+ .from(user)+ .limit(1);++ // Race the query against the timeout+ await Promise.race([dbPromise, timeoutPromise]);++ // Query succeeded before timeout+ if (timeoutId) clearTimeout(timeoutId);health.checks.database.status = "ok";} catch (error) {+ // Clear timeout if it exists+ if (timeoutId) clearTimeout(timeoutId);+health.status = "unhealthy";health.checks.database.status = "error";- health.checks.database.message =- error instanceof Error ? error.message : "Database connection failed";++ // Log the actual error for debugging+ console.error(+ "[Health] Database check failed:",+ error instanceof Error ? error.message : String(error)+ );++ // Provide generic message to client+ if (error instanceof Error && error.message.includes("timeout")) {+ health.checks.database.message = "Database query timeout";+ } else {+ health.checks.database.message = "Database unavailable";+ }}const responseTime = Date.now() - startTime;diff --git a/app/api/version/route.ts b/app/api/version/route.tsindex c445b24..36b29bb 100644--- a/app/api/version/route.ts+++ b/app/api/version/route.ts@@ -1,6 +1,5 @@import { NextResponse } from "next/server";-import { readFileSync, existsSync } from "fs";-import { join } from "path";+import { getCurrentVersion } from "@/lib/version";/*** Cache Strategy: 15 minutes unified across all version/release endpoints@@ -24,9 +23,6 @@ let cachedLatestRelease: {} | null = null;let cachedLatestReleaseExpiresAt = 0;-let cachedDockerVersion: string | null = null;-let cachedPackageVersion = "";-// Unified cache duration: 15 minutesconst CACHE_DURATION = 15 * 60 * 1000; // 15 minutesconst CACHE_SECONDS = 15 * 60; // 15 minutes@@ -36,45 +32,6 @@ const GITHUB_REPO_NAME = process.env.GITHUB_REPO_NAME || "BetterShift";const GITHUB_BRANCH = process.env.GITHUB_BRANCH || "main";const GITHUB_TOKEN = process.env.GITHUB_TOKEN;-function getDockerVersion(): string | null {- if (cachedDockerVersion !== null) {- return cachedDockerVersion;- }-- try {- const versionFilePath = join(process.cwd(), ".version");- if (existsSync(versionFilePath)) {- // Remove 'v' prefix for consistent version comparison- cachedDockerVersion = readFileSync(versionFilePath, "utf-8")- .trim()- .replace(/^v/, "");- return cachedDockerVersion;- }- } catch {- console.log("No .version file found, not running in Docker");- }-- cachedDockerVersion = null;- return null;-}--function getPackageVersion(): string {- if (cachedPackageVersion) {- return cachedPackageVersion;- }-- try {- const packageJsonPath = join(process.cwd(), "package.json");- const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));- cachedPackageVersion = packageJson.version || "unknown";- return cachedPackageVersion;- } catch (error) {- console.error("Failed to read package.json version:", error);- cachedPackageVersion = "unknown";- return "unknown";- }-}-async function fetchCommitHash(): Promise<string> {try {const response = await fetch(@@ -217,9 +174,8 @@ export async function GET() {);}- // Try to get version from Docker build arg first- const dockerVersion = getDockerVersion();- const version = dockerVersion || getPackageVersion();+ // Get current version+ const version = await getCurrentVersion();const commitHash = await fetchCommitHash();cachedVersion = {diff --git a/app/layout.tsx b/app/layout.tsxindex b2d7054..7e9e4df 100644--- a/app/layout.tsx+++ b/app/layout.tsx@@ -20,8 +20,8 @@ const geistMono = Geist_Mono({});export const metadata: Metadata = {- title: "BetterShift - Shift Schedule Manager",- description: "Manage your work shifts with ease",+ title: "BetterShift",+ description: "Your favorite shift management application!",applicationName: "BetterShift",manifest: "/manifest.json",appleWebApp: {diff --git a/app/system-unavailable/page.tsx b/app/system-unavailable/page.tsxnew file mode 100644index 0000000..2e278b8--- /dev/null+++ b/app/system-unavailable/page.tsx@@ -0,0 +1,42 @@+import { getTranslations } from "next-intl/server";+import { AlertTriangle } from "lucide-react";+import { AppFooter } from "@/components/app-footer";+import { AuthHeader } from "@/components/auth-header";+import { getVersionInfo } from "@/lib/version";++export default async function SystemUnavailablePage() {+ const t = await getTranslations();+ const versionInfo = await getVersionInfo();++ return (+ <div className="flex flex-col min-h-screen">+ <AuthHeader />++ <div className="flex flex-1 items-center justify-center bg-gradient-to-br from-background via-background to-destructive/5 px-4 py-8">+ <div className="w-full max-w-2xl">+ {/* Error Banner */}+ <div className="rounded-lg border-2 border-destructive bg-destructive/10 p-8 shadow-lg animate-in fade-in slide-in-from-top-4 duration-500">+ <div className="flex gap-4 items-start">+ <AlertTriangle className="h-12 w-12 text-destructive flex-shrink-0 mt-1" />+ <div className="space-y-3 flex-1">+ <h1 className="text-3xl font-semibold text-destructive">+ {t("system.unavailable")}+ </h1>+ <p className="text-sm text-muted-foreground mt-4">+ {t("system.unavailableDescription")}+ </p>+ <div className="pt-4 border-t border-destructive/20 mt-6">+ <p className="text-xs text-muted-foreground">+ {t("system.unavailableRetry")}+ </p>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>++ <AppFooter versionInfo={versionInfo} />+ </div>+ );+}diff --git a/instrumentation.ts b/instrumentation.tsindex 06e1529..f858f16 100644--- a/instrumentation.ts+++ b/instrumentation.ts@@ -5,6 +5,10 @@export async function register() {if (process.env.NEXT_RUNTIME === "nodejs") {+ // Preload version during startup to avoid blocking on first request+ const { initializeVersion } = await import("@/lib/version");+ await initializeVersion();+// Import and start the auto-sync serviceconst { autoSyncService } = await import("@/lib/auto-sync-service");await autoSyncService.start();diff --git a/lib/version.ts b/lib/version.tsnew file mode 100644index 0000000..4b0a7d8--- /dev/null+++ b/lib/version.ts@@ -0,0 +1,130 @@+import { readFile, access } from "fs/promises";+import { join } from "path";++let cachedVersion: string | null = null;+let versionLoadPromise: Promise<string> | null = null;++/**+ * Get version from Docker .version file+ */+async function getDockerVersion(): Promise<string | null> {+ try {+ const versionFilePath = join(process.cwd(), ".version");++ // Check if file exists+ await access(versionFilePath);++ // Read and parse version+ const content = await readFile(versionFilePath, "utf-8");+ // Remove 'v' prefix for consistent version comparison+ return content.trim().replace(/^v/, "");+ } catch {+ // File doesn't exist or can't be read+ return null;+ }+}++/**+ * Get version from package.json+ */+async function getPackageVersion(): Promise<string> {+ try {+ const packageJsonPath = join(process.cwd(), "package.json");+ const content = await readFile(packageJsonPath, "utf-8");+ const packageJson = JSON.parse(content);+ return packageJson.version || "unknown";+ } catch (error) {+ console.error("Failed to read package.json version:", error);+ return "unknown";+ }+}++/**+ * Load version from filesystem+ * Tries Docker .version file first, then package.json+ */+async function loadVersion(): Promise<string> {+ const dockerVersion = await getDockerVersion();+ if (dockerVersion) {+ return dockerVersion;+ }+ return getPackageVersion();+}++/**+ * Initialize version cache during server startup+ * This should be called from instrumentation.ts register() hook+ */+export async function initializeVersion(): Promise<void> {+ if (cachedVersion === null && versionLoadPromise === null) {+ versionLoadPromise = loadVersion();+ cachedVersion = await versionLoadPromise;+ versionLoadPromise = null;+ }+}++/**+ * Get current application version (async)+ * Returns cached version if available, otherwise loads it+ */+export async function getCurrentVersion(): Promise<string> {+ if (cachedVersion !== null) {+ return cachedVersion;+ }++ // If another call is already loading the version, wait for it+ if (versionLoadPromise !== null) {+ return versionLoadPromise;+ }++ // Load version and cache it+ versionLoadPromise = loadVersion();+ cachedVersion = await versionLoadPromise;+ versionLoadPromise = null;++ return cachedVersion;+}++/**+ * Get current application version (sync - for backwards compatibility)+ * Returns cached version if available, otherwise returns "loading..."+ * @deprecated Use getCurrentVersion() async function instead+ */+export function getCurrentVersionSync(): string {+ return cachedVersion || "loading...";+}++/**+ * Build GitHub URL for a version+ */+export function buildGitHubUrl(version: string): string {+ const repoOwner = process.env.GITHUB_REPO_OWNER || "panteLx";+ const repoName = process.env.GITHUB_REPO_NAME || "BetterShift";+ const baseUrl = `https://github.com/${repoOwner}/${repoName}`;++ // Check if version matches semver pattern (e.g., 1.1.1 or v1.1.1)+ const semverPattern = /^v?\d+\.\d+\.\d+$/;+ if (semverPattern.test(version)) {+ const tag = version.startsWith("v") ? version : `v${version}`;+ return `${baseUrl}/releases/tag/${tag}`;+ }++ // Otherwise link to main repo+ return baseUrl;+}++/**+ * Get version info for UI components (like AppFooter)+ */+export async function getVersionInfo(): Promise<{+ version: string;+ githubUrl: string;+}> {+ const version = await getCurrentVersion();+ const githubUrl = buildGitHubUrl(version);++ return {+ version,+ githubUrl,+ };+}diff --git a/messages/de.json b/messages/de.jsonindex e539d09..ab64d34 100644--- a/messages/de.json+++ b/messages/de.json@@ -504,6 +504,11 @@"sessionsRevokedCount": "Von {count} Gerät(en) abgemeldet","accountBanned": "Konto gesperrt"},+ "system": {+ "unavailable": "System nicht verfügbar",+ "unavailableDescription": "Das System ist derzeit durch einen kritischen Fehler nicht verfügbar. Bitte versuche es später erneut oder kontaktiere einen Administrator.",+ "unavailableRetry": "Bitte aktualisiere diese Seite, um es erneut zu versuchen, oder schaue später wieder vorbei."+ },"guest": {"viewingAsGuest": "Du betrachtest als Gast","bannerMessage": "Du betrachtest diesen Kalender als Gast. Melde dich an für vollen Zugriff.",@@ -631,7 +636,7 @@"orphanedCalendars": "Verwaiste Kalender","totalShifts": "Schichten gesamt","activeShares": "Aktive Freigaben",- "recentActivity": "Letzte Admin Aktivitäten",+ "recentActivity": "Letzte Aktivitäten","usersByRole": "{superadmin} Superadmin, {admin} Admin, {user} Benutzer","calendarsDescription": "Kalender mit Besitzern","orphanedDescription": "Kalender ohne Besitzer",@@ -644,7 +649,7 @@"orphanedCalendarsWarning": "Verwaiste Kalender erkannt","orphanedCalendarsWarningDescription": "{count, plural, =1 {Es gibt 1 Kalender ohne Besitzer} other {Es gibt # Kalender ohne Besitzer}}. Bitte weise diese(n) Benutzern zu.","manageOrphanedCalendars": "Verwaiste Kalender verwalten",- "recentActivityDescription": "Neueste Admin-Aktivitätsprotokolle",+ "recentActivityDescription": "Admin- und sicherheitsrelevante Aktivitätsprotokolle","statsFetchError": "Fehler beim Laden der Statistiken","userManagement": "Benutzerverwaltung","userManagementDescription": "Benutzerkonten und Berechtigungen verwalten",diff --git a/messages/en.json b/messages/en.jsonindex e45627d..7bfd98b 100644--- a/messages/en.json+++ b/messages/en.json@@ -504,6 +504,11 @@"logoutAllDevices": "Logout from all other devices","sessionsRevokedCount": "Logged out from {count} device(s)"},+ "system": {+ "unavailable": "System Unavailable",+ "unavailableDescription": "The system is currently unavailable due to a critical error. Please try again later or contact an administrator.",+ "unavailableRetry": "Please refresh this page to try again or check back later."+ },"guest": {"viewingAsGuest": "You are viewing as guest","bannerMessage": "You are viewing this calendar as a guest. Sign in for full access.",@@ -631,7 +636,7 @@"orphanedCalendars": "Orphaned Calendars","totalShifts": "Total Shifts","activeShares": "Active Shares",- "recentActivity": "Recent Admin Activity",+ "recentActivity": "Recent Activity","usersByRole": "{superadmin} superadmin, {admin} admin, {user} users","calendarsDescription": "Total calendars with owners","orphanedDescription": "Calendars without an owner",@@ -644,7 +649,7 @@"orphanedCalendarsWarning": "Orphaned Calendars Detected","orphanedCalendarsWarningDescription": "{count, plural, =1 {There is 1 calendar without an owner} other {There are # calendars without an owner}}. Please assign them to users.","manageOrphanedCalendars": "Manage Orphaned Calendars",- "recentActivityDescription": "Latest admin activity logs",+ "recentActivityDescription": "Latest admin- and security-related activity logs","statsFetchError": "Failed to load statistics","userManagement": "User Management","userManagementDescription": "Manage user accounts and permissions",diff --git a/messages/it.json b/messages/it.jsonindex 0b24e12..82b2bbd 100644--- a/messages/it.json+++ b/messages/it.json@@ -504,6 +504,11 @@"logoutAllDevices": "Disconnetti da tutti gli altri dispositivi","sessionsRevokedCount": "Disconnesso da {count} dispositivo/i"},+ "system": {+ "unavailable": "Sistema non disponibile",+ "unavailableDescription": "Il sistema è attualmente non disponibile a causa di un errore critico. Riprova più tardi o contatta un amministratore.",+ "unavailableRetry": "Aggiorna questa pagina per riprovare o torna più tardi."+ },"guest": {"viewingAsGuest": "Stai visualizzando come ospite","bannerMessage": "Stai visualizzando questo calendario come ospite. Accedi per l'accesso completo.",@@ -631,7 +636,7 @@"orphanedCalendars": "Calendari Orfani","totalShifts": "Turni Totali","activeShares": "Condivisioni Attive",- "recentActivity": "Attività Admin Recente",+ "recentActivity": "Attività Recente","usersByRole": "{superadmin} superadmin, {admin} admin, {user} utenti","calendarsDescription": "Calendari con proprietari","orphanedDescription": "Calendari senza proprietario",@@ -644,7 +649,7 @@"orphanedCalendarsWarning": "Calendari Orfani Rilevati","orphanedCalendarsWarningDescription": "{count, plural, =1 {C'è 1 calendario senza proprietario} other {Ci sono # calendari senza proprietario}}. Si prega di assegnarli agli utenti.","manageOrphanedCalendars": "Gestisci Calendari Orfani",- "recentActivityDescription": "Log delle ultime attività admin",+ "recentActivityDescription": "Log delle ultime attività admin e di sicurezza","statsFetchError": "Impossibile caricare le statistiche","userManagement": "Gestione Utenti","userManagementDescription": "Gestisci account utente e permessi",diff --git a/proxy.ts b/proxy.tsindex d3754f6..336e6f1 100644--- a/proxy.ts+++ b/proxy.ts@@ -10,6 +10,104 @@ import { logAuditEvent } from "@/lib/audit-log";import { rateLimit } from "@/lib/rate-limiter";import { auth } from "@/lib/auth";import { isAdmin } from "@/lib/auth/admin";+import { db } from "@/lib/db";+import { sql } from "drizzle-orm";+import { user } from "@/lib/db/schema";++// =====================================================+// Health Check Cache (In-Memory)+// =====================================================+interface HealthCacheEntry {+ status: "healthy" | "unhealthy";+ timestamp: number;+ ttl: number; // Time-to-live in milliseconds+}++let healthCache: HealthCacheEntry | null = null;+const HEALTH_CACHE_TTL = 10000; // 10 seconds+const HEALTH_CHECK_TIMEOUT = 2000; // 2 seconds++/**+ * Lightweight internal health check function that directly probes the database+ * without calling API routes. Avoids middleware recursion and internal fetch issues.+ */+async function checkHealthInternal(): Promise<"healthy" | "unhealthy"> {+ let timeoutId: NodeJS.Timeout | null = null;++ try {+ // Create a timeout promise that rejects after HEALTH_CHECK_TIMEOUT+ const timeoutPromise = new Promise<never>((_, reject) => {+ timeoutId = setTimeout(() => {+ reject(new Error("Database health check timeout"));+ }, HEALTH_CHECK_TIMEOUT);+ });++ // Create the database query promise+ const dbPromise = db+ .select({ count: sql<number>`count(*)` })+ .from(user)+ .limit(1);++ // Race the query against the timeout+ await Promise.race([dbPromise, timeoutPromise]);++ // Query succeeded before timeout+ if (timeoutId) clearTimeout(timeoutId);+ return "healthy";+ } catch (error) {+ // Clear timeout if it exists+ if (timeoutId) clearTimeout(timeoutId);++ // Log specific message for timeout vs other errors+ if (error instanceof Error && error.message.includes("timeout")) {+ console.error(+ "[Middleware] Health check timed out after",+ HEALTH_CHECK_TIMEOUT,+ "ms"+ );+ } else {+ console.error(+ "[Middleware] Health check failed:",+ error instanceof Error ? error.message : String(error)+ );+ }+ return "unhealthy";+ }+}++/**+ * Cached health check with TTL. Returns cached result if fresh,+ * otherwise performs a new check. Does not cache transient errors.+ */+async function getCachedHealthStatus(): Promise<"healthy" | "unhealthy"> {+ const now = Date.now();++ // Return cached result if still valid+ if (healthCache && now - healthCache.timestamp < healthCache.ttl) {+ return healthCache.status;+ }++ // Perform new health check+ const status = await checkHealthInternal();++ // Only cache successful results to avoid caching transient errors+ if (status === "healthy") {+ healthCache = {+ status,+ timestamp: now,+ ttl: HEALTH_CACHE_TTL,+ };+ } else {+ // For unhealthy status, use a shorter TTL to allow faster recovery+ healthCache = {+ status,+ timestamp: now,+ ttl: 5000, // 5 seconds for unhealthy state+ };+ }++ return status;+}/*** Proxy for authentication and route protection (Next.js 16)@@ -21,10 +119,71 @@ import { isAdmin } from "@/lib/auth/admin";* - Stores return URL for post-login redirect* - Supports guest access for viewing calendars* - Handles access token sharing (/share/token/xyz)+ * - Blocks all routes when system is unhealthy (except health check, version, and release APIs)*/export async function proxy(request: NextRequest) {const { pathname } = request.nextUrl;+ // =====================================================+ // Health Check - Block all routes if system unhealthy+ // =====================================================+ const healthCheckExemptRoutes = [+ "/api/health",+ "/api/version",+ "/api/releases",+ "/manifest.json", // Allow manifest.json for PWA+ ];++ const isHealthCheckExempt = healthCheckExemptRoutes.some((route) =>+ pathname.startsWith(route)+ );++ // Special handling for /system-unavailable route+ if (pathname.startsWith("/system-unavailable")) {+ // Use cached health check to avoid blocking and redirect loops+ try {+ const status = await getCachedHealthStatus();++ // Only redirect to home if we have a definitive healthy result+ if (status === "healthy") {+ return NextResponse.redirect(new URL("/", request.url));+ }++ // System is unhealthy - allow access to error page+ return NextResponse.next();+ } catch (error) {+ // Log the error instead of silently swallowing it+ console.error(+ "[Middleware] Health check failed in /system-unavailable handler:",+ error instanceof Error ? error.message : String(error)+ );+ // Always treat fetch failures/timeouts as "unhealthy" to allow access to error page+ return NextResponse.next();+ }+ }++ if (!isHealthCheckExempt) {+ try {+ // Use cached, timeout-protected health check (non-blocking)+ const status = await getCachedHealthStatus();++ if (status === "unhealthy") {+ // System is definitively unhealthy - redirect to error page+ return NextResponse.redirect(+ new URL("/system-unavailable", request.url)+ );+ }+ } catch (error) {+ // Health check middleware error (not a system health issue)+ // Log the error but allow the request through to avoid blocking all traffic+ console.error(+ "[Middleware] Health check error - allowing request through:",+ error instanceof Error ? error.message : String(error)+ );+ // Continue to authentication/authorization checks below+ }+ }+// =====================================================// Access Token Handling (/share/token/[token])// =====================================================diff --git a/public/manifest.json b/public/manifest.jsonindex 6fd0a38..a0ce6c3 100644--- a/public/manifest.json+++ b/public/manifest.json@@ -1,7 +1,7 @@{- "name": "BetterShift - Shift Schedule Manager",+ "name": "BetterShift","short_name": "BetterShift",- "description": "Manage your work shifts with ease using BetterShift",+ "description": "Your favorite shift management application!","start_url": "/","display": "standalone","background_color": "#0a0a0a",