Branchwell

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

Raw 20.5 KB on a4acba8fed02ff053e24fa2ab137b32f1b601fa1
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 { dateLabel, 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 { credentialsFor, LINK_MINUTES, makeLink } from '../lib/biolock';
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 [devices, tokens, grants] = await Promise.all([
50 credentialsFor(c, user.id),
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 return render(
59 c,
60 { title: 'Settings', noindex: true },
61 <div class="wrap section settings">
62 <h1>Settings</h1>
63
64 <section class="card pad">
65 <h2>Profile</h2>
66 <div class="avatar-edit" data-avatar>
67 <div data-avatar-preview><Avatar user={user} size={128} /></div>
68 <div>
69 <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>
70 <label class="btn btn-ghost btn-sm file-btn">
71 Choose image
72 <input type="file" accept="image/jpeg,image/png,image/webp" data-avatar-input hidden />
73 </label>
74 {user.avatar_key ? (
75 <form method="post" action="/settings/avatar/remove" class="inline">
76 <button class="link-btn" type="submit">Remove avatar</button>
77 </form>
78 ) : null}
79 <p class="muted" data-avatar-status role="status"></p>
80 </div>
81 </div>
82 <form method="post" action="/settings/profile" class="form">
83 <label>
84 <span>Display name</span>
85 <input name="display_name" value={user.display_name} required maxlength={60} />
86 </label>
87 <label>
88 <span>Handle</span>
89 <div class="input-prefix">
90 <span>skillfarm.ai/u/</span>
91 <input name="handle" value={user.handle} required minlength={2} maxlength={30} autocapitalize="none" spellcheck={false} />
92 </div>
93 <small>Changing your handle changes the address of your profile and skills.</small>
94 </label>
95 <label>
96 <span>Bio</span>
97 <textarea name="bio" rows={3} maxlength={280}>{user.bio}</textarea>
98 </label>
99 <label>
100 <span>Website</span>
101 <input name="website" type="url" value={user.website} maxlength={200} placeholder="https://" />
102 </label>
103 <button class="btn btn-primary" type="submit">Save profile</button>
104 </form>
105 </section>
106
107 <section class="card pad">
108 <h2>Email notices</h2>
109 <p>{user.email ? <>Notices go to <strong>{user.email}</strong>. It is never shown on the site.</> : 'Skillfarm has no email address for you, so it cannot email you. Notices still show on the site.'}</p>
110 <form method="post" action="/settings/notices" class="form">
111 <label class="confirm">
112 <input type="checkbox" name="email_notices" value="1" checked={!!user.email_notices} />
113 <span>Email me when a skill of mine is approved, denied or taken down, and when I reach a new tier</span>
114 </label>
115 <button class="btn btn-ghost btn-sm" type="submit">Save</button>
116 </form>
117 </section>
118
119 <section class="card pad" id="biolock">
120 <h2>BioLock</h2>
121 <p class="muted">Each device signs you in with its own fingerprint or face reader. Add every device you use, so losing one never locks you out.</p>
122 {devices.length ? (
123 <ul class="rows">
124 {devices.map((d) => (
125 <li>
126 <span class="row-main">{icon('lock', 20)} <strong>{d.name || 'Device'}</strong> <em>added {dateLabel(d.created_at)}</em> <em>last used {timeAgo(d.last_used_at)}</em></span>
127 {devices.length > 1 ? (
128 <form method="post" action={`/settings/biolock/${encodeURIComponent(d.id)}/remove`}>
129 <button class="btn btn-ghost btn-sm" type="submit">Remove</button>
130 </form>
131 ) : (
132 <span class="muted">Your only device</span>
133 )}
134 </li>
135 ))}
136 </ul>
137 ) : (
138 <p class="notice notice-info">This account has no BioLock yet. Add it on this device now, or you will not be able to sign in again after this session ends.</p>
139 )}
140 <div class="signin-buttons" data-biolock data-next="/settings#biolock">
141 <button type="button" class="btn btn-primary btn-sm" data-biolock-register="add">{icon('lock', 18)} Add BioLock on this device</button>
142 <p class="fine biolock-status" data-biolock-status role="status" aria-live="polite"></p>
143 </div>
144 <form method="post" action="/settings/biolock/link" class="form">
145 <button class="btn btn-ghost btn-sm" type="submit">Make a one-time link for another device</button>
146 </form>
147 </section>
148
149 <section class="card pad" id="access">
150 <h2>Connected apps</h2>
151 <p class="muted">MCP clients you signed in to. Revoking one signs it out at once.</p>
152 {grants.results.length ? (
153 <ul class="rows">
154 {grants.results.map((g) => (
155 <li>
156 <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>
157 <form method="post" action={`/settings/grants/${g.grant_id}/revoke`}>
158 <button class="btn btn-ghost btn-sm" type="submit">Revoke</button>
159 </form>
160 </li>
161 ))}
162 </ul>
163 ) : (
164 <p>No apps connected. See <a href="/connect">how to connect over MCP</a>.</p>
165 )}
166
167 <h2>Personal access tokens</h2>
168 <p class="muted">For scripts and MCP clients without sign-in support. A token acts as you, within the access you give it.</p>
169 {tokens.results.length ? (
170 <ul class="rows">
171 {tokens.results.map((t) => (
172 <li>
173 <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>
174 <form method="post" action={`/settings/tokens/${t.id}/revoke`}>
175 <button class="btn btn-ghost btn-sm" type="submit">Revoke</button>
176 </form>
177 </li>
178 ))}
179 </ul>
180 ) : null}
181 <form method="post" action="/settings/tokens" class="form token-form">
182 <label>
183 <span>Token name</span>
184 <input name="name" required maxlength={60} placeholder="My laptop" />
185 </label>
186 <fieldset class="checks">
187 <legend>Access</legend>
188 {SCOPES.map((s) => (
189 <label>
190 <input type="checkbox" name="scopes" value={s} checked={s === 'skills:read'} />
191 <span><code>{s}</code> {SCOPE_TEXT[s]}</span>
192 </label>
193 ))}
194 </fieldset>
195 <button class="btn btn-ghost" type="submit">Create token</button>
196 </form>
197 </section>
198
199 <section class="card pad danger-zone">
200 <h2>Delete account</h2>
201 <p>This removes your profile, email, sign-in links, sessions and tokens, and takes your skills down. It cannot be undone.</p>
202 <form method="post" action="/settings/delete" class="form">
203 <label>
204 <span>Type your handle to confirm</span>
205 <input name="confirm" required autocomplete="off" autocapitalize="none" spellcheck={false} />
206 </label>
207 <button class="btn btn-danger" type="submit">Delete my account</button>
208 </form>
209 </section>
210 </div>,
211 );
212 });
213
214 app.post('/settings/profile', async (c) => {
215 const user = requireUser(c);
216 const form = await c.req.parseBody();
217 const name = String(form.display_name ?? '').trim().replace(/\s+/g, ' ').slice(0, 60);
218 const handle = String(form.handle ?? '').trim().toLowerCase();
219 const bio = String(form.bio ?? '').trim().replace(/\s+/g, ' ').slice(0, 280);
220 const websiteRaw = String(form.website ?? '').trim().slice(0, 200);
221 const website = websiteRaw ? safeUrl(websiteRaw) : '';
222 // A handle someone already holds stays valid for them, even a reserved one (the studio's own account).
223 let problem = !name ? 'Add a display name.' : handle === user.handle.toLowerCase() ? null : handleProblem(handle);
224 if (!problem && websiteRaw && !website) problem = 'The website must be an http or https address.';
225 if (!problem && handle !== user.handle.toLowerCase()) {
226 if (!(await rateLimit(c.env, `handle:${user.id}`, 3, 604800))) problem = 'You changed your handle several times this week. Try again later.';
227 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.';
228 }
229 if (problem) {
230 setFlash(c, 'error', problem);
231 return c.redirect('/settings');
232 }
233 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();
234 setFlash(c, 'ok', 'Profile saved.');
235 return c.redirect('/settings');
236 });
237
238 app.post('/settings/notices', async (c) => {
239 const user = requireUser(c);
240 const form = await c.req.parseBody();
241 await c.env.DB.prepare('UPDATE users SET email_notices = ? WHERE id = ?').bind(form.email_notices ? 1 : 0, user.id).run();
242 setFlash(c, 'ok', form.email_notices ? 'Email notices are on.' : 'Email notices are off.');
243 return c.redirect('/settings');
244 });
245
246 // Avatar upload. The browser crops and resizes; the Worker re-checks type, size and dimensions.
247 app.post('/api/me/avatar', async (c) => {
248 const user = c.get('user');
249 if (!user) return c.json({ error: 'sign_in', message: 'Sign in first.' }, 401);
250 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);
251 const len = parseInt(c.req.header('content-length') ?? '0', 10);
252 if (len > MAX_AVATAR * 2 + 4096) return c.json({ error: 'too_large', message: 'Avatars can be up to 2 MB.' }, 413);
253 try {
254 const form = await c.req.formData();
255 const big = form.get('avatar') as unknown;
256 const small = form.get('avatar_small') as unknown;
257 if (!(big instanceof File)) throw new HttpError(400, 'No image was sent.');
258 const key = await storeAvatar(c, user, new Uint8Array(await big.arrayBuffer()), small instanceof File ? new Uint8Array(await small.arrayBuffer()) : null);
259 return c.json({ ok: true, url: `/${key}` });
260 } catch (e) {
261 if (e instanceof HttpError) return c.json({ error: 'refused', message: e.message }, e.status as 400);
262 throw e;
263 }
264 });
265
266 app.post('/settings/avatar/remove', async (c) => {
267 const user = requireUser(c);
268 if (user.avatar_key) {
269 await c.env.AVATARS.delete([user.avatar_key, user.avatar_key.replace(/(\.\w+)$/, '-128$1')]).catch(() => {});
270 await c.env.DB.prepare('UPDATE users SET avatar_key = NULL WHERE id = ?').bind(user.id).run();
271 }
272 setFlash(c, 'ok', 'Avatar removed.');
273 return c.redirect('/settings');
274 });
275
276 app.get('/avatars/:uid/:file', async (c) => {
277 const key = `avatars/${c.req.param('uid')}/${c.req.param('file')}`;
278 if (!/^avatars\/[a-z0-9]{8,32}\/[a-f0-9]{20}(-128)?\.(webp|png|jpg)$/.test(key)) return c.notFound();
279 const obj = await c.env.AVATARS.get(key);
280 if (!obj) return c.notFound();
281 return new Response(obj.body, {
282 headers: { 'content-type': obj.httpMetadata?.contentType ?? 'image/webp', 'cache-control': 'public, max-age=31536000, immutable', 'x-content-type-options': 'nosniff', etag: obj.httpEtag },
283 });
284 });
285
286 app.post('/settings/biolock/link', async (c) => {
287 const user = requireUser(c);
288 if (!(await rateLimit(c.env, `biolock-link:${user.id}`, 10, 3600))) throw new HttpError(429, 'Too many links. Try again later.');
289 const link = await makeLink(c, user.id);
290 return render(
291 c,
292 { title: 'Add another device', noindex: true, narrow: true },
293 <section class="auth-card card">
294 <h1>Open this link on the other device</h1>
295 <p class="lede">Send it to yourself, open it on the device you want to add, and use that device's fingerprint or face. It works once, for {LINK_MINUTES} minutes.</p>
296 <Copy text={link} label="Copy link" />
297 <a class="btn btn-ghost" href="/settings#biolock">Back to settings</a>
298 </section>,
299 );
300 });
301
302 app.post('/settings/biolock/:id/remove', async (c) => {
303 const user = requireUser(c);
304 const devices = await credentialsFor(c, user.id);
305 const id = c.req.param('id');
306 if (devices.length < 2 || !devices.some((d) => d.id === id)) {
307 setFlash(c, 'error', 'You cannot remove your only device. Add another one first.');
308 return c.redirect('/settings#biolock');
309 }
310 await c.env.DB.prepare('DELETE FROM biolock_credentials WHERE id = ? AND user_id = ?').bind(id, user.id).run();
311 setFlash(c, 'ok', 'Device removed. It can no longer sign in.');
312 return c.redirect('/settings#biolock');
313 });
314
315 app.post('/settings/tokens', async (c) => {
316 const user = requireUser(c);
317 const form = await c.req.parseBody({ all: true });
318 const scopes = cleanScopes(([] as unknown[]).concat(form.scopes ?? []).filter((x): x is string => typeof x === 'string'));
319 const name = String(form.name ?? '').trim().slice(0, 60);
320 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 }>();
321 if (!name || !scopes.length || (count?.n ?? 0) >= 10) {
322 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.');
323 return c.redirect('/settings#access');
324 }
325 const { token } = await createToken(c.env, { userId: user.id, kind: 'pat', name, scopes });
326 // Shown once, on this response only. It is never stored in readable form.
327 return render(
328 c,
329 { title: 'New token', noindex: true, narrow: true },
330 <section class="auth-card card">
331 <h1>Copy your token now</h1>
332 <p class="lede">This is the only time it is shown. Skillfarm keeps only a hash of it.</p>
333 <Copy text={token} label="Copy token" />
334 <p class="fine">Name: {name}. Access: {scopes.join(', ')}.</p>
335 <a class="btn btn-primary" href="/settings#access">Done</a>
336 </section>,
337 );
338 });
339
340 app.post('/settings/tokens/:id/revoke', async (c) => {
341 const user = requireUser(c);
342 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();
343 setFlash(c, 'ok', 'Token revoked.');
344 return c.redirect('/settings#access');
345 });
346
347 app.post('/settings/grants/:id/revoke', async (c) => {
348 const user = requireUser(c);
349 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();
350 setFlash(c, 'ok', 'App disconnected.');
351 return c.redirect('/settings#access');
352 });
353
354 app.post('/settings/delete', async (c) => {
355 const user = requireUser(c);
356 const form = await c.req.parseBody();
357 if (String(form.confirm ?? '').trim().toLowerCase() !== user.handle.toLowerCase()) {
358 setFlash(c, 'error', 'The handle you typed does not match.');
359 return c.redirect('/settings');
360 }
361 if (user.is_admin) {
362 setFlash(c, 'error', 'Admin accounts cannot be deleted from here.');
363 return c.redirect('/settings');
364 }
365 const ts = now();
366 const skills = await c.env.DB.prepare("SELECT id FROM skills WHERE owner_id = ? AND state != 'removed'").bind(user.id).all<{ id: string }>();
367 const { reverseSkillPoints } = await import('../lib/points');
368 for (const s of skills.results) await reverseSkillPoints(c.env, s.id);
369 if (user.avatar_key) await c.env.AVATARS.delete([user.avatar_key, user.avatar_key.replace(/(\.\w+)$/, '-128$1')]).catch(() => {});
370 await c.env.DB.batch([
371 c.env.DB.prepare("UPDATE skills SET state = 'removed', featured_at = NULL, updated_at = ? WHERE owner_id = ?").bind(ts, user.id),
372 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),
373 c.env.DB.prepare('DELETE FROM oauth_accounts WHERE user_id = ?').bind(user.id),
374 c.env.DB.prepare('DELETE FROM biolock_credentials WHERE user_id = ?').bind(user.id),
375 c.env.DB.prepare('DELETE FROM biolock_links WHERE user_id = ?').bind(user.id),
376 c.env.DB.prepare('DELETE FROM sessions WHERE user_id = ?').bind(user.id),
377 c.env.DB.prepare('UPDATE api_tokens SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL').bind(ts, user.id),
378 c.env.DB.prepare(
379 "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 = ?",
380 ).bind(`deleted-${newId(10)}`, user.id),
381 ]);
382 await destroySession(c);
383 setFlash(c, 'ok', 'Your account was deleted.');
384 return c.redirect('/');
385 });
386}