[];
}
@@ -198,6 +201,7 @@ export function buildApiPlugin<
personalData,
reactions,
searchIndexers,
+ sitemap,
}: {
/**
* Managed AI actions the plugin runs with `c.get("ai").run()` or
@@ -267,6 +271,12 @@ export function buildApiPlugin<
reactions?: ReactionsPluginConfig;
/** Search indexers in addition to those modules declare. */
searchIndexers?: SearchIndexer[];
+ /**
+ * Pages and sources the plugin adds to the sitemap: `paths` join core's
+ * `static` source (localized for every language), `sources` get their own
+ * files. Content types with `delivery.sitemap` are added automatically.
+ */
+ sitemap?: SeoSitemapContribution;
}): BuildPluginApiReturn {
const pluginId = manifest.id;
// Run for checking if the plugin is valid
@@ -449,6 +459,7 @@ export function buildApiPlugin<
personalData,
ogImageTemplates,
searchIndexers: indexers,
+ sitemap,
webSockets,
// Every content type contributes can_view/can_create/can_edit/can_delete
// unless the plugin declared that module itself.
diff --git a/packages/api/src/lib/seo/config.test.ts b/packages/api/src/lib/seo/config.test.ts
new file mode 100644
index 0000000000..e16bc6012a
--- /dev/null
+++ b/packages/api/src/lib/seo/config.test.ts
@@ -0,0 +1,106 @@
+import type { Context } from "hono";
+
+import { describe, expect, it } from "vitest";
+
+import { createLocaleRouting } from "@/lib/i18n/locale-routing";
+
+import type { SitemapSource } from "./sitemap";
+
+import { resolveSeoConfig } from "./config";
+import { DEFAULT_ROBOTS_DISALLOW } from "./robots";
+
+const source = (id: string): SitemapSource => ({
+ count: async () => await Promise.resolve(0),
+ getEntries: async () => await Promise.resolve([]),
+ id,
+ label: id,
+});
+
+const c = {
+ get: (key: string) =>
+ key === "core"
+ ? {
+ i18n: {
+ localeRouting: createLocaleRouting({
+ defaultLocale: "en",
+ locales: ["en"],
+ }),
+ },
+ }
+ : undefined,
+} as unknown as Context;
+
+describe("resolveSeoConfig", () => {
+ it("orders sources static, content types, plugins, then the app", () => {
+ const { sitemapSources } = resolveSeoConfig({
+ config: { sitemap: { sources: [source("app")] } },
+ contentSources: [source("blog_post")],
+ plugins: [
+ { pluginId: "a", sitemap: { sources: [source("plugin_a")] } },
+ { pluginId: "b" },
+ ],
+ });
+
+ expect(sitemapSources.map(entry => entry.id)).toStrictEqual([
+ "static",
+ "blog_post",
+ "plugin_a",
+ "app",
+ ]);
+ });
+
+ it.each([
+ [
+ "a plugin reuses the static id",
+ {
+ plugins: [{ pluginId: "a", sitemap: { sources: [source("static")] } }],
+ },
+ 'share the id "static"',
+ ],
+ [
+ "the app reuses a content type's id",
+ {
+ config: { sitemap: { sources: [source("blog_post")] } },
+ contentSources: [source("blog_post")],
+ },
+ 'share the id "blog_post"',
+ ],
+ [
+ "an id is invalid",
+ { config: { sitemap: { sources: [source("Bad.Id")] } } },
+ "Invalid sitemap source id",
+ ],
+ ])("throws when %s", (_, args, message) => {
+ expect(() =>
+ resolveSeoConfig({ contentSources: [], plugins: [], ...args }),
+ ).toThrow(message);
+ });
+
+ it("lists `/` and every contributed path once, the later definition winning", async () => {
+ const { sitemapSources } = resolveSeoConfig({
+ config: {
+ sitemap: { paths: [{ path: "/blog", priority: 0.9 }, "/"] },
+ },
+ contentSources: [],
+ plugins: [{ pluginId: "a", sitemap: { paths: ["/blog", "/forum"] } }],
+ });
+
+ expect(
+ await sitemapSources[0].getEntries(c, { limit: 10, offset: 0 }),
+ ).toStrictEqual([
+ { changeFrequency: null, loc: "/", priority: null },
+ { changeFrequency: null, loc: "/blog", priority: 0.9 },
+ { changeFrequency: null, loc: "/forum", priority: null },
+ ]);
+ });
+
+ it("adds the app's disallowed paths to core's, once each", () => {
+ expect(
+ resolveSeoConfig({
+ config: { robots: { disallow: ["/admin", "/drafts"] } },
+ contentSources: [],
+ plugins: [],
+ }).robotsDisallow,
+ ).toStrictEqual([...DEFAULT_ROBOTS_DISALLOW, "/drafts"]);
+ });
+});
diff --git a/packages/api/src/lib/seo/config.ts b/packages/api/src/lib/seo/config.ts
new file mode 100644
index 0000000000..c690de4834
--- /dev/null
+++ b/packages/api/src/lib/seo/config.ts
@@ -0,0 +1,99 @@
+import type { SitemapSource } from "./sitemap";
+import type { SitemapStaticPath } from "./static-source";
+
+import { DEFAULT_ROBOTS_DISALLOW } from "./robots";
+import { defineSitemapSource } from "./sitemap";
+import { staticSitemapSource } from "./static-source";
+
+/** Sitemap pages and sources a plugin or the app adds. */
+export interface SeoSitemapContribution {
+ /** Internal paths added to core's `static` source, e.g. `/blog`. */
+ paths?: readonly (SitemapStaticPath | string)[];
+ /** Sources with their own sub-sitemap files. */
+ sources?: readonly SitemapSource[];
+}
+
+/** `buildApiConfig({ seo })`: what the app adds to `robots.txt` and the sitemap. */
+export interface SeoApiConfig {
+ robots?: {
+ /**
+ * Paths disallowed for every crawler, on top of the private areas core
+ * always lists (`/admin`, `/settings`, `/modcp`, `/notifications`,
+ * `/files`). Localized for every language automatically.
+ */
+ disallow?: readonly string[];
+ };
+ /**
+ * Extra pages and sources. The `static` source lists `/` plus every path
+ * given here and by plugins, in every language.
+ */
+ sitemap?: SeoSitemapContribution;
+}
+
+/** The SEO registrations of one installation, resolved at boot. */
+export interface ResolvedSeoConfig {
+ /** Unlocalized paths disallowed for every crawler. */
+ robotsDisallow: string[];
+ /** Declared sources, in index order: static, content types, plugins, app. */
+ sitemapSources: SitemapSource[];
+}
+
+/** Id and label of core's own source of fixed pages. */
+export const STATIC_SITEMAP_SOURCE = {
+ id: "static",
+ label: "admin.system.seo.sources.static",
+} as const;
+
+const pathOf = (path: SitemapStaticPath | string) =>
+ typeof path === "string" ? path : path.path;
+
+/**
+ * Collects every sitemap source and robots path. Server-only.
+ *
+ * @throws At startup, when a source id is invalid or two sources share one.
+ */
+export const resolveSeoConfig = ({
+ config,
+ contentSources,
+ plugins,
+}: {
+ config?: SeoApiConfig;
+ contentSources: readonly SitemapSource[];
+ plugins: readonly { pluginId: string; sitemap?: SeoSitemapContribution }[];
+}): ResolvedSeoConfig => {
+ const byPath = new Map([["/", "/"]]);
+ for (const path of [
+ ...plugins.flatMap(plugin => plugin.sitemap?.paths ?? []),
+ ...(config?.sitemap?.paths ?? []),
+ ]) {
+ byPath.set(pathOf(path), path);
+ }
+ const paths = [...byPath.values()];
+
+ const sources: SitemapSource[] = [
+ staticSitemapSource({ ...STATIC_SITEMAP_SOURCE, paths }),
+ ...contentSources,
+ ...plugins.flatMap(plugin => plugin.sitemap?.sources ?? []),
+ ...(config?.sitemap?.sources ?? []),
+ ];
+ const seen = new Set();
+ for (const source of sources) {
+ defineSitemapSource(source);
+ if (seen.has(source.id)) {
+ throw new Error(
+ `Two sitemap sources share the id "${source.id}". Give one of them another id.`,
+ );
+ }
+ seen.add(source.id);
+ }
+
+ return {
+ robotsDisallow: [
+ ...new Set([
+ ...DEFAULT_ROBOTS_DISALLOW,
+ ...(config?.robots?.disallow ?? []),
+ ]),
+ ],
+ sitemapSources: sources,
+ };
+};
diff --git a/packages/api/src/lib/seo/registry.ts b/packages/api/src/lib/seo/registry.ts
new file mode 100644
index 0000000000..b2da8386d9
--- /dev/null
+++ b/packages/api/src/lib/seo/registry.ts
@@ -0,0 +1,33 @@
+import type { SitemapSource } from "./sitemap";
+
+import { defineSitemapSource } from "./sitemap";
+
+const registered = new Map();
+
+/**
+ * Adds a sitemap source at runtime, next to those declared with
+ * `buildApiPlugin({ sitemapSources })` and `buildApiConfig({ seo })`.
+ * Registering the same id again replaces the earlier source, so a reloaded
+ * module does not throw. Declared sources win over registered ones with the
+ * same id. Server-only.
+ *
+ * @throws When `source.id` does not match `/^[a-z0-9_-]+$/`.
+ *
+ * @example
+ * import { registerSitemapSource } from "@vitnode/api/lib/seo/registry";
+ *
+ * registerSitemapSource({
+ * id: "landing",
+ * label: "Landing pages",
+ * count: async () => 2,
+ * getEntries: async () => [{ loc: "/pricing" }, { loc: "/about" }],
+ * });
+ */
+export const registerSitemapSource = (source: SitemapSource): void => {
+ registered.set(source.id, defineSitemapSource(source));
+};
+
+/** Every source added with {@link registerSitemapSource}, in registration order. */
+export const registeredSitemapSources = (): SitemapSource[] => [
+ ...registered.values(),
+];
diff --git a/packages/api/src/lib/seo/robots.test.ts b/packages/api/src/lib/seo/robots.test.ts
new file mode 100644
index 0000000000..cfc96b960c
--- /dev/null
+++ b/packages/api/src/lib/seo/robots.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from "vitest";
+
+import type { RobotsTxtInput } from "./robots";
+
+import {
+ AI_TRAINING_CRAWLERS,
+ buildRobotsTxt,
+ normalizeCustomRobots,
+} from "./robots";
+
+const input = (overrides: Partial = {}): RobotsTxtInput => ({
+ allowIndexing: true,
+ blockAiCrawlers: false,
+ customRobots: "",
+ disallow: ["/admin", "/pl/admin"],
+ sitemapUrl: "https://example.com/sitemap.xml",
+ ...overrides,
+});
+
+describe("normalizeCustomRobots", () => {
+ it.each([
+ ["CRLF and CR line endings", "a\r\nb\rc", "a\nb\nc"],
+ [
+ "control characters",
+ "User-agent: *\u0000\u0007\u001B\u007F",
+ "User-agent: *",
+ ],
+ ["trailing whitespace on each line", "a \nb\t", "a\nb"],
+ [
+ "trailing and leading blank lines",
+ "\n\nDisallow: /x\n\n\n",
+ "Disallow: /x",
+ ],
+ ["tabs inside a line, which are kept", "a\tb", "a\tb"],
+ ])("handles %s", (_, value, expected) => {
+ expect(normalizeCustomRobots(value)).toBe(expected);
+ });
+});
+
+describe("buildRobotsTxt", () => {
+ it("says only `Disallow: /` when indexing is off, whatever else is set", () => {
+ expect(
+ buildRobotsTxt(
+ input({
+ allowIndexing: false,
+ blockAiCrawlers: true,
+ customRobots: "User-agent: Foo\nAllow: /",
+ offline: true,
+ }),
+ ),
+ ).toBe(
+ "# Search engine indexing is turned off for this site.\nUser-agent: *\nDisallow: /\n",
+ );
+ });
+
+ it("disallows each path once, then lists the sitemap", () => {
+ expect(
+ buildRobotsTxt(input({ disallow: ["/admin", "/pl/admin", "/admin"] })),
+ ).toBe(
+ [
+ "User-agent: *",
+ "Disallow: /admin",
+ "Disallow: /pl/admin",
+ "",
+ "Sitemap: https://example.com/sitemap.xml",
+ "",
+ ].join("\n"),
+ );
+ });
+
+ it("allows everything when no path is disallowed and leaves out a missing sitemap", () => {
+ expect(buildRobotsTxt(input({ disallow: [], sitemapUrl: null }))).toBe(
+ "User-agent: *\nAllow: /\n",
+ );
+ });
+
+ it("adds one group that blocks every AI training crawler", () => {
+ const lines = buildRobotsTxt(
+ input({ blockAiCrawlers: true, sitemapUrl: null }),
+ ).split("\n");
+ const group = lines.slice(lines.indexOf("") + 1, -1);
+
+ expect(group).toStrictEqual([
+ ...AI_TRAINING_CRAWLERS.map(agent => `User-agent: ${agent}`),
+ "Disallow: /",
+ ]);
+ });
+
+ it("appends normalized custom rules between the groups and the sitemap", () => {
+ expect(
+ buildRobotsTxt(
+ input({
+ customRobots: "User-agent: Foo\r\nDisallow: /bar\r\n\r\n",
+ disallow: ["/admin"],
+ }),
+ ),
+ ).toBe(
+ [
+ "User-agent: *",
+ "Disallow: /admin",
+ "",
+ "User-agent: Foo",
+ "Disallow: /bar",
+ "",
+ "Sitemap: https://example.com/sitemap.xml",
+ "",
+ ].join("\n"),
+ );
+ });
+
+ it("leaves out custom rules that are only whitespace", () => {
+ expect(buildRobotsTxt(input({ customRobots: " \n\t\n" }))).toBe(
+ buildRobotsTxt(input()),
+ );
+ });
+
+ it("opens with a comment while the site is offline", () => {
+ expect(buildRobotsTxt(input({ offline: true }))).toBe(
+ `# The site is offline for maintenance. Please come back later.\n${buildRobotsTxt(input())}`,
+ );
+ });
+});
diff --git a/packages/api/src/lib/seo/robots.ts b/packages/api/src/lib/seo/robots.ts
new file mode 100644
index 0000000000..2b5c8c55cf
--- /dev/null
+++ b/packages/api/src/lib/seo/robots.ts
@@ -0,0 +1,120 @@
+/**
+ * User agents of crawlers that collect pages to train AI models. Search and
+ * user-triggered assistants (Googlebot, Bingbot, ChatGPT-User,
+ * PerplexityBot) are not listed: blocking those hides the site from search
+ * and answers, not from training sets.
+ */
+export const AI_TRAINING_CRAWLERS = [
+ "GPTBot",
+ "ClaudeBot",
+ "anthropic-ai",
+ "Google-Extended",
+ "Applebot-Extended",
+ "CCBot",
+ "Bytespider",
+ "meta-externalagent",
+ "FacebookBot",
+ "cohere-training-data-crawler",
+ "Diffbot",
+ "Omgilibot",
+ "ImagesiftBot",
+ "PanguBot",
+ "Timpibot",
+] as const;
+
+/** Private areas every VitNode site keeps out of crawlers' way. */
+export const DEFAULT_ROBOTS_DISALLOW = [
+ "/admin",
+ "/settings",
+ "/modcp",
+ "/notifications",
+ "/files",
+] as const;
+
+export interface RobotsTxtInput {
+ /** `false` answers `Disallow: /` for everyone and nothing else. */
+ allowIndexing: boolean;
+ blockAiCrawlers: boolean;
+ /** Appended after the generated groups, as written. */
+ customRobots: string;
+ /** Paths disallowed for every crawler, already localized. */
+ disallow: readonly string[];
+ /** While the site is offline the file says so in a comment. */
+ offline?: boolean;
+ /** Absolute URL of the sitemap index, or `null` when sitemaps are off. */
+ sitemapUrl: null | string;
+}
+
+// oxlint-disable-next-line no-control-regex -- stripping them is the point
+const CONTROL_CHARACTERS = /[\u0000-\u0008\u000B-\u001F\u007F]/g;
+
+/** Custom rules with Unix line endings, no control characters and no trailing blank lines. */
+export const normalizeCustomRobots = (value: string): string =>
+ value
+ .replace(/\r\n?/g, "\n")
+ .replace(CONTROL_CHARACTERS, "")
+ .split("\n")
+ .map(line => line.trimEnd())
+ .join("\n")
+ .trim();
+
+/**
+ * The `robots.txt` body. Pure and browser-safe, so the AdminCP previews
+ * exactly what `/robots.txt` serves.
+ *
+ * @example
+ * buildRobotsTxt({
+ * allowIndexing: true,
+ * blockAiCrawlers: false,
+ * customRobots: "",
+ * disallow: ["/admin"],
+ * sitemapUrl: "https://example.com/sitemap.xml",
+ * });
+ */
+export const buildRobotsTxt = ({
+ allowIndexing,
+ blockAiCrawlers,
+ customRobots,
+ disallow,
+ offline = false,
+ sitemapUrl,
+}: RobotsTxtInput): string => {
+ if (!allowIndexing) {
+ return [
+ "# Search engine indexing is turned off for this site.",
+ "User-agent: *",
+ "Disallow: /",
+ "",
+ ].join("\n");
+ }
+
+ const lines: string[] = [];
+ if (offline) {
+ lines.push(
+ "# The site is offline for maintenance. Please come back later.",
+ );
+ }
+
+ lines.push("User-agent: *");
+ const paths = [...new Set(disallow)];
+ if (paths.length === 0) {
+ lines.push("Allow: /");
+ } else {
+ for (const path of paths) lines.push(`Disallow: ${path}`);
+ }
+
+ if (blockAiCrawlers) {
+ lines.push("");
+ for (const agent of AI_TRAINING_CRAWLERS) {
+ lines.push(`User-agent: ${agent}`);
+ }
+ lines.push("Disallow: /");
+ }
+
+ const custom = normalizeCustomRobots(customRobots);
+ if (custom) lines.push("", custom);
+
+ if (sitemapUrl) lines.push("", `Sitemap: ${sitemapUrl}`);
+
+ return `${lines.join("\n")}\n`;
+};
diff --git a/packages/api/src/lib/seo/serve.server.ts b/packages/api/src/lib/seo/serve.server.ts
new file mode 100644
index 0000000000..d629de5e50
--- /dev/null
+++ b/packages/api/src/lib/seo/serve.server.ts
@@ -0,0 +1,180 @@
+import type { Context } from "hono";
+
+import type { SeoSettings } from "./settings";
+import type { SitemapSource } from "./sitemap";
+
+import { contentSitemapIndexXml } from "../../content/sitemap";
+import { CONFIG } from "../config";
+import { loadSiteStatus } from "../site-status.server";
+import { registeredSitemapSources } from "./registry";
+import { buildRobotsTxt } from "./robots";
+import { loadSeoSettings } from "./settings.server";
+import {
+ parseSitemapFileName,
+ sitemapFileName,
+ sitemapPageCount,
+ sitemapUrlsetXml,
+} from "./sitemap";
+
+/** The canonical site origin, without a trailing slash. */
+export const seoSiteOrigin = (): string => CONFIG.web.origin;
+
+/** The absolute URL of `/sitemap.xml`. */
+export const sitemapIndexUrl = (): string =>
+ new URL("/sitemap.xml", seoSiteOrigin()).href;
+
+/**
+ * Every sitemap source: the declared ones (static, content types, plugins,
+ * app) and then those added with `registerSitemapSource`. Server-only.
+ */
+export const getSitemapSources = (c: Context): SitemapSource[] => {
+ const declared = c.get("core").seo.sitemapSources;
+ const ids = new Set(declared.map(source => source.id));
+
+ return [
+ ...declared,
+ ...registeredSitemapSources().filter(source => !ids.has(source.id)),
+ ];
+};
+
+/** The sources the settings leave switched on. */
+export const enabledSitemapSources = (
+ c: Context,
+ settings: SeoSettings,
+): SitemapSource[] => {
+ const disabled = new Set(settings.sitemap.disabledSources);
+
+ return getSitemapSources(c).filter(source => !disabled.has(source.id));
+};
+
+/** Whether `/sitemap.xml` and its files answer at all. */
+export const sitemapsServed = (settings: SeoSettings): boolean =>
+ settings.allowIndexing && settings.sitemap.enabled;
+
+/**
+ * Disallowed paths in every language: `/settings` and `/pl/settings`.
+ * Paths on another locale domain cannot be written in this host's file, so
+ * they are left out.
+ */
+export const robotsDisallowPaths = (c: Context): string[] => {
+ const { i18n, seo } = c.get("core");
+ const paths = new Set();
+
+ for (const path of seo.robotsDisallow) {
+ paths.add(path);
+ for (const alternate of i18n.localeRouting.alternatesFor(path)) {
+ if (alternate.origin === undefined) paths.add(alternate.pathname);
+ }
+ }
+
+ return [...paths];
+};
+
+/** The context the robots generator needs, for `/robots.txt` and the AdminCP preview. */
+export const robotsContext = async (c: Context) => {
+ const status = await loadSiteStatus(c);
+
+ return {
+ disallow: robotsDisallowPaths(c),
+ offline: status.offline,
+ opensAt: status.opensAt,
+ sitemapUrl: sitemapIndexUrl(),
+ };
+};
+
+/** The `robots.txt` body for `settings`. Server-only. */
+export const renderRobotsTxt = async (
+ c: Context,
+ settings: SeoSettings,
+): Promise<{ body: string; offline: boolean; opensAt: null | string }> => {
+ const context = await robotsContext(c);
+
+ return {
+ body: buildRobotsTxt({
+ allowIndexing: settings.allowIndexing,
+ blockAiCrawlers: settings.blockAiCrawlers,
+ customRobots: settings.customRobots,
+ disallow: context.disallow,
+ offline: context.offline,
+ sitemapUrl: sitemapsServed(settings) ? context.sitemapUrl : null,
+ }),
+ offline: context.offline,
+ opensAt: context.opensAt,
+ };
+};
+
+/** One source's size: URLs and files. Failing sources count as empty. */
+export const sitemapSourceStats = async (
+ c: Context,
+ source: SitemapSource,
+ perFile: number,
+): Promise<{ error: boolean; files: number; urls: number }> => {
+ try {
+ const urls = await source.count(c);
+
+ return { error: false, files: sitemapPageCount(urls, perFile), urls };
+ } catch (error) {
+ await c
+ .get("log")
+ .error(`Sitemap source "${source.id}" failed to count: ${String(error)}`);
+
+ return { error: true, files: 0, urls: 0 };
+ }
+};
+
+/** The `` document, or `null` when sitemaps are off. Server-only. */
+export const renderSitemapIndex = async (
+ c: Context,
+): Promise => {
+ const settings = await loadSeoSettings(c);
+ if (!sitemapsServed(settings)) return null;
+
+ const perFile = settings.sitemap.maxUrlsPerFile;
+ const sources = enabledSitemapSources(c, settings);
+ const files = await Promise.all(
+ sources.map(async source => {
+ const { files: pages } = await sitemapSourceStats(c, source, perFile);
+ if (pages === 0) return [];
+ const lastModified = await source.getLastModified?.(c).catch(() => null);
+
+ return Array.from({ length: pages }, (_, index) => ({
+ path: `/sitemaps/${sitemapFileName(source.id, index + 1)}`,
+ ...(lastModified ? { lastModified } : {}),
+ }));
+ }),
+ );
+
+ return contentSitemapIndexXml({
+ entries: files.flat(),
+ origin: seoSiteOrigin(),
+ });
+};
+
+/**
+ * One `` file, or `null` for a 404: sitemaps off, an unknown or
+ * disabled source, or a page past the end. Server-only.
+ */
+export const renderSitemapFile = async (
+ c: Context,
+ fileName: string,
+): Promise => {
+ const parsed = parseSitemapFileName(fileName);
+ if (!parsed) return null;
+
+ const settings = await loadSeoSettings(c);
+ if (!sitemapsServed(settings)) return null;
+
+ const source = enabledSitemapSources(c, settings).find(
+ entry => entry.id === parsed.sourceId,
+ );
+ if (!source) return null;
+
+ const limit = settings.sitemap.maxUrlsPerFile;
+ const offset = (parsed.page - 1) * limit;
+ const total = await source.count(c);
+ if (offset >= total) return null;
+
+ const entries = await source.getEntries(c, { limit, offset });
+
+ return sitemapUrlsetXml({ entries, origin: seoSiteOrigin() });
+};
diff --git a/packages/api/src/lib/seo/settings.server.ts b/packages/api/src/lib/seo/settings.server.ts
new file mode 100644
index 0000000000..45d20bf8d2
--- /dev/null
+++ b/packages/api/src/lib/seo/settings.server.ts
@@ -0,0 +1,108 @@
+import type { Context } from "hono";
+
+import { eq } from "drizzle-orm";
+
+import { core_seo_settings } from "@/database/seo";
+import { manifest } from "@/manifest";
+
+import type { DomainCache } from "../cache";
+import type { SeoSettings } from "./settings";
+
+import { defineCacheEntry } from "../cache-entry";
+import { SEO_SETTINGS_DEFAULTS, zodSeoSettings } from "./settings";
+
+const seoSettingsCache = defineCacheEntry({
+ pluginId: manifest.id,
+ name: "seo.settings",
+ version: 1,
+ schema: zodSeoSettings,
+ ttlSeconds: 300,
+});
+
+const cacheOf = (c: Context): DomainCache | undefined => c.get("cache");
+
+const perRequest = new WeakMap>();
+
+type SeoSettingsRow = typeof core_seo_settings.$inferSelect;
+
+const fromRow = (row: SeoSettingsRow | undefined): SeoSettings =>
+ row
+ ? {
+ allowIndexing: row.allowIndexing,
+ blockAiCrawlers: row.blockAiCrawlers,
+ customRobots: row.customRobots,
+ sitemap: {
+ disabledSources: row.disabledSitemapSources,
+ enabled: row.sitemapEnabled,
+ maxUrlsPerFile: row.sitemapMaxUrls,
+ },
+ }
+ : SEO_SETTINGS_DEFAULTS;
+
+const readRow = async (c: Context): Promise => {
+ const [row] = await c
+ .get("db")
+ .select()
+ .from(core_seo_settings)
+ .where(eq(core_seo_settings.id, 1))
+ .limit(1);
+
+ return fromRow(row);
+};
+
+/**
+ * The SEO settings with their defaults, read once per request and shared
+ * across requests through the cache. Server-only.
+ */
+export const loadSeoSettings = async (c: Context): Promise => {
+ const remembered = perRequest.get(c);
+ if (remembered) return await remembered;
+
+ const cache = cacheOf(c);
+ const loading = cache
+ ? cache.entry(seoSettingsCache).remember(async () => await readRow(c))
+ : readRow(c);
+ perRequest.set(c, loading);
+
+ return await loading;
+};
+
+/**
+ * Writes the SEO settings and returns what was saved before (the defaults
+ * when there was no row). Run it inside the caller's transaction, then call
+ * {@link afterSeoSettingsSaved} once it has committed. Server-only.
+ */
+export const saveSeoSettings = async (
+ tx: Omit,
+ settings: SeoSettings,
+ userId: number,
+): Promise => {
+ const [before] = await tx
+ .select()
+ .from(core_seo_settings)
+ .where(eq(core_seo_settings.id, 1))
+ .limit(1)
+ .for("update");
+ const values = {
+ allowIndexing: settings.allowIndexing,
+ blockAiCrawlers: settings.blockAiCrawlers,
+ customRobots: settings.customRobots,
+ disabledSitemapSources: settings.sitemap.disabledSources,
+ sitemapEnabled: settings.sitemap.enabled,
+ sitemapMaxUrls: settings.sitemap.maxUrlsPerFile,
+ updatedById: userId,
+ };
+
+ await tx
+ .insert(core_seo_settings)
+ .values({ id: 1, ...values })
+ .onConflictDoUpdate({ set: values, target: core_seo_settings.id });
+
+ return fromRow(before);
+};
+
+/** Expires the cached SEO settings. Call it after the save has committed. */
+export const afterSeoSettingsSaved = async (c: Context): Promise => {
+ perRequest.delete(c);
+ await cacheOf(c)?.entry(seoSettingsCache).delete();
+};
diff --git a/packages/api/src/lib/seo/settings.test.ts b/packages/api/src/lib/seo/settings.test.ts
new file mode 100644
index 0000000000..49e48ebb8d
--- /dev/null
+++ b/packages/api/src/lib/seo/settings.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from "vitest";
+
+import type { SeoSettings } from "./settings";
+
+import { mergeSeoSettings } from "./settings";
+
+const SAVED: SeoSettings = {
+ allowIndexing: true,
+ blockAiCrawlers: false,
+ customRobots: "User-agent: Foo",
+ sitemap: {
+ disabledSources: ["static"],
+ enabled: true,
+ maxUrlsPerFile: 5000,
+ },
+};
+
+describe("mergeSeoSettings", () => {
+ it("keeps every saved value a partial update leaves out", () => {
+ expect(
+ mergeSeoSettings(SAVED, {
+ blockAiCrawlers: true,
+ sitemap: { maxUrlsPerFile: 100 },
+ }),
+ ).toStrictEqual({
+ ...SAVED,
+ blockAiCrawlers: true,
+ sitemap: { ...SAVED.sitemap, maxUrlsPerFile: 100 },
+ });
+ });
+
+ it("saves an empty custom block and `false` flags rather than ignoring them", () => {
+ expect(
+ mergeSeoSettings(SAVED, {
+ allowIndexing: false,
+ customRobots: "",
+ sitemap: { disabledSources: [], enabled: false },
+ }),
+ ).toStrictEqual({
+ allowIndexing: false,
+ blockAiCrawlers: false,
+ customRobots: "",
+ sitemap: { disabledSources: [], enabled: false, maxUrlsPerFile: 5000 },
+ });
+ });
+
+ it("dedupes and sorts the disabled sources", () => {
+ expect(
+ mergeSeoSettings(SAVED, {
+ sitemap: { disabledSources: ["blog_post", "static", "blog_post"] },
+ }).sitemap.disabledSources,
+ ).toStrictEqual(["blog_post", "static"]);
+ });
+});
diff --git a/packages/api/src/lib/seo/settings.ts b/packages/api/src/lib/seo/settings.ts
new file mode 100644
index 0000000000..cd091ea67d
--- /dev/null
+++ b/packages/api/src/lib/seo/settings.ts
@@ -0,0 +1,80 @@
+import { z } from "zod";
+
+/** Limits of the SEO settings. Browser-safe. */
+export const SEO_SETTINGS_LIMITS = {
+ /** Longest custom `robots.txt` block, in characters. */
+ customRobotsMaxLength: 10_000,
+ /** The sitemap protocol's ceiling for one file. */
+ sitemapMaxUrlsMax: 50_000,
+ sitemapMaxUrlsMin: 100,
+} as const;
+
+/** A sitemap source id: lowercase letters, digits, `_` and `-`. */
+export const SITEMAP_SOURCE_ID_PATTERN = /^[a-z0-9_-]+$/;
+
+/** Crawling and indexing settings, as stored and served. Browser-safe. */
+export const zodSeoSettings = z.object({
+ /** `false` turns the whole site into `Disallow: /` and hides every sitemap. */
+ allowIndexing: z.boolean(),
+ /** Adds a `Disallow: /` group for the known AI training crawlers. */
+ blockAiCrawlers: z.boolean(),
+ /** Extra `robots.txt` lines, appended as written. */
+ customRobots: z.string().max(SEO_SETTINGS_LIMITS.customRobotsMaxLength),
+ sitemap: z.object({
+ /** Source ids switched off in the AdminCP. */
+ disabledSources: z.array(z.string().regex(SITEMAP_SOURCE_ID_PATTERN)),
+ enabled: z.boolean(),
+ /** URLs per sub-sitemap file. */
+ maxUrlsPerFile: z
+ .number()
+ .int()
+ .min(SEO_SETTINGS_LIMITS.sitemapMaxUrlsMin)
+ .max(SEO_SETTINGS_LIMITS.sitemapMaxUrlsMax),
+ }),
+});
+
+export type SeoSettings = z.output;
+
+/** What a site without a saved row runs with. */
+export const SEO_SETTINGS_DEFAULTS: SeoSettings = {
+ allowIndexing: true,
+ blockAiCrawlers: false,
+ customRobots: "",
+ sitemap: { disabledSources: [], enabled: true, maxUrlsPerFile: 10_000 },
+};
+
+/**
+ * What the AdminCP sends to change the SEO settings: any subset of the
+ * fields; the rest keep their saved values. Browser-safe.
+ */
+export const zodSeoSettingsUpdate = z.object({
+ allowIndexing: z.boolean().optional(),
+ blockAiCrawlers: z.boolean().optional(),
+ customRobots: zodSeoSettings.shape.customRobots.optional(),
+ sitemap: zodSeoSettings.shape.sitemap.partial().optional(),
+});
+
+export type SeoSettingsUpdate = z.input;
+
+/** `settings` with `update` applied. Browser-safe. */
+export const mergeSeoSettings = (
+ settings: SeoSettings,
+ update: SeoSettingsUpdate,
+): SeoSettings => ({
+ allowIndexing: update.allowIndexing ?? settings.allowIndexing,
+ blockAiCrawlers: update.blockAiCrawlers ?? settings.blockAiCrawlers,
+ customRobots: update.customRobots ?? settings.customRobots,
+ sitemap: {
+ disabledSources: [
+ ...new Set(
+ update.sitemap?.disabledSources ?? settings.sitemap.disabledSources,
+ ),
+ ].sort(),
+ enabled: update.sitemap?.enabled ?? settings.sitemap.enabled,
+ maxUrlsPerFile:
+ update.sitemap?.maxUrlsPerFile ?? settings.sitemap.maxUrlsPerFile,
+ },
+});
+
+/** The page-cache tag of everything that read the SEO settings. */
+export const SEO_SETTINGS_PAGE_CACHE_TAG = "core:seo-settings";
diff --git a/packages/api/src/lib/seo/sitemap.test.ts b/packages/api/src/lib/seo/sitemap.test.ts
new file mode 100644
index 0000000000..af04ddcca7
--- /dev/null
+++ b/packages/api/src/lib/seo/sitemap.test.ts
@@ -0,0 +1,192 @@
+import { describe, expect, it } from "vitest";
+
+import { CONTENT_SITEMAP_MAX_URLS } from "@/content/const";
+
+import type { SitemapEntry, SitemapSource } from "./sitemap";
+
+import {
+ defineSitemapSource,
+ parseSitemapFileName,
+ sitemapPageCount,
+ sitemapUrlsetXml,
+} from "./sitemap";
+
+const ORIGIN = "https://example.com";
+
+const XHTML_NS = 'xmlns:xhtml="http://www.w3.org/1999/xhtml"';
+const IMAGE_NS =
+ 'xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"';
+
+const urlset = (...entries: SitemapEntry[]) =>
+ sitemapUrlsetXml({ entries, origin: ORIGIN });
+
+describe("parseSitemapFileName", () => {
+ it.each([
+ ["blog_post-1.xml", { page: 1, sourceId: "blog_post" }],
+ ["static-12.xml", { page: 12, sourceId: "static" }],
+ ["my-source-3.xml", { page: 3, sourceId: "my-source" }],
+ ])("reads %s", (fileName, expected) => {
+ expect(parseSitemapFileName(fileName)).toStrictEqual(expected);
+ });
+
+ it.each([
+ ["page 0", "blog_post-0.xml"],
+ ["an uppercase id", "Blog-1.xml"],
+ ["path traversal", "../static-1.xml"],
+ ["an encoded slash", "a%2Fb-1.xml"],
+ ["no extension", "static-1"],
+ ["another extension", "static-1.xml.gz"],
+ ["no page", "static.xml"],
+ ["a page too long to be a page", "static-1234567890.xml"],
+ ])("refuses %s", (_, fileName) => {
+ expect(parseSitemapFileName(fileName)).toBeNull();
+ });
+});
+
+describe("sitemapPageCount", () => {
+ it.each([
+ [0, 100, 0],
+ [1, 100, 1],
+ [100, 100, 1],
+ [101, 100, 2],
+ [10, 0, 10],
+ [10, 2.9, 5],
+ [CONTENT_SITEMAP_MAX_URLS + 1, CONTENT_SITEMAP_MAX_URLS * 2, 2],
+ ])("splits %i URLs at %d per file into %i files", (total, perFile, files) => {
+ expect(sitemapPageCount(total, perFile)).toBe(files);
+ });
+});
+
+describe("sitemapUrlsetXml", () => {
+ it("declares only the sitemap namespace when no entry has alternates or images", () => {
+ expect(urlset({ loc: "/a" })).toBe(
+ [
+ '',
+ '',
+ " ",
+ " https://example.com/a",
+ " ",
+ "",
+ "",
+ ].join("\n"),
+ );
+ });
+
+ it.each([
+ [
+ "alternates",
+ { alternates: [{ href: "/pl/a", hreflang: "pl" }], loc: "/a" },
+ [XHTML_NS],
+ ],
+ ["images", { images: [{ loc: "/i.png" }], loc: "/a" }, [IMAGE_NS]],
+ [
+ "both",
+ {
+ alternates: [{ href: "/pl/a", hreflang: "pl" }],
+ images: [{ loc: "/i.png" }],
+ loc: "/a",
+ },
+ [XHTML_NS, IMAGE_NS],
+ ],
+ ] satisfies [string, SitemapEntry, string[]][])(
+ "declares the namespaces an entry with %s needs",
+ (_, entry, expected) => {
+ const root = urlset({ loc: "/b" }, entry).split("\n")[1];
+
+ expect(
+ [XHTML_NS, IMAGE_NS].filter(ns => root.includes(ns)),
+ ).toStrictEqual(expected);
+ },
+ );
+
+ it("renders every field of an entry, resolving relative URLs against the origin", () => {
+ expect(
+ urlset({
+ alternates: [
+ { href: "/a", hreflang: "en" },
+ { href: "https://example.pl/a", hreflang: "pl" },
+ { href: "/a", hreflang: "x-default" },
+ ],
+ changeFrequency: "weekly",
+ images: [{ loc: "/files/cover.png" }],
+ lastModified: new Date("2026-01-02T03:04:05.000Z"),
+ loc: "/a",
+ priority: 0.75,
+ })
+ .split("\n")
+ .slice(2, -3),
+ ).toStrictEqual([
+ " ",
+ " https://example.com/a",
+ " 2026-01-02T03:04:05.000Z",
+ " weekly",
+ " 0.8",
+ ' ',
+ ' ',
+ ' ',
+ " ",
+ " https://example.com/files/cover.png",
+ " ",
+ ]);
+ });
+
+ it("escapes URLs and hreflang values", () => {
+ const xml = urlset({
+ alternates: [{ href: "/a?x=1&y=2", hreflang: 'p"l' }],
+ loc: "/a?x=1&y=<2>",
+ });
+
+ expect(xml).toContain("https://example.com/a?x=1&y=%3C2%3E");
+ expect(xml).toContain(
+ 'hreflang="p"l" href="https://example.com/a?x=1&y=2"',
+ );
+ });
+
+ it("skips an invalid lastmod but keeps the entry", () => {
+ const xml = urlset({ lastModified: new Date("nope"), loc: "/a" });
+
+ expect(xml).toContain("https://example.com/a");
+ expect(xml).not.toContain("");
+ });
+
+ it("skips an entry whose URL cannot be built", () => {
+ expect(
+ sitemapUrlsetXml({ entries: [{ loc: "/a" }], origin: "not a url" }),
+ ).not.toContain("");
+ });
+
+ it.each([
+ [-1, "0.0"],
+ [0, "0.0"],
+ [0.5, "0.5"],
+ [2, "1.0"],
+ ])("clamps priority %d to %s", (priority, expected) => {
+ expect(urlset({ loc: "/a", priority })).toContain(
+ `${expected}`,
+ );
+ });
+});
+
+describe("defineSitemapSource", () => {
+ const source = (id: string): SitemapSource => ({
+ count: async () => await Promise.resolve(0),
+ getEntries: async () => await Promise.resolve([]),
+ id,
+ label: "Source",
+ });
+
+ it("returns a source with a valid id unchanged", () => {
+ const valid = source("blog_post-2");
+
+ expect(defineSitemapSource(valid)).toBe(valid);
+ });
+
+ it.each(["", "Blog", "blog.post", "a/b", "a b"])(
+ "throws for the id %j",
+ id => {
+ expect(() => defineSitemapSource(source(id))).toThrow(
+ "Invalid sitemap source id",
+ );
+ },
+ );
+});
diff --git a/packages/api/src/lib/seo/sitemap.ts b/packages/api/src/lib/seo/sitemap.ts
new file mode 100644
index 0000000000..b715733660
--- /dev/null
+++ b/packages/api/src/lib/seo/sitemap.ts
@@ -0,0 +1,186 @@
+import type { Context } from "hono";
+
+import type { ContentSitemapChangeFrequency } from "@/content/types";
+
+import { CONTENT_SITEMAP_MAX_URLS } from "@/content/const";
+import { escapeXml } from "@/content/sitemap";
+
+import { SITEMAP_SOURCE_ID_PATTERN } from "./settings";
+
+/** One `` of a sub-sitemap. */
+export interface SitemapEntry {
+ /**
+ * Other languages of the same page, each with an absolute or relative
+ * `href`. Include the entry's own language; add `x-default` yourself.
+ */
+ alternates?: readonly { href: string; hreflang: string }[];
+ changeFrequency?: ContentSitemapChangeFrequency | null;
+ /** Images on the page, for ``. Absolute or relative URLs. */
+ images?: readonly { loc: string }[];
+ lastModified?: Date | null;
+ /** Absolute URL, or a path resolved against the site origin. */
+ loc: string;
+ /** `0` to `1`. */
+ priority?: null | number;
+}
+
+/**
+ * A list of public URLs the sitemap includes, in its own sub-sitemap files
+ * (`/sitemaps/{id}-{page}.xml`). Register one with `registerSitemapSource`,
+ * `buildApiPlugin({ sitemapSources })` or `buildApiConfig({ seo })`. The
+ * Content Engine registers one per content type with `delivery.sitemap`.
+ *
+ * Both functions run for anonymous crawlers: return only what a guest may
+ * read, in a stable order, so page `n` always holds the same URLs.
+ *
+ * @example
+ * import { defineSitemapSource } from "@vitnode/api/lib/seo/sitemap";
+ *
+ * export const docsSitemap = defineSitemapSource({
+ * id: "docs",
+ * label: "@my/plugin.sitemap.docs",
+ * count: async () => pages.length,
+ * getEntries: async (_c, { limit, offset }) =>
+ * pages.slice(offset, offset + limit).map(page => ({ loc: page.path })),
+ * });
+ */
+export interface SitemapSource {
+ /** Set by the Content Engine, so the AdminCP shows the content type's name. */
+ contentType?: { id: string; pluginId: string };
+ /** How many entries `getEntries` returns in total. */
+ count: (c: Context) => Promise;
+ /** One page of entries, `offset` from the start. */
+ getEntries: (
+ c: Context,
+ page: { limit: number; offset: number },
+ ) => Promise;
+ /** The newest `lastmod`, for the sitemap index. Optional. */
+ getLastModified?: (c: Context) => Promise;
+ /** Unique, matching `/^[a-z0-9_-]+$/`. Becomes part of the file name. */
+ id: string;
+ /** An i18n key (or plain text) the AdminCP shows. */
+ label: string;
+}
+
+/**
+ * Checks a source's id and returns it unchanged.
+ *
+ * @throws When `id` does not match `/^[a-z0-9_-]+$/`.
+ */
+export const defineSitemapSource = (source: T): T => {
+ if (!SITEMAP_SOURCE_ID_PATTERN.test(source.id)) {
+ throw new Error(
+ `Invalid sitemap source id "${source.id}": use lowercase letters, digits, "_" and "-".`,
+ );
+ }
+
+ return source;
+};
+
+/** The file name of one page of a source: `{id}-{page}.xml`, 1-indexed. */
+export const sitemapFileName = (sourceId: string, page: number): string =>
+ `${sourceId}-${page}.xml`;
+
+const FILE_NAME_PATTERN = /^([a-z0-9_-]+)-(\d{1,9})\.xml$/;
+
+/**
+ * Splits `blog_post-2.xml` into `{ sourceId: "blog_post", page: 2 }`, or
+ * `null` for anything else (including page `0`).
+ */
+export const parseSitemapFileName = (
+ fileName: string,
+): null | { page: number; sourceId: string } => {
+ const match = FILE_NAME_PATTERN.exec(fileName);
+ if (!match) return null;
+
+ const page = Number(match[2]);
+ if (!Number.isSafeInteger(page) || page < 1) return null;
+
+ return { page, sourceId: match[1] };
+};
+
+/** Files a source needs: `0` for an empty one, so it is left out of the index. */
+export const sitemapPageCount = (total: number, perFile: number): number => {
+ const size = Math.max(
+ 1,
+ Math.min(Math.floor(perFile), CONTENT_SITEMAP_MAX_URLS),
+ );
+
+ return total > 0 ? Math.ceil(total / size) : 0;
+};
+
+const absolute = (origin: string, path: string): null | string => {
+ try {
+ return new URL(path, origin).toString();
+ } catch {
+ return null;
+ }
+};
+
+/**
+ * A `` document. The `xhtml` and `image` namespaces are declared only
+ * when an entry uses them; entries whose URL cannot be built are skipped.
+ */
+export const sitemapUrlsetXml = ({
+ entries,
+ origin,
+}: {
+ entries: readonly SitemapEntry[];
+ origin: string;
+}): string => {
+ const withAlternates = entries.some(entry => entry.alternates?.length);
+ const withImages = entries.some(entry => entry.images?.length);
+ const namespaces = [
+ 'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"',
+ ...(withAlternates ? ['xmlns:xhtml="http://www.w3.org/1999/xhtml"'] : []),
+ ...(withImages
+ ? ['xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"']
+ : []),
+ ];
+ const lines = [
+ '',
+ ``,
+ ];
+
+ for (const entry of entries) {
+ const loc = absolute(origin, entry.loc);
+ if (loc === null) continue;
+
+ lines.push(" ", ` ${escapeXml(loc)}`);
+ if (entry.lastModified && !Number.isNaN(entry.lastModified.getTime())) {
+ lines.push(` ${entry.lastModified.toISOString()}`);
+ }
+ if (entry.changeFrequency) {
+ lines.push(` ${entry.changeFrequency}`);
+ }
+ if (typeof entry.priority === "number") {
+ const priority = Math.min(1, Math.max(0, entry.priority));
+ lines.push(` ${priority.toFixed(1)}`);
+ }
+ for (const alternate of entry.alternates ?? []) {
+ const href = absolute(origin, alternate.href);
+ if (href === null) continue;
+ lines.push(
+ ` `,
+ );
+ }
+ for (const image of entry.images ?? []) {
+ const src = absolute(origin, image.loc);
+ if (src === null) continue;
+ lines.push(
+ " ",
+ ` ${escapeXml(src)}`,
+ " ",
+ );
+ }
+ lines.push(" ");
+ }
+
+ lines.push("");
+
+ return `${lines.join("\n")}\n`;
+};
+
+/** The headers every sitemap and `robots.txt` response carries. */
+export const SEO_CACHE_CONTROL =
+ "public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400";
diff --git a/packages/api/src/lib/seo/static-source.test.ts b/packages/api/src/lib/seo/static-source.test.ts
new file mode 100644
index 0000000000..7567b4dd3f
--- /dev/null
+++ b/packages/api/src/lib/seo/static-source.test.ts
@@ -0,0 +1,90 @@
+import type { Context } from "hono";
+
+import { describe, expect, it } from "vitest";
+
+import type { LocaleRoutingConfig } from "@/lib/i18n/locale-routing";
+
+import { createLocaleRouting } from "@/lib/i18n/locale-routing";
+
+import { staticSitemapEntries, staticSitemapSource } from "./static-source";
+
+const contextWith = (config: Partial = {}): Context => {
+ const localeRouting = createLocaleRouting({
+ defaultLocale: "en",
+ locales: ["en", "pl"],
+ ...config,
+ });
+
+ return {
+ get: (key: string) =>
+ key === "core" ? { i18n: { localeRouting } } : undefined,
+ } as unknown as Context;
+};
+
+describe("staticSitemapEntries", () => {
+ it("lists a page once per language, each with every language plus x-default", () => {
+ const alternates = [
+ { href: "/blog", hreflang: "en" },
+ { href: "/pl/blog", hreflang: "pl" },
+ { href: "/blog", hreflang: "x-default" },
+ ];
+
+ expect(
+ staticSitemapEntries(contextWith(), [
+ { changeFrequency: "daily", path: "/blog", priority: 0.8 },
+ ]),
+ ).toStrictEqual([
+ { alternates, changeFrequency: "daily", loc: "/blog", priority: 0.8 },
+ { alternates, changeFrequency: "daily", loc: "/pl/blog", priority: 0.8 },
+ ]);
+ });
+
+ it("lists a URL once, without alternates, on a single-language site", () => {
+ expect(
+ staticSitemapEntries(
+ contextWith({ locales: ["en"], localePrefix: "never" }),
+ ["/", "/"],
+ ),
+ ).toStrictEqual([{ changeFrequency: null, loc: "/", priority: null }]);
+ });
+
+ it("writes absolute URLs for languages on their own domain", () => {
+ const entries = staticSitemapEntries(
+ contextWith({
+ domains: [
+ { defaultLocale: "en", origin: "https://example.com" },
+ { defaultLocale: "pl", origin: "https://example.pl" },
+ ],
+ localePrefix: "never",
+ }),
+ ["/"],
+ );
+
+ expect(entries.map(entry => entry.loc)).toStrictEqual([
+ "https://example.com/",
+ "https://example.pl/",
+ ]);
+ expect(entries[0].alternates?.at(-1)).toStrictEqual({
+ href: "https://example.com/",
+ hreflang: "x-default",
+ });
+ });
+});
+
+describe("staticSitemapSource", () => {
+ it("counts and pages the localized entries", async () => {
+ const c = contextWith();
+ const source = staticSitemapSource({
+ id: "landing",
+ label: "Landing",
+ paths: c2 => (c2 === c ? ["/", "/pricing"] : []),
+ });
+
+ expect(await source.count(c)).toBe(4);
+ expect(
+ (await source.getEntries(c, { limit: 2, offset: 1 })).map(
+ entry => entry.loc,
+ ),
+ ).toStrictEqual(["/pl", "/pricing"]);
+ });
+});
diff --git a/packages/api/src/lib/seo/static-source.ts b/packages/api/src/lib/seo/static-source.ts
new file mode 100644
index 0000000000..a245de3912
--- /dev/null
+++ b/packages/api/src/lib/seo/static-source.ts
@@ -0,0 +1,106 @@
+import type { Context } from "hono";
+
+import type { ContentSitemapChangeFrequency } from "@/content/types";
+
+import type { SitemapEntry, SitemapSource } from "./sitemap";
+
+import { defineSitemapSource } from "./sitemap";
+
+/** One page of the static sitemap source. */
+export interface SitemapStaticPath {
+ changeFrequency?: ContentSitemapChangeFrequency;
+ /** The internal (unlocalized) path, e.g. `/` or `/blog`. */
+ path: string;
+ /** `0` to `1`. */
+ priority?: number;
+}
+
+const toStaticPath = (path: SitemapStaticPath | string): SitemapStaticPath =>
+ typeof path === "string" ? { path } : path;
+
+const urlOf = (url: { origin?: string; pathname: string }): string =>
+ url.origin === undefined
+ ? url.pathname
+ : new URL(url.pathname, url.origin).href;
+
+/**
+ * One entry per page and language, each with every language as an `hreflang`
+ * alternate plus `x-default` for the default locale. Duplicate URLs (a
+ * `localePrefix: "never"` site) are listed once.
+ */
+export const staticSitemapEntries = (
+ c: Context,
+ paths: readonly (SitemapStaticPath | string)[],
+): SitemapEntry[] => {
+ const routing = c.get("core").i18n.localeRouting;
+ const seen = new Set();
+ const entries: SitemapEntry[] = [];
+
+ for (const page of paths.map(toStaticPath)) {
+ const localized = routing.alternatesFor(page.path).map(alternate => ({
+ href: urlOf(alternate),
+ hreflang: alternate.locale,
+ }));
+ const unique = localized.filter(
+ (alternate, index) =>
+ localized.findIndex(other => other.href === alternate.href) === index,
+ );
+ const xDefault = unique.find(
+ alternate => alternate.hreflang === routing.defaultLocale,
+ );
+ const alternates =
+ unique.length > 1
+ ? [
+ ...unique,
+ ...(xDefault
+ ? [{ href: xDefault.href, hreflang: "x-default" }]
+ : []),
+ ]
+ : undefined;
+
+ for (const { href } of unique) {
+ if (seen.has(href)) continue;
+ seen.add(href);
+ entries.push({
+ changeFrequency: page.changeFrequency ?? null,
+ loc: href,
+ priority: page.priority ?? null,
+ ...(alternates ? { alternates } : {}),
+ });
+ }
+ }
+
+ return entries;
+};
+
+/**
+ * A sitemap source for a fixed list of pages, localized for every language
+ * of the site. Core's `static` source is one; plugins can make their own.
+ *
+ * @example
+ * import { staticSitemapSource } from "@vitnode/api/lib/seo/static-source";
+ *
+ * staticSitemapSource({ id: "landing", label: "Landing pages", paths: ["/pricing"] });
+ */
+export const staticSitemapSource = ({
+ id,
+ label,
+ paths,
+}: {
+ id: string;
+ label: string;
+ paths:
+ | ((c: Context) => readonly (SitemapStaticPath | string)[])
+ | readonly (SitemapStaticPath | string)[];
+}): SitemapSource => {
+ const entriesOf = (c: Context) =>
+ staticSitemapEntries(c, typeof paths === "function" ? paths(c) : paths);
+
+ return defineSitemapSource({
+ count: async c => await Promise.resolve(entriesOf(c).length),
+ getEntries: async (c, { limit, offset }) =>
+ await Promise.resolve(entriesOf(c).slice(offset, offset + limit)),
+ id,
+ label,
+ });
+};
diff --git a/packages/api/src/middlewares/global.middleware.ts b/packages/api/src/middlewares/global.middleware.ts
index c4321521eb..bd3e90b20f 100644
--- a/packages/api/src/middlewares/global.middleware.ts
+++ b/packages/api/src/middlewares/global.middleware.ts
@@ -80,6 +80,7 @@ import type { PaymentProviderApiPlugin } from "../lib/payments/provider";
import type { PermissionStaffCatalogEntry } from "../lib/permission-staff";
import type { QueueTaskConfig } from "../lib/queue";
import type { ReactionsRegistry } from "../lib/reactions/targets";
+import type { ResolvedSeoConfig } from "../lib/seo/config";
import type { UpdateComponent } from "../lib/updates/components";
import type { WebSocketConfig } from "../lib/websocket";
import type { EventsApiPlugin } from "../models/events";
@@ -89,6 +90,7 @@ import type {
} from "../models/search";
import type { SSOApiPlugin } from "../models/sso";
+import { contentSitemapSources } from "../content/server/sitemap-source";
import { assertAiModelPricing } from "../lib/ai/pricing";
import { assertContentAiActions, collectAiActions } from "../lib/ai/registry";
import { collectAuditActions } from "../lib/audit/registry";
@@ -113,6 +115,7 @@ import { resolvePasskeysConfig } from "../lib/passkey-config";
import { validatePaymentProviders } from "../lib/payments/provider";
import { normalizePermissionStaffModules } from "../lib/permission-staff";
import { validateReactionsRegistry } from "../lib/reactions/targets";
+import { resolveSeoConfig } from "../lib/seo/config";
import { collectUpdateComponents } from "../lib/updates/components";
import { resolveUpdatesConfig } from "../lib/updates/config";
@@ -280,6 +283,8 @@ export interface EnvVariablesVitNode {
reactions: ReactionsRegistry;
search: { adapter: SearchProviderApiPlugin };
searchIndexers: SearchIndexerConfig[];
+ /** `robots.txt` paths and every declared sitemap source, resolved at boot. */
+ seo: ResolvedSeoConfig;
storage?: VitNodeApiConfig["storage"];
/** Core and every catalog plugin, with the update source and versions to check. */
updates: {
@@ -392,6 +397,7 @@ export const globalMiddleware = ({
ogImage,
payments,
search,
+ seo,
storage,
updates,
users,
@@ -415,6 +421,7 @@ export const globalMiddleware = ({
| "payments"
| "plugins"
| "search"
+ | "seo"
| "storage"
| "updates"
| "users"
@@ -563,6 +570,12 @@ export const globalMiddleware = ({
})),
);
+ const seoMetadata = resolveSeoConfig({
+ config: seo,
+ contentSources: contentSitemapSources(contentModelsMetadata),
+ plugins,
+ });
+
// Computed at boot, outside the request: "does anything need the languages
// table" is a property of the installed plugins, not of a request.
const hasLocalizedContentTypes = contentTypesMetadata.some(
@@ -750,6 +763,7 @@ export const globalMiddleware = ({
payments: paymentsMetadata,
contentContainers: contentContainersMetadata,
contentModels: contentModelsMetadata,
+ seo: seoMetadata,
contentNotifications: contentNotificationsMetadata,
contentRevalidateOrigins: content?.revalidateOrigins,
contentTypes: contentTypesMetadata,
diff --git a/packages/api/src/modules/admin/admin.module.ts b/packages/api/src/modules/admin/admin.module.ts
index 8bbcc1c2e5..ff256c23a6 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 { seoAdminModule } from "./seo/seo.module";
import { siteAdminModule } from "./site/site.module";
import { staffAdminModule } from "./staff/staff.module";
import { usersAdminModule } from "./users/users.module";
@@ -36,6 +37,7 @@ export const adminModule = buildModule({
reactionsAdminModule,
reportReasonsAdminModule,
warningsAdminModule,
+ seoAdminModule,
siteAdminModule,
],
cronJobs: [],
diff --git a/packages/api/src/modules/admin/seo/admin-settings.server.ts b/packages/api/src/modules/admin/seo/admin-settings.server.ts
new file mode 100644
index 0000000000..4553d9ea2c
--- /dev/null
+++ b/packages/api/src/modules/admin/seo/admin-settings.server.ts
@@ -0,0 +1,46 @@
+import type { Context } from "hono";
+
+import {
+ getSitemapSources,
+ robotsContext,
+ seoSiteOrigin,
+ sitemapSourceStats,
+} from "@/lib/seo/serve.server";
+import { loadSeoSettings } from "@/lib/seo/settings.server";
+
+import type { SeoAdminSettings } from "./seo.schema";
+
+/** The settings with every source's size, for the AdminCP. Server-only. */
+export const readSeoAdminSettings = async (
+ c: Context,
+): Promise => {
+ const settings = await loadSeoSettings(c);
+ const disabled = new Set(settings.sitemap.disabledSources);
+ const [context, sources] = await Promise.all([
+ robotsContext(c),
+ Promise.all(
+ getSitemapSources(c).map(async source => ({
+ contentType: source.contentType ?? null,
+ enabled: !disabled.has(source.id),
+ id: source.id,
+ label: source.label,
+ ...(await sitemapSourceStats(
+ c,
+ source,
+ settings.sitemap.maxUrlsPerFile,
+ )),
+ })),
+ ),
+ ]);
+
+ return {
+ robots: {
+ disallow: context.disallow,
+ offline: context.offline,
+ sitemapUrl: context.sitemapUrl,
+ },
+ settings,
+ siteOrigin: seoSiteOrigin(),
+ sources,
+ };
+};
diff --git a/packages/api/src/modules/admin/seo/routes/robots-preview.route.ts b/packages/api/src/modules/admin/seo/routes/robots-preview.route.ts
new file mode 100644
index 0000000000..1a843ec7d4
--- /dev/null
+++ b/packages/api/src/modules/admin/seo/routes/robots-preview.route.ts
@@ -0,0 +1,33 @@
+import { z } from "zod";
+
+import { buildRoute } from "@/builders";
+import { coreStaffPermissions } from "@/lib/core-staff-permissions";
+import { renderRobotsTxt } from "@/lib/seo/serve.server";
+import { loadSeoSettings } from "@/lib/seo/settings.server";
+
+export const robotsPreviewAdminRoute = buildRoute({
+ adminStaffPermission: coreStaffPermissions.admin.seo.canView,
+ route: {
+ method: "get",
+ description: "The robots.txt the site serves right now, as text.",
+ path: "/robots/preview",
+ responses: {
+ 200: {
+ content: {
+ "application/json": {
+ schema: z.object({ content: z.string(), offline: z.boolean() }),
+ },
+ },
+ description: "robots.txt preview",
+ },
+ },
+ },
+ handler: async c => {
+ const { body, offline } = await renderRobotsTxt(
+ c,
+ await loadSeoSettings(c),
+ );
+
+ return c.json({ content: body, offline }, 200);
+ },
+});
diff --git a/packages/api/src/modules/admin/seo/routes/seo.route.test.ts b/packages/api/src/modules/admin/seo/routes/seo.route.test.ts
new file mode 100644
index 0000000000..926a904291
--- /dev/null
+++ b/packages/api/src/modules/admin/seo/routes/seo.route.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from "vitest";
+
+import type { PermissionsStaffArgs } from "@/lib/permission-staff";
+
+import { core_audit_logs } from "@/database/audit";
+import { seoSettingsUpdatedEvent } from "@/events/seo";
+import { createSeoWorld, SEO_ADMIN } from "@/tests/seo";
+import { sessionCookies } from "@/tests/sessions";
+import { grantStaffPermissions } from "@/tests/staff-permissions";
+
+const CAN_VIEW: PermissionsStaffArgs = {
+ module: "seo",
+ permission: "can_view",
+ plugin: "@vitnode/core",
+};
+const CAN_MANAGE: PermissionsStaffArgs = {
+ ...CAN_VIEW,
+ permission: "can_manage",
+};
+
+const setup = async (permissions: PermissionsStaffArgs[]) => {
+ const world = await createSeoWorld();
+ await grantStaffPermissions(world.cache, {
+ permissions,
+ userId: SEO_ADMIN.userId,
+ });
+
+ const send = async (path: string, init: RequestInit = {}) =>
+ await world.app.request(`/admin${path}`, {
+ ...init,
+ headers: {
+ "content-type": "application/json",
+ cookie: sessionCookies(SEO_ADMIN, "admin"),
+ },
+ });
+ const patch = async (body: unknown) =>
+ await send("/settings", { body: JSON.stringify(body), method: "PATCH" });
+
+ return { patch, send, world };
+};
+
+describe("SEO AdminCP routes", () => {
+ it.each([
+ ["GET", "/settings", []],
+ ["GET", "/robots/preview", []],
+ ["PATCH", "/settings", [CAN_VIEW]],
+ ] satisfies [string, string, PermissionsStaffArgs[]][])(
+ "refuses %s %s to an admin without the permission",
+ async (method, path, permissions) => {
+ const { send } = await setup(permissions);
+
+ expect(
+ (
+ await send(path, {
+ body: method === "GET" ? undefined : "{}",
+ method,
+ })
+ ).status,
+ ).toBe(403);
+ },
+ );
+
+ it("shows the settings with every source's size to an admin who can view", async () => {
+ const { send } = await setup([CAN_VIEW]);
+ const response = await send("/settings");
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({
+ settings: { allowIndexing: true, sitemap: { disabledSources: [] } },
+ siteOrigin: "http://localhost:3000",
+ sources: [
+ { enabled: true, error: false, files: 1, id: "static", urls: 2 },
+ { enabled: true, error: false, files: 1, id: "docs", urls: 3 },
+ ],
+ });
+ });
+
+ it("previews the robots.txt the site serves", async () => {
+ const { send, world } = await setup([CAN_VIEW]);
+ const preview = await send("/robots/preview");
+
+ expect(preview.status).toBe(200);
+ expect(await preview.json()).toStrictEqual({
+ content: await (await world.app.request("/robots")).text(),
+ offline: false,
+ });
+ });
+
+ it("refuses to disable a source that is not registered", async () => {
+ const { patch, world } = await setup([CAN_VIEW, CAN_MANAGE]);
+
+ expect(
+ (await patch({ sitemap: { disabledSources: ["docs", "nope"] } })).status,
+ ).toBe(400);
+ expect(world.emit).not.toHaveBeenCalled();
+ });
+
+ it("takes a disabled source out of the sitemap at once, and records the change", async () => {
+ const { patch, world } = await setup([CAN_VIEW, CAN_MANAGE]);
+ // Warm the cached settings, so the save has to expire them.
+ expect((await world.app.request("/sitemaps/docs-1.xml")).status).toBe(200);
+
+ const response = await patch({ sitemap: { disabledSources: ["docs"] } });
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({
+ settings: { sitemap: { disabledSources: ["docs"] } },
+ sources: [
+ { enabled: true, id: "static" },
+ { enabled: false, id: "docs" },
+ ],
+ });
+ expect((await world.app.request("/sitemaps/docs-1.xml")).status).toBe(404);
+ expect(await (await world.app.request("/sitemap")).text()).not.toContain(
+ "docs-1.xml",
+ );
+ expect(world.emit).toHaveBeenCalledWith(
+ seoSettingsUpdatedEvent,
+ expect.objectContaining({
+ changedById: SEO_ADMIN.userId,
+ disabledSitemapSources: ["docs"],
+ }),
+ );
+ expect(world.rows(core_audit_logs)).toHaveLength(1);
+ });
+});
diff --git a/packages/api/src/modules/admin/seo/routes/show.route.ts b/packages/api/src/modules/admin/seo/routes/show.route.ts
new file mode 100644
index 0000000000..636d2cc574
--- /dev/null
+++ b/packages/api/src/modules/admin/seo/routes/show.route.ts
@@ -0,0 +1,22 @@
+import { buildRoute } from "@/builders";
+import { coreStaffPermissions } from "@/lib/core-staff-permissions";
+
+import { readSeoAdminSettings } from "../admin-settings.server";
+import { zodSeoAdminSettings } from "../seo.schema";
+
+export const showSeoSettingsAdminRoute = buildRoute({
+ adminStaffPermission: coreStaffPermissions.admin.seo.canView,
+ route: {
+ method: "get",
+ description:
+ "The SEO settings with their defaults, every registered sitemap source with its URL count, and what the robots.txt preview needs.",
+ path: "/settings",
+ responses: {
+ 200: {
+ content: { "application/json": { schema: zodSeoAdminSettings } },
+ description: "SEO settings",
+ },
+ },
+ },
+ handler: async c => c.json(await readSeoAdminSettings(c), 200),
+});
diff --git a/packages/api/src/modules/admin/seo/routes/update.route.ts b/packages/api/src/modules/admin/seo/routes/update.route.ts
new file mode 100644
index 0000000000..8da5ba487f
--- /dev/null
+++ b/packages/api/src/modules/admin/seo/routes/update.route.ts
@@ -0,0 +1,100 @@
+import { HTTPException } from "hono/http-exception";
+
+import { buildRoute } from "@/builders";
+import { seoSettingsUpdatedEvent } from "@/events/seo";
+import { auditDiff } from "@/lib/audit/diff";
+import { writeAuditLog } from "@/lib/audit/write";
+import { coreStaffPermissions } from "@/lib/core-staff-permissions";
+import { getSitemapSources } from "@/lib/seo/serve.server";
+import { mergeSeoSettings, zodSeoSettingsUpdate } from "@/lib/seo/settings";
+import {
+ afterSeoSettingsSaved,
+ loadSeoSettings,
+ saveSeoSettings,
+} from "@/lib/seo/settings.server";
+
+import { readSeoAdminSettings } from "../admin-settings.server";
+import { zodSeoAdminSettings } from "../seo.schema";
+
+export const updateSeoSettingsAdminRoute = buildRoute({
+ adminStaffPermission: coreStaffPermissions.admin.seo.canManage,
+ route: {
+ method: "patch",
+ description:
+ "Change any of the SEO settings; fields left out keep their saved values.",
+ path: "/settings",
+ request: {
+ body: {
+ required: true,
+ content: { "application/json": { schema: zodSeoSettingsUpdate } },
+ },
+ },
+ responses: {
+ 200: {
+ content: { "application/json": { schema: zodSeoAdminSettings } },
+ description: "Saved; the settings as they are now",
+ },
+ 400: { description: "A disabled source id is not registered" },
+ },
+ },
+ handler: async c => {
+ const body = c.req.valid("json");
+ const admin = c.get("admin");
+ if (!admin) throw new HTTPException(403);
+
+ const next = mergeSeoSettings(await loadSeoSettings(c), body);
+ const known = new Set(getSitemapSources(c).map(source => source.id));
+ const unknown = body.sitemap?.disabledSources?.filter(id => !known.has(id));
+ if (unknown?.length) {
+ throw new HTTPException(400, {
+ message: `Unknown sitemap source: ${unknown.join(", ")}.`,
+ });
+ }
+
+ await c.get("db").transaction(async tx => {
+ const before = await saveSeoSettings(tx, next, admin.user.id);
+ const flatten = (settings: typeof next) => ({
+ allowIndexing: settings.allowIndexing,
+ blockAiCrawlers: settings.blockAiCrawlers,
+ customRobots: settings.customRobots,
+ disabledSitemapSources: settings.sitemap.disabledSources.join(", "),
+ sitemapEnabled: settings.sitemap.enabled,
+ sitemapMaxUrls: settings.sitemap.maxUrlsPerFile,
+ });
+ const changes = auditDiff({
+ after: flatten(next),
+ before: flatten(before),
+ include: [
+ "allowIndexing",
+ "blockAiCrawlers",
+ "customRobots",
+ "disabledSitemapSources",
+ "sitemapEnabled",
+ "sitemapMaxUrls",
+ ],
+ });
+ if (changes) {
+ await writeAuditLog(
+ c,
+ {
+ action: "settings.updated",
+ changes,
+ target: { id: "seo", label: "SEO", type: "settings" },
+ },
+ tx,
+ );
+ }
+ });
+
+ await afterSeoSettingsSaved(c);
+ await c.get("events").emit(seoSettingsUpdatedEvent, {
+ allowIndexing: next.allowIndexing,
+ blockAiCrawlers: next.blockAiCrawlers,
+ changedById: admin.user.id,
+ disabledSitemapSources: next.sitemap.disabledSources,
+ sitemapEnabled: next.sitemap.enabled,
+ });
+
+ return c.json(await readSeoAdminSettings(c), 200);
+ },
+});
diff --git a/packages/api/src/modules/admin/seo/seo.module.ts b/packages/api/src/modules/admin/seo/seo.module.ts
new file mode 100644
index 0000000000..008e874f4a
--- /dev/null
+++ b/packages/api/src/modules/admin/seo/seo.module.ts
@@ -0,0 +1,14 @@
+import { buildModule } from "@/builders";
+
+import { robotsPreviewAdminRoute } from "./routes/robots-preview.route";
+import { showSeoSettingsAdminRoute } from "./routes/show.route";
+import { updateSeoSettingsAdminRoute } from "./routes/update.route";
+
+export const seoAdminModule = buildModule({
+ name: "seo",
+ routes: [
+ showSeoSettingsAdminRoute,
+ updateSeoSettingsAdminRoute,
+ robotsPreviewAdminRoute,
+ ],
+});
diff --git a/packages/api/src/modules/admin/seo/seo.schema.ts b/packages/api/src/modules/admin/seo/seo.schema.ts
new file mode 100644
index 0000000000..954c7484de
--- /dev/null
+++ b/packages/api/src/modules/admin/seo/seo.schema.ts
@@ -0,0 +1,35 @@
+import { z } from "zod";
+
+import { zodSeoSettings } from "@/lib/seo/settings";
+
+/** One sitemap source as the AdminCP lists it. Browser-safe. */
+export const zodSeoAdminSitemapSource = z.object({
+ id: z.string(),
+ /** An i18n key, or plain text from a plugin. */
+ label: z.string(),
+ /** Set for Content Engine sources; the AdminCP names the content type. */
+ contentType: z.object({ id: z.string(), pluginId: z.string() }).nullable(),
+ enabled: z.boolean(),
+ /** URLs the source lists right now. */
+ urls: z.number().int(),
+ /** Sub-sitemap files at the saved `maxUrlsPerFile`. */
+ files: z.number().int(),
+ /** The source failed to count; it is left out of the index. */
+ error: z.boolean(),
+});
+
+/** What `GET /admin/seo/settings` answers. Browser-safe. */
+export const zodSeoAdminSettings = z.object({
+ settings: zodSeoSettings,
+ sources: z.array(zodSeoAdminSitemapSource),
+ /** What the AdminCP needs to preview `robots.txt` as the visitor gets it. */
+ robots: z.object({
+ disallow: z.array(z.string()),
+ offline: z.boolean(),
+ sitemapUrl: z.string(),
+ }),
+ siteOrigin: z.string(),
+});
+
+export type SeoAdminSettings = z.output;
+export type SeoAdminSitemapSource = z.output;
diff --git a/packages/api/src/modules/seo/routes/robots.route.ts b/packages/api/src/modules/seo/routes/robots.route.ts
new file mode 100644
index 0000000000..218a64e924
--- /dev/null
+++ b/packages/api/src/modules/seo/routes/robots.route.ts
@@ -0,0 +1,50 @@
+import { z } from "zod";
+
+import { buildRoute } from "@/builders";
+import { renderRobotsTxt } from "@/lib/seo/serve.server";
+import { loadSeoSettings } from "@/lib/seo/settings.server";
+import { retryAfterSeconds } from "@/lib/site-status";
+
+/** Short, so turning indexing off reaches crawlers within minutes. */
+const ROBOTS_CACHE_CONTROL =
+ "public, max-age=300, s-maxage=300, stale-while-revalidate=3600";
+
+export const robotsRoute = buildRoute({
+ allowWhenOffline: true,
+ route: {
+ method: "get",
+ description:
+ "The site's `robots.txt`, generated from the AdminCP SEO settings. While the site is offline it answers `503` with `Retry-After`, which crawlers read as a temporary pause rather than a reason to drop pages.",
+ path: "/robots",
+ responses: {
+ 200: {
+ content: { "text/plain": { schema: z.string() } },
+ description: "robots.txt",
+ },
+ 503: {
+ content: { "text/plain": { schema: z.string() } },
+ description: "The site is offline",
+ },
+ },
+ },
+ handler: async c => {
+ const settings = await loadSeoSettings(c);
+ const { body, offline, opensAt } = await renderRobotsTxt(c, settings);
+
+ if (offline) {
+ const retryAfter = retryAfterSeconds(opensAt);
+
+ return c.text(body, 503, {
+ "Cache-Control": "no-store",
+ "Content-Type": "text/plain; charset=utf-8",
+ ...(retryAfter === null ? {} : { "Retry-After": String(retryAfter) }),
+ });
+ }
+
+ return c.text(body, 200, {
+ "Cache-Control": ROBOTS_CACHE_CONTROL,
+ "Content-Type": "text/plain; charset=utf-8",
+ "X-Content-Type-Options": "nosniff",
+ });
+ },
+});
diff --git a/packages/api/src/modules/seo/routes/seo.route.test.ts b/packages/api/src/modules/seo/routes/seo.route.test.ts
new file mode 100644
index 0000000000..8654d233c5
--- /dev/null
+++ b/packages/api/src/modules/seo/routes/seo.route.test.ts
@@ -0,0 +1,142 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { SEO_CACHE_CONTROL } from "@/lib/seo/sitemap";
+import { createSeoWorld } from "@/tests/seo";
+
+const T0 = new Date("2026-11-23T12:00:00.000Z");
+const OPENS_IN_SECONDS = 600;
+
+const OFFLINE = {
+ offline: true,
+ opensAt: new Date(T0.getTime() + OPENS_IN_SECONDS * 1000),
+};
+
+const read = async (
+ world: Awaited>,
+ path: string,
+) => {
+ const response = await world.app.request(path);
+
+ return {
+ body: await response.text(),
+ cacheControl: response.headers.get("cache-control"),
+ contentType: response.headers.get("content-type"),
+ retryAfter: response.headers.get("retry-after"),
+ status: response.status,
+ };
+};
+
+beforeEach(() => {
+ vi.useFakeTimers({ now: T0 });
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("GET /robots", () => {
+ it("serves the generated file as cacheable plain text", async () => {
+ const response = await read(await createSeoWorld(), "/robots");
+
+ expect(response).toMatchObject({
+ cacheControl: expect.stringMatching(/^public, max-age=300/),
+ contentType: "text/plain; charset=utf-8",
+ status: 200,
+ });
+ expect(response.body).toContain("Disallow: /pl/settings\n");
+ expect(response.body).toContain(
+ "Sitemap: http://localhost:3000/sitemap.xml\n",
+ );
+ });
+
+ it("leaves out the sitemap line when sitemaps are off", async () => {
+ const { body } = await read(
+ await createSeoWorld({ settings: { sitemapEnabled: false } }),
+ "/robots",
+ );
+
+ expect(body).not.toContain("Sitemap:");
+ });
+
+ it("answers 503 with Retry-After and no caching while the site is offline", async () => {
+ expect(
+ await read(await createSeoWorld({ siteStatus: OFFLINE }), "/robots"),
+ ).toMatchObject({
+ body: expect.stringMatching(/^# The site is offline/),
+ cacheControl: "no-store",
+ retryAfter: String(OPENS_IN_SECONDS),
+ status: 503,
+ });
+ });
+});
+
+describe("GET /sitemap and /sitemaps/{file}", () => {
+ it("lists one file per page of every non-empty source, as cacheable XML", async () => {
+ const response = await read(
+ await createSeoWorld({
+ docsSize: 150,
+ settings: { sitemapMaxUrls: 100 },
+ }),
+ "/sitemap",
+ );
+
+ expect(response).toMatchObject({
+ cacheControl: SEO_CACHE_CONTROL,
+ contentType: "application/xml; charset=utf-8",
+ status: 200,
+ });
+ expect(
+ [...response.body.matchAll(/([^<]+)<\/loc>/g)].map(
+ match => match[1],
+ ),
+ ).toStrictEqual([
+ "http://localhost:3000/sitemaps/static-1.xml",
+ "http://localhost:3000/sitemaps/docs-1.xml",
+ "http://localhost:3000/sitemaps/docs-2.xml",
+ ]);
+ });
+
+ it("serves the second page of a source", async () => {
+ const response = await read(
+ await createSeoWorld({
+ docsSize: 150,
+ settings: { sitemapMaxUrls: 100 },
+ }),
+ "/sitemaps/docs-2.xml",
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.match(//g)).toHaveLength(50);
+ expect(response.body).toContain(
+ "http://localhost:3000/docs/101",
+ );
+ });
+
+ it.each([
+ ["indexing is off", { allowIndexing: false }, "/sitemap"],
+ ["sitemaps are off", { sitemapEnabled: false }, "/sitemap"],
+ ["sitemaps are off", { sitemapEnabled: false }, "/sitemaps/docs-1.xml"],
+ [
+ "the source is disabled",
+ { disabledSitemapSources: ["docs"] },
+ "/sitemaps/docs-1.xml",
+ ],
+ ["the page is past the end", {}, "/sitemaps/docs-2.xml"],
+ ["the source is unknown", {}, "/sitemaps/nope-1.xml"],
+ ["the name is not a sitemap file", {}, "/sitemaps/docs-0.xml"],
+ ])("answers an uncached 404 when %s (%o, %s)", async (_, settings, path) => {
+ expect(await read(await createSeoWorld({ settings }), path)).toMatchObject({
+ cacheControl: "no-store",
+ status: 404,
+ });
+ });
+
+ it.each(["/sitemap", "/sitemaps/docs-1.xml"])(
+ "answers an uncached 503 for %s while the site is offline",
+ async path => {
+ expect(
+ await read(await createSeoWorld({ siteStatus: OFFLINE }), path),
+ ).toMatchObject({ cacheControl: "no-store", status: 503 });
+ },
+ );
+});
diff --git a/packages/api/src/modules/seo/routes/sitemap.route.ts b/packages/api/src/modules/seo/routes/sitemap.route.ts
new file mode 100644
index 0000000000..a3c898a63c
--- /dev/null
+++ b/packages/api/src/modules/seo/routes/sitemap.route.ts
@@ -0,0 +1,77 @@
+import { z } from "zod";
+
+import { buildRoute } from "@/builders";
+import { renderSitemapFile, renderSitemapIndex } from "@/lib/seo/serve.server";
+import { SEO_CACHE_CONTROL } from "@/lib/seo/sitemap";
+import { loadSiteStatus } from "@/lib/site-status.server";
+
+const XML = "application/xml; charset=utf-8";
+
+const xmlResponses = {
+ 200: {
+ content: { "application/xml": { schema: z.string() } },
+ description: "Sitemap XML",
+ },
+ 404: { description: "Sitemaps are off, or there is no such file" },
+ 503: { description: "The site is offline" },
+} as const;
+
+const notFound = () =>
+ new Response("Not Found", {
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/plain" },
+ status: 404,
+ });
+
+const offline = () =>
+ new Response("Service Unavailable", {
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/plain" },
+ status: 503,
+ });
+
+const xml = (body: string) =>
+ new Response(body, {
+ headers: {
+ "Cache-Control": SEO_CACHE_CONTROL,
+ "Content-Type": XML,
+ "X-Content-Type-Options": "nosniff",
+ },
+ status: 200,
+ });
+
+export const sitemapIndexRoute = buildRoute({
+ allowWhenOffline: true,
+ route: {
+ method: "get",
+ description:
+ "The sitemap index: one file per page of every enabled sitemap source.",
+ path: "/sitemap",
+ responses: xmlResponses,
+ },
+ handler: async c => {
+ if ((await loadSiteStatus(c)).offline) return offline();
+ const body = await renderSitemapIndex(c);
+
+ return body === null ? notFound() : xml(body);
+ },
+});
+
+export const sitemapFileRoute = buildRoute({
+ allowWhenOffline: true,
+ route: {
+ method: "get",
+ description:
+ "One sitemap file, `{sourceId}-{page}.xml` with 1-indexed pages.",
+ path: "/sitemaps/{file}",
+ request: {
+ params: z.object({ file: z.string().max(128) }),
+ },
+ responses: xmlResponses,
+ },
+ handler: async c => {
+ if ((await loadSiteStatus(c)).offline) return offline();
+ const { file } = c.req.valid("param");
+ const body = await renderSitemapFile(c, file);
+
+ return body === null ? notFound() : xml(body);
+ },
+});
diff --git a/packages/api/src/modules/seo/seo.module.ts b/packages/api/src/modules/seo/seo.module.ts
new file mode 100644
index 0000000000..73216ef456
--- /dev/null
+++ b/packages/api/src/modules/seo/seo.module.ts
@@ -0,0 +1,10 @@
+import { buildModule } from "@/builders";
+
+import { robotsRoute } from "./routes/robots.route";
+import { sitemapFileRoute, sitemapIndexRoute } from "./routes/sitemap.route";
+
+/** `robots.txt` and the XML sitemaps the web app serves at its root. */
+export const seoModule = buildModule({
+ name: "seo",
+ routes: [robotsRoute, sitemapIndexRoute, sitemapFileRoute],
+});
diff --git a/packages/api/src/plugin.ts b/packages/api/src/plugin.ts
index c32c57dbfe..522d510ff3 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 { seoEventDefinitions } from "./events/seo";
import { siteEventDefinitions } from "./events/site";
import { userEventDefinitions } from "./events/users";
import { corePersonalData } from "./lib/account-deletion/core-personal-data";
@@ -41,6 +42,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 { seoModule } from "./modules/seo/seo.module";
import { siteModule } from "./modules/site/site.module";
import { usersModule } from "./modules/users/users.module";
@@ -67,6 +69,7 @@ export const newBuildPluginApiCore = buildApiPlugin({
...reactionEventDefinitions,
...roleEventDefinitions,
...siteEventDefinitions,
+ ...seoEventDefinitions,
...userEventDefinitions,
],
modules: [
@@ -84,6 +87,7 @@ export const newBuildPluginApiCore = buildApiPlugin({
queueModule,
reactionsModule,
searchModule,
+ seoModule,
siteModule,
],
permissionStaff: coreStaffPermissions,
diff --git a/packages/api/src/tests/memory-db.ts b/packages/api/src/tests/memory-db.ts
index d6cdc6ff38..059dc6083a 100644
--- a/packages/api/src/tests/memory-db.ts
+++ b/packages/api/src/tests/memory-db.ts
@@ -33,6 +33,7 @@ type Node =
| { item: Node; kind: "not" }
| { items: Node[]; kind: "and" | "or" }
| { kind: "compare"; left: Node; operator: string; right: Node }
+ | { kind: "distinct"; left: Node; negated: boolean; right: Node }
| { kind: "in"; left: Node; negated: boolean; options: Node[] }
| { kind: "value"; value: unknown };
@@ -242,6 +243,12 @@ const parseTokens = (tokens: Token[], source: string) => {
position++;
const negated = isWord("not");
if (negated) position++;
+ if (isWord("distinct")) {
+ position++;
+ expect("from");
+
+ return { kind: "distinct", left, negated, right: parseConcat() };
+ }
expect("null");
return { item: left, kind: "isNull", negated };
@@ -478,6 +485,16 @@ const evaluate = (
}
case "compare":
return compare(of(node.left), node.operator, of(node.right));
+ case "distinct": {
+ const left = of(node.left);
+ const right = of(node.right);
+ const same =
+ isMissing(left) || isMissing(right)
+ ? isMissing(left) && isMissing(right)
+ : compare(left, "=", right) === true;
+
+ return same === node.negated;
+ }
case "in": {
const left = of(node.left);
if (isMissing(left)) return null;
@@ -579,6 +596,7 @@ const isAggregate = (node: Node): boolean => {
case "not":
return isAggregate(node.item);
case "compare":
+ case "distinct":
case "like":
return isAggregate(node.left) || isAggregate(node.right);
case "in":
diff --git a/packages/api/src/tests/seo.ts b/packages/api/src/tests/seo.ts
new file mode 100644
index 0000000000..926a2cc421
--- /dev/null
+++ b/packages/api/src/tests/seo.ts
@@ -0,0 +1,118 @@
+import type { Context, Next } from "hono";
+
+import { OpenAPIHono } from "@hono/zod-openapi";
+
+import type { SitemapEntry, SitemapSource } from "@/lib/seo/sitemap";
+import type {
+ EnvVariablesVitNode,
+ EnvVitNode,
+} from "@/middlewares/global.middleware";
+
+import { core_seo_settings } from "@/database/seo";
+import { core_site_status } from "@/database/site";
+import { createLocaleRouting } from "@/lib/i18n/locale-routing";
+import { resolveSeoConfig } from "@/lib/seo/config";
+import { globalAdminMiddleware } from "@/middlewares/global.middleware";
+import { seoAdminModule } from "@/modules/admin/seo/seo.module";
+import { seoModule } from "@/modules/seo/seo.module";
+
+import { createSessionWorld, fakeSession } from "./sessions";
+
+/** A plugin source of `size` pages, `/docs/1` and on. */
+export const testDocsSitemapSource = (size: number): SitemapSource => ({
+ count: async () => await Promise.resolve(size),
+ getEntries: async (_c, { limit, offset }) =>
+ await Promise.resolve(
+ Array.from(
+ { length: Math.max(0, Math.min(limit, size - offset)) },
+ (_, index): SitemapEntry => ({ loc: `/docs/${offset + index + 1}` }),
+ ),
+ ),
+ id: "docs",
+ label: "Docs",
+});
+
+export const SEO_ADMIN = fakeSession(1, { id: 1, publicId: "laptop" });
+
+/**
+ * The public SEO routes at the root and the AdminCP ones under `/admin`, on an
+ * in-memory database with an English and Polish site whose sitemap holds the
+ * static source and a `docs` source of `docsSize` pages.
+ */
+export const createSeoWorld = async ({
+ docsSize = 3,
+ settings,
+ siteStatus,
+}: {
+ docsSize?: number;
+ settings?: Partial;
+ siteStatus?: Partial;
+} = {}) => {
+ const world = await createSessionWorld({
+ extraTables: [
+ [
+ core_seo_settings,
+ settings
+ ? [
+ {
+ allowIndexing: true,
+ blockAiCrawlers: false,
+ customRobots: "",
+ disabledSitemapSources: [],
+ id: 1,
+ sitemapEnabled: true,
+ sitemapMaxUrls: 10_000,
+ ...settings,
+ },
+ ]
+ : [],
+ ],
+ [
+ core_site_status,
+ siteStatus
+ ? [
+ {
+ changedAt: new Date(),
+ id: 1,
+ message: [],
+ offline: false,
+ opensAt: null,
+ showCountdown: true,
+ ...siteStatus,
+ },
+ ]
+ : [],
+ ],
+ ],
+ sessions: [SEO_ADMIN],
+ });
+ const seo = resolveSeoConfig({
+ config: { sitemap: { sources: [testDocsSitemapSource(docsSize)] } },
+ contentSources: [],
+ plugins: [],
+ });
+ const localeRouting = createLocaleRouting({
+ defaultLocale: "en",
+ locales: ["en", "pl"],
+ });
+
+ world.app.use("*", async (c: Context, next: Next) => {
+ c.set("core", {
+ ...c.get("core"),
+ i18n: { localeRouting },
+ seo,
+ } as unknown as EnvVariablesVitNode["core"]);
+ await next();
+ });
+ for (const { handler, hook, route } of seoModule.routes) {
+ world.app.openapi(route as never, handler as never, hook as never);
+ }
+ const admin = new OpenAPIHono();
+ admin.use("*", globalAdminMiddleware());
+ for (const { handler, hook, route } of seoAdminModule.routes) {
+ admin.openapi(route as never, handler as never, hook as never);
+ }
+ world.app.route("/admin", admin);
+
+ return world;
+};
diff --git a/packages/api/src/vitnode.config.ts b/packages/api/src/vitnode.config.ts
index e030ed299d..73f18cdc9a 100644
--- a/packages/api/src/vitnode.config.ts
+++ b/packages/api/src/vitnode.config.ts
@@ -11,6 +11,7 @@ import type { PasskeysConfig } from "./lib/passkey-config";
import type { PaymentProviderApiPlugin } from "./lib/payments/provider";
import type { BuildPluginApiReturn } from "./lib/plugin";
import type { FrontendPluginInventory } from "./lib/plugin-manifest";
+import type { SeoApiConfig } from "./lib/seo/config";
import type { UpdateChannel } from "./lib/updates/manifest";
import type { PersonalInformationFieldsConfig } from "./lib/user-personal-information";
import type { RateLimiterConfig } from "./middlewares/rate-limiter-config";
@@ -229,6 +230,12 @@ export interface VitNodeApiConfig {
/** The search provider. Defaults to PostgreSQL full-text search. */
adapter?: SearchProviderApiPlugin;
};
+ /**
+ * `robots.txt` and XML sitemaps. Both work without it; use it to disallow
+ * more paths or to add pages and sources to the sitemap. Admins manage the
+ * rest in AdminCP → System → SEO.
+ */
+ seo?: SeoApiConfig;
/** File uploads, served through `c.get("storage")`. */
storage?: {
diff --git a/packages/create-vitnode-app/copy-of-vitnode-app/root/src/routes/robots[.]txt.ts b/packages/create-vitnode-app/copy-of-vitnode-app/root/src/routes/robots[.]txt.ts
new file mode 100644
index 0000000000..c1b10f131a
--- /dev/null
+++ b/packages/create-vitnode-app/copy-of-vitnode-app/root/src/routes/robots[.]txt.ts
@@ -0,0 +1,6 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { robotsTxtHandler } from "@vitnode/core/tanstack/seo/server";
+
+export const Route = createFileRoute("/robots.txt")({
+ server: { handlers: { GET: robotsTxtHandler } },
+});
diff --git a/packages/create-vitnode-app/copy-of-vitnode-app/root/src/routes/sitemap[.]xml.ts b/packages/create-vitnode-app/copy-of-vitnode-app/root/src/routes/sitemap[.]xml.ts
new file mode 100644
index 0000000000..2ebc6b0a59
--- /dev/null
+++ b/packages/create-vitnode-app/copy-of-vitnode-app/root/src/routes/sitemap[.]xml.ts
@@ -0,0 +1,6 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { sitemapIndexHandler } from "@vitnode/core/tanstack/seo/server";
+
+export const Route = createFileRoute("/sitemap.xml")({
+ server: { handlers: { GET: sitemapIndexHandler } },
+});
diff --git a/packages/create-vitnode-app/copy-of-vitnode-app/root/src/routes/sitemaps.$file.ts b/packages/create-vitnode-app/copy-of-vitnode-app/root/src/routes/sitemaps.$file.ts
new file mode 100644
index 0000000000..0cf94c5e14
--- /dev/null
+++ b/packages/create-vitnode-app/copy-of-vitnode-app/root/src/routes/sitemaps.$file.ts
@@ -0,0 +1,6 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { sitemapFileHandler } from "@vitnode/core/tanstack/seo/server";
+
+export const Route = createFileRoute("/sitemaps/$file")({
+ server: { handlers: { GET: sitemapFileHandler } },
+});
diff --git a/packages/vitnode/src/locales/en.json b/packages/vitnode/src/locales/en.json
index 3267592331..383d334da9 100644
--- a/packages/vitnode/src/locales/en.json
+++ b/packages/vitnode/src/locales/en.json
@@ -40,6 +40,9 @@
"@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:seo": "SEO",
+ "@vitnode/core:seo:can_view": "View the robots.txt and sitemap settings",
+ "@vitnode/core:seo:can_manage": "Change the robots.txt and sitemap settings",
"@vitnode/core:queue": "Queue Tasks",
"@vitnode/core:queue:can_view": "View queue tasks",
"@vitnode/core:plugins": "Plugins",
@@ -4035,7 +4038,8 @@
"integrations": "Integrations",
"files": "Files",
"notifications": "Notifications",
- "plugins": "Plugins"
+ "plugins": "Plugins",
+ "seo": "SEO"
},
"ai": {
"title": "Artificial Intelligence (AI)",
@@ -5644,6 +5648,80 @@
"desc": "Show a live countdown. When off, visitors see only the date."
}
}
+ },
+ "seo": {
+ "title": "SEO",
+ "desc": "Decide what search engines and AI crawlers may visit, and which pages your sitemap lists.",
+ "tabs": {
+ "general": "General & robots.txt",
+ "sitemaps": "Sitemaps"
+ },
+ "submit": "Save",
+ "saved": {
+ "title": "SEO settings saved",
+ "desc": "Crawlers pick up the new robots.txt and sitemap on their next visit."
+ },
+ "robots": {
+ "allow_indexing": {
+ "label": "Allow search engines to index this site",
+ "desc": "Turn it off for a staging or private site: every crawler is told to stay away and the sitemaps stop answering."
+ },
+ "indexing_off": {
+ "title": "Search engines are blocked",
+ "desc": "robots.txt says \"Disallow: /\" to everyone. Pages already in search results drop out over the next weeks, so only use this on a site that shouldn't be found."
+ },
+ "block_ai": {
+ "label": "Block AI training crawlers",
+ "desc": "Asks bots that collect pages to train AI models (GPTBot, ClaudeBot, Google-Extended, CCBot and friends) to skip the site. Regular search keeps working."
+ },
+ "custom": {
+ "label": "Custom robots.txt rules",
+ "desc": "Added to the end of the file exactly as written, one rule per line."
+ },
+ "preview": {
+ "title": "Live preview",
+ "desc": "What /robots.txt serves once you save. It updates as you type.",
+ "offline": "The site is offline right now, so /robots.txt answers 503 and crawlers come back later. This is what they get once it opens.",
+ "open": "Open robots.txt",
+ "copy": "Copy robots.txt"
+ }
+ },
+ "sitemaps": {
+ "enabled": {
+ "label": "Enable XML sitemaps",
+ "desc": "Serves /sitemap.xml with every public page your plugins and content types list, split into smaller files."
+ },
+ "open": "Open {url}",
+ "indexing_off": "Sitemaps are hidden while search engine indexing is turned off.",
+ "max_urls": {
+ "label": "URLs per sitemap file",
+ "desc": "Bigger files mean fewer requests; the protocol allows up to {max, number}.",
+ "unit": "URLs"
+ }
+ },
+ "sources": {
+ "title": "Sources",
+ "desc": "Everything that adds pages to your sitemap. Switch a source off to drop its pages from /sitemap.xml right away.",
+ "columns": {
+ "source": "Source",
+ "urls": "URLs",
+ "files": "Files",
+ "preview": "Preview",
+ "enabled": "In sitemap"
+ },
+ "preview": "First file",
+ "empty": "No public pages yet",
+ "not_served": "Not served",
+ "error": "Failed to count",
+ "static": "Pages",
+ "toggle_label": "Include {label} in the sitemap",
+ "toggled": {
+ "on": "{label} added to the sitemap",
+ "on_desc": "Its pages show up in /sitemap.xml again.",
+ "off": "{label} removed from the sitemap",
+ "off_desc": "Its pages and files are gone from /sitemap.xml."
+ }
+ }
}
},
"debug": {
diff --git a/packages/vitnode/src/pages/admin/system/seo.tsx b/packages/vitnode/src/pages/admin/system/seo.tsx
new file mode 100644
index 0000000000..49fd711d04
--- /dev/null
+++ b/packages/vitnode/src/pages/admin/system/seo.tsx
@@ -0,0 +1,23 @@
+import type { PluginRoutePageProps } from "@/routing";
+import type { AdminSeoRouteData } from "@/tanstack/admin/seo/route";
+
+import { adminBreadcrumb } from "@/tanstack/admin/breadcrumb";
+import { loadAdminSeoRoute } from "@/tanstack/admin/seo/route";
+import { AdminSeoRouteContent } from "@/tanstack/admin/seo/screen";
+import { defineAdminRoute } from "@/tanstack/plugin-routes";
+
+const AdminSeoPage = ({
+ loaderData,
+}: PluginRoutePageProps) => (
+
+);
+
+export const route = defineAdminRoute({
+ // `head` after `load`, always.
+ load: async ({ context, t }) => await loadAdminSeoRoute({ ...context, t }),
+ head: ({ loaderData }) => ({ ...loaderData }),
+
+ breadcrumb: adminBreadcrumb({ segments: ["core", "system", "seo"] }),
+});
+
+export default AdminSeoPage;
diff --git a/packages/vitnode/src/routes.tsx b/packages/vitnode/src/routes.tsx
index cfe96957f4..0239aed727 100644
--- a/packages/vitnode/src/routes.tsx
+++ b/packages/vitnode/src/routes.tsx
@@ -36,6 +36,7 @@ import { ADMIN_REPORT_REASONS_NAMESPACES } from "./tanstack/admin/report-reasons
import { ADMIN_ROLES_NAMESPACES } from "./tanstack/admin/roles/route";
import { normalizeRolesRouteSearch } from "./tanstack/admin/roles/route-search";
import { normalizeSearchIndexRouteSearch } from "./tanstack/admin/search-index/route-search";
+import { ADMIN_SEO_NAMESPACES } from "./tanstack/admin/seo/route";
import { ADMIN_SIGN_IN_NAMESPACES } from "./tanstack/admin/sign-in-route";
import { normalizeAdminSignInSearch } from "./tanstack/admin/sign-in-search";
import { ADMIN_STAFF_CREATE_NAMESPACES } from "./tanstack/admin/staff/create-route";
@@ -398,6 +399,13 @@ export const routes = defineRoutes([
pendingComponent: CardsPendingSkeleton,
}),
+ page("/admin/core/system/seo", {
+ area: "admin",
+ component: lazy(() => import("./pages/admin/system/seo")),
+ messages: ADMIN_SEO_NAMESPACES,
+ pendingComponent: FormPendingSkeleton,
+ }),
+
page("/admin/core/moderation/report-reasons", {
area: "admin",
component: lazy(() => import("./pages/admin/moderation/report-reasons")),
diff --git a/packages/vitnode/src/tanstack/admin/seo/index.ts b/packages/vitnode/src/tanstack/admin/seo/index.ts
new file mode 100644
index 0000000000..3f9f26f00c
--- /dev/null
+++ b/packages/vitnode/src/tanstack/admin/seo/index.ts
@@ -0,0 +1,3 @@
+export type { AdminSeoRouteData } from "./route";
+export { ADMIN_SEO_NAMESPACES, loadAdminSeoRoute } from "./route";
+export { AdminSeoRouteContent } from "./screen";
diff --git a/packages/vitnode/src/tanstack/admin/seo/route.ts b/packages/vitnode/src/tanstack/admin/seo/route.ts
new file mode 100644
index 0000000000..2b9a6d2815
--- /dev/null
+++ b/packages/vitnode/src/tanstack/admin/seo/route.ts
@@ -0,0 +1,37 @@
+import type { PluginRouteTranslator } from "@/routing";
+
+import { ADMIN_SEO_PERMISSIONS } from "@/views/admin/views/core/shared/admin-permissions";
+import { adminSeoQueryOptions } from "@/views/admin/views/core/system/seo/seo-query";
+
+import type { AdminScreenContext } from "../screen";
+
+import { requireAdminPermission } from "../screen";
+
+/** `/admin/core/system/seo`: `robots.txt` and the XML sitemaps. */
+export const ADMIN_SEO_NAMESPACES = [
+ "admin.system.seo",
+ "core.global",
+] as const;
+
+/** What {@link loadAdminSeoRoute} returns - and what `head` receives. */
+export interface AdminSeoRouteData {
+ description: string;
+ title: string;
+}
+
+export const loadAdminSeoRoute = async ({
+ adminAccess,
+ queryClient,
+ t,
+}: AdminScreenContext & {
+ t: PluginRouteTranslator;
+}): Promise => {
+ requireAdminPermission(adminAccess, ADMIN_SEO_PERMISSIONS.view);
+
+ await queryClient.query({ ...adminSeoQueryOptions(), staleTime: "static" });
+
+ return {
+ description: t("admin.system.seo.desc"),
+ title: t("admin.system.seo.title"),
+ };
+};
diff --git a/packages/vitnode/src/tanstack/admin/seo/screen.tsx b/packages/vitnode/src/tanstack/admin/seo/screen.tsx
new file mode 100644
index 0000000000..0e76a9221d
--- /dev/null
+++ b/packages/vitnode/src/tanstack/admin/seo/screen.tsx
@@ -0,0 +1,125 @@
+import type { SeoSettingsUpdate } from "@vitnode/api/lib/seo/settings";
+
+import { useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
+import { FileCode2Icon, NetworkIcon } from "lucide-react";
+import React from "react";
+import { useTranslations } from "use-intl";
+
+import type { SeoAdminSettings } from "@/views/admin/views/core/system/seo/seo-query";
+
+import { useAdminStaffPermission } from "@/components/staff-permission/provider";
+import { PageTitle } from "@/components/ui/page-title";
+import {
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsPanels,
+ TabsTrigger,
+} from "@/components/ui/tabs";
+import { TablePendingSkeleton } from "@/tanstack/pending";
+import { ADMIN_SEO_PERMISSIONS } from "@/views/admin/views/core/shared/admin-permissions";
+import { RobotsForm } from "@/views/admin/views/core/system/seo/robots-form";
+import {
+ adminSeoQueryKey,
+ adminSeoQueryOptions,
+ updateAdminSeoSettings,
+} from "@/views/admin/views/core/system/seo/seo-query";
+import { SitemapsForm } from "@/views/admin/views/core/system/seo/sitemaps-form";
+import { SourcesTable } from "@/views/admin/views/core/system/seo/sources-table";
+
+import type { AdminSeoRouteData } from "./route";
+
+import { RouteMessages } from "../../i18n/route-messages";
+import { ADMIN_SEO_NAMESPACES } from "./route";
+
+const SeoScreen = ({ description, title }: AdminSeoRouteData) => {
+ const t = useTranslations("admin.system.seo");
+ const queryClient = useQueryClient();
+ const { data } = useSuspenseQuery(adminSeoQueryOptions());
+ const canManage = useAdminStaffPermission(ADMIN_SEO_PERMISSIONS.manage);
+ // Content sources are named by their plugin's content messages.
+ const sourceNamespaces = [
+ ...ADMIN_SEO_NAMESPACES,
+ ...new Set(
+ data.sources.flatMap(source =>
+ source.contentType ? [`${source.contentType.pluginId}.content`] : [],
+ ),
+ ),
+ ];
+
+ const save = async (body: SeoSettingsUpdate) => {
+ const result = await updateAdminSeoSettings(body);
+ if ("data" in result) {
+ queryClient.setQueryData(adminSeoQueryKey, result.data);
+ await queryClient.invalidateQueries({ queryKey: adminSeoQueryKey });
+ }
+
+ return result;
+ };
+
+ return (
+
+
+
+
+
+
+
+
+ {t("tabs.general")}
+
+
+
+ {t("tabs.sitemaps")}
+
+
+
+
+
+
+
+
+
+
+
+ await save({ sitemap })}
+ />
+
+ }
+ >
+
+ {
+ const disabled = new Set(
+ data.settings.sitemap.disabledSources,
+ );
+ if (enabled) disabled.delete(source.id);
+ else disabled.add(source.id);
+
+ return await save({
+ sitemap: { disabledSources: [...disabled] },
+ });
+ }}
+ />
+
+
+
+
+
+
+
+ );
+};
+
+export const AdminSeoRouteContent = (props: AdminSeoRouteData) => (
+
+
+
+);
diff --git a/packages/vitnode/src/tanstack/seo/server.ts b/packages/vitnode/src/tanstack/seo/server.ts
new file mode 100644
index 0000000000..0913b3db51
--- /dev/null
+++ b/packages/vitnode/src/tanstack/seo/server.ts
@@ -0,0 +1,92 @@
+import "@tanstack/react-start/server-only";
+
+import { fetcher } from "@/tanstack/fetcher/server";
+
+const RELAYED_HEADERS = [
+ "cache-control",
+ "content-type",
+ "retry-after",
+ "x-content-type-options",
+] as const;
+
+const relay = (response: Response): Response => {
+ const headers = new Headers();
+ for (const name of RELAYED_HEADERS) {
+ const value = response.headers.get(name);
+ if (value !== null) headers.set(name, value);
+ }
+
+ return new Response(response.body, { headers, status: response.status });
+};
+
+const unavailable = (): Response =>
+ new Response("Service Unavailable", {
+ headers: {
+ "cache-control": "no-store",
+ "content-type": "text/plain; charset=utf-8",
+ "retry-after": "60",
+ },
+ status: 503,
+ });
+
+const safely = async (load: () => Promise): Promise => {
+ try {
+ return relay(await load());
+ } catch {
+ // A crawler that gets a 5xx retries later and keeps what it has indexed.
+ return unavailable();
+ }
+};
+
+/**
+ * `GET /robots.txt`: the file the API generates from the AdminCP SEO
+ * settings, with its status and cache headers. Server-only.
+ *
+ * @example
+ * // src/routes/robots[.]txt.ts
+ * import { createFileRoute } from "@tanstack/react-router";
+ * import { robotsTxtHandler } from "@vitnode/core/tanstack/seo/server";
+ *
+ * export const Route = createFileRoute("/robots.txt")({
+ * server: { handlers: { GET: robotsTxtHandler } },
+ * });
+ */
+export const robotsTxtHandler = async (): Promise =>
+ await safely(
+ async () =>
+ await fetcher({
+ method: "get",
+ module: "seo",
+ path: "/robots",
+ plugin: "@vitnode/core",
+ }),
+ );
+
+/** `GET /sitemap.xml`: the sitemap index. Server-only. */
+export const sitemapIndexHandler = async (): Promise =>
+ await safely(
+ async () =>
+ await fetcher({
+ method: "get",
+ module: "seo",
+ path: "/sitemap",
+ plugin: "@vitnode/core",
+ }),
+ );
+
+/** `GET /sitemaps/{file}`: one sub-sitemap, e.g. `blog_post-1.xml`. Server-only. */
+export const sitemapFileHandler = async ({
+ params,
+}: {
+ params: { file: string };
+}): Promise =>
+ await safely(
+ async () =>
+ await fetcher({
+ args: { params: { file: params.file } },
+ method: "get",
+ module: "seo",
+ path: "/sitemaps/{file}",
+ plugin: "@vitnode/core",
+ }),
+ );
diff --git a/packages/vitnode/src/views/admin/layouts/sidebar/nav/nav-model.tsx b/packages/vitnode/src/views/admin/layouts/sidebar/nav/nav-model.tsx
index a99b428783..1ed41e9ddb 100644
--- a/packages/vitnode/src/views/admin/layouts/sidebar/nav/nav-model.tsx
+++ b/packages/vitnode/src/views/admin/layouts/sidebar/nav/nav-model.tsx
@@ -191,6 +191,11 @@ const coreNavGroup = (): AdminNavGroupDeclaration => ({
href: "/admin/core/system/notifications",
permission: staffPermissionArgs(admin.notifications.canView),
},
+ {
+ title: key("admin.global.nav.system.seo"),
+ href: "/admin/core/system/seo",
+ permission: staffPermissionArgs(admin.seo.canView),
+ },
],
},
{
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 22260e6dce..a3b9474728 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
@@ -53,6 +53,11 @@ export const ADMIN_REPORT_REASON_PERMISSIONS = {
view: admin.report_reasons.canView,
} as const;
+export const ADMIN_SEO_PERMISSIONS = {
+ manage: admin.seo.canManage,
+ view: admin.seo.canView,
+} as const;
+
export const ADMIN_WARNING_PERMISSIONS = {
manage: admin.warning_settings.canManage,
view: admin.warning_settings.canView,
diff --git a/packages/vitnode/src/views/admin/views/core/system/seo/robots-form.tsx b/packages/vitnode/src/views/admin/views/core/system/seo/robots-form.tsx
new file mode 100644
index 0000000000..6be297d336
--- /dev/null
+++ b/packages/vitnode/src/views/admin/views/core/system/seo/robots-form.tsx
@@ -0,0 +1,212 @@
+import { useSelector } from "@tanstack/react-form";
+import { buildRobotsTxt } from "@vitnode/api/lib/seo/robots";
+import { SEO_SETTINGS_LIMITS } from "@vitnode/api/lib/seo/settings";
+import { ExternalLinkIcon, SaveIcon, TriangleAlertIcon } 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 { AutoForm, AutoFormSubmitButton } from "@/components/form/auto-form";
+import { AutoFormSwitch } from "@/components/form/fields/switch";
+import { AutoFormTextarea } from "@/components/form/fields/textarea";
+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
+import { CopyButton } from "@/components/ui/copy-button";
+import { useFormApi } from "@/components/ui/form";
+
+import type { SeoAdminSettings } from "./seo-query";
+
+import { seoSaveErrorDescription } from "./save-error";
+
+interface RobotsPreviewValues {
+ allowIndexing?: boolean;
+ blockAiCrawlers?: boolean;
+ customRobots?: string;
+}
+
+const RobotsPreview = ({ data }: { data: SeoAdminSettings }) => {
+ const t = useTranslations("admin.system.seo.robots.preview");
+ const { form } = useFormApi();
+ const values = useSelector(
+ form.store,
+ state => state.values as RobotsPreviewValues,
+ );
+ const sitemapOn = data.settings.sitemap.enabled;
+ const content = buildRobotsTxt({
+ allowIndexing: values.allowIndexing ?? data.settings.allowIndexing,
+ blockAiCrawlers: values.blockAiCrawlers ?? data.settings.blockAiCrawlers,
+ customRobots: values.customRobots ?? data.settings.customRobots,
+ disallow: data.robots.disallow,
+ offline: data.robots.offline,
+ sitemapUrl: sitemapOn ? data.robots.sitemapUrl : null,
+ });
+ const robotsUrl = new URL("/robots.txt", data.siteOrigin).href;
+
+ return (
+
+
+
+
+ {t("title")}
+
+
+ {data.robots.offline ? t("offline") : t("desc")}
+
+
+
+
+
+ {content}
+
+
+ );
+};
+
+const IndexingOffWarning = () => {
+ const t = useTranslations("admin.system.seo.robots.indexing_off");
+ const { form } = useFormApi();
+ const allowIndexing = useSelector(
+ form.store,
+ state => (state.values as RobotsPreviewValues).allowIndexing,
+ );
+ if (allowIndexing !== false) return null;
+
+ return (
+ } variant="warning">
+ {t("title")}
+ {t("desc")}
+
+ );
+};
+
+export interface RobotsFormProps {
+ canManage: boolean;
+ data: SeoAdminSettings;
+ onSave: (
+ values: Pick<
+ SeoAdminSettings["settings"],
+ "allowIndexing" | "blockAiCrawlers" | "customRobots"
+ >,
+ ) => Promise>;
+}
+
+/** General crawling settings and the custom `robots.txt` rules, with a live preview. */
+export const RobotsForm = ({ canManage, data, onSave }: RobotsFormProps) => {
+ const t = useTranslations("admin.system.seo");
+ const tError = useTranslations("core.global.errors");
+ const { settings } = data;
+
+ const formSchema = z.object({
+ allowIndexing: z.boolean().default(settings.allowIndexing),
+ blockAiCrawlers: z.boolean().default(settings.blockAiCrawlers),
+ customRobots: z
+ .string()
+ .max(SEO_SETTINGS_LIMITS.customRobotsMaxLength)
+ .default(settings.customRobots),
+ });
+
+ const onSubmit: AutoFormOnSubmit = async (
+ values,
+ formApi,
+ ) => {
+ const result = await onSave(values);
+ if ("error" in result) {
+ toast.error(tError("title"), {
+ description: seoSaveErrorDescription(result.error, tError),
+ });
+
+ return;
+ }
+
+ formApi.reset(formApi.state.values);
+ toast.success(t("saved.title"), { description: t("saved.desc") });
+ };
+
+ return (
+ (
+
+ ),
+ id: "allowIndexing",
+ },
+ {
+ component: props => (
+
+ ),
+ id: "blockAiCrawlers",
+ },
+ {
+ component: props => (
+
+ ),
+ id: "customRobots",
+ },
+ ]}
+ formSchema={formSchema}
+ layout={rendered => (
+ <>
+
+ {rendered.allowIndexing}
+
+ {rendered.blockAiCrawlers}
+ {rendered.customRobots}
+
+
+ {canManage && (
+
+ )}
+ >
+ )}
+ onSubmit={onSubmit}
+ />
+ );
+};
diff --git a/packages/vitnode/src/views/admin/views/core/system/seo/save-error.ts b/packages/vitnode/src/views/admin/views/core/system/seo/save-error.ts
new file mode 100644
index 0000000000..414310a590
--- /dev/null
+++ b/packages/vitnode/src/views/admin/views/core/system/seo/save-error.ts
@@ -0,0 +1,10 @@
+import type { AdminMutationError } from "@/views/admin/views/core/shared/admin-mutation";
+
+/** The toast description of a failed SEO save: the API's own message for a `400`. */
+export const seoSaveErrorDescription = (
+ error: AdminMutationError,
+ tError: (key: "internal_server_error") => string,
+): string =>
+ error.status === 400 && error.message
+ ? error.message
+ : tError("internal_server_error");
diff --git a/packages/vitnode/src/views/admin/views/core/system/seo/seo-query.ts b/packages/vitnode/src/views/admin/views/core/system/seo/seo-query.ts
new file mode 100644
index 0000000000..94a6d1e9d7
--- /dev/null
+++ b/packages/vitnode/src/views/admin/views/core/system/seo/seo-query.ts
@@ -0,0 +1,58 @@
+import type { SeoSettingsUpdate } from "@vitnode/api/lib/seo/settings";
+import type { SeoAdminSettings } from "@vitnode/api/modules/admin/seo/seo.schema";
+
+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 { SeoAdminSettings };
+
+export const adminSeoQueryKey = adminQueryRoot("seo");
+
+export const adminSeoQueryOptions = () =>
+ queryOptions({
+ queryFn: async (): Promise => {
+ const response = await fetcher({
+ plugin: manifest.id,
+ method: "get",
+ module: "admin/seo",
+ path: "/settings",
+ });
+ if (!response.ok) {
+ throw new AdminRequestError(response.status, "the SEO settings");
+ }
+
+ return await response.json();
+ },
+ queryKey: adminSeoQueryKey,
+ retry: false,
+ /** {@link RECORD_STALE_TIME} - it changes when an administrator saves it. */
+ staleTime: RECORD_STALE_TIME,
+ });
+
+/** Saves any subset of the SEO settings; resolves with the settings as saved. */
+export const updateAdminSeoSettings = async (
+ body: SeoSettingsUpdate,
+): Promise> =>
+ await runAdminApiMutation({
+ expected: 200,
+ parse: async response => (await response.json()) as SeoAdminSettings,
+ request: async () =>
+ await fetcherClient({
+ plugin: manifest.id,
+ args: { body },
+ method: "patch",
+ module: "admin/seo",
+ options: { credentials: "include" },
+ path: "/settings",
+ }),
+ });
diff --git a/packages/vitnode/src/views/admin/views/core/system/seo/sitemaps-form.tsx b/packages/vitnode/src/views/admin/views/core/system/seo/sitemaps-form.tsx
new file mode 100644
index 0000000000..0d9d90cac1
--- /dev/null
+++ b/packages/vitnode/src/views/admin/views/core/system/seo/sitemaps-form.tsx
@@ -0,0 +1,151 @@
+import { useSelector } from "@tanstack/react-form";
+import { SEO_SETTINGS_LIMITS } from "@vitnode/api/lib/seo/settings";
+import { ExternalLinkIcon, 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 { AutoForm, AutoFormSubmitButton } from "@/components/form/auto-form";
+import { AutoFormNumber } from "@/components/form/fields/number";
+import { AutoFormSwitch } from "@/components/form/fields/switch";
+import { Alert, AlertDescription } from "@/components/ui/alert";
+import { useFormApi } from "@/components/ui/form";
+
+import type { SeoAdminSettings } from "./seo-query";
+
+import { seoSaveErrorDescription } from "./save-error";
+
+const SitemapLink = ({ data }: { data: SeoAdminSettings }) => {
+ const t = useTranslations("admin.system.seo.sitemaps");
+ const { form } = useFormApi();
+ const enabled = useSelector(
+ form.store,
+ state => (state.values as { enabled?: boolean }).enabled,
+ );
+ if (!data.settings.allowIndexing) {
+ return (
+
+ {t("indexing_off")}
+
+ );
+ }
+ if (!enabled || !data.settings.sitemap.enabled) return null;
+
+ return (
+
+
+ {t("open", { url: data.robots.sitemapUrl })}
+
+ );
+};
+
+export interface SitemapsFormProps {
+ canManage: boolean;
+ data: SeoAdminSettings;
+ onSave: (values: {
+ enabled: boolean;
+ maxUrlsPerFile: number;
+ }) => Promise>;
+}
+
+/** Whether sitemaps are served, and how many URLs go in one file. */
+export const SitemapsForm = ({
+ canManage,
+ data,
+ onSave,
+}: SitemapsFormProps) => {
+ const t = useTranslations("admin.system.seo");
+ const tError = useTranslations("core.global.errors");
+ const { sitemap } = data.settings;
+
+ const formSchema = z.object({
+ enabled: z.boolean().default(sitemap.enabled),
+ maxUrlsPerFile: z
+ .number()
+ .int()
+ .min(SEO_SETTINGS_LIMITS.sitemapMaxUrlsMin)
+ .max(SEO_SETTINGS_LIMITS.sitemapMaxUrlsMax)
+ .default(sitemap.maxUrlsPerFile),
+ });
+
+ const onSubmit: AutoFormOnSubmit = async (
+ values,
+ formApi,
+ ) => {
+ const result = await onSave(values);
+ if ("error" in result) {
+ toast.error(tError("title"), {
+ description: seoSaveErrorDescription(result.error, tError),
+ });
+
+ return;
+ }
+
+ formApi.reset(formApi.state.values);
+ toast.success(t("saved.title"), { description: t("saved.desc") });
+ };
+
+ return (
+ (
+
+ ),
+ id: "enabled",
+ },
+ {
+ component: props => (
+
+ ),
+ hidden: values => values.enabled === false,
+ id: "maxUrlsPerFile",
+ },
+ ]}
+ formSchema={formSchema}
+ layout={rendered => (
+ <>
+
+ {rendered.enabled}
+
+ {rendered.maxUrlsPerFile}
+
+ {canManage && (
+
+ )}
+ >
+ )}
+ onSubmit={onSubmit}
+ />
+ );
+};
diff --git a/packages/vitnode/src/views/admin/views/core/system/seo/sources-table.tsx b/packages/vitnode/src/views/admin/views/core/system/seo/sources-table.tsx
new file mode 100644
index 0000000000..05fdd077a2
--- /dev/null
+++ b/packages/vitnode/src/views/admin/views/core/system/seo/sources-table.tsx
@@ -0,0 +1,199 @@
+import type { ContentLabelTranslator } from "@vitnode/api/content/admin/labels";
+
+import { contentNouns } from "@vitnode/api/content/admin/labels";
+import { ExternalLinkIcon, FileWarningIcon } from "lucide-react";
+import React from "react";
+import { toast } from "sonner";
+import { useFormatter, useTranslations } from "use-intl";
+
+import type { AdminMutationResult } from "@/views/admin/views/core/shared/admin-mutation";
+
+import { Badge } from "@/components/ui/badge";
+import { Switch } from "@/components/ui/switch";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+
+import type { SeoAdminSettings } from "./seo-query";
+
+import { seoSaveErrorDescription } from "./save-error";
+
+type SeoSource = SeoAdminSettings["sources"][number];
+
+type LabelTranslator = ContentLabelTranslator;
+
+/** A source's name: the content type's noun, the translated key, or the text as given. */
+export const seoSourceLabel = (source: SeoSource, t: LabelTranslator) =>
+ source.contentType
+ ? contentNouns(
+ { id: source.contentType.id },
+ source.contentType.pluginId,
+ t,
+ ).title
+ : t.has(source.label)
+ ? t(source.label)
+ : source.label;
+
+const SourceSwitch = ({
+ canManage,
+ label,
+ onToggle,
+ source,
+}: {
+ canManage: boolean;
+ label: string;
+ onToggle: (
+ source: SeoSource,
+ enabled: boolean,
+ ) => Promise>;
+ source: SeoSource;
+}) => {
+ const t = useTranslations("admin.system.seo.sources");
+ const tError = useTranslations("core.global.errors");
+ const [pending, setPending] = React.useState(null);
+
+ const onCheckedChange = async (enabled: boolean) => {
+ setPending(enabled);
+ try {
+ const result = await onToggle(source, enabled);
+ if ("error" in result) {
+ toast.error(tError("title"), {
+ description: seoSaveErrorDescription(result.error, tError),
+ });
+
+ return;
+ }
+ toast.success(t(enabled ? "toggled.on" : "toggled.off", { label }), {
+ description: t(enabled ? "toggled.on_desc" : "toggled.off_desc"),
+ });
+ } finally {
+ setPending(null);
+ }
+ };
+
+ return (
+ void onCheckedChange(enabled)}
+ />
+ );
+};
+
+export interface SourcesTableProps {
+ canManage: boolean;
+ data: SeoAdminSettings;
+ onToggle: (
+ source: SeoSource,
+ enabled: boolean,
+ ) => Promise>;
+}
+
+/** Every registered sitemap source with its size, a switch and a preview link. */
+export const SourcesTable = ({
+ canManage,
+ data,
+ onToggle,
+}: SourcesTableProps) => {
+ const t = useTranslations("admin.system.seo.sources");
+ const tAll = useTranslations() as unknown as LabelTranslator;
+ const format = useFormatter();
+ const served = data.settings.allowIndexing && data.settings.sitemap.enabled;
+
+ return (
+
+
+
+ {t("title")}
+
+
+ {t("desc")}
+
+
+
+
+
+
+ {t("columns.source")}
+ {t("columns.urls")}
+ {t("columns.files")}
+ {t("columns.preview")}
+ {t("columns.enabled")}
+
+
+
+ {data.sources.map(source => {
+ const label = seoSourceLabel(source, tAll);
+ const previewUrl = new URL(
+ `/sitemaps/${source.id}-1.xml`,
+ data.siteOrigin,
+ ).href;
+
+ return (
+
+
+
+ {label}
+
+ {source.id}
+
+
+
+
+ {source.error ? (
+
+
+ {t("error")}
+
+ ) : (
+ format.number(source.urls)
+ )}
+
+
+ {format.number(source.files)}
+
+
+ {served && source.enabled && source.urls > 0 ? (
+
+
+ {t("preview")}
+ {label}
+
+ ) : (
+
+ {source.urls === 0 ? t("empty") : t("not_served")}
+
+ )}
+
+
+
+
+
+ );
+ })}
+
+
+
+
+ );
+};
diff --git a/plugins/blog/src/config.api.ts b/plugins/blog/src/config.api.ts
index 788a4ba9ef..8a8104f6ff 100644
--- a/plugins/blog/src/config.api.ts
+++ b/plugins/blog/src/config.api.ts
@@ -52,6 +52,9 @@ import { manifest } from "@/manifest.gen";
export const blogApiPlugin = () =>
buildApiPlugin({
manifest,
+ sitemap: {
+ paths: [{ path: "/blog", changeFrequency: "daily", priority: 0.8 }],
+ },
aiActions: blogAiActions,
contentNotifications: [commentNotifications],
eventDefinitions: blogEventDefinitions,
diff --git a/plugins/forum/src/config.api.ts b/plugins/forum/src/config.api.ts
index 307f589d77..8f38ff62a0 100644
--- a/plugins/forum/src/config.api.ts
+++ b/plugins/forum/src/config.api.ts
@@ -18,6 +18,9 @@ import { manifest } from "@/manifest.gen";
export const forumApiPlugin = () =>
buildApiPlugin({
manifest,
+ sitemap: {
+ paths: [{ path: "/forum", changeFrequency: "hourly", priority: 0.8 }],
+ },
contentNotifications: [commentNotifications, topicNotifications],
messages,
modules: [