diff --git a/apps/api/migrations/20261123201237_add_seo_settings/migration.sql b/apps/api/migrations/20261123201237_add_seo_settings/migration.sql new file mode 100644 index 0000000000..4d56cb11ac --- /dev/null +++ b/apps/api/migrations/20261123201237_add_seo_settings/migration.sql @@ -0,0 +1,14 @@ +CREATE TABLE "core_seo_settings" ( + "id" integer PRIMARY KEY DEFAULT 1, + "allowIndexing" boolean DEFAULT true NOT NULL, + "blockAiCrawlers" boolean DEFAULT false NOT NULL, + "customRobots" text DEFAULT '' NOT NULL, + "sitemapEnabled" boolean DEFAULT true NOT NULL, + "sitemapMaxUrls" integer DEFAULT 10000 NOT NULL, + "disabledSitemapSources" jsonb DEFAULT '[]' NOT NULL, + "updatedById" integer, + "updatedAt" timestamp DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "core_seo_settings" ENABLE ROW LEVEL SECURITY;--> statement-breakpoint +ALTER TABLE "core_seo_settings" ADD CONSTRAINT "core_seo_settings_updatedById_core_users_id_fkey" FOREIGN KEY ("updatedById") REFERENCES "core_users"("id") ON DELETE SET NULL; \ No newline at end of file diff --git a/apps/api/migrations/20261123201237_add_seo_settings/snapshot.json b/apps/api/migrations/20261123201237_add_seo_settings/snapshot.json new file mode 100644 index 0000000000..67009a5b77 --- /dev/null +++ b/apps/api/migrations/20261123201237_add_seo_settings/snapshot.json @@ -0,0 +1,242 @@ +{ + "type": "diff", + "version": "9", + "dialect": "postgres", + "id": "d185c917-2729-4144-b3d6-9e1b9ba1d3da", + "prevIds": [ + "d68f291f-7e91-4b91-b606-bca1ba71055c", + "7453f5c0-b352-419a-bc5e-314a1576c86f" + ], + "footprints": [ + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "core_seo_settings" + ], + "writes": [ + "s|tbl|public.core_seo_settings", + "n|tbl|public.core_seo_settings", + "e|tbl|public.core_seo_settings", + "n|rel|public.core_seo_settings", + "n|type|public.core_seo_settings", + "n|rel|public.core_seo_settings_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "core_seo_settings" + ], + "writes": [ + "s|fk|public.core_seo_settings.core_seo_settings_updatedById_core_users_id_fkey", + "n|fk|public.core_seo_settings.core_seo_settings_updatedById_core_users_id_fkey", + "e|fk|public.core_seo_settings.core_seo_settings_updatedById_core_users_id_fkey", + "n|con|public.core_seo_settings.core_seo_settings_updatedById_core_users_id_fkey" + ], + "reads": [ + "n|tbl|public.core_seo_settings", + "n|sch|public", + "n|tbl|public.core_users", + "n|sch|public", + "n|col|public.core_seo_settings.updatedById", + "n|col|public.core_users.id", + "e|uniqueness|public.core_users.id" + ] + } + ], + "deltas": [ + { + "op": "create", + "row": { + "schema": "public", + "name": "core_seo_settings", + "isRlsEnabled": true, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_seo_settings", + "name": "id", + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "1", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_seo_settings", + "name": "allowIndexing", + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_seo_settings", + "name": "blockAiCrawlers", + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_seo_settings", + "name": "customRobots", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "''", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_seo_settings", + "name": "sitemapEnabled", + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_seo_settings", + "name": "sitemapMaxUrls", + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "10000", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_seo_settings", + "name": "disabledSitemapSources", + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'[]'", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_seo_settings", + "name": "updatedById", + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_seo_settings", + "name": "updatedAt", + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_seo_settings", + "name": "core_seo_settings_updatedById_core_users_id_fkey", + "nameExplicit": false, + "columns": [ + "updatedById" + ], + "schemaTo": "public", + "tableTo": "core_users", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_seo_settings", + "name": "core_seo_settings_pkey", + "columns": [ + "id" + ], + "nameExplicit": false, + "entityType": "pks" + } + } + ] +} \ No newline at end of file diff --git a/apps/web/content/docs/content-engine/public-lists.mdx b/apps/web/content/docs/content-engine/public-lists.mdx index 88c8d97961..3adfe7b59b 100644 --- a/apps/web/content/docs/content-engine/public-lists.mdx +++ b/apps/web/content/docs/content-engine/public-lists.mdx @@ -423,7 +423,7 @@ A filter needs a field that `publicApi.filterableFields` lists, such as a relati - **Caching.** The API caches each list read per query and locale, and every publish, edit, unpublish, hide or delete of the content type expires it. TanStack Query keeps its own copy in the browser for `RECORD_STALE_TIME`, which is why a page that writes records invalidates its list. - **Hidden records.** With [`visibility`](/docs/content-engine/content-visibility#who-can-still-see-it), a signed-in author, editor or moderator also gets the hidden records they may see. Those rows carry `hidden: true`, so mark them, for example with `HiddenIcon` from `@vitnode/core/components/hidden-icon`. That response is `private, no-store` and skips the API cache. A route with a page `cache` serves signed-in visitors the HTML rendered for guests, so refetch the list in the browser under a key that includes the viewer, like the blog's `blogViewerPostsQueryOptions`. For your own counts or queries, combine `contentListHiddenAccess` and `contentPublicListCondition` from `@vitnode/api/content/server`. -Records reach crawlers through their own pages and the [sitemap](/docs/content-engine/seo#sitemap). The sitemap route lists records, not lists, so add the list's own URL, such as `/news`, where your app builds `/sitemap.xml`. +Records reach crawlers through their own pages and the [sitemap](/docs/content-engine/seo#sitemap). The sitemap lists records, not lists, so add the list's own URL, such as `/news`, with `buildApiPlugin({ sitemap: { paths: ["/news"] } })`, as [Sitemap sources](/docs/dev/sitemap-sources#add-plugin-pages) shows. The blog plugin builds `/blog` and `/blog/category/:slug` from the same pieces with only pages and a category, in `plugins/blog/src/pages/blog-list.ts` and `blog-queries.ts`. diff --git a/apps/web/content/docs/content-engine/seo.mdx b/apps/web/content/docs/content-engine/seo.mdx index 463829e602..ed64ca4886 100644 --- a/apps/web/content/docs/content-engine/seo.mdx +++ b/apps/web/content/docs/content-engine/seo.mdx @@ -176,7 +176,42 @@ delivery: { ## Sitemap -`delivery.sitemap` adds a public route that lists every published URL of the content type, oldest record first. Pass `true` or `{ changeFrequency, priority }`. It needs `publication: true`, since a sitemap lists only what readers can reach. +`delivery.sitemap` puts every published record of the content type in the site's [`/sitemap.xml`](/docs/dev/robots-and-sitemaps). Pass `true` or `{ changeFrequency, priority }`. It needs `publication: true`, since a sitemap lists only what readers can reach. + +```ts title="plugins/newsroom/src/content/story.ts" +delivery: { + sitemap: { changeFrequency: "weekly", priority: 0.7 }, +}, +``` + +The content type gets its own files, named after its id with the dot swapped for `_`: `newsroom.story` is served at `/sitemaps/newsroom_story-1.xml`, `-2.xml` and so on. + +```xml title="/sitemaps/newsroom_story-1.xml" + + + + https://example.com/stories/hello-content-engine + 2026-10-10T11:06:30.518Z + weekly + 0.7 + + +``` + +A record is listed only when a guest could open its page: + +- It is published, and its `publishedAt` has passed. Drafts, scheduled records, [hidden](/docs/content-engine/content-visibility) and deleted ones stay out. +- A guest may read it under the type's [access rules](/docs/content-engine/access-behavior), whoever requests the sitemap. +- Its `noIndexField` is not `true`. +- The URL uses the current slug, never one from slug history. + +A localized type lists one URL per published translation. Each one carries `xhtml:link` alternates for every published language, plus `x-default` with `delivery.hreflang`. With `delivery.seo.openGraph.imageField`, the record's cover is added as ``. Records come in id order, so a file always holds the same records between visits. + +Admins switch a content type out of the sitemap in **AdminCP → System → SEO → Sitemaps**. + +### Sitemap API for external front ends + +A front end that builds its own sitemap reads the same records, one language at a time, from a JSON route: ```bash curl "http://localhost:3000/api/newsroom/content/stories/delivery/sitemap?cursor=1&limit=1" @@ -198,84 +233,9 @@ curl "http://localhost:3000/api/newsroom/content/stories/delivery/sitemap?cursor } ``` -- A page holds 1,000 entries by default and up to 50,000 with `?limit=`. `cursor` is the `itemId` to continue after, so pass `nextCursor` back as `?cursor=` until it is `null`. -- `lastModified` is the record's `updatedAt`, or the translation's when that is newer. -- Records whose `noIndexField` is `true` are left out, and so are [hidden](/docs/content-engine/content-visibility) records. -- Entries come in id order. For a [uuid](/docs/content-engine/id-strategy) content type that order is lexical, not creation order, and every record still appears once. -- A localized type returns one language per request. Ask for another with `?locale=`: - -```bash -curl "http://localhost:3000/api/@vitnode/blog/content/blog/delivery/sitemap?locale=pl&limit=1" -``` - -```json -{ - "entries": [ - { - "changeFrequency": "weekly", - "itemId": 4, - "lastModified": "2026-08-12T18:00:43.308Z", - "locale": "pl", - "path": "/pl/wpisy/polish-title", - "priority": 0.7 - } - ], - "nextCursor": 4 -} -``` - -The app's `/sitemap.xml` does not read these routes for you, so add the entries where you build it. `contentSitemapXml` from `@vitnode/core/content` writes the XML: - -```ts -import { - contentSitemapXml, - isContentSitemapChangeFrequency, -} from "@vitnode/core/content"; -import { fetcher } from "@vitnode/core/tanstack/fetcher"; - -const response = await fetcher({ - plugin: "newsroom", - method: "get", - module: "content/stories", - path: "/delivery/sitemap", - args: { query: { limit: 1000 } }, -}); -if (!response.ok) throw new Error("Could not load the story sitemap."); -const { entries } = await response.json(); - -const xml = contentSitemapXml({ - origin: "https://example.com", - entries: entries.map(entry => ({ - ...entry, - changeFrequency: isContentSitemapChangeFrequency(entry.changeFrequency) - ? entry.changeFrequency - : null, - lastModified: new Date(entry.lastModified), - })), -}); -``` - -With the newsroom plugin's two published stories, `xml` is: - -```xml - - - - https://example.com/stories/jbbjk-1 - 2026-08-30T09:18:25.398Z - weekly - 0.7 - - - https://example.com/stories/hello-content-engine - 2026-10-10T11:06:30.518Z - weekly - 0.7 - - -``` - -`contentSitemapIndexXml` writes a `` once one file is not enough, for example one file per content type and language. +- A page holds 1,000 entries by default and up to 50,000 with `?limit=`. Pass `nextCursor` back as `?cursor=` until it is `null`. +- A localized type returns one language per request; ask for another with `?locale=pl`. +- `contentSitemapXml` and `contentSitemapIndexXml` from `@vitnode/core/content` turn the entries into XML. ## Retired slugs @@ -305,4 +265,4 @@ Then ask the resolve route what the page was given, `openGraph` and `robots` inc curl http://localhost:3000/api/newsroom/content/stories/delivery/resolve/hello-content-engine ``` -Set `noIndex` on a test story, publish it, and run both commands again. The page gains the `robots` tag, and the [sitemap](#sitemap) route stops listing it. +Set `noIndex` on a test story, publish it, and run both commands again. The page gains the `robots` tag, and `/sitemaps/newsroom_story-1.xml` stops listing it. diff --git a/apps/web/content/docs/dev/events/built-in-events.mdx b/apps/web/content/docs/dev/events/built-in-events.mdx index 328381d397..3359bee592 100644 --- a/apps/web/content/docs/dev/events/built-in-events.mdx +++ b/apps/web/content/docs/dev/events/built-in-events.mdx @@ -781,6 +781,53 @@ message fires it too, with `switched: false`. See +## SEO events + +One name, exported from `@vitnode/api/events/seo` as +`seoSettingsUpdatedEvent`. It fires **after** the save has committed and the +cached settings are expired. + +| Event | Payload | Fires when | +| ---------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------- | +| `seo.settings.updated` | `{ allowIndexing, blockAiCrawlers, sitemapEnabled, disabledSitemapSources, changedById }` | An admin saves anything in **AdminCP → System → SEO**, including a sitemap source switch | + + + + +Emitted by `PATCH /admin/seo/settings`. See +[Robots and sitemaps](/docs/dev/robots-and-sitemaps). + + + +**A listener would** ping a chat channel when `allowIndexing` turns `false` +on a production site, or ask a search console to refetch the sitemap. + + + + ## Page layout events One name, exported from `@vitnode/api/events/pages` as diff --git a/apps/web/content/docs/dev/meta.json b/apps/web/content/docs/dev/meta.json index 5f5336e3b1..4210b115e7 100644 --- a/apps/web/content/docs/dev/meta.json +++ b/apps/web/content/docs/dev/meta.json @@ -27,6 +27,8 @@ "navigation", "mobile-navigation", "social-images", + "robots-and-sitemaps", + "sitemap-sources", "performance", "---Extend VitNode---", "widgets", diff --git a/apps/web/content/docs/dev/robots-and-sitemaps.mdx b/apps/web/content/docs/dev/robots-and-sitemaps.mdx new file mode 100644 index 0000000000..95ad993676 --- /dev/null +++ b/apps/web/content/docs/dev/robots-and-sitemaps.mdx @@ -0,0 +1,141 @@ +--- +title: Robots and sitemaps +description: Control robots.txt, block AI training crawlers and serve XML sitemaps for every public VitNode page from AdminCP → System → SEO, with no code. +icon: SearchCheck +--- + +import { ImgDocs } from "@/components/fumadocs/img"; +import robotsAdmin from "./seo-robots-admin.webp"; +import sitemapsAdmin from "./seo-sitemaps-admin.webp"; + +Every VitNode site serves `/robots.txt` and `/sitemap.xml` out of the box. Admins decide what crawlers may visit and which pages the sitemap lists in **AdminCP → System → SEO**, so a staging site can hide from Google and a forum can keep AI scrapers out without touching a file. + +## What you get without configuring anything + +| URL | What it serves | +| -------------------------- | ------------------------------------------------------------------------------------------------ | +| `/robots.txt` | `Disallow` for the private areas (`/admin`, `/settings`, `/modcp`, `/notifications`, `/files`) in every language, plus a `Sitemap:` line | +| `/sitemap.xml` | A sitemap index with one entry per file of every source that has public pages | +| `/sitemaps/{source}-{n}.xml` | One file of a source, such as `/sitemaps/blog_post-1.xml`, with `hreflang` alternates for localized pages | + +The sitemap lists the home page, the listing pages plugins register (`/blog`, `/forum`) and every published record of a [content type with `delivery.sitemap`](/docs/content-engine/seo#sitemap). Only what a guest may read gets in: drafts, scheduled, hidden, `noIndex` and members-only records stay out. URLs use `VITNODE_WEB_URL` as the origin, so set it to your public address in production. + +Apps created with `create-vitnode-app` already have the three route files. An app made earlier needs them added once, as [Add the routes to an older app](#add-the-routes-to-an-older-app) shows. + +## Change what crawlers may visit + + + + + +### Open the SEO settings + +Go to **AdminCP → System → SEO**. Viewing it takes the **SEO → View** staff permission, and saving takes **SEO → Manage**. + + + + + +### Pick the rules on General & robots.txt + +- **Allow search engines to index this site**: turn it off on a staging or private site. `/robots.txt` then answers `Disallow: /` to everyone and the sitemaps answer `404`. Pages already in search results drop out over the following weeks, so leave it on for a live site. +- **Block AI training crawlers**: adds one group that disallows the bots collecting pages for AI training, such as GPTBot, ClaudeBot, Google-Extended, CCBot and Bytespider. Search engines and assistants that fetch a page for a reader keep working. +- **Custom robots.txt rules**: lines appended to the end of the file as written, for example a `Crawl-delay` for one bot. + +The **Live preview** below the fields shows the exact file `/robots.txt` will serve, and changes as you type. Select **Save** to publish it. + + + + + + + +### Tune the sitemaps + +Open the **Sitemaps** tab. **Enable XML sitemaps** switches `/sitemap.xml` on or off, and **URLs per sitemap file** (100 to 50,000, default 10,000) sets how many URLs each file holds. A source with 25,000 URLs at the default size gets three files. + +The **Sources** table lists everything that adds pages, with its URL count and a link to its first file. Turn off a source's switch to drop it from `/sitemap.xml` at once; its files answer `404` until you turn it back on. Sources a plugin adds later start switched on. + + + + + + + +Each save writes an entry to the [activity log](/docs/dev/audit-logs) and emits [`seo.settings.updated`](/docs/dev/events/built-in-events#seo-events). + +## While the site is offline + +When [site offline mode](/docs/dev/site-offline-mode) is on, `/robots.txt` and the sitemaps answer `503` with `Retry-After` set to the opening time. Crawlers read that as "come back later" and keep the pages they already indexed, which a `Disallow: /` would not do. The AdminCP preview says so above the file. + +## Caching + +`/robots.txt` is cached for 5 minutes, so turning indexing off reaches crawlers quickly. `/sitemap.xml` and its files are cached for an hour (`public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400`), which is often enough for crawlers and spares the database. A CDN in front of the site keeps its copy for the same time. + +## Add the routes to an older app + +The files live in the web app, at the root of the site rather than under `/api`. Create the three route files, then delete any static `public/robots.txt` or `public/sitemap.xml`, because a static file wins over a route. + +```ts title="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 } }, +}); +``` + +```ts title="src/routes/sitemap[.]xml.ts" +import { createFileRoute } from "@tanstack/react-router"; +import { sitemapIndexHandler } from "@vitnode/core/tanstack/seo/server"; + +export const Route = createFileRoute("/sitemap.xml")({ + server: { handlers: { GET: sitemapIndexHandler } }, +}); +``` + +```ts title="src/routes/sitemaps.$file.ts" +import { createFileRoute } from "@tanstack/react-router"; +import { sitemapFileHandler } from "@vitnode/core/tanstack/seo/server"; + +export const Route = createFileRoute("/sitemaps/$file")({ + server: { handlers: { GET: sitemapFileHandler } }, +}); +``` + +The handlers call the API in-process in a single app, and over `VITNODE_API_URL` when the API runs on its own. These three paths are never locale-prefixed: `/pl/robots.txt` redirects to `/robots.txt`. + +## Check the result + +Open `/robots.txt` and `/sitemap.xml` in the browser, or with `curl`: + +```bash +curl -i http://localhost:3000/robots.txt +curl http://localhost:3000/sitemap.xml +``` + +```xml + + + + http://localhost:3000/sitemaps/static-1.xml + + + http://localhost:3000/sitemaps/blog_post-1.xml + 2026-11-23T20:18:25.940Z + + +``` + +Then turn off **Allow search engines to index this site**, save, and request both again: `/robots.txt` answers `Disallow: /` and `/sitemap.xml` answers `404`. Submit `https://your-site/sitemap.xml` in Google Search Console and Bing Webmaster Tools once the site is live. + +## Related + +- [Sitemap sources](/docs/dev/sitemap-sources): add your own pages and sources to the sitemap. +- [Content Engine SEO](/docs/content-engine/seo#sitemap): which records a content type lists. diff --git a/apps/web/content/docs/dev/seo-robots-admin.webp b/apps/web/content/docs/dev/seo-robots-admin.webp new file mode 100644 index 0000000000..1fb48f3fde Binary files /dev/null and b/apps/web/content/docs/dev/seo-robots-admin.webp differ diff --git a/apps/web/content/docs/dev/seo-sitemaps-admin.webp b/apps/web/content/docs/dev/seo-sitemaps-admin.webp new file mode 100644 index 0000000000..2b89a4df6c Binary files /dev/null and b/apps/web/content/docs/dev/seo-sitemaps-admin.webp differ diff --git a/apps/web/content/docs/dev/sitemap-sources.mdx b/apps/web/content/docs/dev/sitemap-sources.mdx new file mode 100644 index 0000000000..ff8d154e50 --- /dev/null +++ b/apps/web/content/docs/dev/sitemap-sources.mdx @@ -0,0 +1,105 @@ +--- +title: Sitemap sources +description: Add pages and custom sources to the VitNode XML sitemap from a plugin or an app with buildApiPlugin({ sitemap }), buildApiConfig({ seo }) and registerSitemapSource. +icon: Network +--- + +A sitemap source is a list of public URLs with its own files in `/sitemap.xml`. VitNode makes one for the site's fixed pages (`static`) and one per [content type with `delivery.sitemap`](/docs/content-engine/seo#sitemap). Add your own when a plugin or an app has pages the Content Engine doesn't know about, such as a listing page, a docs site or records from an external service. + +## Add plugin pages + +A listing page like `/news` belongs in the `static` source. Name it in the plugin's API config: + +```ts title="plugins/newsroom/src/config.api.ts" +export const newsroomApiPlugin = () => + buildApiPlugin({ + manifest, + sitemap: { + paths: [{ path: "/news", changeFrequency: "daily", priority: 0.8 }], + }, + modules: [ + // ... + ], + }); +``` + +A path is the internal, unlocalized route. VitNode writes one URL per language with the translated route path (`/pl/wiadomosci` when the app's `routePaths` translate it) and `hreflang` alternates plus `x-default`. A plain string such as `"/news"` works too. The blog and forum plugins add `/blog` and `/forum` this way. + +## Add app pages + +The app adds pages, more disallowed paths and whole sources in `buildApiConfig({ seo })`: + +```ts title="src/vitnode.api.config.ts" +import { buildApiConfig } from "@vitnode/api/vitnode.config"; + +export const vitNodeApiConfig = buildApiConfig({ + // ... + seo: { + robots: { disallow: ["/checkout"] }, + sitemap: { + paths: ["/", "/pricing", { path: "/about", priority: 0.5 }], + sources: [docsSitemapSource], + }, + }, +}); +``` + +`robots.disallow` adds paths to the private areas `/robots.txt` always disallows, in every language. + +## Write a source + +Build a source with `defineSitemapSource` when its URLs come from data. It needs a `count` and a page of entries at an `offset`, both in a stable order so file 2 always holds the same URLs: + +```ts title="src/docs/sitemap-source.ts" +import { defineSitemapSource } from "@vitnode/api/lib/seo/sitemap"; + +const docsUrls = async (): Promise => { + const { source } = await import("./source.server"); + + return source + .getPages() + .map(page => page.url) + .sort((a, b) => a.localeCompare(b)); +}; + +export const docsSitemapSource = defineSitemapSource({ + id: "docs", + label: "Documentation", + count: async () => (await docsUrls()).length, + getEntries: async (_c, { limit, offset }) => + (await docsUrls()) + .slice(offset, offset + limit) + .map(loc => ({ changeFrequency: "weekly", loc, priority: 0.6 })), +}); +``` + +This is the source `apps/web` uses for its documentation. Pass it to `buildApiConfig({ seo: { sitemap: { sources } } })` or, from a plugin, to `buildApiPlugin({ sitemap: { sources } })`. Both functions receive the Hono context, so a source can query `c.get("db")`. They run for anonymous crawlers: return only what a guest may open. + +For a fixed list that should be localized like the `static` source but get its own files, use `staticSitemapSource({ id, label, paths })` from `@vitnode/api/lib/seo/static-source`. + +### Register at runtime + +`registerSitemapSource(source)` from `@vitnode/api/lib/seo/registry` adds a source from code that runs at startup, for example an integration that is only configured sometimes. Registering the same id again replaces the earlier source. A declared source with the same id wins over a registered one. + +## Source reference + +| Name | Type | Required | Description | +| ------------------ | ------------------------------------------------------------ | -------- | --------------------------------------------------------------------------------------------- | +| `id` | `string` | Yes | Unique, lowercase letters, digits, `_` and `-` (`/^[a-z0-9_-]+$/`). Files are `/sitemaps/{id}-{n}.xml` | +| `label` | `string` | Yes | An i18n key or plain text, shown in **AdminCP → System → SEO** | +| `count` | `(c) => Promise` | Yes | Total entries. `0` keeps the source out of the index | +| `getEntries` | `(c, { limit, offset }) => Promise` | Yes | One page of entries | +| `getLastModified` | `(c) => Promise` | No | The newest change, written as `` of the source's files in the index | + +A `SitemapEntry` has `loc` (an absolute URL or a path on the site origin) and, optionally, `lastModified`, `changeFrequency` (`"always"` to `"never"`), `priority` (`0` to `1`), `alternates` (`{ hreflang, href }[]`, including the entry's own language and `x-default` if you want one) and `images` (`{ loc }[]`). The `xhtml` and `image` namespaces are only declared in a file that uses them, and every value is XML-escaped. + +Boot stops with an error when an id is invalid or two declared sources share one. Content type sources take their id from the content type (`newsroom.story` becomes `newsroom_story`), so pick a different id for your own. + +## Check the result + +Restart the dev server and open `/sitemap.xml`: your source's files are listed once `count` returns more than `0`, and **AdminCP → System → SEO → Sitemaps** shows it in **Sources** with its URL count. Open its first file, such as `/sitemaps/docs-1.xml`, to see the entries. + +## Related + +- [Robots and sitemaps](/docs/dev/robots-and-sitemaps): the AdminCP settings and the files VitNode serves. +- [Content Engine SEO](/docs/content-engine/seo#sitemap): sitemaps for content types. diff --git a/apps/web/content/docs/guides/blog.mdx b/apps/web/content/docs/guides/blog.mdx index 046f59f1de..71081a9598 100644 --- a/apps/web/content/docs/guides/blog.mdx +++ b/apps/web/content/docs/guides/blog.mdx @@ -163,10 +163,8 @@ articles in that language, and offers **See all articles**. The first page of `/blog` and of every category is indexed by search engines, with a canonical link and `hreflang` alternates that use each language's own slug. Later pages get `noindex, follow`, so crawlers still reach every -article. Add `/blog` to your app's `/sitemap.xml` -next to the article entries; the -[sitemap route](/docs/content-engine/seo#sitemap) lists articles, not the -index. +article. The site's [`/sitemap.xml`](/docs/dev/robots-and-sitemaps) lists +`/blog` and every published article in each language on its own. ### Read an article diff --git a/apps/web/content/docs/guides/forum.mdx b/apps/web/content/docs/guides/forum.mdx index 0c6cd2acad..4f5705dde3 100644 --- a/apps/web/content/docs/guides/forum.mdx +++ b/apps/web/content/docs/guides/forum.mdx @@ -127,8 +127,8 @@ read one topic for its body. Topic pages set a canonical URL and Topics also have [delivery](/docs/content-engine/seo): a renamed topic redirects its old address to the new one, and -`/api/@vitnode/forum/content/topics/delivery/sitemap` lists every public topic -for your `sitemap.xml`. Topics waiting for approval never appear there, in +every public topic and `/forum` itself are listed in the site's +[`/sitemap.xml`](/docs/dev/robots-and-sitemaps). Topics waiting for approval never appear there, in search or in any list - until a moderator says yes, they don't exist for anyone but their author. diff --git a/apps/web/public/robots.txt b/apps/web/public/robots.txt deleted file mode 100644 index 7418a79cc1..0000000000 --- a/apps/web/public/robots.txt +++ /dev/null @@ -1,6 +0,0 @@ -User-agent: * -Allow: / -Disallow: /admin -Disallow: /settings - -Sitemap: https://vitnode.com/sitemap.xml diff --git a/apps/web/public/sitemap.xml b/apps/web/public/sitemap.xml deleted file mode 100644 index b35258839e..0000000000 --- a/apps/web/public/sitemap.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - https://vitnode.com/weekly1.0 - https://vitnode.com/pluginsmonthly0.8 - https://vitnode.com/solutionsmonthly0.8 - https://vitnode.com/solutions/help-centermonthly0.7 - https://vitnode.com/solutions/membership-sitemonthly0.7 - https://vitnode.com/solutions/open-source-hubmonthly0.7 - https://vitnode.com/solutions/multilingual-magazinemonthly0.7 - https://vitnode.com/solutions/gaming-guildmonthly0.7 - https://vitnode.com/docs/devweekly0.9 - https://vitnode.com/docs/dev/setupweekly0.8 - https://vitnode.com/docs/guides/first-pluginmonthly0.7 - https://vitnode.com/docs/dev/plugins/createmonthly0.7 - https://vitnode.com/docs/dev/content-enginemonthly0.7 - https://vitnode.com/docs/dev/plugins/adminmonthly0.6 - https://vitnode.com/docs/dev/deployments/self-hostedmonthly0.6 - diff --git a/apps/web/src/docs/sitemap-source.ts b/apps/web/src/docs/sitemap-source.ts new file mode 100644 index 0000000000..373e11966f --- /dev/null +++ b/apps/web/src/docs/sitemap-source.ts @@ -0,0 +1,21 @@ +import { defineSitemapSource } from '@vitnode/api/lib/seo/sitemap' + +const docsUrls = async (): Promise => { + const { source } = await import('./source.server') + + return source + .getPages() + .map((page) => page.url) + .sort((a, b) => a.localeCompare(b)) +} + +/** Every documentation page, in its own sitemap files. */ +export const docsSitemapSource = defineSitemapSource({ + id: 'docs', + label: 'Documentation', + count: async () => (await docsUrls()).length, + getEntries: async (_c, { limit, offset }) => + (await docsUrls()) + .slice(offset, offset + limit) + .map((loc) => ({ changeFrequency: 'weekly', loc, priority: 0.6 })), +}) diff --git a/apps/web/src/locales/@vitnode/core/pl.json b/apps/web/src/locales/@vitnode/core/pl.json index c5cde2eb6c..d3a092a41f 100644 --- a/apps/web/src/locales/@vitnode/core/pl.json +++ b/apps/web/src/locales/@vitnode/core/pl.json @@ -27,6 +27,9 @@ "@vitnode/core:site_status:can_view": "Podgląd, czy strona jest dostępna, i jej komunikatu o przerwie", "@vitnode/core:site_status:can_manage": "Wyłączanie i włączanie strony oraz edycja komunikatu o przerwie", "@vitnode/core:site_status:can_access_offline": "Dostęp do strony, gdy jest wyłączona", + "@vitnode/core:seo": "SEO", + "@vitnode/core:seo:can_view": "Podgląd ustawień robots.txt i map witryny", + "@vitnode/core:seo:can_manage": "Zmiana ustawień robots.txt i map witryny", "@vitnode/core:plugins": "Wtyczki", "@vitnode/core:plugins:can_view": "Przeglądanie zainstalowanych wtyczek i ich wersji", "@vitnode/core:queue": "Zadania w kolejce", @@ -528,7 +531,8 @@ "integrations": "Integracje", "plugins": "Wtyczki", "title": "System", - "notifications": "Powiadomienia" + "notifications": "Powiadomienia", + "seo": "SEO" }, "user_bar": { "debug": "Panel debugowania", @@ -1615,6 +1619,80 @@ "desc": "Pokazuj odliczanie na żywo. Po wyłączeniu odwiedzający widzą tylko datę." } } + }, + "seo": { + "title": "SEO", + "desc": "Zdecyduj, co mogą odwiedzać wyszukiwarki i roboty AI oraz które strony trafiają do mapy witryny.", + "tabs": { + "general": "Ogólne i robots.txt", + "sitemaps": "Mapy witryny" + }, + "submit": "Zapisz", + "saved": { + "title": "Zapisano ustawienia SEO", + "desc": "Roboty pobiorą nowy robots.txt i mapę witryny przy następnej wizycie." + }, + "robots": { + "allow_indexing": { + "label": "Pozwól wyszukiwarkom indeksować stronę", + "desc": "Wyłącz na stronie testowej lub prywatnej: każdy robot dostaje zakaz wstępu, a mapy witryny przestają odpowiadać." + }, + "indexing_off": { + "title": "Wyszukiwarki są zablokowane", + "desc": "robots.txt mówi wszystkim \"Disallow: /\". Strony znikną z wyników wyszukiwania w ciągu kilku tygodni, więc używaj tego tylko na stronie, której nikt nie powinien znaleźć." + }, + "block_ai": { + "label": "Blokuj roboty trenujące AI", + "desc": "Prosi boty zbierające strony do trenowania modeli AI (GPTBot, ClaudeBot, Google-Extended, CCBot i inne), żeby omijały stronę. Zwykłe wyszukiwanie działa dalej." + }, + "custom": { + "label": "Własne reguły robots.txt", + "desc": "Dopisywane na końcu pliku dokładnie tak, jak je wpiszesz, jedna reguła na linię." + }, + "preview": { + "title": "Podgląd na żywo", + "desc": "Tak będzie wyglądał /robots.txt po zapisaniu. Zmienia się w trakcie pisania.", + "offline": "Strona jest teraz wyłączona, więc /robots.txt odpowiada 503 i roboty wrócą później. Po otwarciu strony dostaną ten plik.", + "open": "Otwórz robots.txt", + "copy": "Kopiuj robots.txt" + } + }, + "sitemaps": { + "enabled": { + "label": "Włącz mapy witryny XML", + "desc": "Udostępnia /sitemap.xml ze wszystkimi publicznymi stronami z wtyczek i typów treści, podzielonymi na mniejsze pliki." + }, + "open": "Otwórz {url}", + "indexing_off": "Mapy witryny są ukryte, dopóki indeksowanie przez wyszukiwarki jest wyłączone.", + "max_urls": { + "label": "Adresów URL w jednym pliku", + "desc": "Większe pliki to mniej zapytań; protokół pozwala na maksymalnie {max, number}.", + "unit": "adresów" + } + }, + "sources": { + "title": "Źródła", + "desc": "Wszystko, co dodaje strony do mapy witryny. Wyłącz źródło, a jego strony od razu znikną z /sitemap.xml.", + "columns": { + "source": "Źródło", + "urls": "Adresy", + "files": "Pliki", + "preview": "Podgląd", + "enabled": "W mapie" + }, + "preview": "Pierwszy plik", + "empty": "Brak publicznych stron", + "not_served": "Niedostępne", + "error": "Nie udało się policzyć", + "static": "Strony", + "toggle_label": "Uwzględnij {label} w mapie witryny", + "toggled": { + "on": "Dodano {label} do mapy witryny", + "on_desc": "Jego strony znów są w /sitemap.xml.", + "off": "Usunięto {label} z mapy witryny", + "off_desc": "Jego strony i pliki zniknęły z /sitemap.xml." + } + } } }, "user": { diff --git a/apps/web/src/page-cache.gen.ts b/apps/web/src/page-cache.gen.ts index 0e7fda628d..c5baf771a8 100644 --- a/apps/web/src/page-cache.gen.ts +++ b/apps/web/src/page-cache.gen.ts @@ -45,6 +45,7 @@ export const pageCacheRoutes: PageCacheRouteTable = [ { path: '/admin/core/system/integrations' }, { path: '/admin/core/system/notifications' }, { path: '/admin/core/system/plugins' }, + { path: '/admin/core/system/seo' }, { path: '/admin/core/users/reactions' }, { path: '/admin/core/users/roles' }, { path: '/admin/core/users/:id' }, @@ -101,6 +102,7 @@ export const pageCacheRoutes: PageCacheRouteTable = [ { path: '/news/:slug' }, { path: '/stories/:slug' }, { path: '/users/:nameCode' }, + { path: '/sitemaps/:file' }, { path: '/solutions/:slug' }, { path: '/admin/:section/*' }, { path: '/admin' }, diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 4aade34210..db5a83fd37 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -14,11 +14,14 @@ import { Route as DocsRouteImport } from './routes/_docs' import { Route as MainRouteImport } from './routes/_main' import { Route as LlmsFullDottxtRouteImport } from './routes/llms-full[.]txt' import { Route as LlmsDottxtRouteImport } from './routes/llms[.]txt' +import { Route as RobotsDottxtRouteImport } from './routes/robots[.]txt' +import { Route as SitemapDotxmlRouteImport } from './routes/sitemap[.]xml' import { Route as MainIndexRouteImport } from './routes/_main/index' import { Route as MainPluginsRouteImport } from './routes/_main/plugins' import { Route as ApiSplatRouteImport } from './routes/api/$' import { Route as DocsSearchRouteImport } from './routes/docs.search' import { Route as DocsChar123Char125DotmdRouteImport } from './routes/docs.{$}[.]md' +import { Route as SitemapsFileRouteImport } from './routes/sitemaps.$file' import { Route as DocsDocsIndexRouteImport } from './routes/_docs/docs.index' import { Route as DocsDocsSplatRouteImport } from './routes/_docs/docs.$' import { Route as MainSolutionsIndexRouteImport } from './routes/_main/solutions/index' @@ -47,6 +50,16 @@ const LlmsDottxtRoute = LlmsDottxtRouteImport.update({ path: '/llms.txt', getParentRoute: () => rootRouteImport, } as any) +const RobotsDottxtRoute = RobotsDottxtRouteImport.update({ + id: '/robots.txt', + path: '/robots.txt', + getParentRoute: () => rootRouteImport, +} as any) +const SitemapDotxmlRoute = SitemapDotxmlRouteImport.update({ + id: '/sitemap.xml', + path: '/sitemap.xml', + getParentRoute: () => rootRouteImport, +} as any) const MainIndexRoute = MainIndexRouteImport.update({ id: '/', path: '/', @@ -72,6 +85,11 @@ const DocsChar123Char125DotmdRoute = DocsChar123Char125DotmdRouteImport.update({ path: '/docs/{$}.md', getParentRoute: () => rootRouteImport, } as any) +const SitemapsFileRoute = SitemapsFileRouteImport.update({ + id: '/sitemaps/$file', + path: '/sitemaps/$file', + getParentRoute: () => rootRouteImport, +} as any) const DocsDocsIndexRoute = DocsDocsIndexRouteImport.update({ id: '/docs/', path: '/docs/', @@ -102,10 +120,13 @@ export interface FileRoutesByFullPath { '/': typeof MainIndexRoute '/llms-full.txt': typeof LlmsFullDottxtRoute '/llms.txt': typeof LlmsDottxtRoute + '/robots.txt': typeof RobotsDottxtRoute + '/sitemap.xml': typeof SitemapDotxmlRoute '/plugins': typeof MainPluginsRoute '/api/$': typeof ApiSplatRoute '/docs/search': typeof DocsSearchRoute '/docs/{$}.md': typeof DocsChar123Char125DotmdRoute + '/sitemaps/$file': typeof SitemapsFileRoute '/docs/$': typeof DocsDocsSplatRoute '/solutions/$slug': typeof MainSolutionsSlugRoute '/docs/': typeof DocsDocsIndexRoute @@ -116,10 +137,13 @@ export interface FileRoutesByTo { '/': typeof MainIndexRoute '/llms-full.txt': typeof LlmsFullDottxtRoute '/llms.txt': typeof LlmsDottxtRoute + '/robots.txt': typeof RobotsDottxtRoute + '/sitemap.xml': typeof SitemapDotxmlRoute '/plugins': typeof MainPluginsRoute '/api/$': typeof ApiSplatRoute '/docs/search': typeof DocsSearchRoute '/docs/{$}.md': typeof DocsChar123Char125DotmdRoute + '/sitemaps/$file': typeof SitemapsFileRoute '/docs/$': typeof DocsDocsSplatRoute '/solutions/$slug': typeof MainSolutionsSlugRoute '/docs': typeof DocsDocsIndexRoute @@ -133,10 +157,13 @@ export interface FileRoutesById { '/_main': typeof MainRouteWithChildren '/llms-full.txt': typeof LlmsFullDottxtRoute '/llms.txt': typeof LlmsDottxtRoute + '/robots.txt': typeof RobotsDottxtRoute + '/sitemap.xml': typeof SitemapDotxmlRoute '/_main/plugins': typeof MainPluginsRoute '/api/$': typeof ApiSplatRoute '/docs/search': typeof DocsSearchRoute '/docs/{$}.md': typeof DocsChar123Char125DotmdRoute + '/sitemaps/$file': typeof SitemapsFileRoute '/_main/': typeof MainIndexRoute '/_docs/docs/$': typeof DocsDocsSplatRoute '/_main/solutions/$slug': typeof MainSolutionsSlugRoute @@ -150,10 +177,13 @@ export interface FileRouteTypes { | '/' | '/llms-full.txt' | '/llms.txt' + | '/robots.txt' + | '/sitemap.xml' | '/plugins' | '/api/$' | '/docs/search' | '/docs/{$}.md' + | '/sitemaps/$file' | '/docs/$' | '/solutions/$slug' | '/docs/' @@ -164,10 +194,13 @@ export interface FileRouteTypes { | '/' | '/llms-full.txt' | '/llms.txt' + | '/robots.txt' + | '/sitemap.xml' | '/plugins' | '/api/$' | '/docs/search' | '/docs/{$}.md' + | '/sitemaps/$file' | '/docs/$' | '/solutions/$slug' | '/docs' @@ -180,10 +213,13 @@ export interface FileRouteTypes { | '/_main' | '/llms-full.txt' | '/llms.txt' + | '/robots.txt' + | '/sitemap.xml' | '/_main/plugins' | '/api/$' | '/docs/search' | '/docs/{$}.md' + | '/sitemaps/$file' | '/_main/' | '/_docs/docs/$' | '/_main/solutions/$slug' @@ -198,9 +234,12 @@ export interface RootRouteChildren { MainRoute: typeof MainRouteWithChildren LlmsFullDottxtRoute: typeof LlmsFullDottxtRoute LlmsDottxtRoute: typeof LlmsDottxtRoute + RobotsDottxtRoute: typeof RobotsDottxtRoute + SitemapDotxmlRoute: typeof SitemapDotxmlRoute ApiSplatRoute: typeof ApiSplatRoute DocsSearchRoute: typeof DocsSearchRoute DocsChar123Char125DotmdRoute: typeof DocsChar123Char125DotmdRoute + SitemapsFileRoute: typeof SitemapsFileRoute } declare module '@tanstack/react-router' { @@ -240,6 +279,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LlmsDottxtRouteImport parentRoute: typeof rootRouteImport } + '/robots.txt': { + id: '/robots.txt' + path: '/robots.txt' + fullPath: '/robots.txt' + preLoaderRoute: typeof RobotsDottxtRouteImport + parentRoute: typeof rootRouteImport + } + '/sitemap.xml': { + id: '/sitemap.xml' + path: '/sitemap.xml' + fullPath: '/sitemap.xml' + preLoaderRoute: typeof SitemapDotxmlRouteImport + parentRoute: typeof rootRouteImport + } '/_main/': { id: '/_main/' path: '/' @@ -275,6 +328,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DocsChar123Char125DotmdRouteImport parentRoute: typeof rootRouteImport } + '/sitemaps/$file': { + id: '/sitemaps/$file' + path: '/sitemaps/$file' + fullPath: '/sitemaps/$file' + preLoaderRoute: typeof SitemapsFileRouteImport + parentRoute: typeof rootRouteImport + } '/_docs/docs/': { id: '/_docs/docs/' path: '/docs' @@ -357,9 +417,12 @@ const rootRouteChildren: RootRouteChildren = { MainRoute: MainRouteWithChildren, LlmsFullDottxtRoute: LlmsFullDottxtRoute, LlmsDottxtRoute: LlmsDottxtRoute, + RobotsDottxtRoute: RobotsDottxtRoute, + SitemapDotxmlRoute: SitemapDotxmlRoute, ApiSplatRoute: ApiSplatRoute, DocsSearchRoute: DocsSearchRoute, DocsChar123Char125DotmdRoute: DocsChar123Char125DotmdRoute, + SitemapsFileRoute: SitemapsFileRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/apps/web/src/routes/robots[.]txt.ts b/apps/web/src/routes/robots[.]txt.ts new file mode 100644 index 0000000000..5911d4f7a0 --- /dev/null +++ b/apps/web/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/apps/web/src/routes/sitemap[.]xml.ts b/apps/web/src/routes/sitemap[.]xml.ts new file mode 100644 index 0000000000..c24e5b4b73 --- /dev/null +++ b/apps/web/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/apps/web/src/routes/sitemaps.$file.ts b/apps/web/src/routes/sitemaps.$file.ts new file mode 100644 index 0000000000..757e0e5f0e --- /dev/null +++ b/apps/web/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/apps/web/src/vitnode.api.config.ts b/apps/web/src/vitnode.api.config.ts index 21ea0ba63b..411c93168d 100644 --- a/apps/web/src/vitnode.api.config.ts +++ b/apps/web/src/vitnode.api.config.ts @@ -16,8 +16,10 @@ import { newsroomApiPlugin } from 'newsroom/config.api' import { paymentsDemoApiPlugin } from 'payments-demo/config.api' import { contentModules } from './content-modules.gen' +import { docsSitemapSource } from './docs/sitemap-source' import { appMessages } from './locales/app' import { frontendPlugins } from './plugin-inventory.gen' +import { PRERENDERED_PATHS } from './site/prerender' import { vitNodeConfig } from './vitnode.config' config({ quiet: true }) @@ -47,6 +49,16 @@ export const vitNodeApiConfig = buildApiConfig({ ], contentModules, frontendPlugins, + seo: { + sitemap: { + paths: PRERENDERED_PATHS.map((path) => ({ + changeFrequency: 'monthly', + path, + priority: path === '/' ? 1 : 0.8, + })), + sources: [docsSitemapSource], + }, + }, storage: { // Re-encoding needs sharp, a native module Workers cannot load: there, // images are stored as uploaded. diff --git a/packages/api/src/config.ts b/packages/api/src/config.ts index aba0c1cdfd..5c4c752bd6 100644 --- a/packages/api/src/config.ts +++ b/packages/api/src/config.ts @@ -271,6 +271,7 @@ export function VitNodeAPI({ activityLogs: vitNodeApiConfig.activityLogs, payments: vitNodeApiConfig.payments, search: vitNodeApiConfig.search, + seo: vitNodeApiConfig.seo, storage: vitNodeApiConfig.storage, updates: vitNodeApiConfig.updates, users: vitNodeApiConfig.users, diff --git a/packages/api/src/content/server/delivery-sitemap.ts b/packages/api/src/content/server/delivery-sitemap.ts index afd0ed2148..411ef1533b 100644 --- a/packages/api/src/content/server/delivery-sitemap.ts +++ b/packages/api/src/content/server/delivery-sitemap.ts @@ -51,6 +51,47 @@ const noIndexColumn = ( return leaf === undefined ? null : (columns[leaf.columnName] ?? null); }; +/** + * What every sitemap line of a content type must satisfy, on its base table: + * published (not scheduled, hidden or deleted), readable by a guest, and not + * marked `noIndex`. Localized types also need their translation published. + */ +export const contentSitemapConditions = async < + TDefinition extends AnyContentTypeDefinition, +>({ + c, + model, +}: { + c: Context; + model: ContentModel; +}): Promise => { + const { columns, definition } = model; + const exclude = noIndexColumn(definition, columns); + const conditions: (SQL | undefined)[] = [ + publishedCondition(publicationColumns(definition, columns)), + // A sitemap is public, so it lists only what a guest may read - whoever + // happens to be asking for it. + await contentPublicAccessCondition(c, definition, { + actor: CONTENT_ACCESS_GUEST, + }), + // `IS DISTINCT FROM TRUE`, which is the only spelling that agrees with the + // metadata. `contentDeliveryRobots` reads `value !== true`, so a `noIndex` of + // `null` means `index: true` - and the sitemap has to list exactly what claims + // to be indexable, because "absent from the sitemap" and "robots says index + // me" is a contradiction a crawler resolves however it likes. + // + // `<> TRUE` cannot say it. In SQL `NULL <> TRUE` is `NULL`, not `TRUE`, and a + // `WHERE` clause drops every row it cannot prove - so a nullable `noIndexField` + // would quietly empty the sitemap of every record nobody had ever set the flag + // on, while every one of their pages rendered `index: true`. `IS DISTINCT + // FROM` is the null-aware comparison: `true` excludes, `false` and `null` + // include, which is the metadata rule written once more in SQL. + exclude === null ? undefined : sql`${exclude} is distinct from true`, + ]; + + return conditions.filter((part): part is SQL => part !== undefined); +}; + export const readContentDeliverySitemapPage = async < TDefinition extends AnyContentTypeDefinition, >({ @@ -87,8 +128,6 @@ export const readContentDeliverySitemapPage = async < ), ); const slugField = definition.publicApi.slugField; - const base = publicationColumns(definition, columns); - const exclude = noIndexColumn(definition, columns); const localized = definition.localization.enabled; // Widened, not cast - see `readDeliveryAlternatesMany` for why. The translation // table needs the same treatment for the join below. @@ -96,26 +135,8 @@ export const readContentDeliverySitemapPage = async < const joinedTranslations: null | PgTable = model.translationTable; const conditions: (SQL | undefined)[] = [ - publishedCondition(base), - // A sitemap is public, so it lists only what a guest may read - whoever - // happens to be asking for it. - await contentPublicAccessCondition(c, definition, { - actor: CONTENT_ACCESS_GUEST, - }), + ...(await contentSitemapConditions({ c, model })), cursor === null ? undefined : gt(columns.id, cursor), - // `IS DISTINCT FROM TRUE`, which is the only spelling that agrees with the - // metadata. `contentDeliveryRobots` reads `value !== true`, so a `noIndex` of - // `null` means `index: true` - and the sitemap has to list exactly what claims - // to be indexable, because "absent from the sitemap" and "robots says index - // me" is a contradiction a crawler resolves however it likes. - // - // `<> TRUE` cannot say it. In SQL `NULL <> TRUE` is `NULL`, not `TRUE`, and a - // `WHERE` clause drops every row it cannot prove - so a nullable `noIndexField` - // would quietly empty the sitemap of every record nobody had ever set the flag - // on, while every one of their pages rendered `index: true`. `IS DISTINCT - // FROM` is the null-aware comparison: `true` excludes, `false` and `null` - // include, which is the metadata rule written once more in SQL. - exclude === null ? undefined : sql`${exclude} is distinct from true`, ]; if (!localized) { diff --git a/packages/api/src/content/server/sitemap-source.test.ts b/packages/api/src/content/server/sitemap-source.test.ts new file mode 100644 index 0000000000..41d16e3cd3 --- /dev/null +++ b/packages/api/src/content/server/sitemap-source.test.ts @@ -0,0 +1,222 @@ +import type { Context } from "hono"; + +import { beforeAll, describe, expect, it } from "vitest"; + +import { defineContentType } from "@/content/define"; +import { field } from "@/content/fields"; +import { createContentModel } from "@/content/server/model"; +import { core_content_slug_history } from "@/database/content"; +import { core_languages } from "@/database/languages"; +import { + ACCESS_PLUGIN_ID, + BOARD, + createAccessWorld, + testAccessBoards, +} from "@/tests/content-access"; +import { testContentLocaleRouting } from "@/tests/content-fixtures"; + +import { contentSitemapSource } from "./sitemap-source"; + +const sitemapPostType = defineContentType({ + id: "test.sitemap-post", + tableName: "test_sitemap_posts", + publication: true, + visibility: true, + fields: { + title: field.text({ required: true, maxLength: 200 }), + slug: field.slug({ source: "title" }), + noIndex: field.boolean({ nullable: true }), + board: field.container({ definition: testAccessBoards, required: true }), + }, + publicApi: { + path: "sitemap-posts", + fields: ["id", "title", "slug", "noIndex"], + }, + delivery: { + seo: { noIndexField: "noIndex", titleField: "title" }, + sitemap: { changeFrequency: "weekly", priority: 0.6 }, + }, +}); + +const sitemapPageType = defineContentType({ + id: "test.sitemap-page", + tableName: "test_sitemap_pages", + localization: { defaultLocale: "en", fallback: "default" }, + publication: true, + fields: { + title: field.text({ localized: true, required: true, maxLength: 200 }), + slug: field.slug({ localized: true, source: "title" }), + }, + publicApi: { path: "sitemap-pages", fields: ["id", "title", "slug"] }, + delivery: { hreflang: { xDefault: "defaultLocale" }, sitemap: true }, +}); + +const posts = createContentModel(sitemapPostType); +const pages = createContentModel(sitemapPageType); + +const LIVE = new Date("2026-01-01T00:00:00.000Z"); +const LATER = new Date("2026-02-01T00:00:00.000Z"); +const FUTURE = new Date("2999-01-01T00:00:00.000Z"); +const LANGUAGE = { EN: 1, PL: 2 } as const; + +const post = (id: number, overrides: Record = {}) => ({ + board: BOARD.OPEN, + createdAt: LIVE, + hiddenAt: null, + id, + noIndex: false, + publishedAt: LIVE, + slug: `post-${id}`, + status: "published", + title: `Post ${id}`, + updatedAt: LIVE, + ...overrides, +}); + +const translation = ( + itemId: number, + languageId: number, + overrides: Record = {}, +) => ({ + createdAt: LIVE, + itemId, + languageId, + publishedAt: LIVE, + slug: `${languageId === LANGUAGE.EN ? "page" : "strona"}-${itemId}`, + status: "published", + title: `Page ${itemId}`, + updatedAt: LIVE, + ...overrides, +}); + +let c: Context; + +beforeAll(async () => { + const world = await createAccessWorld(); + const { db } = world.memory; + await db + .insert(posts.table) + .values([ + post(1), + post(2, { status: "draft" }), + post(3, { publishedAt: FUTURE }), + post(4, { hiddenAt: LIVE }), + post(5, { noIndex: true }), + post(6, { noIndex: null }), + post(7, { board: BOARD.MEMBERS }), + post(8, { slug: "renamed" }), + ]); + await db.insert(core_content_slug_history).values({ + contentTypeId: sitemapPostType.id, + itemId: "8", + languageId: null, + path: "/sitemap-posts/post-8", + pluginId: ACCESS_PLUGIN_ID, + retiredAt: LIVE, + slug: "post-8", + }); + await db.insert(core_languages).values([ + { code: "en", default: true, id: LANGUAGE.EN, name: "English" }, + { code: "pl", default: false, id: LANGUAGE.PL, name: "Polski" }, + ]); + await db.insert(pages.table).values( + [10, 11, 12].map(id => ({ + createdAt: LIVE, + id, + publishedAt: LIVE, + status: id === 12 ? "draft" : "published", + updatedAt: LIVE, + })), + ); + if (!pages.translationTable) throw new Error("pages are localized"); + await db + .insert(pages.translationTable) + .values([ + translation(10, LANGUAGE.EN), + translation(10, LANGUAGE.PL, { updatedAt: LATER }), + translation(11, LANGUAGE.EN), + translation(11, LANGUAGE.PL, { status: "draft" }), + translation(12, LANGUAGE.EN), + ]); + + const values = world.contextValues(null); + const core = values.core as { contentModels: unknown[] }; + const given: Record = { + ...values, + core: { + ...core, + contentModels: [ + ...core.contentModels, + { model: posts, pluginId: ACCESS_PLUGIN_ID }, + { model: pages, pluginId: ACCESS_PLUGIN_ID }, + ], + i18n: { localeRouting: testContentLocaleRouting() }, + }, + }; + c = { get: (key: string) => given[key] } as unknown as Context; +}); + +describe("contentSitemapSource", () => { + const source = contentSitemapSource({ + model: posts, + pluginId: ACCESS_PLUGIN_ID, + }); + + it("lists only what a guest may read and may index, at the current slug", async () => { + expect(await source.count(c)).toBe(3); + expect(await source.getEntries(c, { limit: 10, offset: 0 })).toStrictEqual( + ["post-1", "post-6", "renamed"].map(slug => ({ + changeFrequency: "weekly", + lastModified: LIVE, + loc: `/sitemap-posts/${slug}`, + priority: 0.6, + })), + ); + }); + + it("pages in id order, so page n always holds the same URLs", async () => { + const locs = async (offset: number) => + (await source.getEntries(c, { limit: 2, offset })).map( + entry => entry.loc, + ); + + expect([...(await locs(0)), ...(await locs(2))]).toStrictEqual([ + "/sitemap-posts/post-1", + "/sitemap-posts/post-6", + "/sitemap-posts/renamed", + ]); + }); +}); + +describe("contentSitemapSource for a localized type", () => { + const source = contentSitemapSource({ + model: pages, + pluginId: ACCESS_PLUGIN_ID, + }); + + it("lists one URL per published translation, each with its languages and x-default", async () => { + const alternates = [ + { href: "/sitemap-pages/page-10", hreflang: "en" }, + { href: "/pl/sitemap-pages/strona-10", hreflang: "pl" }, + { href: "/sitemap-pages/page-10", hreflang: "x-default" }, + ]; + const entry = { changeFrequency: null, priority: null }; + + expect(await source.count(c)).toBe(3); + expect(await source.getEntries(c, { limit: 10, offset: 0 })).toStrictEqual([ + { + ...entry, + alternates, + lastModified: LIVE, + loc: "/sitemap-pages/page-10", + }, + { + ...entry, + alternates, + lastModified: LATER, + loc: "/pl/sitemap-pages/strona-10", + }, + { ...entry, lastModified: LIVE, loc: "/sitemap-pages/page-11" }, + ]); + }); +}); diff --git a/packages/api/src/content/server/sitemap-source.ts b/packages/api/src/content/server/sitemap-source.ts new file mode 100644 index 0000000000..a03c9f47d4 --- /dev/null +++ b/packages/api/src/content/server/sitemap-source.ts @@ -0,0 +1,332 @@ +import type { SQL } from "drizzle-orm"; +import type { PgColumn, PgTable } from "drizzle-orm/pg-core"; +import type { Context } from "hono"; + +import { and, asc, count, eq, inArray, max, sql } from "drizzle-orm"; + +import type { SitemapEntry, SitemapSource } from "../../lib/seo/sitemap"; +import type { ContentDeliveryAlternate } from "../delivery"; +import type { ContentId } from "../ids"; +import type { ContentPublicUrl } from "../public-url"; +import type { AnyContentTypeDefinition } from "../types"; +import type { AnyContentModel, ContentModel } from "./model"; + +import { core_files } from "../../database/files"; +import { CONFIG } from "../../lib/config"; +import { contentDeliveryPublicUrl } from "../delivery"; +import { contentIdKey } from "../ids"; +import { readDeliveryAlternatesMany } from "./delivery-alternates"; +import { contentSitemapConditions } from "./delivery-sitemap"; +import { listContentLanguages } from "./language-resolver"; +import { contentLocaleRouting } from "./locale-routing"; +import { contentDefinitionOf } from "./model"; +import { + contentTranslationPublicationColumns, + publishedCondition, +} from "./publication"; + +/** `blog.post` → `blog_post`. Content ids never hold `_`, so this is one-to-one. */ +export const contentSitemapSourceId = (contentTypeId: string): string => + contentTypeId.replaceAll(".", "_"); + +/** Whether a registered content type lists its records in the sitemap. */ +export const hasContentSitemap = (definition: AnyContentTypeDefinition) => + definition.delivery.enabled && + definition.publicApi.enabled && + definition.delivery.sitemap.enabled; + +const href = (url: ContentPublicUrl | { origin?: string; path: string }) => { + const path = "pathname" in url ? url.pathname : url.path; + + return url.origin === undefined ? path : new URL(path, url.origin).href; +}; + +const asFileId = (value: unknown): null | number => + typeof value === "number" && Number.isSafeInteger(value) && value > 0 + ? value + : null; + +/** Public image URLs by file id. Images are never access-restricted. */ +const publicImageUrls = async ( + c: Context, + fileIds: readonly number[], +): Promise> => { + const unique = [...new Set(fileIds)]; + if (unique.length === 0 || !c.get("core").storage?.adapter) return new Map(); + + const rows = await c + .get("db") + .select({ id: core_files.id, key: core_files.key }) + .from(core_files) + .where( + and( + inArray(core_files.id, unique), + eq(core_files.visibility, "public"), + sql`${core_files.mimeType} like 'image/%'`, + ), + ); + const storage = c.get("storage"); + + return new Map( + rows.flatMap((row): [number, string][] => { + try { + const url = storage.getUrl(row.key); + + return url ? [[row.id, new URL(url, CONFIG.api.origin).href]] : []; + } catch { + // An image is optional in a sitemap; a storage adapter that cannot + // build its URL drops the image, never the page. + return []; + } + }), + ); +}; + +interface Row { + imageId: null | number; + itemId: ContentId; + lastModified: Date; + locale: null | string; + slug: unknown; +} + +const toDate = (value: unknown): Date => + value instanceof Date ? value : new Date(String(value)); + +/** + * A sitemap source for one content type: every published record a guest may + * read and that is not `noIndex`, at its current slug. A localized type lists + * one URL per published translation, each with all its languages as + * `hreflang` alternates (plus `x-default` when `delivery.hreflang` asks for + * it). Records are ordered by id, so pages are stable. Server-only. + */ +export const contentSitemapSource = < + TDefinition extends AnyContentTypeDefinition, +>({ + model, + pluginId, +}: { + model: ContentModel; + pluginId: string; +}): SitemapSource => { + const { columns, definition, translationColumns } = model; + const { sitemap } = definition.delivery; + const slugField = definition.publicApi.slugField; + const imageField = definition.delivery.seo.openGraph?.imageField ?? null; + const imageColumn: null | PgColumn = + imageField === null ? null : (columns[imageField] ?? null); + // Widened, not cast - see `readDeliveryAlternatesMany` for why. + const baseTable: PgTable = model.table; + const translationTable: null | PgTable = model.translationTable; + const localized = + definition.localization.enabled && + translationTable !== null && + translationColumns !== null; + + const languagesOf = async (c: Context) => { + const enabled = (await listContentLanguages(c)).filter( + language => language.isEnabled, + ); + + return new Map(enabled.map(language => [language.id, language.locale])); + }; + + const translationJoin = (languageIds: number[]): SQL => + (translationColumns + ? and( + eq(translationColumns.itemId, columns.id), + inArray(translationColumns.languageId, languageIds), + ) + : undefined) ?? sql`false`; + + const translationPublished = (): (SQL | undefined)[] => + translationColumns + ? [ + publishedCondition( + contentTranslationPublicationColumns( + definition, + translationColumns, + ), + ), + ] + : []; + + const readRows = async ( + c: Context, + { limit, offset }: { limit: number; offset: number }, + ): Promise => { + const conditions = await contentSitemapConditions({ c, model }); + + if (!localized || !translationTable || !translationColumns) { + const rows = await c + .get("db") + .select({ + imageId: imageColumn ?? sql`null`, + itemId: columns.id, + lastModified: columns.updatedAt, + slug: columns[slugField], + }) + .from(baseTable) + .where(and(...conditions)) + .orderBy(asc(columns.id)) + .limit(limit) + .offset(offset); + + return rows.map(row => ({ + imageId: asFileId(row.imageId), + itemId: row.itemId as ContentId, + lastModified: toDate(row.lastModified), + locale: null, + slug: row.slug, + })); + } + + const languages = await languagesOf(c); + if (languages.size === 0) return []; + const slugColumn: PgColumn = + definition.delivery.slugScope === "localized" + ? translationColumns[slugField] + : columns[slugField]; + + const rows = await c + .get("db") + .select({ + imageId: imageColumn ?? sql`null`, + itemId: columns.id, + languageId: translationColumns.languageId, + // See `readContentDeliverySitemapPage`: the later of both halves, read + // with the column's own decoder so it stays in UTC. + lastModified: + sql`greatest(${columns.updatedAt}, ${translationColumns.updatedAt})`.mapWith( + columns.updatedAt, + ), + slug: slugColumn, + }) + .from(baseTable) + .innerJoin(translationTable, translationJoin([...languages.keys()])) + .where(and(...conditions, ...translationPublished())) + .orderBy(asc(columns.id), asc(translationColumns.languageId)) + .limit(limit) + .offset(offset); + + return rows.map(row => ({ + imageId: asFileId(row.imageId), + itemId: row.itemId as ContentId, + lastModified: toDate(row.lastModified), + locale: languages.get(Number(row.languageId)) ?? null, + slug: row.slug, + })); + }; + + return { + contentType: { id: definition.id, pluginId }, + count: async c => { + const conditions = await contentSitemapConditions({ c, model }); + + if (!localized || !translationTable || !translationColumns) { + const [row] = await c + .get("db") + .select({ total: count() }) + .from(baseTable) + .where(and(...conditions)); + + return row?.total ?? 0; + } + + const languages = await languagesOf(c); + if (languages.size === 0) return 0; + const [row] = await c + .get("db") + .select({ total: count() }) + .from(baseTable) + .innerJoin(translationTable, translationJoin([...languages.keys()])) + .where(and(...conditions, ...translationPublished())); + + return row?.total ?? 0; + }, + getEntries: async (c, page) => { + const rows = await readRows(c, page); + const routing = contentLocaleRouting(c); + const [alternates, images] = await Promise.all([ + localized + ? readDeliveryAlternatesMany({ + c, + itemIds: [...new Set(rows.map(row => row.itemId))], + model, + }) + : Promise.resolve(new Map()), + publicImageUrls( + c, + rows.flatMap(row => (row.imageId === null ? [] : [row.imageId])), + ), + ]); + const xDefaultLocale = + definition.delivery.hreflang.xDefault === "defaultLocale" + ? definition.localization.defaultLocale + : null; + + return rows.flatMap((row): SitemapEntry[] => { + if (localized && row.locale === null) return []; + const url = contentDeliveryPublicUrl({ + definition, + locale: row.locale, + routing, + slug: typeof row.slug === "string" ? row.slug : "", + }); + if (url === null) return []; + + const languages = alternates.get(contentIdKey(row.itemId)) ?? []; + const xDefault = languages.find( + alternate => alternate.locale === xDefaultLocale, + ); + const image = + row.imageId === null ? undefined : images.get(row.imageId); + + return [ + { + changeFrequency: sitemap.changeFrequency, + lastModified: row.lastModified, + loc: href(url), + priority: sitemap.priority, + ...(languages.length > 1 + ? { + alternates: [ + ...languages.map(alternate => ({ + href: href(alternate), + hreflang: alternate.locale, + })), + ...(xDefault + ? [{ href: href(xDefault), hreflang: "x-default" }] + : []), + ], + } + : {}), + ...(image ? { images: [{ loc: image }] } : {}), + }, + ]; + }); + }, + getLastModified: async c => { + const conditions = await contentSitemapConditions({ c, model }); + const [row] = await c + .get("db") + .select({ value: max(columns.updatedAt) }) + .from(baseTable) + .where(and(...conditions)); + + return row?.value ? toDate(row.value) : null; + }, + id: contentSitemapSourceId(definition.id), + label: definition.id, + }; +}; + +/** One source per registered content type with `delivery.sitemap`. Server-only. */ +export const contentSitemapSources = ( + models: readonly { model: AnyContentModel; pluginId: string }[], +): SitemapSource[] => + models.flatMap(({ model, pluginId }) => + hasContentSitemap(contentDefinitionOf(model)) + ? [contentSitemapSource({ model, pluginId })] + : [], + ); diff --git a/packages/api/src/database/relations.ts b/packages/api/src/database/relations.ts index dffaffb5a0..baa76a6cc9 100644 --- a/packages/api/src/database/relations.ts +++ b/packages/api/src/database/relations.ts @@ -21,6 +21,7 @@ import * as queue from "./queue"; import * as roles from "./roles"; import * as search from "./search"; import * as secrets from "./secrets"; +import * as seo from "./seo"; import * as sessions from "./sessions"; import * as site from "./site"; import * as users from "./users"; @@ -47,6 +48,7 @@ export const coreSchema = { ...roles, ...search, ...secrets, + ...seo, ...sessions, ...site, ...users, diff --git a/packages/api/src/database/seo.ts b/packages/api/src/database/seo.ts new file mode 100644 index 0000000000..f447a5d26b --- /dev/null +++ b/packages/api/src/database/seo.ts @@ -0,0 +1,33 @@ +import { camelCase } from "drizzle-orm/pg-core"; + +import { core_users } from "./users"; + +/** + * Crawling and indexing settings: `robots.txt` and XML sitemaps. One row + * (`id = 1`); a missing row means the defaults (indexing on, sitemaps on). + */ +export const core_seo_settings = camelCase.table.withRLS( + "core_seo_settings", + t => ({ + id: t.integer().primaryKey().default(1), + allowIndexing: t.boolean().notNull().default(true), + blockAiCrawlers: t.boolean().notNull().default(false), + /** Extra `robots.txt` lines appended as written. */ + customRobots: t.text().notNull().default(""), + sitemapEnabled: t.boolean().notNull().default(true), + sitemapMaxUrls: t.integer().notNull().default(10_000), + /** + * Sitemap source ids an admin switched off. Stored as the disabled set, so a + * source a plugin adds later is listed until somebody turns it off. + */ + disabledSitemapSources: t.jsonb().$type().notNull().default([]), + updatedById: t + .integer() + .references(() => core_users.id, { onDelete: "set null" }), + updatedAt: t + .timestamp() + .notNull() + .defaultNow() + .$onUpdate(() => new Date()), + }), +); diff --git a/packages/api/src/events/seo.ts b/packages/api/src/events/seo.ts new file mode 100644 index 0000000000..a10802c4af --- /dev/null +++ b/packages/api/src/events/seo.ts @@ -0,0 +1,25 @@ +import { z } from "zod"; + +import { manifest } from "@/manifest"; + +import { defineEvent } from "../lib/event-definition"; + +/** + * The SEO settings were saved in the AdminCP. Fires after the write has + * committed. + */ +export const seoSettingsUpdatedEvent = defineEvent({ + pluginId: manifest.id, + name: "seo.settings.updated", + payload: z.object({ + allowIndexing: z.boolean(), + blockAiCrawlers: z.boolean(), + sitemapEnabled: z.boolean(), + /** Source ids switched off after this save. */ + disabledSitemapSources: z.array(z.string()), + changedById: z.number().int(), + }), +}); + +/** Every `seo.*` event core defines. */ +export const seoEventDefinitions = [seoSettingsUpdatedEvent]; diff --git a/packages/api/src/lib/core-staff-permissions.ts b/packages/api/src/lib/core-staff-permissions.ts index 8477ed697a..026f4c2ed0 100644 --- a/packages/api/src/lib/core-staff-permissions.ts +++ b/packages/api/src/lib/core-staff-permissions.ts @@ -80,6 +80,7 @@ export const coreStaffPermissions = defineStaffPermissions(manifest, { "can_view", { permission: "can_manage", dependsOn: ["can_view"] }, ], + seo: ["can_view", { permission: "can_manage", dependsOn: ["can_view"] }], cron: ["can_view", { permission: "can_run", dependsOn: ["can_view"] }], activity_logs: [ "can_view", diff --git a/packages/api/src/lib/i18n/locale-routing.ts b/packages/api/src/lib/i18n/locale-routing.ts index 9bcf9eeed7..82a9a17003 100644 --- a/packages/api/src/lib/i18n/locale-routing.ts +++ b/packages/api/src/lib/i18n/locale-routing.ts @@ -11,7 +11,17 @@ import { normalizeHost, resolveLocaleDomains } from "./locale-domains"; import { negotiateLocale } from "./negotiate-locale"; import { compileRoutePaths } from "./route-paths"; -export const DEFAULT_IGNORED_LOCALE_PATHS = ["/admin", "/api"] as const; +/** + * Paths that are never localized: the AdminCP, the API and the crawler files + * (`robots.txt` and sitemaps), which live at the root of the site. + */ +export const DEFAULT_IGNORED_LOCALE_PATHS = [ + "/admin", + "/api", + "/robots.txt", + "/sitemap.xml", + "/sitemaps", +] as const; /** How a locale is (or is not) written into a public URL. */ export type LocalePrefixMode = NonNullable; diff --git a/packages/api/src/lib/plugin.ts b/packages/api/src/lib/plugin.ts index 5bf3671dbe..4fd7dfeda7 100644 --- a/packages/api/src/lib/plugin.ts +++ b/packages/api/src/lib/plugin.ts @@ -54,6 +54,7 @@ import type { ReactionsPluginConfig, ReactionTargetDefinition, } from "./reactions/targets"; +import type { SeoSitemapContribution } from "./seo/config"; import type { WebSocketConfig } from "./websocket"; import { validateSearchIndexers } from "../models/search"; @@ -129,6 +130,8 @@ export interface BuildPluginApiReturn< /** Declared reaction targets plus one per content model with reactions enabled. */ reactions?: Required; searchIndexers?: SearchIndexer[]; + /** Pages and sources the plugin adds to the sitemap. */ + sitemap?: SeoSitemapContribution; webSockets?: Omit[]; } @@ -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 ( +
+ + + +
+ + + + + + +
+ + +
+ +
+
+ +
+ 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 ( + + ); +}; + +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 ( + + + ); +}; + +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 ? ( + + + ) : ( + format.number(source.urls) + )} + + + {format.number(source.files)} + + + {served && source.enabled && source.urls > 0 ? ( + + + ) : ( + + {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: [