Skillfarm / website · skillfarm.ai / src / index.tsx
| 1 | import { Hono } from 'hono'; |
| 2 | import type { AppEnv, Ctx, Env } from './env'; |
| 3 | import { PROMPTS } from './content/prompts'; |
| 4 | import { processAiQueue } from './lib/ai'; |
| 5 | import { refreshAllStale } from './lib/github'; |
| 6 | import { processImportQueue } from './lib/imports'; |
| 7 | import { pruneRateLimits } from './lib/ratelimit'; |
| 8 | import { loadSessionUser, takeFlash } from './lib/session'; |
| 9 | import { DAY, HttpError, now } from './lib/util'; |
| 10 | import { registerAdmin } from './routes/admin'; |
| 11 | import { registerAuth } from './routes/auth'; |
| 12 | import { registerMcp } from './routes/mcp'; |
| 13 | import { registerOAuth } from './routes/oauth'; |
| 14 | import { registerPages } from './routes/pages'; |
| 15 | import { registerSettings } from './routes/settings'; |
| 16 | import { registerSkills } from './routes/skills'; |
| 17 | import { Empty } from './views/components'; |
| 18 | import { render } from './views/layout'; |
| 19 | |
| 20 | const app = new Hono<AppEnv>(); |
| 21 | |
| 22 | /** Requests that are answered for programs, not browsers: no cookies are read and no session is loaded. */ |
| 23 | const isMachinePath = (p: string) => p === '/mcp' || p.startsWith('/mcp/') || p === '/oauth/token' || p === '/oauth/register' || p === '/oauth/revoke' || p.startsWith('/.well-known/'); |
| 24 | const wantsJson = (c: Ctx) => c.req.path.startsWith('/api/') || isMachinePath(c.req.path) || (c.req.header('accept') ?? '').includes('application/json'); |
| 25 | |
| 26 | const CSP = [ |
| 27 | "default-src 'self'", |
| 28 | "script-src 'self' https://www.googletagmanager.com", |
| 29 | "style-src 'self' 'unsafe-inline'", |
| 30 | "img-src 'self' data: blob: https://avatars.githubusercontent.com https://*.googleusercontent.com https://www.googletagmanager.com https://*.google-analytics.com", |
| 31 | "font-src 'self'", |
| 32 | "connect-src 'self' https://projectatom.ai https://*.google-analytics.com https://*.analytics.google.com https://www.googletagmanager.com", |
| 33 | "object-src 'none'", |
| 34 | "base-uri 'self'", |
| 35 | "frame-ancestors 'none'", |
| 36 | ]; |
| 37 | |
| 38 | // Canonical host and old addresses. |
| 39 | app.use('*', async (c, next) => { |
| 40 | const url = new URL(c.req.url); |
| 41 | const www = url.hostname === 'www.skillfarm.ai'; |
| 42 | // Plain http is only allowed on a development machine. |
| 43 | const plain = url.protocol === 'http:' && (www || url.hostname === 'skillfarm.ai' || url.hostname.endsWith('.workers.dev')); |
| 44 | if (www || plain) { |
| 45 | if (www) url.hostname = 'skillfarm.ai'; |
| 46 | url.protocol = 'https:'; |
| 47 | return c.redirect(url.toString(), 308); |
| 48 | } |
| 49 | await next(); |
| 50 | }); |
| 51 | app.get('/waitlist', (c) => c.redirect('/', 308)); |
| 52 | app.get('/apply', (c) => c.redirect('/signin', 308)); |
| 53 | |
| 54 | // Security headers on everything the Worker answers. |
| 55 | app.use('*', async (c, next) => { |
| 56 | await next(); |
| 57 | const h = c.res.headers; |
| 58 | h.set('x-content-type-options', 'nosniff'); |
| 59 | h.set('referrer-policy', 'strict-origin-when-cross-origin'); |
| 60 | h.set('permissions-policy', 'camera=(), microphone=(), geolocation=(), interest-cohort=()'); |
| 61 | if (new URL(c.req.url).protocol === 'https:') h.set('strict-transport-security', 'max-age=31536000; includeSubDomains'); |
| 62 | if ((h.get('content-type') ?? '').includes('text/html')) { |
| 63 | // The consent screen hands the browser back to the app that asked, so it cannot pin form targets to this site. |
| 64 | h.set('content-security-policy', [...CSP, ...(c.req.path === '/oauth/authorize' ? [] : ["form-action 'self'"])].join('; ')); |
| 65 | h.set('x-frame-options', 'DENY'); |
| 66 | if (!h.has('cache-control')) h.set('cache-control', 'private, no-store'); |
| 67 | } |
| 68 | }); |
| 69 | |
| 70 | // Cross-site request forgery: a browser request that changes something must come from our own pages. |
| 71 | app.use('*', async (c, next) => { |
| 72 | const method = c.req.method; |
| 73 | if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS' || isMachinePath(c.req.path)) return next(); |
| 74 | const here = new URL(c.req.url).origin; |
| 75 | const origin = c.req.header('origin'); |
| 76 | const site = c.req.header('sec-fetch-site'); |
| 77 | const ok = origin ? origin === here : site === 'same-origin'; |
| 78 | if (!ok) throw new HttpError(403, 'That request did not come from Skillfarm. Go back, reload the page and try again.', 'bad_origin'); |
| 79 | return next(); |
| 80 | }); |
| 81 | |
| 82 | // Who is asking. |
| 83 | app.use('*', async (c, next) => { |
| 84 | c.set('user', null); |
| 85 | c.set('flash', null); |
| 86 | if (isMachinePath(c.req.path)) return next(); |
| 87 | if (c.env.SESSION_SECRET) c.set('user', await loadSessionUser(c)); |
| 88 | const p = c.req.path; |
| 89 | if (c.req.method === 'GET' && !p.startsWith('/api/') && !p.startsWith('/avatars/') && !p.startsWith('/auth/') && !p.endsWith('/download')) c.set('flash', takeFlash(c)); |
| 90 | return next(); |
| 91 | }); |
| 92 | |
| 93 | registerAuth(app); |
| 94 | registerOAuth(app); |
| 95 | registerMcp(app); |
| 96 | registerPages(app); |
| 97 | registerSkills(app); |
| 98 | registerSettings(app); |
| 99 | registerAdmin(app); |
| 100 | |
| 101 | app.get('/robots.txt', (c) => |
| 102 | c.text( |
| 103 | ['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'), |
| 104 | 200, |
| 105 | { 'cache-control': 'public, max-age=3600' }, |
| 106 | ), |
| 107 | ); |
| 108 | |
| 109 | app.get('/sitemap.xml', async (c) => { |
| 110 | const site = c.env.SITE_URL; |
| 111 | const [skills, growers] = await Promise.all([ |
| 112 | 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 }>(), |
| 113 | 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 }>(), |
| 114 | ]); |
| 115 | const urls = ['/', '/skills', '/prompts', '/growers', '/leaderboard', '/seeds', '/connect', '/help', '/guidelines', '/privacy', '/research', ...PROMPTS.map((p) => `/prompts/${p.slug}`)].map((p) => `<url><loc>${site}${p}</loc></url>`); |
| 116 | for (const s of skills.results) urls.push(`<url><loc>${site}/skills/${s.handle}/${s.slug}</loc><lastmod>${new Date(s.updated_at * 1000).toISOString().slice(0, 10)}</lastmod></url>`); |
| 117 | for (const g of growers.results) urls.push(`<url><loc>${site}/u/${g.handle}</loc></url>`); |
| 118 | return c.body(`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.join('\n')}\n</urlset>\n`, 200, { |
| 119 | 'content-type': 'application/xml; charset=utf-8', |
| 120 | 'cache-control': 'public, max-age=3600', |
| 121 | }); |
| 122 | }); |
| 123 | |
| 124 | app.notFound((c) => { |
| 125 | if (wantsJson(c)) return c.json({ error: 'not_found', message: 'Nothing here.' }, 404); |
| 126 | return render( |
| 127 | c, |
| 128 | { title: 'Nothing planted here', noindex: true }, |
| 129 | <div class="wrap section"> |
| 130 | <Empty title="Nothing planted here"> |
| 131 | <p>That page does not exist, or it was moved. The skills are still where you left them.</p> |
| 132 | <p class="cta-row"> |
| 133 | <a class="btn btn-primary" href="/skills">Browse skills</a> |
| 134 | <a class="btn btn-ghost" href="/">Go home</a> |
| 135 | </p> |
| 136 | </Empty> |
| 137 | </div>, |
| 138 | 404, |
| 139 | ); |
| 140 | }); |
| 141 | |
| 142 | const TITLES: Record<number, string> = { 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' }; |
| 143 | |
| 144 | app.onError((err, c) => { |
| 145 | const known = err instanceof HttpError; |
| 146 | const status = known ? err.status : 500; |
| 147 | if (!known) console.error('unhandled', c.req.method, c.req.path, err); |
| 148 | const message = known ? err.message : 'Something broke on our side. Try again in a moment.'; |
| 149 | if (wantsJson(c)) return c.json({ error: known ? err.code : 'server_error', message }, status as 500); |
| 150 | if (status === 401 && c.req.method === 'GET') { |
| 151 | const u = new URL(c.req.url); |
| 152 | return c.redirect(`/signin?next=${encodeURIComponent(u.pathname + u.search)}`); |
| 153 | } |
| 154 | return render( |
| 155 | c, |
| 156 | { title: TITLES[status] ?? 'Something went wrong', noindex: true }, |
| 157 | <div class="wrap section"> |
| 158 | <Empty title={TITLES[status] ?? 'Something went wrong'}> |
| 159 | <p>{message}</p> |
| 160 | <p class="cta-row"> |
| 161 | {status === 401 ? <a class="btn btn-primary" href="/signin">Sign in</a> : <a class="btn btn-primary" href="/">Go home</a>} |
| 162 | </p> |
| 163 | </Empty> |
| 164 | </div>, |
| 165 | status, |
| 166 | ); |
| 167 | }); |
| 168 | |
| 169 | /** Housekeeping that keeps the tables small. Nothing here touches member content. */ |
| 170 | async function daily(env: Env): Promise<void> { |
| 171 | const ts = now(); |
| 172 | await refreshAllStale(env, 80).catch((e) => console.error('star refresh failed', e)); |
| 173 | await pruneRateLimits(env); |
| 174 | await env.DB.batch([ |
| 175 | env.DB.prepare('DELETE FROM sessions WHERE expires_at < ?').bind(ts), |
| 176 | env.DB.prepare('DELETE FROM oauth_codes WHERE expires_at < ?').bind(ts), |
| 177 | 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), |
| 178 | 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), |
| 179 | env.DB.prepare('DELETE FROM email_log WHERE created_at < ?').bind(ts - 90 * DAY), |
| 180 | ]); |
| 181 | } |
| 182 | |
| 183 | export default { |
| 184 | fetch: app.fetch, |
| 185 | async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> { |
| 186 | if (event.cron === '*/2 * * * *') { |
| 187 | // Finish reading shared repos first, so their skills are in the queue the AI review works through. |
| 188 | ctx.waitUntil( |
| 189 | processImportQueue(env, ctx) |
| 190 | .catch((e) => console.error('repo share queue failed', e)) |
| 191 | .then(() => processAiQueue(env)) |
| 192 | .catch((e) => console.error('ai queue failed', e)), |
| 193 | ); |
| 194 | } |
| 195 | else ctx.waitUntil(daily(env).catch((e) => console.error('daily job failed', e))); |
| 196 | }, |
| 197 | } satisfies ExportedHandler<Env>; |