Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Add maintenance mode (#2545)
Luke Vella4ede180b51d8
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 9732ca603..35f831315 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -373,6 +373,10 @@"logos": "Logos","logosDescription": "Logo images used throughout the application","logout": "Logout",+ "maintenanceDescription": "We're performing scheduled maintenance. We'll be back online shortly.",+ "maintenanceLabel": "Maintenance",+ "maintenanceTitle": "Be right back",+ "maintenanceTryAgain": "Try again","makeAdmin": "Make admin","makeMember": "Make member","manage": "Manage",diff --git a/apps/web/src/app/[locale]/maintenance/page.tsx b/apps/web/src/app/[locale]/maintenance/page.tsxnew file mode 100644index 000000000..bbace9470--- /dev/null+++ b/apps/web/src/app/[locale]/maintenance/page.tsx@@ -0,0 +1,35 @@+import { buttonVariants } from "@rallly/ui";+import Link from "next/link";++import { ErrorPage } from "@/components/error-page";+import { getTranslation } from "@/i18n/server";++export default async function MaintenancePage({+ params,+}: {+ params: Promise<{ locale: string }>;+}) {+ const { locale } = await params;+ const { t } = await getTranslation(locale);++ return (+ <ErrorPage+ label={t("maintenanceLabel", { defaultValue: "Maintenance" })}+ title={t("maintenanceTitle", { defaultValue: "Be right back" })}+ description={t("maintenanceDescription", {+ defaultValue:+ "We're performing scheduled maintenance. We'll be back online shortly.",+ })}+ actions={+ <Link+ href="/"+ className={buttonVariants({ size: "lg", variant: "primary" })}+ >+ {t("maintenanceTryAgain", { defaultValue: "Try again" })}+ </Link>+ }+ >+ {null}+ </ErrorPage>+ );+}diff --git a/apps/web/src/app/api/private/[...route]/route.ts b/apps/web/src/app/api/private/[...route]/route.tsindex 88a87ba24..f37c459d4 100644--- a/apps/web/src/app/api/private/[...route]/route.ts+++ b/apps/web/src/app/api/private/[...route]/route.ts@@ -15,6 +15,7 @@ import { rateLimiter } from "hono-rate-limiter";import { getPollParticipants, getPollResults } from "@/features/poll/data";import { createPoll, deletePoll } from "@/features/poll/mutations";import { redis } from "@/lib/kv";+import { isMaintenanceModeEnabled } from "@/lib/maintenance";import {createPollInputSchema,createPollSuccessResponseSchema,@@ -46,6 +47,17 @@ type Env = {const app = new Hono<Env>().basePath("/api/private");+app.use("*", async (c, next) => {+ if (isMaintenanceModeEnabled()) {+ return c.json(+ apiError("SERVICE_UNAVAILABLE", "The app is down for maintenance"),+ 503,+ { "Retry-After": "300" },+ );+ }+ await next();+});+const MAX_OPTIONS = 100;const spaceNotProResponse = {diff --git a/apps/web/src/app/api/trpc/[trpc]/route.ts b/apps/web/src/app/api/trpc/[trpc]/route.tsindex 66db1a28f..a718258bf 100644--- a/apps/web/src/app/api/trpc/[trpc]/route.ts+++ b/apps/web/src/app/api/trpc/[trpc]/route.ts@@ -58,7 +58,7 @@ const handler = async (req: NextRequest) => {event.errorMessage = error.message;event.errorType = "TRPCError";- if (statusCode >= 500) {+ if (statusCode >= 500 && error.code !== "SERVICE_UNAVAILABLE") {Sentry.captureException(error);}},diff --git a/apps/web/src/env.ts b/apps/web/src/env.tsindex 0c40e5020..c539449b3 100644--- a/apps/web/src/env.ts+++ b/apps/web/src/env.ts@@ -143,6 +143,18 @@ export const env = createEnv({*/RATE_LIMIT_ENABLED: z.enum(["true", "false"]).default("true"),+ /**+ * Take the app offline for scheduled maintenance. Page traffic is+ * redirected to /maintenance and API requests are rejected with 503.+ * @default "false"+ */+ MAINTENANCE_MODE: z.enum(["true", "false"]).default("false"),+ /**+ * Secret that lets an operator bypass maintenance mode by visiting+ * /maintenance?token=<secret>+ */+ MAINTENANCE_BYPASS_TOKEN: z.string().min(16).optional(),+/*** Upstash Redis URL and token for rate limiting and auth session storage.* If not set, in-memory rate limiting and db session storage is used.@@ -267,6 +279,8 @@ export const env = createEnv({APP_NAME: process.env.APP_NAME,HIDE_ATTRIBUTION: process.env.HIDE_ATTRIBUTION,RATE_LIMIT_ENABLED: process.env.RATE_LIMIT_ENABLED,+ MAINTENANCE_MODE: process.env.MAINTENANCE_MODE,+ MAINTENANCE_BYPASS_TOKEN: process.env.MAINTENANCE_BYPASS_TOKEN,TURNSTILE_SECRET_KEY: process.env.TURNSTILE_SECRET_KEY,API_BASE_URL: process.env.API_BASE_URL,NEXT_PUBLIC_TURNSTILE_SITE_KEY: process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY,diff --git a/apps/web/src/features/branding/queries.ts b/apps/web/src/features/branding/queries.tsindex b67b5ce83..02967c80f 100644--- a/apps/web/src/features/branding/queries.ts+++ b/apps/web/src/features/branding/queries.ts@@ -3,6 +3,7 @@ import "server-only";import { cache } from "react";import { env } from "@/env";import { loadInstanceLicense } from "@/features/licensing/data";+import { isMaintenanceModeEnabled } from "@/lib/maintenance";import { getForegroundColor } from "@/utils/color";import { isSelfHosted } from "@/utils/constants";import type { BrandingConfig } from "./client";@@ -59,6 +60,11 @@ export const getInstanceBrandingConfig = cache(async () => {if (!isSelfHosted) {return getCustomBrandingConfig();}+ if (isMaintenanceModeEnabled()) {+ // Skip the license lookup so the maintenance page can render while the+ // database is unreachable+ return getDefaultBrandingConfig();+ }const license = await loadInstanceLicense();const hasWhiteLabelAddon = license?.whiteLabelAddon ?? false;return hasWhiteLabelAddondiff --git a/apps/web/src/lib/maintenance-server.ts b/apps/web/src/lib/maintenance-server.tsnew file mode 100644index 000000000..b04a5e562--- /dev/null+++ b/apps/web/src/lib/maintenance-server.ts@@ -0,0 +1,37 @@+import "server-only";++import { cookies } from "next/headers";+import { AppError } from "@/lib/errors";+import {+ isMaintenanceModeEnabled,+ isValidBypassCookie,+ MAINTENANCE_BYPASS_COOKIE_NAME,+} from "@/lib/maintenance";++/**+ * Returns true when maintenance mode is enabled and the request does not+ * carry a valid bypass cookie. Must be called in request scope.+ */+export async function isMaintenanceActiveForRequest() {+ if (!isMaintenanceModeEnabled()) {+ return false;+ }++ const cookieStore = await cookies();+ const bypass = cookieStore.get(MAINTENANCE_BYPASS_COOKIE_NAME)?.value;++ if (bypass && (await isValidBypassCookie({ value: bypass }))) {+ return false;+ }++ return true;+}++export async function assertAppAvailable() {+ if (await isMaintenanceActiveForRequest()) {+ throw new AppError({+ code: "SERVICE_UNAVAILABLE",+ message: "The app is down for maintenance",+ });+ }+}diff --git a/apps/web/src/lib/maintenance.test.ts b/apps/web/src/lib/maintenance.test.tsnew file mode 100644index 000000000..4d05ee161--- /dev/null+++ b/apps/web/src/lib/maintenance.test.ts@@ -0,0 +1,72 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ hashBypassToken,+ isMaintenanceModeEnabled,+ isValidBypassCookie,+ isValidBypassToken,+} from "./maintenance";++const TOKEN = "correct-horse-battery-staple";++afterEach(() => {+ vi.unstubAllEnvs();+});++describe("isMaintenanceModeEnabled", () => {+ it("is enabled when MAINTENANCE_MODE is 'true'", () => {+ vi.stubEnv("MAINTENANCE_MODE", "true");+ expect(isMaintenanceModeEnabled()).toBe(true);+ });++ it("is disabled when MAINTENANCE_MODE is 'false'", () => {+ vi.stubEnv("MAINTENANCE_MODE", "false");+ expect(isMaintenanceModeEnabled()).toBe(false);+ });++ it("is disabled when MAINTENANCE_MODE is unset", () => {+ vi.stubEnv("MAINTENANCE_MODE", undefined);+ expect(isMaintenanceModeEnabled()).toBe(false);+ });+});++describe("isValidBypassToken", () => {+ it("accepts the configured token", async () => {+ vi.stubEnv("MAINTENANCE_BYPASS_TOKEN", TOKEN);+ expect(await isValidBypassToken({ token: TOKEN })).toBe(true);+ });++ it("rejects a wrong token", async () => {+ vi.stubEnv("MAINTENANCE_BYPASS_TOKEN", TOKEN);+ expect(await isValidBypassToken({ token: "wrong-token" })).toBe(false);+ });++ it("rejects everything when no token is configured", async () => {+ vi.stubEnv("MAINTENANCE_BYPASS_TOKEN", undefined);+ expect(await isValidBypassToken({ token: TOKEN })).toBe(false);+ expect(await isValidBypassToken({ token: "" })).toBe(false);+ });+});++describe("isValidBypassCookie", () => {+ it("accepts the hash of the configured token", async () => {+ vi.stubEnv("MAINTENANCE_BYPASS_TOKEN", TOKEN);+ const value = await hashBypassToken({ token: TOKEN });+ expect(await isValidBypassCookie({ value })).toBe(true);+ });++ it("rejects the raw token as a cookie value", async () => {+ vi.stubEnv("MAINTENANCE_BYPASS_TOKEN", TOKEN);+ expect(await isValidBypassCookie({ value: TOKEN })).toBe(false);+ });++ it("rejects values of the wrong length", async () => {+ vi.stubEnv("MAINTENANCE_BYPASS_TOKEN", TOKEN);+ expect(await isValidBypassCookie({ value: "abc123" })).toBe(false);+ });++ it("rejects everything when no token is configured", async () => {+ vi.stubEnv("MAINTENANCE_BYPASS_TOKEN", undefined);+ const value = await hashBypassToken({ token: TOKEN });+ expect(await isValidBypassCookie({ value })).toBe(false);+ });+});diff --git a/apps/web/src/lib/maintenance.ts b/apps/web/src/lib/maintenance.tsnew file mode 100644index 000000000..53933f559--- /dev/null+++ b/apps/web/src/lib/maintenance.ts@@ -0,0 +1,54 @@+// Imported by the edge proxy: use Web Crypto (not node:crypto) and read+// process.env inside each function to keep `@/env` out of the bundle —+// t3-env validates eagerly on import and would crash server boot on any+// misconfigured server var. Shape is still validated in `@/env`.++export const MAINTENANCE_PATH = "/maintenance";+export const MAINTENANCE_BYPASS_COOKIE_NAME = "rallly-maintenance-bypass";+export const MAINTENANCE_BYPASS_COOKIE_MAX_AGE = 60 * 60 * 4;++export function isMaintenanceModeEnabled() {+ return process.env.MAINTENANCE_MODE === "true";+}++async function sha256Hex(value: string) {+ const digest = await crypto.subtle.digest(+ "SHA-256",+ new TextEncoder().encode(value),+ );+ return Array.from(new Uint8Array(digest))+ .map((byte) => byte.toString(16).padStart(2, "0"))+ .join("");+}++function timingSafeEqualHex(a: string, b: string) {+ if (a.length !== b.length) {+ return false;+ }+ let result = 0;+ for (let i = 0; i < a.length; i++) {+ result |= a.charCodeAt(i) ^ b.charCodeAt(i);+ }+ return result === 0;+}++export async function hashBypassToken({ token }: { token: string }) {+ return sha256Hex(token);+}++export async function isValidBypassToken({ token }: { token: string }) {+ const secret = process.env.MAINTENANCE_BYPASS_TOKEN;+ if (!secret) {+ return false;+ }+ // Compare digests so the comparison never operates on the raw secret+ return timingSafeEqualHex(await sha256Hex(token), await sha256Hex(secret));+}++export async function isValidBypassCookie({ value }: { value: string }) {+ const secret = process.env.MAINTENANCE_BYPASS_TOKEN;+ if (!secret) {+ return false;+ }+ return timingSafeEqualHex(value, await sha256Hex(secret));+}diff --git a/apps/web/src/lib/safe-action/server.ts b/apps/web/src/lib/safe-action/server.tsindex 474484cc1..e50720c1f 100644--- a/apps/web/src/lib/safe-action/server.ts+++ b/apps/web/src/lib/safe-action/server.ts@@ -8,6 +8,7 @@ import { getCurrentUser } from "@/features/user/data";import { signOut } from "@/lib/auth";import { AppError } from "@/lib/errors";import { InvalidSessionError } from "@/lib/errors/invalid-session-error";+import { assertAppAvailable } from "@/lib/maintenance-server";import type { Duration } from "@/lib/rate-limit";import { createRatelimit } from "@/lib/rate-limit";@@ -60,6 +61,11 @@ export const actionClient = createSafeActionClient({return "UNAUTHORIZED" as const;}+ if (error instanceof AppError && error.code === "SERVICE_UNAVAILABLE") {+ // Maintenance mode — expected, not reported to Sentry+ return error.code;+ }+Sentry.captureException(error, {tags: {errorHandler: "safe-action",@@ -75,6 +81,9 @@ export const actionClient = createSafeActionClient({return "INTERNAL_SERVER_ERROR" as const;},+}).use(async ({ next }) => {+ await assertAppAvailable();+ return next();});export const authActionClient = actionClient.use(async ({ next }) => {diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.tsindex ddf3a9fac..aea665243 100644--- a/apps/web/src/proxy.ts+++ b/apps/web/src/proxy.ts@@ -1,13 +1,63 @@import type { NextRequest } from "next/server";import { NextResponse } from "next/server";import { getLocaleFromRequest, setLocaleCookie } from "@/lib/locale/server";+import {+ hashBypassToken,+ isMaintenanceModeEnabled,+ isValidBypassCookie,+ isValidBypassToken,+ MAINTENANCE_BYPASS_COOKIE_MAX_AGE,+ MAINTENANCE_BYPASS_COOKIE_NAME,+ MAINTENANCE_PATH,+} from "@/lib/maintenance";import { setPathname } from "@/lib/pathname";+async function handleMaintenance(req: NextRequest) {+ const { nextUrl } = req;++ if (nextUrl.pathname === MAINTENANCE_PATH) {+ const token = nextUrl.searchParams.get("token");+ if (token && (await isValidBypassToken({ token }))) {+ const res = NextResponse.redirect(new URL("/", nextUrl));+ res.cookies.set(+ MAINTENANCE_BYPASS_COOKIE_NAME,+ await hashBypassToken({ token }),+ {+ httpOnly: true,+ sameSite: "lax",+ path: "/",+ secure: nextUrl.protocol === "https:",+ maxAge: MAINTENANCE_BYPASS_COOKIE_MAX_AGE,+ },+ );+ return res;+ }+ // Render the maintenance page via the locale rewrite below+ return null;+ }++ const bypass = req.cookies.get(MAINTENANCE_BYPASS_COOKIE_NAME)?.value;+ if (bypass && (await isValidBypassCookie({ value: bypass }))) {+ return null;+ }++ return NextResponse.redirect(new URL(MAINTENANCE_PATH, nextUrl));+}+export const proxy = async (req: NextRequest) => {const { nextUrl } = req;const newUrl = nextUrl.clone();const pathname = newUrl.pathname;+ if (isMaintenanceModeEnabled()) {+ const res = await handleMaintenance(req);+ if (res) {+ return res;+ }+ } else if (pathname === MAINTENANCE_PATH) {+ return NextResponse.redirect(new URL("/", nextUrl));+ }+const locale = getLocaleFromRequest(req);newUrl.pathname = `/${locale}${pathname}`;diff --git a/apps/web/src/trpc/trpc.ts b/apps/web/src/trpc/trpc.tsindex 0db9b38ee..80b9c1d97 100644--- a/apps/web/src/trpc/trpc.ts+++ b/apps/web/src/trpc/trpc.ts@@ -6,6 +6,7 @@ import { getActiveSpaceForUser } from "@/features/space/data";import { createUserDTO } from "@/features/user/data";import { signOut } from "@/lib/auth";import { AppError } from "@/lib/errors";+import { isMaintenanceActiveForRequest } from "@/lib/maintenance-server";import { createRatelimit } from "@/lib/rate-limit";import { isSelfHosted } from "@/utils/constants";import type { TRPCContext } from "./context";@@ -28,6 +29,17 @@ export const router = t.router;export const middleware = t.middleware;+const maintenanceGuard = t.middleware(async ({ next }) => {+ if (await isMaintenanceActiveForRequest()) {+ throw new TRPCError({+ code: "SERVICE_UNAVAILABLE",+ message: "The app is down for maintenance",+ });+ }++ return next();+});+// Reads trust the session (cookie cache) without hitting the database.// Mutations verify the user still exists and run with a fresh DTO; if the// user is gone, the session is revoked so the client can't keep bouncing@@ -60,7 +72,9 @@ const mutationSessionGuard = t.middleware(async ({ ctx, type, next }) => {});});-export const publicProcedure = t.procedure.use(mutationSessionGuard);+export const publicProcedure = t.procedure+ .use(maintenanceGuard)+ .use(mutationSessionGuard);export const possiblyPublicProcedure = publicProcedure.use(middleware(async ({ ctx, next }) => {diff --git a/scripts/docker-start.sh b/scripts/docker-start.shindex c2f232ee2..ab4196778 100755--- a/scripts/docker-start.sh+++ b/scripts/docker-start.sh@@ -4,5 +4,10 @@ set -e# Needed by next-auth to verify the origin of the requestexport AUTH_URL=$NEXT_PUBLIC_BASE_URL-npx prisma migrate deploy --config=./prisma.config.ts+if [ "$MAINTENANCE_MODE" = "true" ]; then+ # The database may be unreachable during maintenance+ echo "MAINTENANCE_MODE is enabled - skipping database migration"+else+ npx prisma migrate deploy --config=./prisma.config.ts+finode apps/web/server.js