Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
51 changes: 51 additions & 0 deletions scripts/agent-discovery.test.mjs
Original file line number Diff line number Diff line change
@@ -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(
'<html><head><title>Tours &amp; More</title></head><body><nav>Menu</nav><main><h2>Iceland</h2><p>See <a href="/tours/iceland">the <b>tour</b></a>.</p><ul><li>One</li><li>Two</li></ul><script>alert(1)</script><form><input></form></main></body></html>',
'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$/);
});
31 changes: 31 additions & 0 deletions scripts/smoke-cms.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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(`<loc>${origin}${homePath}</loc>`), 'sitemap must list the home page');
if (formPath) assert.ok(sitemapText.includes(`${origin}${formPath}</loc>`), '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', {
Expand Down
7 changes: 6 additions & 1 deletion src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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,
Expand Down Expand Up @@ -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);
10 changes: 10 additions & 0 deletions src/lib/agent.ts
Original file line number Diff line number Diff line change
@@ -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';
112 changes: 112 additions & 0 deletions src/lib/server/agent-discovery.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
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 = [
'</.well-known/api-catalog>; rel="api-catalog"',
'</sitemap.xml>; rel="sitemap"; type="application/xml"',
'</.well-known/mcp/server-card.json>; rel="describedby"; type="application/json"',
'</.well-known/agent-skills/index.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(/&nbsp;/g, ' ')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#0?39;|&apos;/g, "'")
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
.replace(/&amp;/g, '&');

/** Small, dependency-free HTML to Markdown conversion for server-rendered pages. */
export function htmlToMarkdown(html: string, origin: string): string {
const title = decode(/<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1]?.trim() ?? '');
let body = /<main[\s\S]*?>([\s\S]*?)<\/main>/i.exec(html)?.[1] ?? /<body[^>]*>([\s\S]*)<\/body>/i.exec(html)?.[1] ?? html;
body = body
.replace(/<!--[\s\S]*?-->/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(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi, (_, l, t) => `\n\n${'#'.repeat(Number(l))} ${t}\n\n`)
.replace(/<a\b[^>]*?href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi, (_, h, t) => (t.replace(/<[^>]+>/g, '').trim() ? `[${t.replace(/<[^>]+>/g, '').trim()}](${abs(decode(h))})` : ''))
.replace(/<img\b[^>]*?alt="([^"]*)"[^>]*>/gi, (_, a) => (a ? `*${a}*` : ''))
.replace(/<(strong|b)\b[^>]*>([\s\S]*?)<\/\1>/gi, '**$2**')
.replace(/<(em|i)\b[^>]*>([\s\S]*?)<\/\1>/gi, '*$2*')
.replace(/<li\b[^>]*>/gi, '\n- ')
.replace(/<br\s*\/?>/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 });
};
13 changes: 13 additions & 0 deletions src/lib/server/sitemap-extra.ts
Original file line number Diff line number Diff line change
@@ -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<SitemapEntry[]> {
return [];
}
11 changes: 11 additions & 0 deletions src/routes/.well-known/agent-skills/[name]/SKILL.md/+server.ts
Original file line number Diff line number Diff line change
@@ -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': '*' }
});
};
21 changes: 21 additions & 0 deletions src/routes/.well-known/agent-skills/index.json/+server.ts
Original file line number Diff line number Diff line change
@@ -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': '*' }
});
};
24 changes: 24 additions & 0 deletions src/routes/.well-known/api-catalog/+server.ts
Original file line number Diff line number Diff line change
@@ -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': '*' }
});
};
25 changes: 25 additions & 0 deletions src/routes/.well-known/mcp/server-card.json/+server.ts
Original file line number Diff line number Diff line change
@@ -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': '*' }
});
};
18 changes: 18 additions & 0 deletions src/routes/robots.txt/+server.ts
Original file line number Diff line number Diff line change
@@ -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' } });
};
Loading
Loading