Branchwell

Skillfarm / website · skillfarm.ai / src / index.tsx

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