diff --git a/apps/api/migrations/20261117104308_add_site_status/migration.sql b/apps/api/migrations/20261117104308_add_site_status/migration.sql new file mode 100644 index 0000000000..f07cec5fa0 --- /dev/null +++ b/apps/api/migrations/20261117104308_add_site_status/migration.sql @@ -0,0 +1,13 @@ +CREATE TABLE "core_site_status" ( + "id" integer PRIMARY KEY DEFAULT 1, + "offline" boolean DEFAULT false NOT NULL, + "message" jsonb DEFAULT '[]' NOT NULL, + "opensAt" timestamp with time zone, + "showCountdown" boolean DEFAULT true NOT NULL, + "changedAt" timestamp with time zone DEFAULT now() NOT NULL, + "changedById" integer, + "updatedAt" timestamp DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "core_site_status" ENABLE ROW LEVEL SECURITY;--> statement-breakpoint +ALTER TABLE "core_site_status" ADD CONSTRAINT "core_site_status_changedById_core_users_id_fkey" FOREIGN KEY ("changedById") REFERENCES "core_users"("id") ON DELETE SET NULL; \ No newline at end of file diff --git a/apps/api/migrations/20261117104308_add_site_status/snapshot.json b/apps/api/migrations/20261117104308_add_site_status/snapshot.json new file mode 100644 index 0000000000..11c2b778db --- /dev/null +++ b/apps/api/migrations/20261117104308_add_site_status/snapshot.json @@ -0,0 +1,225 @@ +{ + "type": "diff", + "version": "9", + "dialect": "postgres", + "id": "7453f5c0-b352-419a-bc5e-314a1576c86f", + "prevIds": [ + "20d31aad-bc7f-4e35-b1f6-059bd8899c2b" + ], + "footprints": [ + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "core_site_status" + ], + "writes": [ + "s|tbl|public.core_site_status", + "n|tbl|public.core_site_status", + "e|tbl|public.core_site_status", + "n|rel|public.core_site_status", + "n|type|public.core_site_status", + "n|rel|public.core_site_status_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "core_site_status" + ], + "writes": [ + "s|fk|public.core_site_status.core_site_status_changedById_core_users_id_fkey", + "n|fk|public.core_site_status.core_site_status_changedById_core_users_id_fkey", + "e|fk|public.core_site_status.core_site_status_changedById_core_users_id_fkey", + "n|con|public.core_site_status.core_site_status_changedById_core_users_id_fkey" + ], + "reads": [ + "n|tbl|public.core_site_status", + "n|sch|public", + "n|tbl|public.core_users", + "n|sch|public", + "n|col|public.core_site_status.changedById", + "n|col|public.core_users.id", + "e|uniqueness|public.core_users.id" + ] + } + ], + "deltas": [ + { + "op": "create", + "row": { + "schema": "public", + "name": "core_site_status", + "isRlsEnabled": true, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_site_status", + "name": "id", + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "1", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_site_status", + "name": "offline", + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_site_status", + "name": "message", + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'[]'", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_site_status", + "name": "opensAt", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_site_status", + "name": "showCountdown", + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_site_status", + "name": "changedAt", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_site_status", + "name": "changedById", + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_site_status", + "name": "updatedAt", + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_site_status", + "name": "core_site_status_changedById_core_users_id_fkey", + "nameExplicit": false, + "columns": [ + "changedById" + ], + "schemaTo": "public", + "tableTo": "core_users", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_site_status", + "name": "core_site_status_pkey", + "columns": [ + "id" + ], + "nameExplicit": false, + "entityType": "pks" + } + } + ] +} \ No newline at end of file diff --git a/apps/web/content/docs/dev/events/built-in-events.mdx b/apps/web/content/docs/dev/events/built-in-events.mdx index 99e5cbaf55..328381d397 100644 --- a/apps/web/content/docs/dev/events/built-in-events.mdx +++ b/apps/web/content/docs/dev/events/built-in-events.mdx @@ -737,6 +737,50 @@ these events for side effects such as a thank-you notification. **A listener would** send a receipt notification, post to a sales channel, or clear a cached page that shows the buyer's purchases. +## Site status events + +One name, exported from `@vitnode/api/events/site` as +`siteStatusUpdatedEvent`. It fires **after** the save has committed and the +cached status is expired. + +| Event | Payload | Fires when | +| --------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------- | +| `site.status.updated` | `{ offline, switched, opensAt, changedById }` | An admin switches the site off or on, or edits its message, in the **Site status** card on **AdminCP → Debug Panel** | + + + + +Emitted by `PUT /admin/site/status`. A save that only edits the offline +message fires it too, with `switched: false`. See +[Site offline mode](/docs/dev/site-offline-mode). + + + +**A listener would** post "We're back!" to a chat webhook when +`switched && !offline`. + + + + ## Page layout events One name, exported from `@vitnode/api/events/pages` as diff --git a/apps/web/content/docs/dev/meta.json b/apps/web/content/docs/dev/meta.json index 9473c1412b..a2544ddc68 100644 --- a/apps/web/content/docs/dev/meta.json +++ b/apps/web/content/docs/dev/meta.json @@ -54,6 +54,7 @@ "cli", "deployments", "updates", + "site-offline-mode", "debugging", "swagger", "contribution", diff --git a/apps/web/content/docs/dev/site-offline-admin.webp b/apps/web/content/docs/dev/site-offline-admin.webp new file mode 100644 index 0000000000..8e37293da7 Binary files /dev/null and b/apps/web/content/docs/dev/site-offline-admin.webp differ diff --git a/apps/web/content/docs/dev/site-offline-mode.mdx b/apps/web/content/docs/dev/site-offline-mode.mdx new file mode 100644 index 0000000000..398926b353 --- /dev/null +++ b/apps/web/content/docs/dev/site-offline-mode.mdx @@ -0,0 +1,138 @@ +--- +title: Site offline mode +description: Take the public site offline from the AdminCP with a message in every language and an optional countdown to the opening. +icon: Power +--- + +import { ImgDocs } from "@/components/fumadocs/img" +import siteOfflineAdmin from "./site-offline-admin.webp" +import siteOfflinePage from "./site-offline-page.webp" + +Site offline mode swaps the public site for a "We'll be right back" page while you upgrade, migrate or prepare a launch. Visitors see your message in their language and, if you set an opening time, a countdown. Admins, and moderators you allow, keep using the site as usual, so you can check everything before you open the doors. + +## Turn the site off + + + + + +### Open the site status card + +Go to **AdminCP → Debug Panel**. The **Site status** card sits at the top of **Overview**. To see it you need two staff permissions, **Debug Panel → View debug panel** and **Site status → View**. Changing it takes **Site status → Manage**. + + + + + +### Switch it off and write the message + +Turn on **Take the site offline**, and the **Message** and **Opening time** fields unfold below the switch. Write why the site is off in **Message**. The editor has a language switcher, and the default language is the one you can't skip. A visitor whose language has no message gets the default one. + + + + + +### Set an opening time (optional) + +Pick an **Opening time** to show visitors a live countdown with rolling digits and the date. Turn off **Show countdown** to show the date alone. + +The site **never opens by itself**. Once the opening time has passed, visitors see **Opening soon** until an admin turns the site on. + + + + + +### Save + +A footer slides in at the bottom of the card once something changes. Select **Turn off site** in it, or **Discard** to drop your changes. The card turns to **Site is offline**. + + + + + + + +While the site is offline, **AdminCP → Debug Panel** lists it as a warning (with the opening time) and counts it in the warning badge next to your name, so nobody forgets it is off. Select the warning to jump to the **Site status** card. + +To open the site, turn off **Take the site offline** and select **Turn on site** in the card's footer. Offline pages that are still open check the status every minute and load the site on their own. + +## What visitors and staff see + + + +| Who | What they get | +| --- | --- | +| Guests and members | The offline page on every public URL, with an HTTP `503` status | +| Admins | The full site, with an **Offline** pill in the bottom corner (click it for details and a link to the site status) and an `(Offline)` prefix on every page title | +| Moderators with **Access the site while it's offline** | The same as admins | +| Other moderators | The offline page, like any member | +| Anyone on `/login` | The sign-in pages. The offline page has no sign-in link, so staff open `/login` or `/admin` directly | +| AdminCP | Works as usual; it needs an AdminCP session anyway | + +The `503` answer tells search engines the outage is temporary, so they keep your pages indexed. It carries `Retry-After` when the opening time is set, and the [page cache](/docs/dev/cache/pages) never stores it. + +## Let moderators in + +Admins always pass. A moderator passes only with the moderator staff permission **Site status → Access the site while it's offline**. Give it to a moderator or a moderator role in **AdminCP → Staff → Moderators**. Root roles and unrestricted moderators hold it already. The server makes the call, so the offline page, the `503` and the API never disagree about who gets in. + +## Keep a route working while offline + +While the site is offline, every API route answers callers who may not use the offline site with `503 { "error": "site_offline" }`, so content cannot be read around the offline page. Routes under `/admin/` and routes with `adminStaffPermission` are never blocked. + +Set `allowWhenOffline` on a route that an offline site still needs, such as a payment webhook or a sign-in step: + +```ts title="plugins/shop/src/api/modules/orders/routes/webhook.route.ts" +import { buildRoute } from "@/api/builders"; + +export const orderWebhookRoute = buildRoute({ + allowWhenOffline: true, // [!code ++] + route: { + method: "post", + path: "/webhook", + responses: { 200: { description: "Received" } }, + }, + handler: c => c.body(null, 200), +}); +``` + +Core already allows signing in, password reset, e-mail verification, SSO, passkey sign-in, cron, payment webhooks and content preview links. + +## Read the status in your code + +`siteStatusQueryOptions` reads the public status with the [fetcher](/docs/dev/fetcher), in a loader or a component: + +```tsx title="plugins/shop/src/components/launch-badge.tsx" +import { useQuery } from "@tanstack/react-query"; +import { siteStatusQueryOptions } from "@vitnode/core/tanstack/site-status"; +import { useFormatter } from "use-intl"; + +export const LaunchBadge = () => { + const format = useFormatter(); + const { data } = useQuery(siteStatusQueryOptions()); + if (!data?.offline || !data.opensAt) return null; + + return ( + + Opens {format.dateTime(new Date(data.opensAt), { dateStyle: "medium" })} + + ); +}; +``` + +To react when an admin switches the site, listen to the [`site.status.updated` event](/docs/dev/events/built-in-events#site-status-events). + +### Custom public layouts + +`ThemeLayoutContent` from `@vitnode/core/tanstack/layout` shows the offline page for you, as long as your `_main` route's loader calls `loadMainShell(context, { location })`. A layout that does not use `ThemeLayoutContent` wraps its content in `SiteOfflineGate` from `@vitnode/core/tanstack/site-status`. + +## Related + +- [Staff permissions](/docs/dev/working-with-users/staff-permissions) +- [Built-in events](/docs/dev/events/built-in-events) +- [API routes](/docs/dev/plugins/api/routes) diff --git a/apps/web/content/docs/dev/site-offline-page.webp b/apps/web/content/docs/dev/site-offline-page.webp new file mode 100644 index 0000000000..dc94846c5f Binary files /dev/null and b/apps/web/content/docs/dev/site-offline-page.webp differ diff --git a/apps/web/content/docs/dev/working-with-users/presence.mdx b/apps/web/content/docs/dev/working-with-users/presence.mdx index 64763546d0..006b5f484e 100644 --- a/apps/web/content/docs/dev/working-with-users/presence.mdx +++ b/apps/web/content/docs/dev/working-with-users/presence.mdx @@ -55,13 +55,13 @@ Each session expires on its own. A member with a laptop and a phone stays online ## Browse anonymously -Members who'd rather lurk in peace open **Settings → Overview** (`/settings`) and turn on **Browse anonymously** under **Privacy**, as long as their [roles allow it](#role-settings). +Members who'd rather lurk in peace open **Settings → Privacy & data** (`/settings/privacy`) and turn on **Browse anonymously** under **Privacy**, as long as their [roles allow it](#role-settings). The switch saves `core_users.hideOnlineStatus` through `PUT /users/me/privacy` and takes effect on the next presence read. Everybody else then gets `{ "status": "hidden" }`, with no timestamp at all, and the profile shows **Activity hidden**. diff --git a/apps/web/content/docs/dev/working-with-users/profile-fields.mdx b/apps/web/content/docs/dev/working-with-users/profile-fields.mdx index 2e768b5e41..b36025d09d 100644 --- a/apps/web/content/docs/dev/working-with-users/profile-fields.mdx +++ b/apps/web/content/docs/dev/working-with-users/profile-fields.mdx @@ -51,7 +51,7 @@ The **Edit profile** button is the header's action slot and shows only on the ac ## Browse anonymously -The **Privacy** group on **Settings → Overview** holds **Browse anonymously**. Turned on, other members see **Activity hidden** instead of the member's online status and last activity, while staff with `users:can_view_hidden_presence` still see it. A role can take the choice away: the switch then stays visible but disabled, with a tooltip saying why. See [User Presence](/docs/dev/working-with-users/presence#role-settings). +The **Privacy** group on **Settings → Privacy & data** (`/settings/privacy`) holds **Browse anonymously**. Turned on, other members see **Activity hidden** instead of the member's online status and last activity, while staff with `users:can_view_hidden_presence` still see it. A role can take the choice away: the switch then stays visible but disabled, with a tooltip saying why. See [User Presence](/docs/dev/working-with-users/presence#role-settings). ## Who may edit diff --git a/apps/web/src/locales/@vitnode/core/pl.json b/apps/web/src/locales/@vitnode/core/pl.json index e4456d1268..c5cde2eb6c 100644 --- a/apps/web/src/locales/@vitnode/core/pl.json +++ b/apps/web/src/locales/@vitnode/core/pl.json @@ -23,6 +23,10 @@ "@vitnode/core:ai": "AI", "@vitnode/core:ai:can_view": "Wyświetlanie użycia, ustawień i historii AI", "@vitnode/core:ai:can_manage": "Zarządzanie ustawieniami, modelami, cenami i dostępem AI", + "@vitnode/core:site_status": "Status strony", + "@vitnode/core:site_status:can_view": "Podgląd, czy strona jest dostępna, i jej komunikatu o przerwie", + "@vitnode/core:site_status:can_manage": "Wyłączanie i włączanie strony oraz edycja komunikatu o przerwie", + "@vitnode/core:site_status:can_access_offline": "Dostęp do strony, gdy jest wyłączona", "@vitnode/core:plugins": "Wtyczki", "@vitnode/core:plugins:can_view": "Przeglądanie zainstalowanych wtyczek i ich wersji", "@vitnode/core:queue": "Zadania w kolejce", @@ -436,6 +440,10 @@ "oldest": "Najstarsze otwarte żądanie: {days} z {deadline} dni", "oldest_late": "Żądanie ma {days} dni i przekroczyło limit RODO wynoszący {deadline} dni", "none": "Brak otwartych żądań" + }, + "site": { + "offline": "Publiczna strona jest wyłączona", + "offline_until": "Publiczna strona jest wyłączona do {opensAt, date, medium}, {opensAt, time, short}" } }, "actions": { @@ -1551,6 +1559,62 @@ "success_desc": "{count, plural, =0 {Nie było nic do usunięcia.} one {# powiadomienie zostało usunięte.} few {# powiadomienia zostały usunięte.} many {# powiadomień zostało usuniętych.} other {# powiadomienia zostało usunięte.}}" } } + }, + "site_status": { + "title": "Status strony", + "retry": "Spróbuj ponownie", + "load_error": { + "title": "Nie udało się wczytać statusu strony", + "desc": "Nie mogliśmy sprawdzić, czy strona jest dostępna. Sprawdź połączenie i spróbuj ponownie." + }, + "status": { + "online": "Strona jest dostępna", + "offline": "Strona jest wyłączona", + "not_saved": "Niezapisane", + "last_switched": "Ostatnia zmiana", + "by": "przez {name}", + "never": "Nigdy nie była wyłączona" + }, + "save_bar": { + "unsaved": "Masz niezapisane zmiany", + "discard": "Odrzuć", + "save": "Zapisz zmiany", + "turn_off": "Wyłącz stronę", + "turn_on": "Włącz stronę" + }, + "toast": { + "saved": { + "title": "Zapisano zmiany", + "desc": "Odwiedzający zobaczą je przy następnym wczytaniu strony przerwy." + }, + "turned_off": { + "title": "Strona jest wyłączona", + "desc": "Odwiedzający widzą teraz stronę przerwy. Administratorzy i moderatorzy z dostępem nadal mogą korzystać ze strony." + }, + "turned_on": { + "title": "Strona jest dostępna", + "desc": "Odwiedzający znów mogą korzystać ze strony. Otwarte strony przerwy przeładują się same w ciągu minuty." + } + }, + "form": { + "offline": { + "label": "Wyłącz stronę", + "desc": "Odwiedzający zobaczą stronę przerwy zamiast strony. Administratorzy i moderatorzy z dostępem nadal z niej korzystają." + }, + "message": { + "label": "Komunikat", + "required": "Napisz komunikat w języku domyślnym, aby każdy odwiedzający wiedział, co się dzieje." + }, + "opens_at": { + "label": "Czas otwarcia", + "desc": "Strona nigdy nie otworzy się sama. Po upływie czasu odwiedzający widzą \"Wkrótce otwarcie\", dopóki jej nie włączysz.", + "past": "Wybierz czas w przyszłości." + }, + "show_countdown": { + "label": "Pokaż odliczanie", + "desc": "Pokazuj odliczanie na żywo. Po wyłączeniu odwiedzający widzą tylko datę." + } + } } }, "user": { @@ -6031,6 +6095,31 @@ "missing": "Jedna z wybranych kategorii już nie istnieje. Nikt nie może czytać umieszczonej w niej treści." } } + }, + "site_offline": { + "title": "Zaraz wracamy", + "desc": "Strona jest chwilowo wyłączona. Zajrzyj tu wkrótce.", + "badge": "Przerwa techniczna", + "countdown": { + "back_in": "Wracamy za", + "expected_back": "Planowany powrót", + "opening_soon": "Wkrótce otwarcie", + "label": "Otwarcie za {days, plural, =0 {} one {# dzień, } other {# dni, }}{hours, plural, one {# godzinę} few {# godziny} many {# godzin} other {# godziny}} i {minutes, plural, one {# minutę} few {# minuty} many {# minut} other {# minuty}}", + "units": { + "days": "d", + "hours": "h", + "minutes": "min", + "seconds": "s" + } + }, + "staff_banner": { + "trigger": "Offline", + "trigger_label": "Strona jest wyłączona dla odwiedzających. Pokaż szczegóły", + "title": "Strona jest wyłączona", + "desc": "Odwiedzający dostają stronę przerwy. Możesz ją przeglądać dzięki uprawnieniom zespołu.", + "manage": "Zarządzaj statusem strony", + "document_title": "(Offline) {title}" + } } }, "@vitnode/core:files:can_edit_alt": "Edycja tekstu alternatywnego obrazów", diff --git a/packages/api/src/content/server/localized-list-routes.test.ts b/packages/api/src/content/server/localized-list-routes.test.ts index c8fd8dcce2..94de4ea29f 100644 --- a/packages/api/src/content/server/localized-list-routes.test.ts +++ b/packages/api/src/content/server/localized-list-routes.test.ts @@ -23,12 +23,12 @@ const LANGUAGE_ROWS = [ const languageDatabase = { select: () => ({ - from: async (table: unknown) => { + from: (table: unknown) => { if (table !== core_languages) { throw new Error("Only core_languages is read directly by this route."); } - return await Promise.resolve(LANGUAGE_ROWS); + return LANGUAGE_ROWS; }, }), }; diff --git a/packages/api/src/content/server/localized-public-routes.test.ts b/packages/api/src/content/server/localized-public-routes.test.ts index 1b39d80a9a..b519bb19f4 100644 --- a/packages/api/src/content/server/localized-public-routes.test.ts +++ b/packages/api/src/content/server/localized-public-routes.test.ts @@ -30,12 +30,12 @@ const CORE = { const languageDatabase = { select: () => ({ - from: async (table: unknown) => { + from: (table: unknown) => { if (table !== core_languages) { throw new Error("Only core_languages is read directly by this route."); } - return await Promise.resolve(LANGUAGE_ROWS); + return LANGUAGE_ROWS; }, }), }; diff --git a/packages/api/src/content/server/public-routes.test.ts b/packages/api/src/content/server/public-routes.test.ts index b4750a33fd..e66a8565a8 100644 --- a/packages/api/src/content/server/public-routes.test.ts +++ b/packages/api/src/content/server/public-routes.test.ts @@ -5,6 +5,7 @@ import { HTTPException } from "hono/http-exception"; import { describe, expect, it, vi } from "vitest"; import { core_content_containers } from "@/database/content-containers"; +import { siteOfflineGuard } from "@/middlewares/site-offline.middleware"; import { testCategoryContentType, testPostContentType, @@ -441,8 +442,6 @@ describe("generated surface", () => { }); it("installs no staff-permission guard", () => { - // `buildRoute` always adds `pluginMiddleware`, and adds a second handler - // only when `adminStaffPermission` is set. Exactly one means none. const routes = buildContentPublicRoutes(posts, { pluginId: PLUGIN_ID }); for (const { route } of routes) { @@ -450,7 +449,9 @@ describe("generated surface", () => { // the shape `buildRoute` actually assembles. const { middleware } = route as unknown as { middleware: unknown[] }; - expect(middleware).toHaveLength(1); + expect( + middleware.filter(handler => handler !== siteOfflineGuard), + ).toHaveLength(1); } }); }); diff --git a/packages/api/src/content/server/public-routes.ts b/packages/api/src/content/server/public-routes.ts index 941d5fdc3c..e64f3ead35 100644 --- a/packages/api/src/content/server/public-routes.ts +++ b/packages/api/src/content/server/public-routes.ts @@ -532,6 +532,7 @@ export const buildContentPublicRoutes = < * would hand a reviewer a different language from the one they were sent. */ const preview = buildRoute({ + allowWhenOffline: true, pluginId, route: { method: "get", diff --git a/packages/api/src/database/relations.ts b/packages/api/src/database/relations.ts index 1ab852d5df..dffaffb5a0 100644 --- a/packages/api/src/database/relations.ts +++ b/packages/api/src/database/relations.ts @@ -22,6 +22,7 @@ import * as roles from "./roles"; import * as search from "./search"; import * as secrets from "./secrets"; import * as sessions from "./sessions"; +import * as site from "./site"; import * as users from "./users"; export const coreSchema = { @@ -47,6 +48,7 @@ export const coreSchema = { ...search, ...secrets, ...sessions, + ...site, ...users, }; diff --git a/packages/api/src/database/site.ts b/packages/api/src/database/site.ts new file mode 100644 index 0000000000..0297d4c5bd --- /dev/null +++ b/packages/api/src/database/site.ts @@ -0,0 +1,32 @@ +import { camelCase } from "drizzle-orm/pg-core"; + +import type { SiteOfflineMessage } from "@/lib/site-status"; + +import { core_users } from "./users"; + +/** + * Whether the public site is open. One row (`id = 1`); a missing row means + * the site is online. + */ +export const core_site_status = camelCase.table.withRLS( + "core_site_status", + t => ({ + id: t.integer().primaryKey().default(1), + offline: t.boolean().notNull().default(false), + /** The reason shown to visitors: one rich-text document per language. */ + message: t.jsonb().$type().notNull().default([]), + /** When the site plans to open. `null` means no countdown. */ + opensAt: t.timestamp({ withTimezone: true }), + showCountdown: t.boolean().notNull().default(true), + /** When `offline` last flipped. */ + changedAt: t.timestamp({ withTimezone: true }).notNull().defaultNow(), + changedById: t + .integer() + .references(() => core_users.id, { onDelete: "set null" }), + updatedAt: t + .timestamp() + .notNull() + .defaultNow() + .$onUpdate(() => new Date()), + }), +); diff --git a/packages/api/src/events/site.ts b/packages/api/src/events/site.ts new file mode 100644 index 0000000000..70a11d95de --- /dev/null +++ b/packages/api/src/events/site.ts @@ -0,0 +1,26 @@ +import { z } from "zod"; + +import { manifest } from "@/manifest"; + +import { defineEvent } from "../lib/event-definition"; + +const pluginId = manifest.id; + +/** + * The site status was saved in the AdminCP: switched off or on, or its + * message or opening time changed. Fires after the write has committed. + */ +export const siteStatusUpdatedEvent = defineEvent({ + pluginId, + name: "site.status.updated", + payload: z.object({ + offline: z.boolean(), + /** Whether this save flipped `offline`. */ + switched: z.boolean(), + opensAt: z.string().nullable(), + changedById: z.number().int().nullable(), + }), +}); + +/** Every `site.*` event core defines. */ +export const siteEventDefinitions = [siteStatusUpdatedEvent]; diff --git a/packages/api/src/lib/core-staff-permissions.ts b/packages/api/src/lib/core-staff-permissions.ts index 13be7426a5..8477ed697a 100644 --- a/packages/api/src/lib/core-staff-permissions.ts +++ b/packages/api/src/lib/core-staff-permissions.ts @@ -11,6 +11,7 @@ export const coreStaffPermissions = defineStaffPermissions(manifest, { moderator: { users: ["can_edit", "can_view_hidden_presence"], widgets: ["can_edit"], + site_status: ["can_access_offline"], warnings: [ "can_view", "can_warn", @@ -75,6 +76,10 @@ export const coreStaffPermissions = defineStaffPermissions(manifest, { { permission: "can_manage", dependsOn: ["can_view"] }, ], ai: ["can_view", { permission: "can_manage", dependsOn: ["can_view"] }], + site_status: [ + "can_view", + { permission: "can_manage", dependsOn: ["can_view"] }, + ], cron: ["can_view", { permission: "can_run", dependsOn: ["can_view"] }], activity_logs: [ "can_view", diff --git a/packages/api/src/lib/route.ts b/packages/api/src/lib/route.ts index 26f9bee927..2e8e033c18 100644 --- a/packages/api/src/lib/route.ts +++ b/packages/api/src/lib/route.ts @@ -14,6 +14,7 @@ import type { import { captchaMiddleware } from "../middlewares/captcha.middleware"; import { pluginMiddleware } from "../middlewares/plugin.middleware"; +import { siteOfflineGuard } from "../middlewares/site-offline.middleware"; import { assertStaffPermission } from "./check-staff-permission"; import { pluginTag } from "./openapi-tags"; import { isAdminApiPath, setRouteStaffPermissions } from "./route-metadata"; @@ -113,6 +114,14 @@ export interface BuildRouteOptions< * guards with that plugin's permission. */ adminStaffPermission?: AdminStaffPermissionRef; + /** + * Keeps the route working for everyone while the site is offline. Without + * it, a visitor who is not staff gets `503 { error: "site_offline" }`. Set + * it on what an offline site still needs: signing in, webhooks, cron, and + * reads the offline page itself makes. Routes under `/admin/` and routes + * with `adminStaffPermission` are never blocked. Defaults to `false`. + */ + allowWhenOffline?: boolean; /** The Hono handler, typed from `route`: `c.req.valid(...)` and `c.json(...)` follow its schemas. */ handler: RouteHandler; hook?: RouteValidationHook; @@ -135,7 +144,8 @@ export interface BuildRouteOptions< * `bindApiPlugin`, which supplies `pluginId`. * * The route is tagged with its plugin for OpenAPI and runs behind middleware - * that sets `c.get("plugin")`, then the admin and moderator staff-permission + * that sets `c.get("plugin")`, then the offline-site guard (see + * `allowWhenOffline`), then the admin and moderator staff-permission * guards and the captcha check when requested, then the route's own * `middleware`. * @@ -173,6 +183,7 @@ export const buildRoute = < hook, pluginId, adminStaffPermission, + allowWhenOffline = false, moderatorStaffPermission, }: BuildRouteOptions & { pluginId: Plugin; @@ -181,6 +192,10 @@ export const buildRoute = < const middleware: MiddlewareHandler[] = [pluginMiddleware(pluginId)]; + if (!allowWhenOffline && !adminStaffPermission) { + middleware.push(siteOfflineGuard); + } + if (adminStaffPermission) { const guard = staffPermissionGuard("admin", adminStaffPermission); staffPermissionGuards.add(guard); diff --git a/packages/api/src/lib/site-status.server.ts b/packages/api/src/lib/site-status.server.ts new file mode 100644 index 0000000000..52ee677ae3 --- /dev/null +++ b/packages/api/src/lib/site-status.server.ts @@ -0,0 +1,180 @@ +import type { Context } from "hono"; + +import { eq } from "drizzle-orm"; +import { z } from "zod"; + +import { core_site_status } from "@/database/site"; +import { manifest } from "@/manifest"; + +import type { DomainCache } from "./cache"; +import type { SiteOfflineMessage, SiteStatusUpdate } from "./site-status"; + +import { defineCacheEntry } from "./cache-entry"; +import { + checkStaffPermissionOfUser, + getStaffFlags, +} from "./check-staff-permission"; +import { coreStaffPermissions } from "./core-staff-permissions"; +import { invalidatePageCacheTags } from "./page-cache"; +import { + SITE_STATUS_PAGE_CACHE_TAG, + zodSiteOfflineMessage, +} from "./site-status"; +import { staffPermissionArgs } from "./staff-permissions"; + +/** The stored row, as every request reads it. */ +export interface StoredSiteStatus { + changedAt: null | string; + changedById: null | number; + message: SiteOfflineMessage; + offline: boolean; + opensAt: null | string; + showCountdown: boolean; +} + +const ONLINE: StoredSiteStatus = { + changedAt: null, + changedById: null, + message: [], + offline: false, + opensAt: null, + showCountdown: true, +}; + +const siteStatusCache = defineCacheEntry({ + pluginId: manifest.id, + name: "site.status", + version: 1, + schema: z.object({ + changedAt: z.string().nullable(), + changedById: z.number().int().nullable(), + messageJson: z.string(), + offline: z.boolean(), + opensAt: z.string().nullable(), + showCountdown: z.boolean(), + }), + ttlSeconds: 300, +}); + +const cacheOf = (c: Context): DomainCache | undefined => c.get("cache"); + +const perRequest = new WeakMap>(); + +const readRow = async (c: Context): Promise => { + const [row] = await c + .get("db") + .select() + .from(core_site_status) + .where(eq(core_site_status.id, 1)) + .limit(1); + if (!row) return ONLINE; + + return { + changedAt: row.changedAt.toISOString(), + changedById: row.changedById, + message: row.message, + offline: row.offline, + opensAt: row.opensAt?.toISOString() ?? null, + showCountdown: row.showCountdown, + }; +}; + +/** + * The site status, read once per request and shared across requests through + * the cache. A missing row means online. Server-only. + */ +export const loadSiteStatus = async (c: Context): Promise => { + const remembered = perRequest.get(c); + if (remembered) return await remembered; + + const cache = cacheOf(c); + const loading = cache + ? cache + .entry(siteStatusCache) + .remember(async () => { + const { message, ...row } = await readRow(c); + + return { ...row, messageJson: JSON.stringify(message) }; + }) + .then(({ messageJson, ...cached }) => ({ + ...cached, + message: zodSiteOfflineMessage.parse(JSON.parse(messageJson)), + })) + : readRow(c); + perRequest.set(c, loading); + + return await loading; +}; + +/** + * Whether the request may use the site while it is offline: an AdminCP + * session, an admin, or a moderator holding + * `coreStaffPermissions.moderator.site_status.canAccessOffline` (a root role + * holds it too). Server-only. + */ +export const canBypassSiteOffline = async (c: Context): Promise => { + if (c.get("admin")) return true; + const user = c.get("user"); + if (!user) return false; + + const { isAdmin, isModerator } = await getStaffFlags(c, user); + if (isAdmin) return true; + if (!isModerator) return false; + + return await checkStaffPermissionOfUser(c, user, { + type: "moderator", + ...staffPermissionArgs( + coreStaffPermissions.moderator.site_status.canAccessOffline, + ), + }); +}; + +/** + * Writes the site status. Returns the row before the write (`null` when there + * was none) and whether this save flipped `offline`. Run it inside the caller's transaction, then call + * {@link afterSiteStatusSaved} once it has committed. Server-only. + */ +export const saveSiteStatus = async ( + tx: Omit, + body: SiteStatusUpdate, + userId: number, +): Promise<{ + before: null | typeof core_site_status.$inferSelect; + switched: boolean; +}> => { + const [before] = await tx + .select() + .from(core_site_status) + .where(eq(core_site_status.id, 1)) + .limit(1) + .for("update"); + const switched = (before?.offline ?? false) !== body.offline; + const values = { + message: body.message, + offline: body.offline, + opensAt: body.opensAt ? new Date(body.opensAt) : null, + showCountdown: body.showCountdown, + ...(switched || !before + ? { changedAt: new Date(), changedById: userId } + : {}), + }; + + await tx + .insert(core_site_status) + .values({ id: 1, ...values }) + .onConflictDoUpdate({ set: values, target: core_site_status.id }); + + return { before: before ?? null, switched }; +}; + +/** + * Expires every copy of the site status: the shared cache entry and every + * cached page that read it. Call it after the save has committed. + */ +export const afterSiteStatusSaved = async (c: Context): Promise => { + perRequest.delete(c); + await cacheOf(c)?.entry(siteStatusCache).delete(); + await invalidatePageCacheTags([SITE_STATUS_PAGE_CACHE_TAG], { + mode: "hard", + }); +}; diff --git a/packages/api/src/lib/site-status.ts b/packages/api/src/lib/site-status.ts new file mode 100644 index 0000000000..7b1251bd85 --- /dev/null +++ b/packages/api/src/lib/site-status.ts @@ -0,0 +1,96 @@ +import { z } from "zod"; + +import type { RichTextDocument } from "@/content/rich-text/document"; +import type { MultiLangValue } from "@/lib/helpers/multi-lang"; + +import { + createRichTextDocumentSchema, + isRichTextEmpty, + zodRichTextDocument, +} from "@/content/rich-text/document"; + +/** The reason the site is offline: one rich-text document per language. */ +export type SiteOfflineMessage = MultiLangValue; + +/** {@link SiteOfflineMessage} as stored and served. Browser-safe. */ +export const zodSiteOfflineMessage = z.array( + z.object({ languageCode: z.string(), value: zodRichTextDocument }), +); + +/** Limits of the offline message. */ +export const SITE_STATUS_LIMITS = { + /** Largest serialised document per language, in bytes. */ + messageMaxBytes: 64 * 1024, +} as const; + +/** Seconds until `opensAt` for a `Retry-After` header, or `null` once it has passed. */ +export const retryAfterSeconds = (opensAt: null | string): null | number => { + const seconds = opensAt + ? Math.ceil((Date.parse(opensAt) - Date.now()) / 1000) + : 0; + + return seconds > 0 ? seconds : null; +}; + +/** The page-cache tag every render that read the site status carries. */ +export const SITE_STATUS_PAGE_CACHE_TAG = "core:site-status"; + +/** What `GET /api/core/site/status` answers. Browser-safe. */ +export const zodSiteStatus = z.object({ + offline: z.boolean(), + message: zodSiteOfflineMessage, + opensAt: z.string().nullable(), + showCountdown: z.boolean(), + /** The server's clock when it answered, so a countdown can correct skew. */ + serverNow: z.string(), + /** + * Whether the requesting viewer may use the site while it is offline + * (admins, and moderators with `site_status.can_access_offline`). Always + * `false` while the site is online. + */ + viewerCanBypass: z.boolean(), +}); + +export type SiteStatus = z.output; + +/** + * What the AdminCP sends to save the site status. Browser-safe. The API also + * requires a non-empty message in the default language while `offline` is on. + */ +export const zodSiteStatusUpdate = z.object({ + offline: z.boolean(), + message: z + .array( + z.object({ + languageCode: z.string().min(1).max(20), + value: createRichTextDocumentSchema({ + maxBytes: SITE_STATUS_LIMITS.messageMaxBytes, + }), + }), + ) + .default([]), + opensAt: z.iso.datetime({ offset: true }).nullable().default(null), + showCountdown: z.boolean().default(true), +}); + +export type SiteStatusUpdate = z.output; + +/** + * The message in `languageCode`, falling back to `defaultLanguageCode`, then + * to the first non-empty one. `null` when every language is empty. + */ +export const pickSiteOfflineMessage = ( + message: SiteOfflineMessage, + languageCode: string, + defaultLanguageCode?: string, +): null | RichTextDocument => { + const filled = message.filter(item => !isRichTextEmpty(item.value)); + + return ( + ( + filled.find(item => item.languageCode === languageCode) ?? + filled.find(item => item.languageCode === defaultLanguageCode) ?? + filled[0] + )?.value ?? null + ); +}; diff --git a/packages/api/src/middlewares/site-offline.middleware.ts b/packages/api/src/middlewares/site-offline.middleware.ts new file mode 100644 index 0000000000..44bdbb624a --- /dev/null +++ b/packages/api/src/middlewares/site-offline.middleware.ts @@ -0,0 +1,29 @@ +import type { MiddlewareHandler } from "hono"; + +import { isAdminApiPath } from "../lib/route-metadata"; +import { retryAfterSeconds } from "../lib/site-status"; +import { + canBypassSiteOffline, + loadSiteStatus, +} from "../lib/site-status.server"; + +/** + * Answers `503 { error: "site_offline" }` while the site is offline, unless + * the caller may use the offline site (see `canBypassSiteOffline`) or the + * request is under `/admin/` (which requires an AdminCP session anyway). A + * status that fails to load counts as online, so the lookup never takes every + * route down with it. `buildRoute` adds it to every route that does not set + * `allowWhenOffline`. + */ +export const siteOfflineGuard: MiddlewareHandler = async (c, next) => { + if (isAdminApiPath(c.req.path)) return await next(); + + const status = await loadSiteStatus(c).catch(() => null); + if (!status?.offline || (await canBypassSiteOffline(c))) return await next(); + + const retryAfter = retryAfterSeconds(status.opensAt); + if (retryAfter) c.header("Retry-After", String(retryAfter)); + c.header("Cache-Control", "no-store"); + + return c.json({ error: "site_offline" }, 503); +}; diff --git a/packages/api/src/modules/admin/admin.module.ts b/packages/api/src/modules/admin/admin.module.ts index aadf238fe7..8bbcc1c2e5 100644 --- a/packages/api/src/modules/admin/admin.module.ts +++ b/packages/api/src/modules/admin/admin.module.ts @@ -13,6 +13,7 @@ import { reportReasonsAdminModule } from "./report-reasons/report-reasons.module import { rolesAdminModule } from "./roles/roles.module"; import { sendNotificationRoute } from "./routes/send-notification.route"; import { sessionAdminRoute } from "./routes/session.route"; +import { siteAdminModule } from "./site/site.module"; import { staffAdminModule } from "./staff/staff.module"; import { usersAdminModule } from "./users/users.module"; import { warningsAdminModule } from "./warnings/warnings.module"; @@ -35,6 +36,7 @@ export const adminModule = buildModule({ reactionsAdminModule, reportReasonsAdminModule, warningsAdminModule, + siteAdminModule, ], cronJobs: [], }); diff --git a/packages/api/src/modules/admin/site/routes/show.route.ts b/packages/api/src/modules/admin/site/routes/show.route.ts new file mode 100644 index 0000000000..d92700e94e --- /dev/null +++ b/packages/api/src/modules/admin/site/routes/show.route.ts @@ -0,0 +1,52 @@ +import { eq } from "drizzle-orm"; + +import { buildRoute } from "@/builders"; +import { core_users } from "@/database/users"; +import { coreStaffPermissions } from "@/lib/core-staff-permissions"; +import { loadSiteStatus } from "@/lib/site-status.server"; + +import { zodSiteStatusAdmin } from "../site.schema"; + +export const showSiteStatusAdminRoute = buildRoute({ + adminStaffPermission: coreStaffPermissions.admin.site_status.canView, + route: { + method: "get", + description: + "The site status with its message in every language and who changed it last.", + path: "/status", + responses: { + 200: { + content: { "application/json": { schema: zodSiteStatusAdmin } }, + description: "Site status", + }, + }, + }, + handler: async c => { + const status = await loadSiteStatus(c); + const [changedBy] = + status.changedById === null + ? [] + : await c + .get("db") + .select({ + id: core_users.id, + name: core_users.name, + nameCode: core_users.nameCode, + }) + .from(core_users) + .where(eq(core_users.id, status.changedById)) + .limit(1); + + return c.json( + { + changedAt: status.changedAt, + changedBy: changedBy ?? null, + message: status.message, + offline: status.offline, + opensAt: status.opensAt, + showCountdown: status.showCountdown, + }, + 200, + ); + }, +}); diff --git a/packages/api/src/modules/admin/site/routes/update.route.ts b/packages/api/src/modules/admin/site/routes/update.route.ts new file mode 100644 index 0000000000..5d93568690 --- /dev/null +++ b/packages/api/src/modules/admin/site/routes/update.route.ts @@ -0,0 +1,118 @@ +import { HTTPException } from "hono/http-exception"; +import { z } from "zod"; + +import { buildRoute } from "@/builders"; +import { isRichTextEmpty } from "@/content/rich-text/document"; +import { siteStatusUpdatedEvent } from "@/events/site"; +import { auditDiff } from "@/lib/audit/diff"; +import { writeAuditLog } from "@/lib/audit/write"; +import { coreStaffPermissions } from "@/lib/core-staff-permissions"; +import { zodSiteStatusUpdate } from "@/lib/site-status"; +import { + afterSiteStatusSaved, + loadSiteStatus, + saveSiteStatus, +} from "@/lib/site-status.server"; + +export const updateSiteStatusAdminRoute = buildRoute({ + adminStaffPermission: coreStaffPermissions.admin.site_status.canManage, + route: { + method: "put", + description: + "Switch the public site off or on, and set the reason and the planned opening time.", + path: "/status", + request: { + body: { + required: true, + content: { "application/json": { schema: zodSiteStatusUpdate } }, + }, + }, + responses: { + 200: { + content: { + "application/json": { schema: z.object({ ok: z.literal(true) }) }, + }, + description: "Saved", + }, + 400: { + description: + "The reason is missing in the default language, or the opening time is in the past", + }, + }, + }, + handler: async c => { + const body = c.req.valid("json"); + const admin = c.get("admin"); + if (!admin) throw new HTTPException(403); + + if (body.offline) { + const defaultLocale = c.get("core").i18n.defaultLocale; + const defaultMessage = body.message.find( + item => item.languageCode === defaultLocale, + ); + if (!defaultMessage || isRichTextEmpty(defaultMessage.value)) { + throw new HTTPException(400, { + message: "Write the reason in the default language.", + }); + } + } + const current = await loadSiteStatus(c); + const opensAtMs = body.opensAt ? Date.parse(body.opensAt) : null; + const unchanged = + current.opensAt !== null && Date.parse(current.opensAt) === opensAtMs; + if (opensAtMs !== null && !unchanged && opensAtMs <= Date.now()) { + throw new HTTPException(400, { + message: "The opening time must be in the future.", + }); + } + + const { switched } = await c.get("db").transaction(async tx => { + const saved = await saveSiteStatus(tx, body, admin.user.id); + const { before } = saved; + const changes = auditDiff({ + after: { + offline: body.offline, + opensAt: body.opensAt, + showCountdown: body.showCountdown, + }, + before: before + ? { + offline: before.offline, + opensAt: before.opensAt?.toISOString() ?? null, + showCountdown: before.showCountdown, + } + : null, + include: ["offline", "opensAt", "showCountdown"], + }); + const messageChanged = + JSON.stringify(before?.message ?? []) !== JSON.stringify(body.message); + if (changes || messageChanged) { + await writeAuditLog( + c, + { + action: "settings.updated", + changes, + target: { + id: "site_status", + label: "Site status", + type: "settings", + }, + }, + tx, + ); + } + + return saved; + }); + + await afterSiteStatusSaved(c); + await c.get("events").emit(siteStatusUpdatedEvent, { + changedById: admin.user.id, + offline: body.offline, + opensAt: body.opensAt, + switched, + }); + + return c.json({ ok: true as const }, 200); + }, +}); diff --git a/packages/api/src/modules/admin/site/site.module.ts b/packages/api/src/modules/admin/site/site.module.ts new file mode 100644 index 0000000000..7320430a9c --- /dev/null +++ b/packages/api/src/modules/admin/site/site.module.ts @@ -0,0 +1,9 @@ +import { buildModule } from "@/builders"; + +import { showSiteStatusAdminRoute } from "./routes/show.route"; +import { updateSiteStatusAdminRoute } from "./routes/update.route"; + +export const siteAdminModule = buildModule({ + name: "site", + routes: [showSiteStatusAdminRoute, updateSiteStatusAdminRoute], +}); diff --git a/packages/api/src/modules/admin/site/site.schema.ts b/packages/api/src/modules/admin/site/site.schema.ts new file mode 100644 index 0000000000..521b4d531a --- /dev/null +++ b/packages/api/src/modules/admin/site/site.schema.ts @@ -0,0 +1,15 @@ +import { z } from "zod"; + +import { zodSiteOfflineMessage } from "@/lib/site-status"; + +export const zodSiteStatusAdmin = z.object({ + offline: z.boolean(), + message: zodSiteOfflineMessage, + opensAt: z.string().nullable(), + showCountdown: z.boolean(), + /** When `offline` last flipped; `null` before the first save. */ + changedAt: z.string().nullable(), + changedBy: z + .object({ id: z.number(), name: z.string(), nameCode: z.string() }) + .nullable(), +}); diff --git a/packages/api/src/modules/cron/routes/run.route.ts b/packages/api/src/modules/cron/routes/run.route.ts index 5c0fba5bc9..924c9705b6 100644 --- a/packages/api/src/modules/cron/routes/run.route.ts +++ b/packages/api/src/modules/cron/routes/run.route.ts @@ -20,6 +20,7 @@ const sameMillisecond = (lastRun: Date) => ); export const runCronRoute = buildRoute({ + allowWhenOffline: true, route: { method: "post", description: "Run cron job", diff --git a/packages/api/src/modules/middleware/routes/show-config.route.ts b/packages/api/src/modules/middleware/routes/show-config.route.ts index ea7b098e68..17db60b734 100644 --- a/packages/api/src/modules/middleware/routes/show-config.route.ts +++ b/packages/api/src/modules/middleware/routes/show-config.route.ts @@ -3,6 +3,7 @@ import { buildRoute } from "@/builders"; import { routeMiddlewareSchema } from "../middleware.schema"; export const routeMiddleware = buildRoute({ + allowWhenOffline: true, route: { path: "/", method: "get", diff --git a/packages/api/src/modules/payments/routes/webhook.route.ts b/packages/api/src/modules/payments/routes/webhook.route.ts index 0dbe505e93..1c1e3f4876 100644 --- a/packages/api/src/modules/payments/routes/webhook.route.ts +++ b/packages/api/src/modules/payments/routes/webhook.route.ts @@ -17,6 +17,7 @@ const outcomeSchema = z.object({ }); export const paymentWebhookRoute = buildRoute({ + allowWhenOffline: true, route: { method: "post", path: "/webhooks/{providerId}", diff --git a/packages/api/src/modules/site/routes/status.route.ts b/packages/api/src/modules/site/routes/status.route.ts new file mode 100644 index 0000000000..12de59a8b3 --- /dev/null +++ b/packages/api/src/modules/site/routes/status.route.ts @@ -0,0 +1,50 @@ +import { buildRoute } from "@/builders"; +import { setPageCacheTags } from "@/lib/page-cache"; +import { SITE_STATUS_PAGE_CACHE_TAG, zodSiteStatus } from "@/lib/site-status"; +import { canBypassSiteOffline, loadSiteStatus } from "@/lib/site-status.server"; + +export const siteStatusRoute = buildRoute({ + allowWhenOffline: true, + route: { + method: "get", + description: + "Whether the public site is online. While it is offline, also the reason per language, the planned opening time and whether the requesting viewer may still use the site.", + path: "/status", + responses: { + 200: { + content: { "application/json": { schema: zodSiteStatus } }, + description: "Site status", + }, + }, + }, + handler: async c => { + const status = await loadSiteStatus(c); + setPageCacheTags(c, [SITE_STATUS_PAGE_CACHE_TAG]); + + if (!status.offline) { + return c.json( + { + message: [], + offline: false, + opensAt: null, + serverNow: new Date().toISOString(), + showCountdown: false, + viewerCanBypass: false, + }, + 200, + ); + } + + return c.json( + { + message: status.message, + offline: true, + opensAt: status.opensAt, + serverNow: new Date().toISOString(), + showCountdown: status.showCountdown && status.opensAt !== null, + viewerCanBypass: await canBypassSiteOffline(c), + }, + 200, + ); + }, +}); diff --git a/packages/api/src/modules/site/site.module.ts b/packages/api/src/modules/site/site.module.ts new file mode 100644 index 0000000000..4c7b3f6c1e --- /dev/null +++ b/packages/api/src/modules/site/site.module.ts @@ -0,0 +1,8 @@ +import { buildModule } from "@/builders"; + +import { siteStatusRoute } from "./routes/status.route"; + +export const siteModule = buildModule({ + name: "site", + routes: [siteStatusRoute], +}); diff --git a/packages/api/src/modules/users/passkeys/routes/admin-sign-in-options.route.ts b/packages/api/src/modules/users/passkeys/routes/admin-sign-in-options.route.ts index 1d7d1c5613..57784be07b 100644 --- a/packages/api/src/modules/users/passkeys/routes/admin-sign-in-options.route.ts +++ b/packages/api/src/modules/users/passkeys/routes/admin-sign-in-options.route.ts @@ -8,6 +8,7 @@ import { } from "../passkeys.schema"; export const passkeyAdminSignInOptionsRoute = buildRoute({ + allowWhenOffline: true, route: { method: "post", description: diff --git a/packages/api/src/modules/users/passkeys/routes/admin-sign-in-verify.route.ts b/packages/api/src/modules/users/passkeys/routes/admin-sign-in-verify.route.ts index a2665119da..f0404b02ab 100644 --- a/packages/api/src/modules/users/passkeys/routes/admin-sign-in-verify.route.ts +++ b/packages/api/src/modules/users/passkeys/routes/admin-sign-in-verify.route.ts @@ -13,6 +13,7 @@ import { } from "../passkeys.schema"; export const passkeyAdminSignInVerifyRoute = buildRoute({ + allowWhenOffline: true, route: { method: "post", description: diff --git a/packages/api/src/modules/users/passkeys/routes/authentication-options.route.ts b/packages/api/src/modules/users/passkeys/routes/authentication-options.route.ts index 7aa2e0330b..92a604e233 100644 --- a/packages/api/src/modules/users/passkeys/routes/authentication-options.route.ts +++ b/packages/api/src/modules/users/passkeys/routes/authentication-options.route.ts @@ -8,6 +8,7 @@ import { } from "../passkeys.schema"; export const passkeyAuthenticationOptionsRoute = buildRoute({ + allowWhenOffline: true, route: { method: "post", description: diff --git a/packages/api/src/modules/users/passkeys/routes/authentication-verify.route.ts b/packages/api/src/modules/users/passkeys/routes/authentication-verify.route.ts index 86e6c1bdb5..1c945f856a 100644 --- a/packages/api/src/modules/users/passkeys/routes/authentication-verify.route.ts +++ b/packages/api/src/modules/users/passkeys/routes/authentication-verify.route.ts @@ -22,6 +22,7 @@ import { } from "../passkeys.schema"; export const passkeyAuthenticationVerifyRoute = buildRoute({ + allowWhenOffline: true, route: { method: "post", description: diff --git a/packages/api/src/modules/users/routes/resend-verification.route.ts b/packages/api/src/modules/users/routes/resend-verification.route.ts index 41b29e884d..bb367e0236 100644 --- a/packages/api/src/modules/users/routes/resend-verification.route.ts +++ b/packages/api/src/modules/users/routes/resend-verification.route.ts @@ -12,6 +12,7 @@ import { import { USER_EMAIL_MAX_LENGTH } from "../lib/credential-limits"; export const resendVerificationRoute = buildRoute({ + allowWhenOffline: true, route: { method: "post", description: diff --git a/packages/api/src/modules/users/routes/reset-password.route.ts b/packages/api/src/modules/users/routes/reset-password.route.ts index 9ea48398a1..3d542335ea 100644 --- a/packages/api/src/modules/users/routes/reset-password.route.ts +++ b/packages/api/src/modules/users/routes/reset-password.route.ts @@ -14,6 +14,7 @@ import { ForgotPasswordTokenModel } from "@/models/password"; import { USER_EMAIL_MAX_LENGTH } from "../lib/credential-limits"; export const resetPasswordRoute = buildRoute({ + allowWhenOffline: true, route: { method: "post", description: "Request a password reset", diff --git a/packages/api/src/modules/users/routes/session.route.ts b/packages/api/src/modules/users/routes/session.route.ts index a5fcba6a34..9699d10211 100644 --- a/packages/api/src/modules/users/routes/session.route.ts +++ b/packages/api/src/modules/users/routes/session.route.ts @@ -6,6 +6,7 @@ import { getNotificationState } from "@/models/notifications/inbox"; import { zodNotificationState } from "@/modules/notifications/notifications.schema"; export const sessionRoute = buildRoute({ + allowWhenOffline: true, route: { method: "get", description: "Verify session", diff --git a/packages/api/src/modules/users/routes/sign-in.route.ts b/packages/api/src/modules/users/routes/sign-in.route.ts index 1f17043512..2e42467aab 100644 --- a/packages/api/src/modules/users/routes/sign-in.route.ts +++ b/packages/api/src/modules/users/routes/sign-in.route.ts @@ -68,6 +68,7 @@ const revokeIfPasswordChanged = async ( }; export const signInRoute = buildRoute({ + allowWhenOffline: true, route: { method: "post", description: "Sign in with email and password", diff --git a/packages/api/src/modules/users/routes/sign-out.route.ts b/packages/api/src/modules/users/routes/sign-out.route.ts index 9398b0bb74..d17c571265 100644 --- a/packages/api/src/modules/users/routes/sign-out.route.ts +++ b/packages/api/src/modules/users/routes/sign-out.route.ts @@ -5,6 +5,7 @@ import { SessionModel } from "@/models/session"; import { SessionAdminModel } from "@/models/session-admin"; export const signOutRoute = buildRoute({ + allowWhenOffline: true, route: { method: "delete", description: "Sign out the current admin", diff --git a/packages/api/src/modules/users/routes/verify-email.route.ts b/packages/api/src/modules/users/routes/verify-email.route.ts index e08c7a47b8..c03417e45f 100644 --- a/packages/api/src/modules/users/routes/verify-email.route.ts +++ b/packages/api/src/modules/users/routes/verify-email.route.ts @@ -13,6 +13,7 @@ export const zodVerifyEmailSchema = z.object({ }); export const verifyEmailRoute = buildRoute({ + allowWhenOffline: true, route: { method: "post", description: "Confirm an email address with the link sent at sign-up", diff --git a/packages/api/src/modules/users/sso/routes/callback.route.ts b/packages/api/src/modules/users/sso/routes/callback.route.ts index 06e2792232..11aac053b9 100644 --- a/packages/api/src/modules/users/sso/routes/callback.route.ts +++ b/packages/api/src/modules/users/sso/routes/callback.route.ts @@ -9,6 +9,7 @@ import { SessionModel } from "@/models/session"; import { SSOModel } from "@/models/sso"; export const callbackRoute = buildRoute({ + allowWhenOffline: true, route: { method: "get", description: "SSO Callback", diff --git a/packages/api/src/modules/users/sso/routes/create-url.route.ts b/packages/api/src/modules/users/sso/routes/create-url.route.ts index efc72dde03..dec90f6af1 100644 --- a/packages/api/src/modules/users/sso/routes/create-url.route.ts +++ b/packages/api/src/modules/users/sso/routes/create-url.route.ts @@ -4,6 +4,7 @@ import { buildRoute } from "@/builders"; import { SSOModel } from "@/models/sso"; export const createUrlRoute = buildRoute({ + allowWhenOffline: true, route: { method: "post", description: "Generate SSO URL", diff --git a/packages/api/src/modules/users/sso/routes/pending-confirm.route.ts b/packages/api/src/modules/users/sso/routes/pending-confirm.route.ts index 84c2be5278..a26e3ce40d 100644 --- a/packages/api/src/modules/users/sso/routes/pending-confirm.route.ts +++ b/packages/api/src/modules/users/sso/routes/pending-confirm.route.ts @@ -19,6 +19,7 @@ export const zodSsoPendingConfirmSchema = z.object({ }); export const ssoPendingConfirmRoute = buildRoute({ + allowWhenOffline: true, route: { method: "post", description: diff --git a/packages/api/src/modules/users/sso/routes/pending-email.route.ts b/packages/api/src/modules/users/sso/routes/pending-email.route.ts index 3f626c7052..f5abb8f7be 100644 --- a/packages/api/src/modules/users/sso/routes/pending-email.route.ts +++ b/packages/api/src/modules/users/sso/routes/pending-email.route.ts @@ -16,6 +16,7 @@ export const zodSsoPendingEmailSchema = z.object({ }); export const ssoPendingEmailRoute = buildRoute({ + allowWhenOffline: true, route: { method: "post", description: diff --git a/packages/api/src/plugin.ts b/packages/api/src/plugin.ts index b5bddbc285..72a1e04319 100644 --- a/packages/api/src/plugin.ts +++ b/packages/api/src/plugin.ts @@ -16,6 +16,7 @@ import { pageEventDefinitions } from "./events/pages"; import { paymentEventDefinitions } from "./events/payments"; import { reactionEventDefinitions } from "./events/reactions"; import { roleEventDefinitions } from "./events/roles"; +import { siteEventDefinitions } from "./events/site"; import { userEventDefinitions } from "./events/users"; import { corePersonalData } from "./lib/account-deletion/core-personal-data"; import { @@ -39,6 +40,7 @@ import { paymentsModule } from "./modules/payments/payments.module"; import { queueModule } from "./modules/queue/queue.module"; import { reactionsModule } from "./modules/reactions/reactions.module"; import { searchModule } from "./modules/search/search.module"; +import { siteModule } from "./modules/site/site.module"; import { usersModule } from "./modules/users/users.module"; export const newBuildPluginApiCore = buildApiPlugin({ @@ -63,6 +65,7 @@ export const newBuildPluginApiCore = buildApiPlugin({ ...paymentEventDefinitions, ...reactionEventDefinitions, ...roleEventDefinitions, + ...siteEventDefinitions, ...userEventDefinitions, ], modules: [ @@ -79,6 +82,7 @@ export const newBuildPluginApiCore = buildApiPlugin({ queueModule, reactionsModule, searchModule, + siteModule, ], permissionStaff: coreStaffPermissions, personalData: corePersonalData, diff --git a/packages/vitnode/src/locales/en.json b/packages/vitnode/src/locales/en.json index 56b0d87706..3267592331 100644 --- a/packages/vitnode/src/locales/en.json +++ b/packages/vitnode/src/locales/en.json @@ -36,6 +36,10 @@ "@vitnode/core:ai": "AI", "@vitnode/core:ai:can_view": "View AI usage, settings and history", "@vitnode/core:ai:can_manage": "Manage AI settings, models, pricing and access", + "@vitnode/core:site_status": "Site status", + "@vitnode/core:site_status:can_view": "View whether the site is online and its offline message", + "@vitnode/core:site_status:can_manage": "Switch the site off and on, and edit its offline message", + "@vitnode/core:site_status:can_access_offline": "Access the site while it's offline", "@vitnode/core:queue": "Queue Tasks", "@vitnode/core:queue:can_view": "View queue tasks", "@vitnode/core:plugins": "Plugins", @@ -1221,6 +1225,11 @@ "standing": "Account status", "privacy": "Privacy & data" }, + "nav_groups": { + "account": "Account", + "preferences": "Preferences", + "safety": "Privacy & safety" + }, "overview": { "desc": "Your avatar and the details on your account.", "profileTitle": "Profile", @@ -1661,7 +1670,7 @@ }, "privacy": { "title": "Privacy & data", - "desc": "Download a copy of your data or delete your account.", + "desc": "Choose who sees your activity, download a copy of your data, or delete your account.", "export": { "title": "Download your data", "desc": "A JSON file with everything this site stores about you: your profile, devices, sign-in methods, files, payments and what plugins keep.", @@ -3809,6 +3818,31 @@ "saved": "Reaction settings saved", "saved_desc": "Your profile timeline follows the new setting." } + }, + "site_offline": { + "title": "We'll be right back", + "desc": "The site is offline for a moment. Please check back soon.", + "badge": "Maintenance", + "countdown": { + "back_in": "Back in", + "expected_back": "Expected back", + "opening_soon": "Opening soon", + "label": "Opens in {days, plural, =0 {} one {# day, } other {# days, }}{hours, plural, one {# hour} other {# hours}} and {minutes, plural, one {# minute} other {# minutes}}", + "units": { + "days": "d", + "hours": "h", + "minutes": "m", + "seconds": "s" + } + }, + "staff_banner": { + "trigger": "Offline", + "trigger_label": "The site is offline for visitors. Show details", + "title": "The site is offline", + "desc": "Visitors get the offline page. You can browse it because of your staff permissions.", + "manage": "Manage site status", + "document_title": "(Offline) {title}" + } } }, "admin": { @@ -5554,6 +5588,62 @@ }, "version_on_side": "{version} ({side})" } + }, + "site_status": { + "title": "Site status", + "retry": "Try again", + "load_error": { + "title": "Site status didn't load", + "desc": "We couldn't read whether the site is online. Check your connection and try again." + }, + "status": { + "online": "Site is online", + "offline": "Site is offline", + "not_saved": "Not saved yet", + "last_switched": "Last switched", + "by": "by {name}", + "never": "Never switched off" + }, + "save_bar": { + "unsaved": "You have unsaved changes", + "discard": "Discard", + "save": "Save changes", + "turn_off": "Turn off site", + "turn_on": "Turn on site" + }, + "toast": { + "saved": { + "title": "Changes saved", + "desc": "Visitors see them the next time the offline page loads." + }, + "turned_off": { + "title": "Site is offline", + "desc": "Visitors now see the offline page. Admins, and moderators with offline access, can still use the site." + }, + "turned_on": { + "title": "Site is online", + "desc": "Visitors can use the site again. Open offline pages reload on their own within a minute." + } + }, + "form": { + "offline": { + "label": "Take the site offline", + "desc": "Visitors see the offline page instead of the site. Admins, and moderators with offline access, keep using it." + }, + "message": { + "label": "Message", + "required": "Write the message in the default language so every visitor knows what's going on." + }, + "opens_at": { + "label": "Opening time", + "desc": "The site never opens by itself. When the time is up, visitors see \"Opening soon\" until you turn it on.", + "past": "Pick a time in the future." + }, + "show_countdown": { + "label": "Show countdown", + "desc": "Show a live countdown. When off, visitors see only the date." + } + } } }, "debug": { @@ -5700,6 +5790,10 @@ "oldest": "Oldest open request: {days} of {deadline} days", "oldest_late": "A request is {days} days old, past GDPR's {deadline}-day limit", "none": "No open requests" + }, + "site": { + "offline": "The public site is offline", + "offline_until": "The public site is offline until {opensAt, date, medium}, {opensAt, time, short}" } }, "actions": { diff --git a/packages/vitnode/src/pages/settings/ai.tsx b/packages/vitnode/src/pages/settings/ai.tsx index 44e0afe625..df4e3718de 100644 --- a/packages/vitnode/src/pages/settings/ai.tsx +++ b/packages/vitnode/src/pages/settings/ai.tsx @@ -4,7 +4,6 @@ import type { PluginRoutePageProps } from "@/routing"; import { defineAuthenticatedRoute } from "@/tanstack/plugin-routes"; import { AiUsagePanelContent } from "@/tanstack/settings-ai/panel"; -import { settingsBreadcrumb } from "@/tanstack/settings/breadcrumb"; import { aiUsageQueryOptions, hasAiFeatures, @@ -34,8 +33,6 @@ export const route = defineAuthenticatedRoute({ head: ({ t }) => ({ title: `${t("core.auth.settings.nav.ai")} - ${t("core.auth.settings.title")}`, }), - - breadcrumb: settingsBreadcrumb("ai"), }); export default AiUsagePage; diff --git a/packages/vitnode/src/pages/settings/devices.tsx b/packages/vitnode/src/pages/settings/devices.tsx index 1de1ead23b..de881ea49b 100644 --- a/packages/vitnode/src/pages/settings/devices.tsx +++ b/packages/vitnode/src/pages/settings/devices.tsx @@ -2,7 +2,6 @@ import type { PluginRoutePageProps } from "@/routing"; import { DevicesPanelContent } from "@/tanstack/devices/panel"; import { defineAuthenticatedRoute } from "@/tanstack/plugin-routes"; -import { settingsBreadcrumb } from "@/tanstack/settings/breadcrumb"; import { devicesQueryOptions } from "@/views/auth/settings/devices/devices-query"; interface DevicesData { @@ -27,8 +26,6 @@ export const route = defineAuthenticatedRoute({ head: ({ t }) => ({ title: `${t("core.auth.settings.nav.devices")} - ${t("core.auth.settings.title")}`, }), - - breadcrumb: settingsBreadcrumb("devices"), }); export default DevicesPage; diff --git a/packages/vitnode/src/pages/settings/layout.tsx b/packages/vitnode/src/pages/settings/layout.tsx index 28ae6d3198..aca41e6a80 100644 --- a/packages/vitnode/src/pages/settings/layout.tsx +++ b/packages/vitnode/src/pages/settings/layout.tsx @@ -4,7 +4,6 @@ import type { PluginRoutePageProps } from "@/routing"; import { middlewareConfigQueryOptions } from "@/tanstack/auth/middleware-config"; import { defineAuthenticatedRoute } from "@/tanstack/plugin-routes"; -import { settingsBreadcrumb } from "@/tanstack/settings/breadcrumb"; import { SettingsLayoutContent } from "@/tanstack/settings/layout"; import { loadPageWidgets } from "@/tanstack/widgets"; import { aiUsageQueryOptions } from "@/views/auth/settings/ai/ai-usage-query"; @@ -43,9 +42,6 @@ export const route = defineAuthenticatedRoute({ return { userId }; }, head: () => ({ robots: "noindex, nofollow" }), - - /** The first crumb of the trail; each panel adds its own after it. */ - breadcrumb: settingsBreadcrumb(), }); export default SettingsLayout; diff --git a/packages/vitnode/src/pages/settings/notifications.tsx b/packages/vitnode/src/pages/settings/notifications.tsx index bf26270f1f..2f8acf550d 100644 --- a/packages/vitnode/src/pages/settings/notifications.tsx +++ b/packages/vitnode/src/pages/settings/notifications.tsx @@ -2,7 +2,6 @@ import type { PluginRoutePageProps } from "@/routing"; import { NotificationSettingsPanel } from "@/tanstack/notifications/settings-screen"; import { defineAuthenticatedRoute } from "@/tanstack/plugin-routes"; -import { settingsBreadcrumb } from "@/tanstack/settings/breadcrumb"; import { notificationPreferencesQueryOptions } from "@/views/notifications/notifications-query"; interface NotificationSettingsData { @@ -29,8 +28,6 @@ export const route = defineAuthenticatedRoute({ head: ({ t }) => ({ title: `${t("core.auth.settings.nav.notifications")} - ${t("core.auth.settings.title")}`, }), - - breadcrumb: settingsBreadcrumb("notifications"), }); export default NotificationSettingsPage; diff --git a/packages/vitnode/src/pages/settings/privacy.tsx b/packages/vitnode/src/pages/settings/privacy.tsx index fdb70aea7d..be386e4304 100644 --- a/packages/vitnode/src/pages/settings/privacy.tsx +++ b/packages/vitnode/src/pages/settings/privacy.tsx @@ -1,7 +1,7 @@ import type { PluginRoutePageProps } from "@/routing"; import { defineAuthenticatedRoute } from "@/tanstack/plugin-routes"; -import { settingsBreadcrumb } from "@/tanstack/settings/breadcrumb"; +import { personalInfoPolicyQuery } from "@/tanstack/settings/personal-policy"; import { PrivacyPanelContent } from "@/tanstack/settings/privacy-panel"; import { accountDeletionQueryOptions } from "@/views/auth/settings/privacy/privacy-query"; @@ -21,18 +21,19 @@ export const route = defineAuthenticatedRoute({ load: async ({ context }) => { const { id: userId, name: userName } = context.auth.user; - await context.queryClient.query({ - ...accountDeletionQueryOptions({ userId }), - staleTime: "static", - }); + await Promise.all([ + context.queryClient.query({ + ...accountDeletionQueryOptions({ userId }), + staleTime: "static", + }), + context.queryClient.query(personalInfoPolicyQuery()), + ]); return { userId, userName }; }, head: ({ t }) => ({ title: `${t("core.auth.settings.nav.privacy")} - ${t("core.auth.settings.title")}`, }), - - breadcrumb: settingsBreadcrumb("privacy"), }); export default PrivacyPage; diff --git a/packages/vitnode/src/pages/settings/security.tsx b/packages/vitnode/src/pages/settings/security.tsx index f5b21fda45..fa31d78584 100644 --- a/packages/vitnode/src/pages/settings/security.tsx +++ b/packages/vitnode/src/pages/settings/security.tsx @@ -8,7 +8,6 @@ import { } from "@/tanstack/auth/middleware-config"; import { PasskeysPanelContent } from "@/tanstack/passkeys/panel"; import { defineAuthenticatedRoute } from "@/tanstack/plugin-routes"; -import { settingsBreadcrumb } from "@/tanstack/settings/breadcrumb"; import { passkeysQueryOptions } from "@/views/auth/settings/passkeys/passkeys-query"; import { SecuritySettings } from "@/views/auth/settings/security/security"; @@ -43,8 +42,6 @@ export const route = defineAuthenticatedRoute({ head: ({ t }) => ({ title: `${t("core.auth.settings.nav.security")} - ${t("core.auth.settings.title")}`, }), - - breadcrumb: settingsBreadcrumb("security"), }); export default SecurityPage; diff --git a/packages/vitnode/src/pages/settings/sso.tsx b/packages/vitnode/src/pages/settings/sso.tsx index 3d4536365c..5204ea6c5a 100644 --- a/packages/vitnode/src/pages/settings/sso.tsx +++ b/packages/vitnode/src/pages/settings/sso.tsx @@ -8,7 +8,6 @@ import { MiddlewareConfigUnknownError, } from "@/tanstack/auth/middleware-config"; import { defineAuthenticatedRoute } from "@/tanstack/plugin-routes"; -import { settingsBreadcrumb } from "@/tanstack/settings/breadcrumb"; import { SsoConnectionsPanelContent } from "@/tanstack/sso-connections/panel"; import { ssoConnectionsQueryOptions } from "@/views/auth/settings/sso/sso-connections-query"; @@ -51,8 +50,6 @@ export const route = defineAuthenticatedRoute({ head: ({ t }) => ({ title: `${t("core.auth.settings.nav.sso")} - ${t("core.auth.settings.title")}`, }), - - breadcrumb: settingsBreadcrumb("sso"), }); export default SsoPage; diff --git a/packages/vitnode/src/pages/settings/standing.tsx b/packages/vitnode/src/pages/settings/standing.tsx index 5ea247fc97..a8c6302072 100644 --- a/packages/vitnode/src/pages/settings/standing.tsx +++ b/packages/vitnode/src/pages/settings/standing.tsx @@ -5,7 +5,6 @@ import type { StandingRouteSearch } from "../../tanstack/settings-standing/route import { defineAuthenticatedRoute } from "../../tanstack/plugin-routes"; import { StandingPanelContent } from "../../tanstack/settings-standing/panel"; import { loadStandingRoute } from "../../tanstack/settings-standing/route"; -import { settingsBreadcrumb } from "../../tanstack/settings/breadcrumb"; type StandingData = Record; @@ -29,8 +28,6 @@ export const route = defineAuthenticatedRoute< robots: "noindex, nofollow", title: `${t("core.auth.settings.nav.standing")} - ${t("core.auth.settings.title")}`, }), - - breadcrumb: settingsBreadcrumb("standing"), }); export default StandingPage; diff --git a/packages/vitnode/src/tanstack/admin/debug/query.ts b/packages/vitnode/src/tanstack/admin/debug/query.ts index f548e40348..c4722c476c 100644 --- a/packages/vitnode/src/tanstack/admin/debug/query.ts +++ b/packages/vitnode/src/tanstack/admin/debug/query.ts @@ -1,6 +1,7 @@ import type { QueryClient } from "@tanstack/react-query"; import type { AnyRouter } from "@tanstack/react-router"; import type { PermissionsStaffArgs } from "@vitnode/api/lib/permission-staff"; +import type { SiteStatusUpdate } from "@vitnode/api/lib/site-status"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useRouter } from "@tanstack/react-router"; @@ -24,9 +25,14 @@ import { import { integrationsQueryOptions } from "@/views/admin/views/core/system/integrations/integrations-query"; import { pluginUpdatesQueryOptions } from "@/views/admin/views/core/system/plugins/plugin-updates-query"; import { installedPluginsQueryOptions } from "@/views/admin/views/core/system/plugins/plugins-query"; +import { + adminSiteStatusQueryOptions, + updateAdminSiteStatus, +} from "@/views/admin/views/core/system/site-status/site-status-query"; import { accountDeletionsSummaryQueryOptions } from "@/views/admin/views/core/users/deletions/deletions-query"; -import { useAdminPermissions } from "../permissions"; +import { siteStatusQueryKey } from "../../site-status/query"; +import { useAdminPermission, useAdminPermissions } from "../permissions"; import { searchIndexQuery } from "../search-index/query"; export const debugLogsQuery = ({ params }: { params: DebugLogsParams }) => @@ -63,6 +69,10 @@ export const debugSourceQueries = () => options: searchIndexQuery(), permission: ADMIN_DEBUG_PERMISSIONS.system, }, + siteStatus: { + options: adminSiteStatusQueryOptions(), + permission: ADMIN_DEBUG_PERMISSIONS.siteStatus, + }, updates: { options: pluginUpdatesQueryOptions(), permission: ADMIN_DEBUG_PERMISSIONS.plugins, @@ -101,6 +111,9 @@ export const warmDebugSources = async ( warm(sources.search.permission, async () => queryClient.query({ ...sources.search.options, ...STATIC }), ), + warm(sources.siteStatus.permission, async () => + queryClient.query({ ...sources.siteStatus.options, ...STATIC }), + ), warm(sources.updates.permission, async () => queryClient.query({ ...sources.updates.options, ...STATIC }), ), @@ -137,6 +150,10 @@ export const useDebugSources = (): DebugSources => { ...sources.search.options, enabled: can(sources.search.permission), }); + const siteStatus = useQuery({ + ...sources.siteStatus.options, + enabled: can(sources.siteStatus.permission), + }); const updates = useQuery({ ...sources.updates.options, enabled: can(sources.updates.permission), @@ -149,6 +166,7 @@ export const useDebugSources = (): DebugSources => { integrations: integrations.data, queue: queue.data, search: search.data, + siteStatus: siteStatus.data, updates: updates.data, }; }; @@ -195,3 +213,34 @@ export const useClearAdminCache = (): (() => Promise) => { [queryClient, router], ); }; + +export const useDebugSiteStatus = () => { + const queryClient = useQueryClient(); + const canView = useAdminPermission(ADMIN_DEBUG_PERMISSIONS.siteStatus); + const canManage = useAdminPermission( + ADMIN_DEBUG_PERMISSIONS.manageSiteStatus, + ); + const query = useQuery({ + ...adminSiteStatusQueryOptions(), + enabled: canView, + }); + + const onSave = React.useCallback( + async (values: SiteStatusUpdate) => { + const result = await updateAdminSiteStatus(values); + if ("data" in result) { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: adminSiteStatusQueryOptions().queryKey, + }), + queryClient.invalidateQueries({ queryKey: siteStatusQueryKey }), + ]); + } + + return result; + }, + [queryClient], + ); + + return { canManage, canView, onSave, query }; +}; diff --git a/packages/vitnode/src/tanstack/admin/debug/route.tsx b/packages/vitnode/src/tanstack/admin/debug/route.tsx index 9fd9cf2e26..debea819d7 100644 --- a/packages/vitnode/src/tanstack/admin/debug/route.tsx +++ b/packages/vitnode/src/tanstack/admin/debug/route.tsx @@ -50,6 +50,7 @@ export const ADMIN_DEBUG_NAMESPACES = [ "admin.user.deletions", "admin.system.integrations", "admin.system.plugins", + "admin.system.site_status", "ai_actions", "core.global", "core.search", diff --git a/packages/vitnode/src/tanstack/admin/debug/sections.tsx b/packages/vitnode/src/tanstack/admin/debug/sections.tsx index d2acafd1fa..68c40270ab 100644 --- a/packages/vitnode/src/tanstack/admin/debug/sections.tsx +++ b/packages/vitnode/src/tanstack/admin/debug/sections.tsx @@ -1,7 +1,19 @@ +import { PowerOffIcon, RotateCwIcon } from "lucide-react"; import { useTranslations } from "use-intl"; +import { Button } from "@/components/ui/button"; +import { + Empty, + EmptyContent, + EmptyDescription, + EmptyHeader, + EmptyMedia, + EmptyTitle, +} from "@/components/ui/empty"; +import { Skeleton } from "@/components/ui/skeleton"; import { debugHealth } from "@/views/admin/views/core/debug/health/health"; import { DebugOverview } from "@/views/admin/views/core/debug/sections/overview"; +import { SiteStatusFrame } from "@/views/admin/views/core/debug/sections/site-status"; import { CacheSection, PluginsSection, @@ -13,6 +25,7 @@ import type { DebugSystemTab } from "./tabs"; import { useClearAdminCache, + useDebugSiteStatus, useDebugSources, useRecheckDebugSources, } from "./query"; @@ -34,6 +47,56 @@ const useDebugArea = (tab: DebugSystemTab) => { return { area, sources }; }; +const SiteStatusSkeleton = () => ( + +); + +const DebugSiteStatus = () => { + const t = useTranslations("admin.system.site_status"); + const { canManage, canView, onSave, query } = useDebugSiteStatus(); + if (!canView) return null; + if (query.isPending) return ; + if (!query.data) { + return ( + + + + + {t("load_error.title")} + {t("load_error.desc")} + + + + + + ); + } + + return ( + + ); +}; + export const DebugOverviewTab = () => { const sources = useDebugSources(); const onClearCache = useClearAdminCache(); @@ -46,6 +109,7 @@ export const DebugOverviewTab = () => { isRechecking={isPending} onClearCache={onClearCache} onRecheck={recheck} + siteStatus={} updates={sources.updates} version={sources.installed?.core.version ?? null} /> diff --git a/packages/vitnode/src/tanstack/layout/header.tsx b/packages/vitnode/src/tanstack/layout/header.tsx index da4fca1431..2d5baacaa4 100644 --- a/packages/vitnode/src/tanstack/layout/header.tsx +++ b/packages/vitnode/src/tanstack/layout/header.tsx @@ -28,8 +28,9 @@ import { useLocale } from "../i18n/locale"; import { GLOBAL_NAMESPACE, intlQueryOptions } from "../i18n/query"; import { redirectSuspendedSession } from "../moderation/suspension-gate"; import { NotificationsBell } from "../notifications/bell"; -import { isSharedRenderRequest } from "../prerender"; +import { isPrerenderRequest, isSharedRenderRequest } from "../prerender"; import { HeaderSearch } from "../search/header-search"; +import { loadSiteStatusGate } from "../site-status/load"; import { MobileUserMenu } from "./mobile-user-menu"; const NO_MESSAGES: AbstractIntlMessages = {}; @@ -151,7 +152,9 @@ const loadNavigationMessages = async ({ * the navigation messages: it skips the session and puts a deferred placeholder * in place of the deployment configuration. Pass `location` to send a * suspended session to the home page from any other page; `MainHeader` does - * the same for prerendered pages, in the browser. + * the same for prerendered pages, in the browser. With `location` it also + * loads the site status and answers `503` when the visitor gets the offline + * page (see `SiteOfflineGate`). * * @throws A router redirect to `/` for a suspended session given `location`. * @@ -184,7 +187,12 @@ export const loadMainShell = async ( middlewareConfigQueryOptions().queryKey, DEFERRED_MIDDLEWARE_CONFIG, ); - await loadNavigationMessages(context); + await Promise.all([ + loadNavigationMessages(context), + isPrerenderRequest() || !location + ? undefined + : loadSiteStatusGate(context, location.pathname), + ]); return; } @@ -197,6 +205,8 @@ export const loadMainShell = async ( }), loadSession(context.queryClient), ]); - if (location) + if (location) { redirectSuspendedSession(context.queryClient, location.pathname); + await loadSiteStatusGate(context, location.pathname); + } }; diff --git a/packages/vitnode/src/tanstack/layout/index.ts b/packages/vitnode/src/tanstack/layout/index.ts index 5a57ea27d4..bf95f9c869 100644 --- a/packages/vitnode/src/tanstack/layout/index.ts +++ b/packages/vitnode/src/tanstack/layout/index.ts @@ -7,6 +7,6 @@ export { MainHeader } from "./main-header"; export { Error500Page, NotFound } from "./not-found"; export { VitNodeRootProviders } from "./root-providers"; export { RouteErrorPage } from "./route-error"; -export { UserHeader } from "./user-header"; +export { ThemeLayoutContent } from "./theme-layout-content"; -export { ThemeLayoutContent } from "@/views/layouts/theme/layout-content"; +export { UserHeader } from "./user-header"; diff --git a/packages/vitnode/src/tanstack/layout/theme-layout-content.tsx b/packages/vitnode/src/tanstack/layout/theme-layout-content.tsx new file mode 100644 index 0000000000..e0b205434d --- /dev/null +++ b/packages/vitnode/src/tanstack/layout/theme-layout-content.tsx @@ -0,0 +1,50 @@ +import { ThemeLayoutContent as ThemeLayoutFrame } from "@/views/layouts/theme/layout-content"; + +import { + SiteOfflineScreen, + SiteOfflineStaffBanner, + useSiteOfflineView, +} from "../site-status/gate"; + +/** + * The public site's page frame: `listeners`, then `header`, then `breadcrumb`, + * then the page inside `
`. While the site is offline, visitors who may + * not use it get the offline page instead (see `SiteOfflineGate`); pair it + * with `loadMainShell` in the route's loader. + * + * @example + * ```tsx + * import { Outlet } from "@tanstack/react-router"; + * import { MainBreadcrumb } from "@vitnode/core/tanstack/breadcrumb"; + * import { MainHeader, ThemeLayoutContent } from "@vitnode/core/tanstack/layout"; + * + * const MainLayout = () => ( + * } header={}> + * + * + * ); + * ``` + */ +export const ThemeLayoutContent = ({ + breadcrumb, + ...props +}: React.ComponentProps) => { + const view = useSiteOfflineView(); + if (view === "closed") return ; + + return ( + + + {breadcrumb} + + ) : ( + breadcrumb + ) + } + {...props} + /> + ); +}; diff --git a/packages/vitnode/src/tanstack/settings/breadcrumb.tsx b/packages/vitnode/src/tanstack/settings/breadcrumb.tsx deleted file mode 100644 index ad87b1196d..0000000000 --- a/packages/vitnode/src/tanstack/settings/breadcrumb.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import type { SettingsNavKey } from "@/views/auth/settings/settings-nav"; - -import { SettingsBreadcrumbContent } from "@/views/auth/settings/settings-breadcrumb-content"; - -/** - * One crumb of the settings trail - "Settings" for the frame itself, and the - * panel's own name below it. - * - * Here rather than in the layout's page module because three routes share it, - * and a page module's job is to export a page: its `default` and its `route`, - * and nothing anything else imports. - * - * The messages it renders from are declared by the `/settings` layout, and the - * runtime wraps a crumb in its route's namespaces - so there is no - * `RouteMessages` here. - */ -export const settingsBreadcrumb = (navKey?: SettingsNavKey) => - function SettingsBreadcrumb() { - return ; - }; diff --git a/packages/vitnode/src/tanstack/settings/index.ts b/packages/vitnode/src/tanstack/settings/index.ts index adf867a204..ead0be78d1 100644 --- a/packages/vitnode/src/tanstack/settings/index.ts +++ b/packages/vitnode/src/tanstack/settings/index.ts @@ -9,8 +9,6 @@ export type { SettingsOverviewUser } from "@/views/auth/settings/overview/overvi export { OverviewSettingsContent } from "@/views/auth/settings/overview/overview"; export { SecuritySettings } from "@/views/auth/settings/security/security"; -export type { SettingsBreadcrumbContentProps } from "@/views/auth/settings/settings-breadcrumb-content"; -export { SettingsBreadcrumbContent } from "@/views/auth/settings/settings-breadcrumb-content"; export { activeSettingsNavKey, isSettingsNavItemActive, diff --git a/packages/vitnode/src/tanstack/settings/overview.tsx b/packages/vitnode/src/tanstack/settings/overview.tsx index ebafd2f7bf..0942b26584 100644 --- a/packages/vitnode/src/tanstack/settings/overview.tsx +++ b/packages/vitnode/src/tanstack/settings/overview.tsx @@ -9,7 +9,6 @@ import React from "react"; import { useTranslations } from "use-intl"; import type { UpdatePersonalInformation } from "@/views/auth/settings/overview/personal-update"; -import type { UpdatePrivacy } from "@/views/auth/settings/overview/privacy-update"; import type { UpdateTimeZone } from "@/views/auth/settings/overview/time-zone-update"; import { Button } from "@/components/ui/button"; @@ -30,16 +29,9 @@ import { hasAiFeatures, } from "@/views/auth/settings/ai/ai-usage-query"; import { OverviewSettingsContent } from "@/views/auth/settings/overview/overview"; -import { - personalInfoPolicyQueryKey, - updatePersonalInformationInBrowser, -} from "@/views/auth/settings/overview/personal-update"; -import { PrivacySettings } from "@/views/auth/settings/overview/privacy-settings"; -import { updatePrivacyInBrowser } from "@/views/auth/settings/overview/privacy-update"; -import { ReactionPrivacySetting } from "@/views/auth/settings/overview/reaction-privacy-setting"; +import { updatePersonalInformationInBrowser } from "@/views/auth/settings/overview/personal-update"; import { updateTimeZoneInBrowser } from "@/views/auth/settings/overview/time-zone-update"; import { SSO_CONNECTIONS_IDENTITY_ROOT } from "@/views/auth/settings/sso/sso-connections-query"; -import { PRESENCE_QUERY_ROOT } from "@/views/presence/presence-query"; import { userProfileQueryKey } from "@/views/profile/profile-query"; import { useMiddlewareConfigQuery } from "../auth/middleware-config"; @@ -137,27 +129,6 @@ export const OverviewSettings = ({ nameCode }: { nameCode: string }) => { [queryClient], ); - const onPrivacyUpdate: UpdatePrivacy = React.useCallback( - async input => { - const result = await updatePrivacyInBrowser(input); - if (result.data) { - await Promise.all([ - invalidateSession(queryClient), - queryClient.invalidateQueries({ queryKey: PRESENCE_QUERY_ROOT }), - ]); - } - // The roles took the choice away while this page was open. - if (result.error?.status === 403) { - await queryClient.invalidateQueries({ - queryKey: personalInfoPolicyQueryKey(), - }); - } - - return result; - }, - [queryClient], - ); - if (!session.user) return null; return ( @@ -168,16 +139,6 @@ export const OverviewSettings = ({ nameCode }: { nameCode: string }) => { onTimeZoneUpdate={onTimeZoneUpdate} onUpdate={onUpdate} personalFields={policy.fields} - privacy={ - <> - - - - } user={{ ...profile, headline: session.user.headline, diff --git a/packages/vitnode/src/tanstack/settings/privacy-panel.tsx b/packages/vitnode/src/tanstack/settings/privacy-panel.tsx index d8b8db1c42..85e7111ba6 100644 --- a/packages/vitnode/src/tanstack/settings/privacy-panel.tsx +++ b/packages/vitnode/src/tanstack/settings/privacy-panel.tsx @@ -1,6 +1,10 @@ import { useQueryClient, useSuspenseQuery } from "@tanstack/react-query"; import { useNavigate } from "@tanstack/react-router"; +import React from "react"; +import type { UpdatePrivacy } from "@/views/auth/settings/privacy/privacy-update"; + +import { personalInfoPolicyQueryKey } from "@/views/auth/settings/overview/personal-update"; import { PrivacySettingsContent } from "@/views/auth/settings/privacy/privacy-content"; import { accountDeletionQueryKey, @@ -9,8 +13,14 @@ import { downloadPersonalData, requestAccountDeletion, } from "@/views/auth/settings/privacy/privacy-query"; +import { PrivacySettings } from "@/views/auth/settings/privacy/privacy-settings"; +import { updatePrivacyInBrowser } from "@/views/auth/settings/privacy/privacy-update"; +import { ReactionPrivacySetting } from "@/views/auth/settings/privacy/reaction-privacy-setting"; +import { PRESENCE_QUERY_ROOT } from "@/views/presence/presence-query"; import { useSignOutAction } from "../auth/actions"; +import { invalidateSession, sessionQueryOptions } from "../auth/session-query"; +import { personalInfoPolicyQuery } from "./personal-policy"; export const PrivacyPanelContent = ({ userId, @@ -23,6 +33,28 @@ export const PrivacyPanelContent = ({ const queryClient = useQueryClient(); const navigate = useNavigate(); const signOut = useSignOutAction(); + const { data: session } = useSuspenseQuery(sessionQueryOptions()); + const { data: policy } = useSuspenseQuery(personalInfoPolicyQuery()); + + const onPrivacyUpdate: UpdatePrivacy = React.useCallback( + async input => { + const result = await updatePrivacyInBrowser(input); + if (result.data) { + await Promise.all([ + invalidateSession(queryClient), + queryClient.invalidateQueries({ queryKey: PRESENCE_QUERY_ROOT }), + ]); + } + if (result.error?.status === 403) { + await queryClient.invalidateQueries({ + queryKey: personalInfoPolicyQueryKey(), + }); + } + + return result; + }, + [queryClient], + ); return ( + {session.user ? ( + + ) : null} + + + } /> ); }; diff --git a/packages/vitnode/src/tanstack/site-status/access.ts b/packages/vitnode/src/tanstack/site-status/access.ts new file mode 100644 index 0000000000..5ee14d6b7b --- /dev/null +++ b/packages/vitnode/src/tanstack/site-status/access.ts @@ -0,0 +1,39 @@ +import type { SiteStatus } from "@vitnode/api/lib/site-status"; + +/** + * Pages every visitor can open while the site is offline, so staff can sign + * in: `/login` and everything below it (password reset, e-mail + * verification, SSO callbacks). Internal paths, without a locale prefix. + */ +export const SITE_OFFLINE_OPEN_PATHS = ["/login"] as const; + +/** Whether `pathname` (internal) stays open while the site is offline. */ +export const isSiteOfflineOpenPath = (pathname: string): boolean => + SITE_OFFLINE_OPEN_PATHS.some( + path => pathname === path || pathname.startsWith(`${path}/`), + ); + +/** + * Whether this viewer keeps using the site while it is offline: the API says + * so for admins and for moderators with the "Access the site while it's + * offline" staff permission. + */ +export const isSiteOfflineBypass = ( + status: Pick | undefined, +): boolean => !!status?.offline && status.viewerCanBypass; + +/** + * Whether this visitor gets the offline page instead of `pathname`: the site + * is offline, they may not bypass it, and the page is not one of + * {@link SITE_OFFLINE_OPEN_PATHS}. + */ +export const isSiteClosedTo = ({ + pathname, + status, +}: { + pathname: string; + status: Pick | undefined; +}): boolean => + !!status?.offline && + !status.viewerCanBypass && + !isSiteOfflineOpenPath(pathname); diff --git a/packages/vitnode/src/tanstack/site-status/gate.tsx b/packages/vitnode/src/tanstack/site-status/gate.tsx new file mode 100644 index 0000000000..c67aeb76c0 --- /dev/null +++ b/packages/vitnode/src/tanstack/site-status/gate.tsx @@ -0,0 +1,126 @@ +import { useQuery } from "@tanstack/react-query"; +import { useLocation, useRouter } from "@tanstack/react-router"; +import React from "react"; +import { useLocale } from "use-intl"; + +import { useLogo } from "@/components/logo-context"; +import { SiteOfflineContent } from "@/views/site-offline/site-offline-content"; +import { getVitNodeConfig } from "@/vitnode.config"; + +import { useSessionQuery } from "../auth/session-query"; +import { RouteMessages } from "../i18n/route-messages"; +import { isSiteClosedTo, isSiteOfflineBypass } from "./access"; +import { SITE_OFFLINE_NAMESPACES } from "./load"; +import { siteStatusQueryOptions } from "./query"; +import { SiteOfflineStaffChip } from "./staff-chip"; + +/** The site status for the signed-in viewer (or a guest). */ +const useViewerSiteStatus = () => { + const { data: session } = useSessionQuery(); + + return useQuery( + siteStatusQueryOptions({ viewerId: session?.user?.id ?? null }), + ); +}; + +const OfflineScreen = () => { + const locale = useLocale(); + const logo = useLogo(); + const { data, dataUpdatedAt } = useViewerSiteStatus(); + if (!data) return null; + + return ( +
+ +
+ ); +}; + +const StaffChip = () => { + const { data } = useViewerSiteStatus(); + if (!data) return null; + + return ; +}; + +/** The full-page offline screen, for a visitor who may not use the offline site. */ +export const SiteOfflineScreen = () => ( + + + +); + +/** + * Tells a viewer who may use the offline site that visitors see the offline + * page: a floating pill with the details and an AdminCP link, and an + * "(Offline)" prefix on the page title. + */ +export const SiteOfflineStaffBanner = () => ( + + + +); + +/** Which frame this visitor gets: the site, the site with the staff reminder, or the offline page. */ +export type SiteOfflineView = "closed" | "open" | "staff"; + +/** + * Which frame this visitor gets, from the viewer's status and the session that + * `loadMainShell` already loaded. + */ +export const useSiteOfflineView = (): SiteOfflineView => { + const { data: status } = useViewerSiteStatus(); + const { pathname } = useLocation(); + + const router = useRouter(); + const wasClosed = React.useRef(false); + + let view: SiteOfflineView = "open"; + if (status?.offline) { + if (isSiteClosedTo({ pathname, status })) view = "closed"; + else if (isSiteOfflineBypass(status)) view = "staff"; + } + + React.useEffect(() => { + if (view === "closed") { + wasClosed.current = true; + + return; + } + if (!wasClosed.current) return; + wasClosed.current = false; + void router.invalidate(); + }, [router, view]); + + return view; +}; + +/** + * Swaps `children` for the offline page while the site is offline, except for + * viewers who may use the offline site (they get a floating reminder pill) + * and the sign-in pages. For a + * custom public layout; `ThemeLayoutContent` already does it. + */ +export const SiteOfflineGate = ({ + children, +}: { + children: React.ReactNode; +}) => { + const view = useSiteOfflineView(); + + if (view === "closed") return ; + + return ( + <> + {view === "staff" ? : null} + {children} + + ); +}; diff --git a/packages/vitnode/src/tanstack/site-status/index.ts b/packages/vitnode/src/tanstack/site-status/index.ts new file mode 100644 index 0000000000..f1c370f0e3 --- /dev/null +++ b/packages/vitnode/src/tanstack/site-status/index.ts @@ -0,0 +1,3 @@ +export { SiteOfflineGate } from "./gate"; +export type { SiteStatus } from "./query"; +export { siteStatusQueryKey, siteStatusQueryOptions } from "./query"; diff --git a/packages/vitnode/src/tanstack/site-status/load.ts b/packages/vitnode/src/tanstack/site-status/load.ts new file mode 100644 index 0000000000..02c2c85292 --- /dev/null +++ b/packages/vitnode/src/tanstack/site-status/load.ts @@ -0,0 +1,36 @@ +import type { QueryClient } from "@tanstack/react-query"; + +import { sessionQueryOptions } from "../auth/session-query"; +import { intlQueryOptions } from "../i18n/query"; +import { isSiteClosedTo } from "./access"; +import { siteStatusQueryOptions } from "./query"; +import { markSiteOfflineResponse } from "./response"; + +/** The strings of the offline page and the staff banner. */ +export const SITE_OFFLINE_NAMESPACES = ["core.site_offline", "core.global"]; + +/** + * Warms the site status for the shell and, when this visitor gets the offline + * page, answers the request with `503`. Call it after the session is loaded + * (a shared render has none, so it is treated as a guest). A status that + * fails to load counts as online: an API hiccup never takes the site down. + */ +export const loadSiteStatusGate = async ( + { locale, queryClient }: { locale: string; queryClient: QueryClient }, + pathname: string, +): Promise => { + const session = queryClient.getQueryData(sessionQueryOptions().queryKey); + const status = await queryClient + .query(siteStatusQueryOptions({ viewerId: session?.user?.id ?? null })) + .catch(() => undefined); + if (!status?.offline) return; + + await queryClient.query({ + ...intlQueryOptions({ locale, namespaces: SITE_OFFLINE_NAMESPACES }), + staleTime: "static", + }); + + if (isSiteClosedTo({ pathname, status })) { + markSiteOfflineResponse(status.opensAt); + } +}; diff --git a/packages/vitnode/src/tanstack/site-status/query.ts b/packages/vitnode/src/tanstack/site-status/query.ts new file mode 100644 index 0000000000..0e5bfa8b5a --- /dev/null +++ b/packages/vitnode/src/tanstack/site-status/query.ts @@ -0,0 +1,64 @@ +import type { SiteStatus } from "@vitnode/api/lib/site-status"; + +import { queryOptions } from "@tanstack/react-query"; +import { manifest } from "@vitnode/api/manifest"; + +import { fetcher } from "../fetcher"; + +export type { SiteStatus } from "@vitnode/api/lib/site-status"; + +/** How often an open offline page asks whether the site is back. */ +const SITE_OFFLINE_POLL_MS = 60_000; + +const SITE_STATUS_STALE_TIME = 60_000; + +export const siteStatusQueryKey = ["@vitnode/core", "site-status"] as const; + +const fetchSiteStatus = async (): Promise => { + const response = await fetcher({ + plugin: manifest.id, + method: "get", + module: "site", + path: "/status", + }); + if (!response.ok) { + throw new Error(`The site status did not load (${response.status}).`); + } + + return await response.json(); +}; + +/** + * Whether the public site is online, as a TanStack Query. While it is offline + * it also holds the reason per language, the planned opening time and whether + * this viewer may still use the site (`viewerCanBypass`), and it + * refetches every minute so an open offline page notices the reopening. + * Universal. + * + * @example + * ```ts + * import { siteStatusQueryOptions } from "@vitnode/core/tanstack/site-status"; + * + * const status = await queryClient.query(siteStatusQueryOptions()); + * if (status.offline) console.log("Closed until", status.opensAt); + * ``` + */ +export const siteStatusQueryOptions = ({ + viewerId = null, +}: { + /** + * The signed-in user's id, or `null` for a guest. The answer says whether + * this viewer may use the offline site, so each viewer gets their own + * cache entry and signing in fetches it again. + */ + viewerId?: null | number; +} = {}) => + queryOptions({ + queryFn: fetchSiteStatus, + queryKey: [...siteStatusQueryKey, viewerId ?? "guest"] as const, + refetchInterval: query => + query.state.data?.offline ? SITE_OFFLINE_POLL_MS : false, + refetchOnWindowFocus: query => query.state.data?.offline === true, + retry: false, + staleTime: SITE_STATUS_STALE_TIME, + }); diff --git a/packages/vitnode/src/tanstack/site-status/response.ts b/packages/vitnode/src/tanstack/site-status/response.ts new file mode 100644 index 0000000000..15ffd63668 --- /dev/null +++ b/packages/vitnode/src/tanstack/site-status/response.ts @@ -0,0 +1,22 @@ +import { createIsomorphicFn } from "@tanstack/react-start"; +import { + setResponseHeader, + setResponseStatus, +} from "@tanstack/react-start/server"; +import { retryAfterSeconds } from "@vitnode/api/lib/site-status"; + +/** + * Answers the current SSR request as an offline page: `503` (so search + * engines keep the old copy and the page cache never stores it), no indexing, + * no caching, and `Retry-After` when the opening time is known. A no-op in the + * browser. + */ +export const markSiteOfflineResponse = createIsomorphicFn() + .server((opensAt: null | string) => { + setResponseStatus(503); + setResponseHeader("cache-control", "no-store"); + setResponseHeader("x-robots-tag", "noindex"); + const retryAfter = retryAfterSeconds(opensAt); + if (retryAfter) setResponseHeader("retry-after", String(retryAfter)); + }) + .client(() => undefined); diff --git a/packages/vitnode/src/tanstack/site-status/staff-chip.tsx b/packages/vitnode/src/tanstack/site-status/staff-chip.tsx new file mode 100644 index 0000000000..0507e1f3bd --- /dev/null +++ b/packages/vitnode/src/tanstack/site-status/staff-chip.tsx @@ -0,0 +1,168 @@ +import type { SiteStatus } from "@vitnode/api/lib/site-status"; + +import { ClockIcon, SettingsIcon } from "lucide-react"; +import React from "react"; +import { useTranslations } from "use-intl"; + +import { buttonVariants } from "@/components/ui/button"; +import { + Popover, + PopoverContent, + PopoverDescription, + PopoverHeader, + PopoverTitle, + PopoverTrigger, +} from "@/components/ui/popover"; +import { countdownParts } from "@/views/site-offline/countdown-parts"; + +import { HrefLink } from "../link"; + +const MANAGE_HREF = "/admin/core/debug#site-status"; +const CLOCK_TICK_MS = 30_000; + +const subscribeToClock = (onTick: () => void) => { + const interval = window.setInterval(onTick, CLOCK_TICK_MS); + document.addEventListener("visibilitychange", onTick); + + return () => { + window.clearInterval(interval); + document.removeEventListener("visibilitychange", onTick); + }; +}; + +const getClockSnapshot = () => + Math.floor(Date.now() / CLOCK_TICK_MS) * CLOCK_TICK_MS; + +const getServerClockSnapshot = () => null; + +const useClientNow = (): null | number => + React.useSyncExternalStore( + subscribeToClock, + getClockSnapshot, + getServerClockSnapshot, + ); + +const useOfflineDocumentTitle = () => { + const t = useTranslations("core.site_offline.staff_banner"); + const format = React.useCallback( + (title: string) => t("document_title", { title }), + [t], + ); + + React.useEffect(() => { + let baseTitle = document.title; + let applied = format(baseTitle); + document.title = applied; + + const observer = new MutationObserver(() => { + if (document.title === applied) return; + baseTitle = document.title; + applied = format(baseTitle); + document.title = applied; + }); + observer.observe(document.head, { + characterData: true, + childList: true, + subtree: true, + }); + + return () => { + observer.disconnect(); + if (document.title === applied) document.title = baseTitle; + }; + }, [format]); +}; + +const ReopenTime = ({ opensAt }: { opensAt: string }) => { + const t = useTranslations("core.site_offline.countdown"); + const now = useClientNow(); + if (now === null) return null; + + const parts = countdownParts(Date.parse(opensAt), now); + + return ( +

+

+ ); +}; + +const CompactReopenTime = ({ opensAt }: { opensAt: string }) => { + const t = useTranslations("core.site_offline.countdown.units"); + const now = useClientNow(); + if (now === null) return null; + + const parts = countdownParts(Date.parse(opensAt), now); + if (parts.done) return null; + const units = [ + parts.days ? `${parts.days}${t("days")}` : null, + parts.hours ? `${parts.hours}${t("hours")}` : null, + `${parts.minutes}${t("minutes")}`, + ].filter(Boolean); + + return ( + + ); +}; + +/** + * A floating pill for viewers who may use the offline site: the details and a + * link to the AdminCP open in a popover, and every page title gets an + * "(Offline)" prefix while it is mounted. Browser-only effects. + */ +export const SiteOfflineStaffChip = ({ + status, +}: { + status: Pick; +}) => { + const t = useTranslations("core.site_offline.staff_banner"); + useOfflineDocumentTitle(); + + return ( +
+ + + + + + {t("title")} + + {t("desc")} + + + {status.opensAt ? : null} + + + + +
+ ); +}; diff --git a/packages/vitnode/src/views/admin/views/core/debug/health/health.ts b/packages/vitnode/src/views/admin/views/core/debug/health/health.ts index 930effbc05..877bd83b93 100644 --- a/packages/vitnode/src/views/admin/views/core/debug/health/health.ts +++ b/packages/vitnode/src/views/admin/views/core/debug/health/health.ts @@ -11,6 +11,7 @@ import type { AdminInstalledPlugin, AdminInstalledPlugins, } from "@/views/admin/views/core/system/plugins/plugins-query"; +import type { AdminSiteStatus } from "@/views/admin/views/core/system/site-status/site-status-query"; import type { AccountDeletionsSummary } from "@/views/admin/views/core/users/deletions/deletions-query"; import type { DebugQueueSnapshot } from "../debug-query"; @@ -24,6 +25,7 @@ export interface DebugSources { integrations?: AdminIntegrations; queue?: DebugQueueSnapshot; search?: SearchIndexStatus; + siteStatus?: AdminSiteStatus; updates?: AdminPluginUpdates; } @@ -73,6 +75,8 @@ export type DebugMessageKey = | "search.subtitle" | "search.sync_errors" | "services.subtitle" + | "site.offline" + | "site.offline_until" | "vitnode.not_checked" | "vitnode.security_update" | "vitnode.source_unreachable" @@ -92,8 +96,11 @@ export interface DebugMessage { export type DebugAreaId = "deletions" | DebugSystemTab; export interface DebugCheck { - area: DebugAreaId; + /** The system area it belongs to; `undefined` for a site-wide state. */ + area?: DebugAreaId; detail?: string; + /** Where the issue is fixed, when that is not a debug tab. */ + href?: string; id: string; message: DebugMessage; tab: DebugTab; @@ -489,6 +496,25 @@ const area = ( tone: worstTone(checks.map(check => check.tone)), }); +/** The public site is switched off: worth a warning until someone turns it on. */ +const siteStatusChecks = (siteStatus: AdminSiteStatus): DebugCheck[] => + siteStatus.offline + ? [ + { + href: "/admin/core/debug#site-status", + id: "site.offline", + message: siteStatus.opensAt + ? { + key: "site.offline_until", + values: { opensAt: Date.parse(siteStatus.opensAt) }, + } + : { key: "site.offline" }, + tab: "overview", + tone: "warn", + }, + ] + : []; + export const debugHealth = ({ cronHealth, deletions, @@ -496,6 +522,7 @@ export const debugHealth = ({ integrations, queue, search, + siteStatus, updates, }: DebugSources): DebugHealth => { const areas: DebugArea[] = []; @@ -593,8 +620,10 @@ export const debugHealth = ({ ); } - const issues = areas - .flatMap(entry => entry.checks) + const issues = [ + ...(siteStatus ? siteStatusChecks(siteStatus) : []), + ...areas.flatMap(entry => entry.checks), + ] .filter(check => isProblem(check.tone)) .sort((a, b) => TONE_RANK[b.tone] - TONE_RANK[a.tone]); diff --git a/packages/vitnode/src/views/admin/views/core/debug/sections/overview.tsx b/packages/vitnode/src/views/admin/views/core/debug/sections/overview.tsx index defc5d8e2c..a17acf7fd0 100644 --- a/packages/vitnode/src/views/admin/views/core/debug/sections/overview.tsx +++ b/packages/vitnode/src/views/admin/views/core/debug/sections/overview.tsx @@ -16,6 +16,7 @@ import { FrameTitle, } from "@/components/ui/frame"; import { debugTabPath } from "@/tanstack/admin/debug/route-search"; +import { HrefLink } from "@/tanstack/link"; import { ADMIN_DEBUG_PERMISSIONS } from "@/views/admin/views/core/shared/admin-permissions"; import type { DebugHealth } from "../health/health"; @@ -36,6 +37,7 @@ export const DebugOverview = ({ isRechecking, onClearCache, onRecheck, + siteStatus, updates, version, }: { @@ -45,6 +47,7 @@ export const DebugOverview = ({ isRechecking: boolean; onClearCache: () => Promise; onRecheck: () => void; + siteStatus?: React.ReactNode; updates: AdminPluginUpdates | undefined; version: null | string; }) => { @@ -59,6 +62,8 @@ export const DebugOverview = ({ ) : null} + {siteStatus} + @@ -86,30 +91,42 @@ export const DebugOverview = ({ {health.issues.length > 0 ? ( - {health.issues.map(issue => ( - - - - - {tHealth(issue.message.key, issue.message.values)} - - {issue.detail ? ( - - {issue.detail} + {health.issues.map(issue => { + const row = ( + <> + + + + {tHealth(issue.message.key, issue.message.values)} - ) : null} - - - - ))} + {issue.detail ? ( + + {issue.detail} + + ) : null} + + + + ); + + return issue.href ? ( + + {row} + + ) : ( + + {row} + + ); + })} ) : null} diff --git a/packages/vitnode/src/views/admin/views/core/debug/sections/site-status.tsx b/packages/vitnode/src/views/admin/views/core/debug/sections/site-status.tsx new file mode 100644 index 0000000000..9cdf76db68 --- /dev/null +++ b/packages/vitnode/src/views/admin/views/core/debug/sections/site-status.tsx @@ -0,0 +1,382 @@ +import type { SiteStatusUpdate } from "@vitnode/api/lib/site-status"; + +import { useSelector } from "@tanstack/react-form"; +import { + isRichTextDocument, + isRichTextEmpty, +} from "@vitnode/api/content/rich-text/document"; +import { cn } from "cn"; +import { + CircleCheckIcon, + PowerIcon, + PowerOffIcon, + SaveIcon, +} from "lucide-react"; +import { toast } from "sonner"; +import { useTranslations } from "use-intl"; +import { z } from "zod"; + +import type { AutoFormOnSubmit } from "@/components/form/auto-form"; +import type { AdminMutationResult } from "@/views/admin/views/core/shared/admin-mutation"; +import type { AdminSiteStatus } from "@/views/admin/views/core/system/site-status/site-status-query"; + +import { DateFormat } from "@/components/date-format"; +import { AutoForm } from "@/components/form/auto-form"; +import { AutoFormDateTime } from "@/components/form/fields/date-time"; +import { AutoFormEditor } from "@/components/form/fields/editor"; +import { AutoFormSwitch } from "@/components/form/fields/switch"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { useFormApi } from "@/components/ui/form"; +import { + Frame, + FrameDescription, + FrameHeader, + FramePanel, + FrameTitle, +} from "@/components/ui/frame"; +import { ValueSwap } from "@/components/ui/value-swap"; +import { getVitNodeConfig } from "@/vitnode.config"; + +const SITE_STATUS_ANCHOR = "site-status"; + +const documentSchema = z.looseObject({ + content: z.array(z.unknown()).optional(), + type: z.literal("doc"), +}); + +const isPast = (iso: string): boolean => Date.parse(iso) <= Date.now(); + +interface FormValues { + message: { languageCode: string; value: unknown }[]; + offline: boolean; + opensAt: null | string; + showCountdown: boolean; +} + +const filledMessage = (message: FormValues["message"]) => + message.flatMap(item => + isRichTextDocument(item.value) && !isRichTextEmpty(item.value) + ? [{ languageCode: item.languageCode, value: item.value }] + : [], + ); + +const useFormValues = (): FormValues => { + const { form } = useFormApi(); + + return useSelector(form.store, state => state.values as FormValues); +}; + +const useIsFormDirty = (): boolean => { + const { form } = useFormApi(); + + return useSelector(form.store, state => !state.isDefaultValue); +}; + +const Reveal = ({ + children, + from, + open, +}: { + children: React.ReactNode; + from: "above" | "below"; + open: boolean; +}) => ( +
+
{children}
+
+); + +const StatusIcon = ({ offline }: { offline: boolean }) => { + const icon = + "absolute inset-0 m-auto size-5 transition-[opacity,scale,filter] motion-reduce:transition-none"; + const shown = "blur-none scale-100 opacity-100 duration-200 ease-out"; + const hidden = "blur-xs scale-75 opacity-0 duration-150 ease-in"; + + return ( + + ); +}; + +const StatusHeader = ({ data }: { data: AdminSiteStatus }) => { + const t = useTranslations("admin.system.site_status"); + const { offline } = useFormValues(); + + return ( + + + + + {offline ? t("status.offline") : t("status.online")} + + {offline === data.offline ? null : ( + + {t("status.not_saved")} + + )} + + + {data.changedAt ? ( + <> + {t("status.last_switched")} + {data.changedBy + ? ` · ${t("status.by", { name: data.changedBy.name })}` + : null} + + ) : ( + t("status.never") + )} + + + ); +}; + +const SubmitButton = ({ data }: { data: AdminSiteStatus }) => { + const t = useTranslations("admin.system.site_status.save_bar"); + const { form } = useFormApi(); + const isSubmitting = useSelector(form.store, state => state.isSubmitting); + const { offline } = useFormValues(); + const switching = offline !== data.offline; + + let action: "save" | "turn_off" | "turn_on" = "save"; + if (switching) action = offline ? "turn_off" : "turn_on"; + const Icon = { + save: SaveIcon, + turn_off: PowerOffIcon, + turn_on: PowerIcon, + }[action]; + + return ( + + ); +}; + +const SaveFooter = ({ data }: { data: AdminSiteStatus }) => { + const t = useTranslations("admin.system.site_status.save_bar"); + const { form } = useFormApi(); + const isDirty = useIsFormDirty(); + const isSubmitting = useSelector(form.store, state => state.isSubmitting); + + return ( + +
+

+ {isDirty ? t("unsaved") : null} +

+
+ + +
+
+
+ ); +}; + +const OfflineDetails = ({ children }: { children: React.ReactNode }) => { + const { offline } = useFormValues(); + + return ( + +
{children}
+
+ ); +}; + +export const SiteStatusFrame = ({ + canManage, + data, + onSave, +}: { + canManage: boolean; + data: AdminSiteStatus; + onSave: (values: SiteStatusUpdate) => Promise>; +}) => { + const t = useTranslations("admin.system.site_status"); + const tError = useTranslations("core.global.errors"); + const defaultLanguage = getVitNodeConfig().i18n.defaultLocale; + + const formSchema = z + .object({ + offline: z.boolean().default(data.offline), + message: z + .array(z.object({ languageCode: z.string(), value: documentSchema })) + .default( + data.message.map(item => ({ + languageCode: item.languageCode, + value: { ...item.value }, + })), + ), + opensAt: z.string().nullable().default(data.opensAt), + showCountdown: z.boolean().default(data.showCountdown), + }) + .superRefine((values, ctx) => { + if ( + values.offline && + !filledMessage(values.message).some( + item => item.languageCode === defaultLanguage, + ) + ) { + ctx.addIssue({ + code: "custom", + message: t("form.message.required"), + path: ["message"], + }); + } + if ( + values.opensAt !== null && + values.opensAt !== data.opensAt && + isPast(values.opensAt) + ) { + ctx.addIssue({ + code: "custom", + message: t("form.opens_at.past"), + path: ["opensAt"], + }); + } + }); + + const onSubmit: AutoFormOnSubmit = async ( + values, + formApi, + ) => { + const result = await onSave({ + message: filledMessage(values.message), + offline: values.offline, + opensAt: values.opensAt, + showCountdown: values.showCountdown, + }); + if ("error" in result) { + toast.error(tError("title"), { + description: + result.error.status === 400 && result.error.message + ? result.error.message + : tError("internal_server_error"), + }); + + return; + } + + formApi.reset(formApi.state.values); + let key: "saved" | "turned_off" | "turned_on" = "saved"; + if (values.offline !== data.offline) { + key = values.offline ? "turned_off" : "turned_on"; + } + toast.success(t(`toast.${key}.title`), { + description: t(`toast.${key}.desc`), + }); + }; + + return ( + ( + + ), + id: "offline", + }, + { + component: props => ( + + ), + id: "message", + }, + { + component: props => ( + + ), + id: "opensAt", + }, + { + component: props => ( + + ), + hidden: values => !values.opensAt, + id: "showCountdown", + }, + ]} + formSchema={formSchema} + layout={rendered => ( + } + > + + +
+ {rendered.offline} + + {rendered.message} +
+ {rendered.opensAt} + {rendered.showCountdown} +
+
+
+
+ {canManage ? : null} + + )} + onSubmit={onSubmit} + /> + ); +}; diff --git a/packages/vitnode/src/views/admin/views/core/shared/admin-permissions.ts b/packages/vitnode/src/views/admin/views/core/shared/admin-permissions.ts index 43bbb2f048..22260e6dce 100644 --- a/packages/vitnode/src/views/admin/views/core/shared/admin-permissions.ts +++ b/packages/vitnode/src/views/admin/views/core/shared/admin-permissions.ts @@ -19,6 +19,8 @@ export const ADMIN_DEBUG_PERMISSIONS = { cron: admin.cron.canView, plugins: admin.plugins.canView, queue: admin.queue.canView, + manageSiteStatus: admin.site_status.canManage, + siteStatus: admin.site_status.canView, system: admin.system.canView, testAi: admin.system.canTestAi, testEmail: admin.system.canSendTestEmail, diff --git a/packages/vitnode/src/views/admin/views/core/system/site-status/site-status-query.ts b/packages/vitnode/src/views/admin/views/core/system/site-status/site-status-query.ts new file mode 100644 index 0000000000..f20d1825f9 --- /dev/null +++ b/packages/vitnode/src/views/admin/views/core/system/site-status/site-status-query.ts @@ -0,0 +1,58 @@ +import type { SiteStatusUpdate } from "@vitnode/api/lib/site-status"; +import type { zodSiteStatusAdmin } from "@vitnode/api/modules/admin/site/site.schema"; +import type { z } from "zod"; + +import { queryOptions } from "@tanstack/react-query"; +import { manifest } from "@vitnode/api/manifest"; + +import { fetcherClient } from "@/lib/fetcher-client"; +import { RECORD_STALE_TIME } from "@/lib/query-freshness"; +import { fetcher } from "@/tanstack/fetcher"; +import { AdminRequestError } from "@/views/admin/admin-request"; +import { adminQueryRoot } from "@/views/admin/table/query"; +import { + type AdminMutationResult, + runAdminApiMutation, +} from "@/views/admin/views/core/shared/admin-mutation"; + +export type AdminSiteStatus = z.infer; + +const adminSiteStatusQueryKey = adminQueryRoot("site-status"); + +export const adminSiteStatusQueryOptions = () => + queryOptions({ + queryFn: async (): Promise => { + const response = await fetcher({ + plugin: manifest.id, + method: "get", + module: "admin/site", + path: "/status", + }); + if (!response.ok) { + throw new AdminRequestError(response.status, "the site status"); + } + + return await response.json(); + }, + queryKey: adminSiteStatusQueryKey, + retry: false, + /** {@link RECORD_STALE_TIME} - it changes when an administrator saves it. */ + staleTime: RECORD_STALE_TIME, + }); + +export const updateAdminSiteStatus = async ( + body: SiteStatusUpdate, +): Promise> => + await runAdminApiMutation({ + expected: 200, + parse: () => true as const, + request: async () => + await fetcherClient({ + plugin: manifest.id, + args: { body }, + method: "put", + module: "admin/site", + options: { credentials: "include" }, + path: "/status", + }), + }); diff --git a/packages/vitnode/src/views/auth/settings/nav-content.tsx b/packages/vitnode/src/views/auth/settings/nav-content.tsx index 66df69d524..198583b330 100644 --- a/packages/vitnode/src/views/auth/settings/nav-content.tsx +++ b/packages/vitnode/src/views/auth/settings/nav-content.tsx @@ -13,7 +13,12 @@ import { import React from "react"; import { useTranslations } from "use-intl"; -import { SideNav, SideNavLink, SideNavList } from "@/components/side-nav"; +import { + SideNav, + SideNavGroup, + SideNavLink, + SideNavList, +} from "@/components/side-nav"; import { Button } from "@/components/ui/button"; import { Drawer, @@ -25,7 +30,11 @@ import { import type { SettingsNavItem, SettingsNavKey } from "./settings-nav"; -import { isSettingsNavItemActive, SETTINGS_NAV_ITEMS } from "./settings-nav"; +import { + groupSettingsNavItems, + isSettingsNavItemActive, + SETTINGS_NAV_ITEMS, +} from "./settings-nav"; const ICONS: Record< SettingsNavKey, @@ -51,21 +60,24 @@ const SettingsNavList = ({ pathname: string; }) => { const tNav = useTranslations("core.auth.settings.nav"); + const tGroups = useTranslations("core.auth.settings.nav_groups"); - return ( - - {items.map(item => ( - - ))} - - ); + return groupSettingsNavItems(items).map(group => ( + + + {group.items.map(item => ( + + ))} + + + )); }; const SettingsNavDrawer = ({ diff --git a/packages/vitnode/src/views/auth/settings/overview/overview.tsx b/packages/vitnode/src/views/auth/settings/overview/overview.tsx index 1628beb3eb..ac382d735c 100644 --- a/packages/vitnode/src/views/auth/settings/overview/overview.tsx +++ b/packages/vitnode/src/views/auth/settings/overview/overview.tsx @@ -41,7 +41,6 @@ export const OverviewSettingsContent = ({ personalFields, onTimeZoneUpdate, onUpdate, - privacy, user, }: { aiPoints?: React.ReactNode; @@ -50,7 +49,6 @@ export const OverviewSettingsContent = ({ onTimeZoneUpdate: UpdateTimeZone; onUpdate: UpdatePersonalInformation; personalFields: PersonalInformationFields; - privacy?: React.ReactNode; user: SettingsOverviewUser; }) => { const t = useTranslations("core.auth.settings.overview"); @@ -166,8 +164,6 @@ export const OverviewSettingsContent = ({ - {privacy} - {aiPoints} ); diff --git a/packages/vitnode/src/views/auth/settings/privacy/privacy-content.tsx b/packages/vitnode/src/views/auth/settings/privacy/privacy-content.tsx index 91252a53ff..5858f59fb8 100644 --- a/packages/vitnode/src/views/auth/settings/privacy/privacy-content.tsx +++ b/packages/vitnode/src/views/auth/settings/privacy/privacy-content.tsx @@ -48,6 +48,8 @@ export interface PrivacySettingsContentProps { }) => Promise; status: AccountDeletionStatus; userName: string; + /** Who can see the member's activity: online status, reactions. Rendered above the data export. */ + visibility?: React.ReactNode; } export const PrivacySettingsHeading = () => { @@ -358,9 +360,11 @@ export const PrivacySettingsContent = ({ onRequestDeletion, status, userName, + visibility, }: PrivacySettingsContentProps) => ( <> + {visibility} { - const t = useTranslations("core.auth.settings"); - const tNav = useTranslations("core.auth.settings.nav"); - - return <>{navKey === undefined ? t("title") : tNav(navKey)}; -}; diff --git a/packages/vitnode/src/views/auth/settings/settings-nav.ts b/packages/vitnode/src/views/auth/settings/settings-nav.ts index 37103fe527..eb39b47c4f 100644 --- a/packages/vitnode/src/views/auth/settings/settings-nav.ts +++ b/packages/vitnode/src/views/auth/settings/settings-nav.ts @@ -13,23 +13,47 @@ export type SettingsNavKey = | "sso" | "standing"; +/** The `core.auth.settings.nav_groups` key a group's heading comes from, in display order. */ +export const SETTINGS_NAV_GROUPS = [ + "account", + "preferences", + "safety", +] as const; + +export type SettingsNavGroupKey = (typeof SETTINGS_NAV_GROUPS)[number]; + export interface SettingsNavItem { + /** The heading the item is listed under. */ + group: SettingsNavGroupKey; href: string; /** The `core.auth.settings.nav` key this item's label comes from. */ key: SettingsNavKey; } export const SETTINGS_NAV_ITEMS: readonly SettingsNavItem[] = [ - { href: SETTINGS_ROOT_HREF, key: "overview" }, - { href: "/settings/notifications", key: "notifications" }, - { href: "/settings/devices", key: "devices" }, - { href: "/settings/security", key: "security" }, - { href: "/settings/sso", key: "sso" }, - { href: "/settings/ai", key: "ai" }, - { href: "/settings/standing", key: "standing" }, - { href: "/settings/privacy", key: "privacy" }, + { group: "account", href: SETTINGS_ROOT_HREF, key: "overview" }, + { + group: "preferences", + href: "/settings/notifications", + key: "notifications", + }, + { group: "account", href: "/settings/devices", key: "devices" }, + { group: "account", href: "/settings/security", key: "security" }, + { group: "account", href: "/settings/sso", key: "sso" }, + { group: "preferences", href: "/settings/ai", key: "ai" }, + { group: "safety", href: "/settings/standing", key: "standing" }, + { group: "safety", href: "/settings/privacy", key: "privacy" }, ]; +/** The items under each non-empty group, groups in display order. */ +export const groupSettingsNavItems = ( + items: readonly SettingsNavItem[], +): { items: SettingsNavItem[]; key: SettingsNavGroupKey }[] => + SETTINGS_NAV_GROUPS.map(key => ({ + items: items.filter(item => item.group === key), + key, + })).filter(group => group.items.length > 0); + export const visibleSettingsNavItems = ({ ai, aiFeatures = true, diff --git a/packages/vitnode/src/views/auth/settings/shell-content.tsx b/packages/vitnode/src/views/auth/settings/shell-content.tsx index 0b12236b0d..5c016893b8 100644 --- a/packages/vitnode/src/views/auth/settings/shell-content.tsx +++ b/packages/vitnode/src/views/auth/settings/shell-content.tsx @@ -30,7 +30,7 @@ export const SettingsShellContent = ({ ); return ( -
+
{header}
{ + const left = Math.max(0, targetMs - nowMs); + + return { + days: Math.floor(left / DAY), + done: left < SECOND, + hours: Math.floor((left % DAY) / HOUR), + minutes: Math.floor((left % HOUR) / MINUTE), + seconds: Math.floor((left % MINUTE) / SECOND), + }; +}; diff --git a/packages/vitnode/src/views/site-offline/countdown.tsx b/packages/vitnode/src/views/site-offline/countdown.tsx new file mode 100644 index 0000000000..6654c20797 --- /dev/null +++ b/packages/vitnode/src/views/site-offline/countdown.tsx @@ -0,0 +1,166 @@ +import { cn } from "cn"; +import { CalendarClockIcon } from "lucide-react"; +import React from "react"; +import { useFormatter, useLocale, useTranslations } from "use-intl"; + +import { SlidingNumber } from "@/components/ui/sliding-number"; + +import { countdownParts } from "./countdown-parts"; + +const TICK_MS = 1000; + +const subscribeToClock = (onTick: () => void) => { + const interval = window.setInterval(onTick, TICK_MS); + document.addEventListener("visibilitychange", onTick); + + return () => { + window.clearInterval(interval); + document.removeEventListener("visibilitychange", onTick); + }; +}; + +const toSecond = (ms: number) => Math.floor(ms / TICK_MS) * TICK_MS; + +/** + * The current time, ticking once a second and corrected by `offsetMs`. During + * SSR and hydration it is `serverNowMs`, so the first paint already shows the + * right digits and the markup matches. + */ +const useServerClock = (serverNowMs: number, offsetMs: number): number => { + const getSnapshot = React.useCallback( + () => toSecond(Date.now() + offsetMs), + [offsetMs], + ); + + return React.useSyncExternalStore(subscribeToClock, getSnapshot, () => + toSecond(serverNowMs), + ); +}; + +const UNITS = ["days", "hours", "minutes", "seconds"] as const; + +const OpensAtDate = ({ opensAt }: { opensAt: string }) => { + const format = useFormatter(); + + return ( + + ); +}; + +/** + * When the site opens, as a compact row: a live countdown with rolling + * digits and the date, or (with `showCountdown` off) the date alone. Once the + * time has passed it shows "Opening soon". It never opens anything itself. + */ +export const SiteOpening = ({ + className, + fetchedAt, + opensAt, + serverNow, + showCountdown, +}: { + className?: string; + /** When the client received `serverNow` (`dataUpdatedAt`), for the skew correction. */ + fetchedAt?: number; + opensAt: string; + /** The server's clock when it answered. */ + serverNow: string; + /** `false` shows the date without the ticking countdown. */ + showCountdown: boolean; +}) => { + const t = useTranslations("core.site_offline.countdown"); + const locale = useLocale(); + const serverNowMs = Date.parse(serverNow); + const offsetMs = fetchedAt ? serverNowMs - fetchedAt : 0; + const now = useServerClock(serverNowMs, offsetMs); + const parts = countdownParts(Date.parse(opensAt), now); + const twoDigits = React.useMemo( + () => new Intl.NumberFormat(locale, { minimumIntegerDigits: 2 }), + [locale], + ); + const frame = cn( + "bg-muted/60 flex flex-col gap-1 rounded-xl px-4 py-3 text-start @sm:flex-row @sm:items-center @sm:justify-between @sm:gap-4", + className, + ); + + if (parts.done) { + return ( +
+

+

+
+ ); + } + + if (!showCountdown) { + return ( +
+
+ ); + } + + const visible = UNITS.filter(unit => unit !== "days" || parts.days > 0); + + return ( +
+
+

+ {t("back_in")} +

+

+ {visible.map(unit => ( + + ))} +

+
+

+

+
+ ); +}; diff --git a/packages/vitnode/src/views/site-offline/site-offline-content.tsx b/packages/vitnode/src/views/site-offline/site-offline-content.tsx new file mode 100644 index 0000000000..48be2dee34 --- /dev/null +++ b/packages/vitnode/src/views/site-offline/site-offline-content.tsx @@ -0,0 +1,86 @@ +import type { SiteStatus } from "@vitnode/api/lib/site-status"; + +import { pickSiteOfflineMessage } from "@vitnode/api/lib/site-status"; +import { cn } from "cn"; +import { useTranslations } from "use-intl"; + +import { RichTextContent } from "@/components/rich-text"; + +import { SiteOpening } from "./countdown"; + +/** + * What a visitor sees while the site is offline: a card with the logo, a + * "Maintenance" badge, the reason in their language (falling back to the + * default one) and, when the site has an opening time, a countdown or the + * date alone. + */ +export const SiteOfflineContent = ({ + className, + defaultLanguage, + fetchedAt, + language, + logo, + status, +}: { + className?: string; + defaultLanguage?: string; + fetchedAt?: number; + language: string; + logo?: React.ReactNode; + status: Pick< + SiteStatus, + "message" | "opensAt" | "serverNow" | "showCountdown" + >; +}) => { + const t = useTranslations("core.site_offline"); + const message = pickSiteOfflineMessage( + status.message, + language, + defaultLanguage, + ); + + return ( +
+
+
{logo}
+ +
+ +
+

+ {t("title")} +

+ {message ? ( + + ) : ( +

+ {t("desc")} +

+ )} +
+ + {status.opensAt ? ( + + ) : null} +
+ ); +}; diff --git a/plans/site-offline-mode.md b/plans/site-offline-mode.md new file mode 100644 index 0000000000..697b585dcd --- /dev/null +++ b/plans/site-offline-mode.md @@ -0,0 +1,125 @@ +# Site offline mode + +Status: implemented. Tests still to write (see the last section). Owner: core. + +An admin switches the public site off in **AdminCP → System → Site status** +and writes why, once per language. Visitors get a card with that message and, +if an opening time is set, a countdown. The site never opens by itself: when +the time runs out the card says "Opening soon" until an admin turns the site +back on. Admins, and moderators given the permission, keep using the site. + +Out of scope: scheduled automatic opening, offline mode per section or per +plugin, IP allowlists. + +## Who gets in + +| Viewer | Gets | +| --- | --- | +| Admin, or any AdminCP session | The site, with a "site is offline" banner | +| Moderator with `moderator.site_status.can_access_offline` | The same as an admin | +| Any other moderator, member or guest | The offline card, `503` | +| Anyone on `/login` and below | The sign-in pages, so staff can sign in | + +Root roles and unrestricted moderator entries hold the permission without +listing it. Registration stays closed: `/register` is not an open path. + +The server makes this call once, in `canBypassSiteOffline` +(`packages/api/src/lib/site-status.server.ts`). The API guard, the SSR `503` +and the client gate all follow it, so they cannot disagree. + +## Storage and API + +- `core_site_status`: one row, `id = 1`. A missing row means online. + `message` is `MultiLangValue` in `jsonb`. `changedAt` and + `changedById` move only when `offline` flips. +- `loadSiteStatus(c)` reads the row once per request and caches it for 300s + (Redis when configured). A save deletes the entry and hard-invalidates the + page-cache tag `core:site-status`. +- `GET /site/status` (public, `allowWhenOffline`): offline flag, message, + opening time, `serverNow` for clock skew, and `viewerCanBypass` for the + requesting viewer. +- `GET` / `PUT /admin/site/status`: guarded by `admin.site_status.can_view` / + `can_manage`. The `PUT` requires a non-empty message in the default language + while offline, refuses a new opening time in the past (an expired one may + stay), writes an audit entry and emits `site.status.updated`. + +## Enforcement + +- **API:** `buildRoute` adds `siteOfflineGuard` to every route unless it sets + `allowWhenOffline` or `adminStaffPermission`. Blocked callers get + `503 { error: "site_offline" }` with `Retry-After`. Core opts in sign-in, + password reset, e-mail verification, SSO, passkey sign-in, the session, + `show-config`, the status itself, cron, payment webhooks and signed content + previews. Deny by default was the point: a path allowlist would have + silently exposed every new plugin route. +- **Pages:** `loadMainShell` loads the status keyed by viewer id (signing in + fetches it again) and answers `503`, `no-store` and `X-Robots-Tag: noindex` + through `setResponseStatus`. `ThemeLayoutContent` swaps the frame for the + offline card, so existing apps needed no route changes; `SiteOfflineGate` + covers custom layouts. +- **Page cache:** it never stores a non-`200` render, so an offline card is + never cached and a cookie-bearing staff request always gets its own render. +- **Failure:** a status that cannot be read counts as online. A broken lookup + should not take every route down with it. +- **Reopening:** an open offline card polls every minute and on focus, then + calls `router.invalidate()` so the page behind it loads its data. No + realtime push: the socket only serves signed-in users, and the card is for + guests. + +## Offline card (decided from `/proto/offline`) + +- **Notice**: one card on a muted page. Logo and a "Maintenance" pill, the + heading, the message, then one row for the opening time. +- The row shows "Back in 02d 05h 37m 09s" with rolling digits + (`SlidingNumber`) and the date. With **Show countdown** off it shows the + date alone. Once the time has passed it shows "Opening soon". No opening + time, no row. +- The row lays out by the card's width (`@container`), not the viewport, so it + fits the narrow AdminCP preview. +- No sign-in link and no mention of staff. Staff open `/login` or `/admin` + directly. +- Rejected: + - **Centred stack with countdown tiles**: the message and the countdown + competed, and it read as a product launch, not maintenance. + - **Editorial split** (left-aligned, ruled countdown list): good for long + reasons, but on phones the countdown dropped below the fold. + - **Giant digital clock**: fun for launches, but it buried the reason, and + "Opening soon" or no time at all left a huge empty hero. + +## AdminCP screen (decided from the in-place prototype) + +- **Inline**: everything is edited on the page. A status card with the "Take + the site offline" switch, the multi-language editor, the opening time and + "Show countdown", next to a sticky live preview of the card (dimmed while + the site is online). +- A save bar appears only with unsaved changes. Its button names the outcome: + "Turn off site" (destructive), "Turn on site" or "Save changes". There is no + extra confirm dialog; the label is the confirmation. +- The form checks the default-language message itself, so the error lands on + the field instead of coming back as a `400` toast. +- Rejected: + - **Status card, side sheet and static preview**: the preview could not show + unsaved edits, and every change took two steps. + - **Control panel** (big Online/Offline switch, summary rows, preview in a + dialog): quick to scan, but the message hid behind "Edit" and the preview + behind a click. + +## Debug panel + +While the site is offline, the Debug Panel lists a warning ("The public site +is offline until ...") that links to Site status. It counts towards the +warning badge in the AdminCP user bar, so an offline site is hard to forget. + +## Tests to write + +Per AGENTS.md, in a separate session: + +- `canBypassSiteOffline`: admin, moderator with and without the permission, + guest. +- `siteOfflineGuard`: blocked route `503` with `Retry-After`; + `allowWhenOffline` and `/admin/` pass. +- `PUT /admin/site/status`: missing default-language message `400`, past + opening time `400`, expired time kept, `403` without `can_manage`. +- `countdownParts` as a pure function. +- The offline card's DOM: message fallback, countdown, date only, + "Opening soon".