From 6e7b2982051cfdbe6bd8728637d7b67d010c5e70 Mon Sep 17 00:00:00 2001 From: Max Farrell Date: Sun, 8 Nov 2026 12:56:47 -0600 Subject: [PATCH] Add agent readiness: robots.txt, sitemap, discovery documents, Link headers, Markdown negotiation Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 1 + scripts/agent-discovery.test.mjs | 51 ++++++++ scripts/smoke-cms.mjs | 31 +++++ src/hooks.server.ts | 7 +- src/lib/agent.ts | 10 ++ src/lib/server/agent-discovery.ts | 112 ++++++++++++++++++ src/lib/server/sitemap-extra.ts | 13 ++ .../agent-skills/[name]/SKILL.md/+server.ts | 11 ++ .../agent-skills/index.json/+server.ts | 21 ++++ src/routes/.well-known/api-catalog/+server.ts | 24 ++++ .../mcp/server-card.json/+server.ts | 25 ++++ src/routes/robots.txt/+server.ts | 18 +++ src/routes/sitemap.xml/+server.ts | 33 ++++++ 13 files changed, 356 insertions(+), 1 deletion(-) create mode 100644 scripts/agent-discovery.test.mjs create mode 100644 src/lib/agent.ts create mode 100644 src/lib/server/agent-discovery.ts create mode 100644 src/lib/server/sitemap-extra.ts create mode 100644 src/routes/.well-known/agent-skills/[name]/SKILL.md/+server.ts create mode 100644 src/routes/.well-known/agent-skills/index.json/+server.ts create mode 100644 src/routes/.well-known/api-catalog/+server.ts create mode 100644 src/routes/.well-known/mcp/server-card.json/+server.ts create mode 100644 src/routes/robots.txt/+server.ts create mode 100644 src/routes/sitemap.xml/+server.ts diff --git a/AGENTS.md b/AGENTS.md index 5bb9143..f9e8aa0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,7 @@ Read `skills/orangecms-setup/SKILL.md` for project setup or source customization - For a new local database, run `pnpm db:migrate:local`. Optional neutral content is installed separately with `pnpm db:seed:local`. Initial migrations create schema; collections and custom fields are data, so they do not require new SQL migrations. - Keep existing consumers' migration history and private configuration intact. Add schema changes as new migrations; never reset an existing database to initialize a project. - Configure branding, public routes, navigation, setting editors, and the public-settings allowlist in `src/lib/site.ts`. `/admin`, `/api`, `/files`, `/mcp`, `/oauth`, and `/.well-known` are reserved endpoints. +- Agent readiness is built in: dynamic `/robots.txt`, `/sitemap.xml`, `/.well-known/{api-catalog,mcp/server-card.json,agent-skills/*}`, discovery `Link` headers, and `Accept: text/markdown` negotiation (hooks only; pages served as static assets bypass them). Tune it with the optional `site.agent` (`AgentConfig` in `src/lib/agent.ts`); consumers with routes outside `site.routes` replace `src/lib/server/sitemap-extra.ts`. - Public settings are opt-in. Sensitive form answers require `FORM_DATA_KEY`, are encrypted in D1, and are excluded from email/MCP. Production admin/upload routes verify Cloudflare Access JWTs and fail closed when unconfigured. - Uploads use optional `FILES_KV` only, with no R2 fallback. Verify the deployment account is Workers Free before provisioning or enabling remote storage; leave it unconfigured when verification is unavailable. `FILES_KV` and `OAUTH_KV` are separate namespaces sharing account quotas. - OAuth connections use `/mcp/authorized`, per-site `OAUTH_KV`, Access-protected `/admin/oauth/authorize`, and explicit read/edit consent. Keep protocol/discovery endpoints outside edge Access; retain `/mcp` anonymous/static-token compatibility. Connected apps and API tokens revoke separately. diff --git a/scripts/agent-discovery.test.mjs b/scripts/agent-discovery.test.mjs new file mode 100644 index 0000000..f5e20fa --- /dev/null +++ b/scripts/agent-discovery.test.mjs @@ -0,0 +1,51 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import ts from 'typescript'; + +async function load(t) { + const temp = await mkdtemp(join(tmpdir(), 'orangecms-agent-test-')); + t.after(() => rm(temp, { recursive: true, force: true })); + await mkdir(join(temp, 'src/lib/server'), { recursive: true }); + await writeFile(join(temp, 'package.json'), JSON.stringify({ type: 'module', imports: { '#lib/*': './src/lib/*' } })); + for (const file of ['server/agent-discovery', 'agent', 'site', 'routing']) { + const source = await readFile(new URL(`../src/lib/${file}.ts`, import.meta.url), 'utf8'); + const out = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }).outputText; + await writeFile(join(temp, `src/lib/${file}.js`), out); + } + return import(pathToFileURL(join(temp, 'src/lib/server/agent-discovery.js')).href); +} + +test('Markdown is chosen only when it is preferred over HTML', async (t) => { + const { wantsMarkdown } = await load(t); + assert.equal(wantsMarkdown('text/markdown'), true); + assert.equal(wantsMarkdown('text/markdown, text/html;q=0.5'), true); + assert.equal(wantsMarkdown('text/html,application/xhtml+xml,*/*;q=0.8'), false); + assert.equal(wantsMarkdown('*/*'), false); + assert.equal(wantsMarkdown('text/html, text/markdown;q=0.1'), false); + assert.equal(wantsMarkdown(null), false); +}); + +test('HTML converts to Markdown without markup, scripts, navigation or forms', async (t) => { + const { htmlToMarkdown } = await load(t); + const md = htmlToMarkdown( + 'Tours & More

Iceland

See the tour.

  • One
  • Two
', + 'https://example.test', + ); + assert.match(md, /^# Tours & More/); + assert.ok(md.includes('## Iceland')); + assert.ok(md.includes('[the tour](https://example.test/tours/iceland)'), md); + assert.ok(md.includes('- One') && md.includes('- Two')); + for (const leaked of ['<', 'alert', 'Menu']) assert.ok(!md.includes(leaked), leaked); +}); + +test('a generic skill is derived from the site identity unless one is configured', async (t) => { + const { agentSkill, sha256Hex } = await load(t); + const skill = agentSkill(); + assert.match(skill.name, /^[a-z0-9-]+$/); + assert.ok(skill.body.startsWith('---\nname: ' + skill.name)); + assert.match(await sha256Hex('x'), /^2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881$/); +}); diff --git a/scripts/smoke-cms.mjs b/scripts/smoke-cms.mjs index 35d7f1d..2fe15c8 100644 --- a/scripts/smoke-cms.mjs +++ b/scripts/smoke-cms.mjs @@ -626,6 +626,37 @@ try { ); } console.log('PASS MCP endpoint serves public tools and gates admin tools'); + // Agent readiness: robots, sitemap, Link headers, Markdown negotiation, discovery documents. + const robots = await (await fetch(origin + '/robots.txt')).text(); + assert.ok( + /User-agent: \*/.test(robots) && + /Content-Signal: /.test(robots) && + robots.includes(`Sitemap: ${origin}/sitemap.xml`) && + robots.includes('Disallow: /admin'), + 'robots.txt must be valid and point to the sitemap', + ); + const sitemap = await fetch(origin + '/sitemap.xml'); + assert.match(sitemap.headers.get('content-type') ?? '', /xml/); + const sitemapText = await sitemap.text(); + if (homePath) assert.ok(sitemapText.includes(`${origin}${homePath}`), 'sitemap must list the home page'); + if (formPath) assert.ok(sitemapText.includes(`${origin}${formPath}`), 'sitemap must list online forms'); + assert.ok(!sitemapText.includes('/admin'), 'sitemap must not list admin routes'); + const landing = await fetch(origin + (homePath ?? contentPath)); + assert.match(landing.headers.get('link') ?? '', /rel="api-catalog"/, 'pages must advertise the API catalog'); + assert.match(landing.headers.get('content-type') ?? '', /text\/html/, 'default representation stays HTML'); + const markdown = await fetch(origin + (homePath ?? contentPath), { headers: { Accept: 'text/markdown' } }); + assert.match(markdown.headers.get('content-type') ?? '', /text\/markdown/, 'Accept: text/markdown must return Markdown'); + assert.ok(!(await markdown.text()).includes('<'), 'Markdown must not contain markup'); + const browser = await fetch(origin + (homePath ?? contentPath), { headers: { Accept: 'text/html,*/*;q=0.8' } }); + assert.match(browser.headers.get('content-type') ?? '', /text\/html/); + assert.match((await fetch(origin + '/.well-known/api-catalog')).headers.get('content-type') ?? '', /linkset\+json/); + assert.equal((await (await fetch(origin + '/.well-known/mcp/server-card.json')).json()).transport.endpoint, '/mcp'); + const skills = (await (await fetch(origin + '/.well-known/agent-skills/index.json')).json()).skills[0]; + const skillText = await (await fetch(skills.url.replace(/^https?:\/\/[^/]+/, origin))).text(); + const digest = [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(skillText)))].map((b) => b.toString(16).padStart(2, '0')).join(''); + assert.equal(skills.digest, `sha256:${digest}`, 'skill digest must match its content'); + assert.equal((await fetch(origin + '/.well-known/agent-skills/nope/SKILL.md')).status, 404); + console.log('PASS agent discovery: robots, sitemap, Link headers, Markdown negotiation, discovery documents'); await testOAuth({ origin, adminJwt }); // Tokens created in the admin UI authorize MCP; revoking them disables access. const createdToken = await fetch(origin + '/admin/tokens?/create', { diff --git a/src/hooks.server.ts b/src/hooks.server.ts index ecd52ce..eadfd4b 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -2,7 +2,9 @@ import { handleOAuthProtocolRequest } from '#lib/server/oauth.js'; import { site } from '#lib/site.js'; import { env } from 'cloudflare:workers'; import { dev } from '$app/env'; +import { sequence } from '@sveltejs/kit/hooks'; import type { Handle } from '@sveltejs/kit/hooks'; +import { agentReadiness } from '#lib/server/agent-discovery.js'; import { createRemoteJWKSet, jwtVerify } from 'jose'; let cachedKeys: @@ -17,7 +19,7 @@ let cachedKeys: const CANONICAL_HOST = site.canonicalHost; const ALIAS_HOSTS = new Set(site.aliasHosts.map((host) => host.toLowerCase())); -export const handle: Handle = async ({ event, resolve }) => { +const coreHandle: Handle = async ({ event, resolve }) => { if (CANONICAL_HOST && ALIAS_HOSTS.has(event.url.hostname.toLowerCase())) { return new Response(null, { status: 308, @@ -81,3 +83,6 @@ export const handle: Handle = async ({ event, resolve }) => { return resolve(event); }; + +// Agent readiness (discovery Link headers, Markdown negotiation) wraps the core handling. +export const handle = sequence(agentReadiness, coreHandle); diff --git a/src/lib/agent.ts b/src/lib/agent.ts new file mode 100644 index 0000000..c95e11d --- /dev/null +++ b/src/lib/agent.ts @@ -0,0 +1,10 @@ +/** Optional agent-discovery settings. Every field has a sensible default. */ +export interface AgentConfig { + /** Extra robots.txt Disallow paths. /admin, /api/ and /oauth/ are always disallowed. */ + robotsDisallow?: string[]; + /** Content Signals policy (contentsignals.org), published in robots.txt. */ + contentSignals?: string; + /** An agent skill (SKILL.md) served under /.well-known/agent-skills. */ + skill?: { name: string; description: string; body: string }; +} +export const DEFAULT_CONTENT_SIGNALS = 'search=yes, ai-input=yes, ai-train=no'; diff --git a/src/lib/server/agent-discovery.ts b/src/lib/server/agent-discovery.ts new file mode 100644 index 0000000..7fedadf --- /dev/null +++ b/src/lib/server/agent-discovery.ts @@ -0,0 +1,112 @@ +import { site } from '#lib/site.js'; +import type { AgentConfig } from '#lib/agent.js'; +import { DEFAULT_CONTENT_SIGNALS } from '#lib/agent.js'; +import type { Handle } from '@sveltejs/kit/hooks'; + +/** `site.agent` is optional so consumer site.ts files that predate it keep working. */ +export const agentConfig = (): AgentConfig => (site as { agent?: AgentConfig }).agent ?? {}; +export const contentSignals = () => agentConfig().contentSignals ?? DEFAULT_CONTENT_SIGNALS; + +/** The skill served to agents: the site's own, else a generic one built from its identity. */ +export function agentSkill() { + const configured = agentConfig().skill; + if (configured) return configured; + const slug = + site.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'site'; + return { + name: slug, + description: `Find and read the public content of ${site.name} via the website or its MCP endpoint.`, + body: `---\nname: ${slug}\ndescription: Find and read the public content of ${site.name} via the website or its MCP endpoint.\n---\n\n# ${site.name}\n\n${site.description}\n\n## Read the site\n\n- Every public page can be fetched as Markdown by sending \`Accept: text/markdown\`.\n- \`/sitemap.xml\` lists all public pages.\n\n## MCP\n\n\`POST /mcp\` (Streamable HTTP, JSON) exposes published content with no credentials. Call \`tools/list\` to discover tools. Administrative access is at \`/mcp/authorized\` with OAuth (\`/.well-known/oauth-authorization-server\`); request edit scope only when editing is the task.\n` + }; +} + +export async function sha256Hex(text: string): Promise { + return [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))] + .map((b) => b.toString(16).padStart(2, '0')) + .join(''); +} + +/** RFC 8288 Link header advertising the machine-readable descriptions of the site. */ +export const DISCOVERY_LINKS = [ + '; rel="api-catalog"', + '; rel="sitemap"; type="application/xml"', + '; rel="describedby"; type="application/json"', + '; rel="describedby"; type="application/json"' +].join(', '); + +const SKIP = /^\/(admin|api|mcp|oauth|files|\.well-known|cdn-cgi|_app)(\/|$)/; + +/** Whether the client prefers Markdown over HTML (Accept: text/markdown). */ +export function wantsMarkdown(accept: string | null): boolean { + if (!accept) return false; + let md = 0; + let html = 0; + for (const part of accept.split(',')) { + const [type, ...params] = part.trim().toLowerCase().split(';'); + const q = Number(params.map((p) => p.trim()).find((p) => p.startsWith('q='))?.slice(2) ?? 1); + if (type === 'text/markdown') md = Math.max(md, q); + else if (type === 'text/html' || type === 'application/xhtml+xml') html = Math.max(html, q); + } + return md > 0 && md >= html; +} + +const decode = (s: string) => + s + .replace(/ /g, ' ') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/�?39;|'/g, "'") + .replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))) + .replace(/&/g, '&'); + +/** Small, dependency-free HTML to Markdown conversion for server-rendered pages. */ +export function htmlToMarkdown(html: string, origin: string): string { + const title = decode(/]*>([\s\S]*?)<\/title>/i.exec(html)?.[1]?.trim() ?? ''); + let body = /([\s\S]*?)<\/main>/i.exec(html)?.[1] ?? /]*>([\s\S]*)<\/body>/i.exec(html)?.[1] ?? html; + body = body + .replace(//g, '') + .replace(/<(script|style|svg|nav|footer|form|noscript|template|button)\b[\s\S]*?<\/\1>/gi, ''); + const abs = (href: string) => { + try { return new URL(href, origin).href; } catch { return href; } + }; + body = body + .replace(/]*>([\s\S]*?)<\/h\1>/gi, (_, l, t) => `\n\n${'#'.repeat(Number(l))} ${t}\n\n`) + .replace(/]*?href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi, (_, h, t) => (t.replace(/<[^>]+>/g, '').trim() ? `[${t.replace(/<[^>]+>/g, '').trim()}](${abs(decode(h))})` : '')) + .replace(/]*?alt="([^"]*)"[^>]*>/gi, (_, a) => (a ? `*${a}*` : '')) + .replace(/<(strong|b)\b[^>]*>([\s\S]*?)<\/\1>/gi, '**$2**') + .replace(/<(em|i)\b[^>]*>([\s\S]*?)<\/\1>/gi, '*$2*') + .replace(/]*>/gi, '\n- ') + .replace(//gi, '\n') + .replace(/<\/(p|div|section|article|ul|ol|tr|header|figure|blockquote)>/gi, '\n\n') + .replace(/<[^>]+>/g, ''); + const text = decode(body) + .split('\n') + .map((l) => l.replace(/[ \t]+/g, ' ').trim()) + .join('\n') + .replace(/\n{3,}/g, '\n\n') + .trim(); + return (/^# /m.test(text) || !title ? text : `# ${title}\n\n${text}`) + '\n'; +} + +/** Adds discovery Link headers to pages and serves Markdown to clients that ask for it. */ +export const agentReadiness: Handle = async ({ event, resolve }) => { + const response = await resolve(event); + const readOnly = event.request.method === 'GET' || event.request.method === 'HEAD'; + if (!readOnly || SKIP.test(event.url.pathname) || response.status !== 200) return response; + if (!response.headers.get('content-type')?.includes('text/html')) return response; + if (!wantsMarkdown(event.request.headers.get('accept'))) { + const headers = new Headers(response.headers); + headers.append('Link', DISCOVERY_LINKS); + return new Response(response.body, { status: response.status, headers }); + } + const markdown = htmlToMarkdown(await response.text(), event.url.origin); + const headers = new Headers(response.headers); + headers.set('Content-Type', 'text/markdown; charset=utf-8'); + headers.set('Vary', 'Accept'); + headers.set('x-markdown-tokens', String(Math.ceil(markdown.length / 4))); + headers.append('Link', DISCOVERY_LINKS); + headers.delete('content-length'); + headers.delete('content-encoding'); + return new Response(event.request.method === 'HEAD' ? null : markdown, { status: 200, headers }); +}; diff --git a/src/lib/server/sitemap-extra.ts b/src/lib/server/sitemap-extra.ts new file mode 100644 index 0000000..d6b5b6c --- /dev/null +++ b/src/lib/server/sitemap-extra.ts @@ -0,0 +1,13 @@ +import type { D1Database } from '@cloudflare/workers-types'; + +/** + * Public URLs that live outside `site.routes` (a consumer's own routes) and belong in + * /sitemap.xml. Consumers replace this file; the shared core has none. + */ +export interface SitemapEntry { + path: string; + lastmod?: string; +} +export async function extraSitemapEntries(_db: D1Database): Promise { + return []; +} diff --git a/src/routes/.well-known/agent-skills/[name]/SKILL.md/+server.ts b/src/routes/.well-known/agent-skills/[name]/SKILL.md/+server.ts new file mode 100644 index 0000000..d4ec7f7 --- /dev/null +++ b/src/routes/.well-known/agent-skills/[name]/SKILL.md/+server.ts @@ -0,0 +1,11 @@ +import { agentSkill } from '#lib/server/agent-discovery.js'; +import { error } from '@sveltejs/kit'; +import type { RequestHandler } from './$types'; + +export const GET: RequestHandler = ({ params }) => { + const skill = agentSkill(); + if (params.name !== skill.name) error(404, 'Not found'); + return new Response(skill.body, { + headers: { 'Content-Type': 'text/markdown; charset=utf-8', 'Cache-Control': 'public, max-age=3600', 'Access-Control-Allow-Origin': '*' } + }); +}; diff --git a/src/routes/.well-known/agent-skills/index.json/+server.ts b/src/routes/.well-known/agent-skills/index.json/+server.ts new file mode 100644 index 0000000..c602616 --- /dev/null +++ b/src/routes/.well-known/agent-skills/index.json/+server.ts @@ -0,0 +1,21 @@ +import { agentSkill, sha256Hex } from '#lib/server/agent-discovery.js'; +import type { RequestHandler } from './$types'; + +export const GET: RequestHandler = async ({ url }) => { + const skill = agentSkill(); + const body = { + $schema: 'https://schemas.agentskills.io/discovery/0.2.0/schema.json', + skills: [ + { + name: skill.name, + type: 'skill-md', + description: skill.description, + url: `${url.origin}/.well-known/agent-skills/${skill.name}/SKILL.md`, + digest: `sha256:${await sha256Hex(skill.body)}` + } + ] + }; + return new Response(JSON.stringify(body), { + headers: { 'Content-Type': 'application/json', 'Cache-Control': 'public, max-age=3600', 'Access-Control-Allow-Origin': '*' } + }); +}; diff --git a/src/routes/.well-known/api-catalog/+server.ts b/src/routes/.well-known/api-catalog/+server.ts new file mode 100644 index 0000000..0688f9b --- /dev/null +++ b/src/routes/.well-known/api-catalog/+server.ts @@ -0,0 +1,24 @@ +import { agentSkill } from '#lib/server/agent-discovery.js'; +import type { RequestHandler } from './$types'; + +// RFC 9727 API catalog (a linkset, RFC 9264) pointing agents at the site's machine interfaces. +export const GET: RequestHandler = ({ url }) => { + const o = url.origin; + const body = { + linkset: [ + { + anchor: `${o}/mcp`, + 'service-desc': [{ href: `${o}/.well-known/mcp/server-card.json`, type: 'application/json' }], + 'service-doc': [{ href: `${o}/.well-known/agent-skills/${agentSkill().name}/SKILL.md`, type: 'text/markdown' }], + status: [{ href: `${o}/mcp`, type: 'application/json' }] + }, + { + anchor: `${o}/mcp/authorized`, + 'service-desc': [{ href: `${o}/.well-known/oauth-authorization-server`, type: 'application/json' }] + } + ] + }; + return new Response(JSON.stringify(body), { + headers: { 'Content-Type': 'application/linkset+json', 'Cache-Control': 'public, max-age=3600', 'Access-Control-Allow-Origin': '*' } + }); +}; diff --git a/src/routes/.well-known/mcp/server-card.json/+server.ts b/src/routes/.well-known/mcp/server-card.json/+server.ts new file mode 100644 index 0000000..1acbd4f --- /dev/null +++ b/src/routes/.well-known/mcp/server-card.json/+server.ts @@ -0,0 +1,25 @@ +import { site } from '#lib/site.js'; +import { agentSkill } from '#lib/server/agent-discovery.js'; +import type { RequestHandler } from './$types'; + +export const GET: RequestHandler = ({ url }) => { + const body = { + $schema: 'https://static.modelcontextprotocol.io/schemas/2025-12-11/server-card.schema.json', + version: '1.0.0', + protocolVersion: '2025-06-18', + serverInfo: { name: site.mcpName, title: `${site.name} content`, version: '1.0.0' }, + description: `Read ${site.name}'s published content. Administrative tools need OAuth sign-in.`, + documentationUrl: `${url.origin}/.well-known/agent-skills/${agentSkill().name}/SKILL.md`, + transport: { type: 'streamable-http', endpoint: '/mcp' }, + capabilities: { tools: { listChanged: false } }, + authentication: { + required: false, + schemes: ['oauth2'], + authorizationServer: `${url.origin}/.well-known/oauth-authorization-server`, + note: 'Public tools work anonymously on /mcp; /mcp/authorized requires OAuth.' + } + }; + return new Response(JSON.stringify(body), { + headers: { 'Content-Type': 'application/json', 'Cache-Control': 'public, max-age=3600', 'Access-Control-Allow-Origin': '*' } + }); +}; diff --git a/src/routes/robots.txt/+server.ts b/src/routes/robots.txt/+server.ts new file mode 100644 index 0000000..6851aa7 --- /dev/null +++ b/src/routes/robots.txt/+server.ts @@ -0,0 +1,18 @@ +import { agentConfig, contentSignals } from '#lib/server/agent-discovery.js'; +import type { RequestHandler } from './$types'; + +export const GET: RequestHandler = ({ url }) => { + const disallow = ['/admin', '/api/', '/oauth/', ...(agentConfig().robotsDisallow ?? [])]; + const body = [ + '# Public pages are open to search engines and AI agents; the admin area and', + '# authenticated endpoints are not for crawlers.', + 'User-agent: *', + `Content-Signal: ${contentSignals()}`, + 'Allow: /', + ...disallow.map((p) => `Disallow: ${p}`), + '', + `Sitemap: ${url.origin}/sitemap.xml`, + '' + ].join('\n'); + return new Response(body, { headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'public, max-age=3600' } }); +}; diff --git a/src/routes/sitemap.xml/+server.ts b/src/routes/sitemap.xml/+server.ts new file mode 100644 index 0000000..74af609 --- /dev/null +++ b/src/routes/sitemap.xml/+server.ts @@ -0,0 +1,33 @@ +import { env } from 'cloudflare:workers'; +import { site } from '#lib/site.js'; +import { getEntries, getForms } from '#lib/server/db.js'; +import { extraSitemapEntries, type SitemapEntry } from '#lib/server/sitemap-extra.js'; +import type { RequestHandler } from './$types'; + +const esc = (s: string) => s.replace(/&/g, '&').replace(//g, '>'); +const fill = (path: string, slug: string) => path.replace(/:[a-zA-Z_][a-zA-Z0-9_]*/, encodeURIComponent(slug)); + +export const GET: RequestHandler = async ({ url }) => { + const entries = new Map(); + const add = (e: SitemapEntry) => { if (!entries.has(e.path)) entries.set(e.path, e); }; + for (const r of site.routes) if (!r.path.includes(':')) add({ path: r.path }); + const db = env.DB; + if (db) { + try { + for (const r of site.routes) { + if (r.kind === 'entry' && r.collection) + for (const e of await getEntries(db, r.collection, true)) + add({ path: fill(r.path, e.slug), lastmod: e.updated_at?.slice(0, 10) }); + if (r.kind === 'form') + for (const f of await getForms(db)) if (f.slug) add({ path: fill(r.path, f.slug) }); + } + for (const e of await extraSitemapEntries(db)) add(e); + } catch { + // Serve the static pages even if the database is unavailable. + } + } + const body = `\n\n${[...entries.values()] + .map((e) => `${esc(url.origin + e.path)}${e.lastmod ? `${e.lastmod}` : ''}`) + .join('\n')}\n\n`; + return new Response(body, { headers: { 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' } }); +};