Branchwell

Skillfarm / website · skillfarm.ai / src / routes / settings.tsx

Raw 19.2 KB on c724bfa127f7a93b48788385cedf1e60cb4e7943
1import type { Hono } from 'hono';
2import type { AppEnv, Ctx, User } from '../env';
3import { sniffImage } from '../lib/images';
4import { rateLimit } from '../lib/ratelimit';
5import { destroySession, setFlash } from '../lib/session';
6import { cleanScopes, createToken, SCOPE_TEXT, SCOPES } from '../lib/tokens';
7import { handleProblem } from '../lib/users';
8import { HttpError, newId, now, safeUrl, sha256Hex, timeAgo } from '../lib/util';
9import { icon } from '../views/art';
10import { Avatar, Copy } from '../views/components';
11import { render } from '../views/layout';
12import { providerReady } from './auth';
13
14function requireUser(c: Ctx): User {
15 const u = c.get('user');
16 if (!u) throw new HttpError(401, 'Sign in first.');
17 return u;
18}
19
20const MAX_AVATAR = 2 * 1024 * 1024;
21
22async function storeAvatar(c: Ctx, user: User, big: Uint8Array, small: Uint8Array | null): Promise<string> {
23 const info = sniffImage(big);
24 if (!info) throw new HttpError(400, 'That file is not a JPEG, PNG or WebP image.');
25 if (big.length > MAX_AVATAR) throw new HttpError(400, 'Avatars can be up to 2 MB.');
26 if (info.width < 64 || info.height < 64 || info.width > 1024 || info.height > 1024) throw new HttpError(400, 'Avatars must be between 64 and 1024 pixels on each side.');
27 if (Math.abs(info.width - info.height) > 2) throw new HttpError(400, 'Avatars must be square.');
28 let smallBytes = big;
29 if (small) {
30 const s = sniffImage(small);
31 if (s && s.type === info.type && small.length <= MAX_AVATAR && s.width <= 256 && s.height <= 256 && Math.abs(s.width - s.height) <= 2) smallBytes = small;
32 }
33 const hash = (await sha256Hex(big)).slice(0, 20);
34 const key = `avatars/${user.id}/${hash}.${info.ext}`;
35 const meta = { httpMetadata: { contentType: info.type, cacheControl: 'public, max-age=31536000, immutable' } };
36 await c.env.AVATARS.put(key, big, meta);
37 await c.env.AVATARS.put(key.replace(/(\.\w+)$/, '-128$1'), smallBytes, meta);
38 if (user.avatar_key && user.avatar_key !== key) {
39 c.executionCtx.waitUntil(c.env.AVATARS.delete([user.avatar_key, user.avatar_key.replace(/(\.\w+)$/, '-128$1')]).catch(() => {}));
40 }
41 await c.env.DB.prepare('UPDATE users SET avatar_key = ? WHERE id = ?').bind(key, user.id).run();
42 return key;
43}
44
45export function registerSettings(app: Hono<AppEnv>) {
46 app.get('/settings', async (c) => {
47 const user = c.get('user');
48 if (!user) return c.redirect('/signin?next=/settings');
49 const [accounts, tokens, grants] = await Promise.all([
50 c.env.DB.prepare('SELECT provider, login FROM oauth_accounts WHERE user_id = ?').bind(user.id).all<{ provider: 'github' | 'google'; login: string | null }>(),
51 c.env.DB.prepare("SELECT id, name, scopes, last_used_at, created_at FROM api_tokens WHERE user_id = ? AND kind = 'pat' AND revoked_at IS NULL ORDER BY created_at DESC").bind(user.id).all<{ id: string; name: string; scopes: string; last_used_at: number | null; created_at: number }>(),
52 c.env.DB.prepare(
53 `SELECT t.grant_id, t.scopes, MAX(t.last_used_at) AS last_used_at, MIN(t.created_at) AS created_at, COALESCE(cl.client_name, 'Unknown app') AS client_name
54 FROM api_tokens t LEFT JOIN oauth_clients cl ON cl.client_id = t.client_id
55 WHERE t.user_id = ? AND t.kind = 'refresh' AND t.revoked_at IS NULL AND (t.expires_at IS NULL OR t.expires_at > ?) GROUP BY t.grant_id ORDER BY created_at DESC`,
56 ).bind(user.id, now()).all<{ grant_id: string; scopes: string; last_used_at: number | null; created_at: number; client_name: string }>(),
57 ]);
58 const linked = new Set(accounts.results.map((a) => a.provider));
59 return render(
60 c,
61 { title: 'Settings', noindex: true },
62 <div class="wrap section settings">
63 <h1>Settings</h1>
64
65 <section class="card pad">
66 <h2>Profile</h2>
67 <div class="avatar-edit" data-avatar>
68 <div data-avatar-preview><Avatar user={user} size={128} /></div>
69 <div>
70 <p>Your avatar shows on your profile and every skill you share. JPEG, PNG or WebP, up to 2 MB. It is cropped to a square in your browser.</p>
71 <label class="btn btn-ghost btn-sm file-btn">
72 Choose image
73 <input type="file" accept="image/jpeg,image/png,image/webp" data-avatar-input hidden />
74 </label>
75 {user.avatar_key ? (
76 <form method="post" action="/settings/avatar/remove" class="inline">
77 <button class="link-btn" type="submit">Remove avatar</button>
78 </form>
79 ) : null}
80 <p class="muted" data-avatar-status role="status"></p>
81 </div>
82 </div>
83 <form method="post" action="/settings/profile" class="form">
84 <label>
85 <span>Display name</span>
86 <input name="display_name" value={user.display_name} required maxlength={60} />
87 </label>
88 <label>
89 <span>Handle</span>
90 <div class="input-prefix">
91 <span>skillfarm.ai/u/</span>
92 <input name="handle" value={user.handle} required minlength={2} maxlength={30} autocapitalize="none" spellcheck={false} />
93 </div>
94 <small>Changing your handle changes the address of your profile and skills.</small>
95 </label>
96 <label>
97 <span>Bio</span>
98 <textarea name="bio" rows={3} maxlength={280}>{user.bio}</textarea>
99 </label>
100 <label>
101 <span>Website</span>
102 <input name="website" type="url" value={user.website} maxlength={200} placeholder="https://" />
103 </label>
104 <button class="btn btn-primary" type="submit">Save profile</button>
105 </form>
106 </section>
107
108 <section class="card pad">
109 <h2>Email notices</h2>
110 <p>{user.email ? <>Notices go to <strong>{user.email}</strong>, the verified address from your sign-in provider. It is never shown on the site.</> : 'Your sign-in provider did not share a verified email, so Skillfarm cannot email you.'}</p>
111 <form method="post" action="/settings/notices" class="form">
112 <label class="confirm">
113 <input type="checkbox" name="email_notices" value="1" checked={!!user.email_notices} />
114 <span>Email me when a skill of mine is approved, denied or taken down, and when I reach a new tier</span>
115 </label>
116 <button class="btn btn-ghost btn-sm" type="submit">Save</button>
117 </form>
118 </section>
119
120 <section class="card pad">
121 <h2>Sign-in methods</h2>
122 <ul class="rows">
123 {(['github', 'google'] as const).map((p) => {
124 const acct = accounts.results.find((a) => a.provider === p);
125 const name = p === 'github' ? 'GitHub' : 'Google';
126 return (
127 <li>
128 <span class="row-main">{icon(p, 20)} <strong>{name}</strong> {acct ? <em>{acct.login ? `@${acct.login}` : 'Linked'}</em> : <em>Not linked</em>}</span>
129 {acct ? (
130 linked.size > 1 ? (
131 <form method="post" action={`/settings/unlink/${p}`}>
132 <button class="btn btn-ghost btn-sm" type="submit">Unlink</button>
133 </form>
134 ) : (
135 <span class="muted">Your only sign-in method</span>
136 )
137 ) : providerReady(c, p) ? (
138 <a class="btn btn-ghost btn-sm" href={`/auth/${p}/start?link=1&next=/settings`}>Link {name}</a>
139 ) : (
140 <span class="muted">Being set up</span>
141 )}
142 </li>
143 );
144 })}
145 </ul>
146 </section>
147
148 <section class="card pad" id="access">
149 <h2>Connected apps</h2>
150 <p class="muted">MCP clients you signed in to. Revoking one signs it out at once.</p>
151 {grants.results.length ? (
152 <ul class="rows">
153 {grants.results.map((g) => (
154 <li>
155 <span class="row-main">{icon('plug', 20)} <strong>{g.client_name}</strong> <em>{g.scopes}</em> <em>last used {timeAgo(g.last_used_at)}</em></span>
156 <form method="post" action={`/settings/grants/${g.grant_id}/revoke`}>
157 <button class="btn btn-ghost btn-sm" type="submit">Revoke</button>
158 </form>
159 </li>
160 ))}
161 </ul>
162 ) : (
163 <p>No apps connected. See <a href="/connect">how to connect over MCP</a>.</p>
164 )}
165
166 <h2>Personal access tokens</h2>
167 <p class="muted">For scripts and MCP clients without sign-in support. A token acts as you, within the access you give it.</p>
168 {tokens.results.length ? (
169 <ul class="rows">
170 {tokens.results.map((t) => (
171 <li>
172 <span class="row-main"><strong>{t.name || 'Unnamed token'}</strong> <em>{t.scopes}</em> <em>created {timeAgo(t.created_at)}, last used {timeAgo(t.last_used_at)}</em></span>
173 <form method="post" action={`/settings/tokens/${t.id}/revoke`}>
174 <button class="btn btn-ghost btn-sm" type="submit">Revoke</button>
175 </form>
176 </li>
177 ))}
178 </ul>
179 ) : null}
180 <form method="post" action="/settings/tokens" class="form token-form">
181 <label>
182 <span>Token name</span>
183 <input name="name" required maxlength={60} placeholder="My laptop" />
184 </label>
185 <fieldset class="checks">
186 <legend>Access</legend>
187 {SCOPES.map((s) => (
188 <label>
189 <input type="checkbox" name="scopes" value={s} checked={s === 'skills:read'} />
190 <span><code>{s}</code> {SCOPE_TEXT[s]}</span>
191 </label>
192 ))}
193 </fieldset>
194 <button class="btn btn-ghost" type="submit">Create token</button>
195 </form>
196 </section>
197
198 <section class="card pad danger-zone">
199 <h2>Delete account</h2>
200 <p>This removes your profile, email, sign-in links, sessions and tokens, and takes your skills down. It cannot be undone.</p>
201 <form method="post" action="/settings/delete" class="form">
202 <label>
203 <span>Type your handle to confirm</span>
204 <input name="confirm" required autocomplete="off" autocapitalize="none" spellcheck={false} />
205 </label>
206 <button class="btn btn-danger" type="submit">Delete my account</button>
207 </form>
208 </section>
209 </div>,
210 );
211 });
212
213 app.post('/settings/profile', async (c) => {
214 const user = requireUser(c);
215 const form = await c.req.parseBody();
216 const name = String(form.display_name ?? '').trim().replace(/\s+/g, ' ').slice(0, 60);
217 const handle = String(form.handle ?? '').trim().toLowerCase();
218 const bio = String(form.bio ?? '').trim().replace(/\s+/g, ' ').slice(0, 280);
219 const websiteRaw = String(form.website ?? '').trim().slice(0, 200);
220 const website = websiteRaw ? safeUrl(websiteRaw) : '';
221 // A handle someone already holds stays valid for them, even a reserved one (the studio's own account).
222 let problem = !name ? 'Add a display name.' : handle === user.handle.toLowerCase() ? null : handleProblem(handle);
223 if (!problem && websiteRaw && !website) problem = 'The website must be an http or https address.';
224 if (!problem && handle !== user.handle.toLowerCase()) {
225 if (!(await rateLimit(c.env, `handle:${user.id}`, 3, 604800))) problem = 'You changed your handle several times this week. Try again later.';
226 else if (await c.env.DB.prepare('SELECT 1 AS x FROM users WHERE handle = ? AND id != ?').bind(handle, user.id).first()) problem = 'That handle is taken.';
227 }
228 if (problem) {
229 setFlash(c, 'error', problem);
230 return c.redirect('/settings');
231 }
232 await c.env.DB.prepare('UPDATE users SET display_name = ?, handle = ?, bio = ?, website = ?, onboarded = 1 WHERE id = ?').bind(name, handle, bio, website ?? '', user.id).run();
233 setFlash(c, 'ok', 'Profile saved.');
234 return c.redirect('/settings');
235 });
236
237 app.post('/settings/notices', async (c) => {
238 const user = requireUser(c);
239 const form = await c.req.parseBody();
240 await c.env.DB.prepare('UPDATE users SET email_notices = ? WHERE id = ?').bind(form.email_notices ? 1 : 0, user.id).run();
241 setFlash(c, 'ok', form.email_notices ? 'Email notices are on.' : 'Email notices are off.');
242 return c.redirect('/settings');
243 });
244
245 // Avatar upload. The browser crops and resizes; the Worker re-checks type, size and dimensions.
246 app.post('/api/me/avatar', async (c) => {
247 const user = c.get('user');
248 if (!user) return c.json({ error: 'sign_in', message: 'Sign in first.' }, 401);
249 if (!(await rateLimit(c.env, `avatar:${user.id}`, 10, 3600))) return c.json({ error: 'rate_limited', message: 'Too many avatar changes. Try again in an hour.' }, 429);
250 const len = parseInt(c.req.header('content-length') ?? '0', 10);
251 if (len > MAX_AVATAR * 2 + 4096) return c.json({ error: 'too_large', message: 'Avatars can be up to 2 MB.' }, 413);
252 try {
253 const form = await c.req.formData();
254 const big = form.get('avatar') as unknown;
255 const small = form.get('avatar_small') as unknown;
256 if (!(big instanceof File)) throw new HttpError(400, 'No image was sent.');
257 const key = await storeAvatar(c, user, new Uint8Array(await big.arrayBuffer()), small instanceof File ? new Uint8Array(await small.arrayBuffer()) : null);
258 return c.json({ ok: true, url: `/${key}` });
259 } catch (e) {
260 if (e instanceof HttpError) return c.json({ error: 'refused', message: e.message }, e.status as 400);
261 throw e;
262 }
263 });
264
265 app.post('/settings/avatar/remove', async (c) => {
266 const user = requireUser(c);
267 if (user.avatar_key) {
268 await c.env.AVATARS.delete([user.avatar_key, user.avatar_key.replace(/(\.\w+)$/, '-128$1')]).catch(() => {});
269 await c.env.DB.prepare('UPDATE users SET avatar_key = NULL WHERE id = ?').bind(user.id).run();
270 }
271 setFlash(c, 'ok', 'Avatar removed.');
272 return c.redirect('/settings');
273 });
274
275 app.get('/avatars/:uid/:file', async (c) => {
276 const key = `avatars/${c.req.param('uid')}/${c.req.param('file')}`;
277 if (!/^avatars\/[a-z0-9]{8,32}\/[a-f0-9]{20}(-128)?\.(webp|png|jpg)$/.test(key)) return c.notFound();
278 const obj = await c.env.AVATARS.get(key);
279 if (!obj) return c.notFound();
280 return new Response(obj.body, {
281 headers: { 'content-type': obj.httpMetadata?.contentType ?? 'image/webp', 'cache-control': 'public, max-age=31536000, immutable', 'x-content-type-options': 'nosniff', etag: obj.httpEtag },
282 });
283 });
284
285 app.post('/settings/unlink/:provider', async (c) => {
286 const user = requireUser(c);
287 const p = c.req.param('provider');
288 const count = await c.env.DB.prepare('SELECT COUNT(*) AS n FROM oauth_accounts WHERE user_id = ?').bind(user.id).first<{ n: number }>();
289 if ((count?.n ?? 0) < 2) {
290 setFlash(c, 'error', 'You cannot unlink your only sign-in method.');
291 return c.redirect('/settings');
292 }
293 await c.env.DB.prepare('DELETE FROM oauth_accounts WHERE user_id = ? AND provider = ?').bind(user.id, p).run();
294 setFlash(c, 'ok', 'Sign-in method unlinked.');
295 return c.redirect('/settings');
296 });
297
298 app.post('/settings/tokens', async (c) => {
299 const user = requireUser(c);
300 const form = await c.req.parseBody({ all: true });
301 const scopes = cleanScopes(([] as unknown[]).concat(form.scopes ?? []).filter((x): x is string => typeof x === 'string'));
302 const name = String(form.name ?? '').trim().slice(0, 60);
303 const count = await c.env.DB.prepare("SELECT COUNT(*) AS n FROM api_tokens WHERE user_id = ? AND kind = 'pat' AND revoked_at IS NULL").bind(user.id).first<{ n: number }>();
304 if (!name || !scopes.length || (count?.n ?? 0) >= 10) {
305 setFlash(c, 'error', !name ? 'Give the token a name.' : !scopes.length ? 'Pick at least one kind of access.' : 'You can have up to 10 tokens. Revoke one first.');
306 return c.redirect('/settings#access');
307 }
308 const { token } = await createToken(c.env, { userId: user.id, kind: 'pat', name, scopes });
309 // Shown once, on this response only. It is never stored in readable form.
310 return render(
311 c,
312 { title: 'New token', noindex: true, narrow: true },
313 <section class="auth-card card">
314 <h1>Copy your token now</h1>
315 <p class="lede">This is the only time it is shown. Skillfarm keeps only a hash of it.</p>
316 <Copy text={token} label="Copy token" />
317 <p class="fine">Name: {name}. Access: {scopes.join(', ')}.</p>
318 <a class="btn btn-primary" href="/settings#access">Done</a>
319 </section>,
320 );
321 });
322
323 app.post('/settings/tokens/:id/revoke', async (c) => {
324 const user = requireUser(c);
325 await c.env.DB.prepare("UPDATE api_tokens SET revoked_at = ? WHERE id = ? AND user_id = ? AND kind = 'pat'").bind(now(), c.req.param('id'), user.id).run();
326 setFlash(c, 'ok', 'Token revoked.');
327 return c.redirect('/settings#access');
328 });
329
330 app.post('/settings/grants/:id/revoke', async (c) => {
331 const user = requireUser(c);
332 await c.env.DB.prepare('UPDATE api_tokens SET revoked_at = ? WHERE grant_id = ? AND user_id = ? AND revoked_at IS NULL').bind(now(), c.req.param('id'), user.id).run();
333 setFlash(c, 'ok', 'App disconnected.');
334 return c.redirect('/settings#access');
335 });
336
337 app.post('/settings/delete', async (c) => {
338 const user = requireUser(c);
339 const form = await c.req.parseBody();
340 if (String(form.confirm ?? '').trim().toLowerCase() !== user.handle.toLowerCase()) {
341 setFlash(c, 'error', 'The handle you typed does not match.');
342 return c.redirect('/settings');
343 }
344 if (user.is_admin) {
345 setFlash(c, 'error', 'Admin accounts cannot be deleted from here.');
346 return c.redirect('/settings');
347 }
348 const ts = now();
349 const skills = await c.env.DB.prepare("SELECT id FROM skills WHERE owner_id = ? AND state != 'removed'").bind(user.id).all<{ id: string }>();
350 const { reverseSkillPoints } = await import('../lib/points');
351 for (const s of skills.results) await reverseSkillPoints(c.env, s.id);
352 if (user.avatar_key) await c.env.AVATARS.delete([user.avatar_key, user.avatar_key.replace(/(\.\w+)$/, '-128$1')]).catch(() => {});
353 await c.env.DB.batch([
354 c.env.DB.prepare("UPDATE skills SET state = 'removed', featured_at = NULL, updated_at = ? WHERE owner_id = ?").bind(ts, user.id),
355 c.env.DB.prepare("UPDATE skill_versions SET status = 'superseded' WHERE status = 'pending' AND skill_id IN (SELECT id FROM skills WHERE owner_id = ?)").bind(user.id),
356 c.env.DB.prepare('DELETE FROM oauth_accounts WHERE user_id = ?').bind(user.id),
357 c.env.DB.prepare('DELETE FROM sessions WHERE user_id = ?').bind(user.id),
358 c.env.DB.prepare('UPDATE api_tokens SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL').bind(ts, user.id),
359 c.env.DB.prepare(
360 "UPDATE users SET status = 'deleted', handle = ?, display_name = 'Deleted member', bio = '', website = '', email = NULL, avatar_key = NULL, avatar_fallback = NULL, spotlight_at = NULL, seeds_total = 0 WHERE id = ?",
361 ).bind(`deleted-${newId(10)}`, user.id),
362 ]);
363 await destroySession(c);
364 setFlash(c, 'ok', 'Your account was deleted.');
365 return c.redirect('/');
366 });
367}