import { Hono } from 'hono'; import type { AppEnv, Ctx, Env } from './env'; import { PROMPTS } from './content/prompts'; import { processAiQueue } from './lib/ai'; import { refreshAllStale } from './lib/github'; import { processImportQueue } from './lib/imports'; import { pruneRateLimits } from './lib/ratelimit'; import { loadSessionUser, takeFlash } from './lib/session'; import { DAY, HttpError, now } from './lib/util'; import { registerAdmin } from './routes/admin'; import { registerAuth } from './routes/auth'; import { registerMcp } from './routes/mcp'; import { registerOAuth } from './routes/oauth'; import { registerPages } from './routes/pages'; import { registerSettings } from './routes/settings'; import { registerSkills } from './routes/skills'; import { Empty } from './views/components'; import { render } from './views/layout'; const app = new Hono(); /** Requests that are answered for programs, not browsers: no cookies are read and no session is loaded. */ const isMachinePath = (p: string) => p === '/mcp' || p.startsWith('/mcp/') || p === '/oauth/token' || p === '/oauth/register' || p === '/oauth/revoke' || p.startsWith('/.well-known/'); const wantsJson = (c: Ctx) => c.req.path.startsWith('/api/') || isMachinePath(c.req.path) || (c.req.header('accept') ?? '').includes('application/json'); const CSP = [ "default-src 'self'", "script-src 'self' https://www.googletagmanager.com", "style-src 'self' 'unsafe-inline'", "img-src 'self' data: blob: https://avatars.githubusercontent.com https://*.googleusercontent.com https://www.googletagmanager.com https://*.google-analytics.com", "font-src 'self'", "connect-src 'self' https://projectatom.ai https://*.google-analytics.com https://*.analytics.google.com https://www.googletagmanager.com", "object-src 'none'", "base-uri 'self'", "frame-ancestors 'none'", ]; // Canonical host and old addresses. app.use('*', async (c, next) => { const url = new URL(c.req.url); const www = url.hostname === 'www.skillfarm.ai'; // Plain http is only allowed on a development machine. const plain = url.protocol === 'http:' && (www || url.hostname === 'skillfarm.ai' || url.hostname.endsWith('.workers.dev')); if (www || plain) { if (www) url.hostname = 'skillfarm.ai'; url.protocol = 'https:'; return c.redirect(url.toString(), 308); } await next(); }); app.get('/waitlist', (c) => c.redirect('/', 308)); app.get('/apply', (c) => c.redirect('/signin', 308)); // Security headers on everything the Worker answers. app.use('*', async (c, next) => { await next(); const h = c.res.headers; h.set('x-content-type-options', 'nosniff'); h.set('referrer-policy', 'strict-origin-when-cross-origin'); h.set('permissions-policy', 'camera=(), microphone=(), geolocation=(), interest-cohort=()'); if (new URL(c.req.url).protocol === 'https:') h.set('strict-transport-security', 'max-age=31536000; includeSubDomains'); if ((h.get('content-type') ?? '').includes('text/html')) { // The consent screen hands the browser back to the app that asked, so it cannot pin form targets to this site. h.set('content-security-policy', [...CSP, ...(c.req.path === '/oauth/authorize' ? [] : ["form-action 'self'"])].join('; ')); h.set('x-frame-options', 'DENY'); if (!h.has('cache-control')) h.set('cache-control', 'private, no-store'); } }); // Cross-site request forgery: a browser request that changes something must come from our own pages. app.use('*', async (c, next) => { const method = c.req.method; if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS' || isMachinePath(c.req.path)) return next(); const here = new URL(c.req.url).origin; const origin = c.req.header('origin'); const site = c.req.header('sec-fetch-site'); const ok = origin ? origin === here : site === 'same-origin'; if (!ok) throw new HttpError(403, 'That request did not come from Skillfarm. Go back, reload the page and try again.', 'bad_origin'); return next(); }); // Who is asking. app.use('*', async (c, next) => { c.set('user', null); c.set('flash', null); if (isMachinePath(c.req.path)) return next(); if (c.env.SESSION_SECRET) c.set('user', await loadSessionUser(c)); const p = c.req.path; if (c.req.method === 'GET' && !p.startsWith('/api/') && !p.startsWith('/avatars/') && !p.startsWith('/auth/') && !p.endsWith('/download')) c.set('flash', takeFlash(c)); return next(); }); registerAuth(app); registerOAuth(app); registerMcp(app); registerPages(app); registerSkills(app); registerSettings(app); registerAdmin(app); app.get('/robots.txt', (c) => c.text( ['User-agent: *', 'Disallow: /admin', 'Disallow: /settings', 'Disallow: /auth/', 'Disallow: /oauth/', 'Disallow: /api/', 'Disallow: /mcp', 'Disallow: /signin', 'Disallow: /share', '', `Sitemap: ${c.env.SITE_URL}/sitemap.xml`, ''].join('\n'), 200, { 'cache-control': 'public, max-age=3600' }, ), ); app.get('/sitemap.xml', async (c) => { const site = c.env.SITE_URL; const [skills, growers] = await Promise.all([ c.env.DB.prepare("SELECT u.handle, s.slug, s.updated_at FROM skills s JOIN users u ON u.id = s.owner_id WHERE s.state = 'live' ORDER BY s.published_at DESC LIMIT 5000").all<{ handle: string; slug: string; updated_at: number }>(), c.env.DB.prepare("SELECT u.handle FROM users u WHERE u.status = 'active' AND EXISTS (SELECT 1 FROM skills s WHERE s.owner_id = u.id AND s.state = 'live') LIMIT 5000").all<{ handle: string }>(), ]); const urls = ['/', '/skills', '/prompts', '/growers', '/leaderboard', '/seeds', '/connect', '/help', '/guidelines', '/privacy', '/research', ...PROMPTS.map((p) => `/prompts/${p.slug}`)].map((p) => `${site}${p}`); for (const s of skills.results) urls.push(`${site}/skills/${s.handle}/${s.slug}${new Date(s.updated_at * 1000).toISOString().slice(0, 10)}`); for (const g of growers.results) urls.push(`${site}/u/${g.handle}`); return c.body(`\n\n${urls.join('\n')}\n\n`, 200, { 'content-type': 'application/xml; charset=utf-8', 'cache-control': 'public, max-age=3600', }); }); app.notFound((c) => { if (wantsJson(c)) return c.json({ error: 'not_found', message: 'Nothing here.' }, 404); return render( c, { title: 'Nothing planted here', noindex: true },

That page does not exist, or it was moved. The skills are still where you left them.

Browse skills Go home

, 404, ); }); const TITLES: Record = { 400: 'That did not work', 401: 'Sign in first', 403: 'Not allowed', 404: 'Nothing planted here', 409: 'That did not work', 413: 'Too large', 429: 'Slow down a little', 503: 'Not ready yet' }; app.onError((err, c) => { const known = err instanceof HttpError; const status = known ? err.status : 500; if (!known) console.error('unhandled', c.req.method, c.req.path, err); const message = known ? err.message : 'Something broke on our side. Try again in a moment.'; if (wantsJson(c)) return c.json({ error: known ? err.code : 'server_error', message }, status as 500); if (status === 401 && c.req.method === 'GET') { const u = new URL(c.req.url); return c.redirect(`/signin?next=${encodeURIComponent(u.pathname + u.search)}`); } return render( c, { title: TITLES[status] ?? 'Something went wrong', noindex: true },

{message}

{status === 401 ? Sign in : Go home}

, status, ); }); /** Housekeeping that keeps the tables small. Nothing here touches member content. */ async function daily(env: Env): Promise { const ts = now(); await refreshAllStale(env, 80).catch((e) => console.error('star refresh failed', e)); await pruneRateLimits(env); await env.DB.batch([ env.DB.prepare('DELETE FROM sessions WHERE expires_at < ?').bind(ts), env.DB.prepare('DELETE FROM oauth_codes WHERE expires_at < ?').bind(ts), env.DB.prepare('DELETE FROM api_tokens WHERE (expires_at IS NOT NULL AND expires_at < ?1) OR (revoked_at IS NOT NULL AND revoked_at < ?1)').bind(ts - 7 * DAY), env.DB.prepare('DELETE FROM oauth_clients WHERE created_at < ? AND client_id NOT IN (SELECT client_id FROM api_tokens WHERE client_id IS NOT NULL)').bind(ts - 30 * DAY), env.DB.prepare('DELETE FROM email_log WHERE created_at < ?').bind(ts - 90 * DAY), ]); } export default { fetch: app.fetch, async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext): Promise { if (event.cron === '*/2 * * * *') { // Finish reading shared repos first, so their skills are in the queue the AI review works through. ctx.waitUntil( processImportQueue(env, ctx) .catch((e) => console.error('repo share queue failed', e)) .then(() => processAiQueue(env)) .catch((e) => console.error('ai queue failed', e)), ); } else ctx.waitUntil(daily(env).catch((e) => console.error('daily job failed', e))); }, } satisfies ExportedHandler;