import type { Hono } from 'hono'; import type { AppEnv, Ctx, User } from '../env'; import { sniffImage } from '../lib/images'; import { rateLimit } from '../lib/ratelimit'; import { destroySession, setFlash } from '../lib/session'; import { cleanScopes, createToken, SCOPE_TEXT, SCOPES } from '../lib/tokens'; import { handleProblem } from '../lib/users'; import { HttpError, newId, now, safeUrl, sha256Hex, timeAgo } from '../lib/util'; import { icon } from '../views/art'; import { Avatar, Copy } from '../views/components'; import { render } from '../views/layout'; import { providerReady } from './auth'; function requireUser(c: Ctx): User { const u = c.get('user'); if (!u) throw new HttpError(401, 'Sign in first.'); return u; } const MAX_AVATAR = 2 * 1024 * 1024; async function storeAvatar(c: Ctx, user: User, big: Uint8Array, small: Uint8Array | null): Promise { const info = sniffImage(big); if (!info) throw new HttpError(400, 'That file is not a JPEG, PNG or WebP image.'); if (big.length > MAX_AVATAR) throw new HttpError(400, 'Avatars can be up to 2 MB.'); 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.'); if (Math.abs(info.width - info.height) > 2) throw new HttpError(400, 'Avatars must be square.'); let smallBytes = big; if (small) { const s = sniffImage(small); 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; } const hash = (await sha256Hex(big)).slice(0, 20); const key = `avatars/${user.id}/${hash}.${info.ext}`; const meta = { httpMetadata: { contentType: info.type, cacheControl: 'public, max-age=31536000, immutable' } }; await c.env.AVATARS.put(key, big, meta); await c.env.AVATARS.put(key.replace(/(\.\w+)$/, '-128$1'), smallBytes, meta); if (user.avatar_key && user.avatar_key !== key) { c.executionCtx.waitUntil(c.env.AVATARS.delete([user.avatar_key, user.avatar_key.replace(/(\.\w+)$/, '-128$1')]).catch(() => {})); } await c.env.DB.prepare('UPDATE users SET avatar_key = ? WHERE id = ?').bind(key, user.id).run(); return key; } export function registerSettings(app: Hono) { app.get('/settings', async (c) => { const user = c.get('user'); if (!user) return c.redirect('/signin?next=/settings'); const [accounts, tokens, grants] = await Promise.all([ c.env.DB.prepare('SELECT provider, login FROM oauth_accounts WHERE user_id = ?').bind(user.id).all<{ provider: 'github' | 'google'; login: string | null }>(), 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 }>(), c.env.DB.prepare( `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 FROM api_tokens t LEFT JOIN oauth_clients cl ON cl.client_id = t.client_id 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`, ).bind(user.id, now()).all<{ grant_id: string; scopes: string; last_used_at: number | null; created_at: number; client_name: string }>(), ]); const linked = new Set(accounts.results.map((a) => a.provider)); return render( c, { title: 'Settings', noindex: true },

Settings

Profile

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.

{user.avatar_key ? (
) : null}

Email notices

{user.email ? <>Notices go to {user.email}, 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.'}

Sign-in methods

    {(['github', 'google'] as const).map((p) => { const acct = accounts.results.find((a) => a.provider === p); const name = p === 'github' ? 'GitHub' : 'Google'; return (
  • {icon(p, 20)} {name} {acct ? {acct.login ? `@${acct.login}` : 'Linked'} : Not linked} {acct ? ( linked.size > 1 ? (
    ) : ( Your only sign-in method ) ) : providerReady(c, p) ? ( Link {name} ) : ( Being set up )}
  • ); })}

Connected apps

MCP clients you signed in to. Revoking one signs it out at once.

{grants.results.length ? (
    {grants.results.map((g) => (
  • {icon('plug', 20)} {g.client_name} {g.scopes} last used {timeAgo(g.last_used_at)}
  • ))}
) : (

No apps connected. See how to connect over MCP.

)}

Personal access tokens

For scripts and MCP clients without sign-in support. A token acts as you, within the access you give it.

{tokens.results.length ? (
    {tokens.results.map((t) => (
  • {t.name || 'Unnamed token'} {t.scopes} created {timeAgo(t.created_at)}, last used {timeAgo(t.last_used_at)}
  • ))}
) : null}
Access {SCOPES.map((s) => ( ))}

Delete account

This removes your profile, email, sign-in links, sessions and tokens, and takes your skills down. It cannot be undone.

, ); }); app.post('/settings/profile', async (c) => { const user = requireUser(c); const form = await c.req.parseBody(); const name = String(form.display_name ?? '').trim().replace(/\s+/g, ' ').slice(0, 60); const handle = String(form.handle ?? '').trim().toLowerCase(); const bio = String(form.bio ?? '').trim().replace(/\s+/g, ' ').slice(0, 280); const websiteRaw = String(form.website ?? '').trim().slice(0, 200); const website = websiteRaw ? safeUrl(websiteRaw) : ''; // A handle someone already holds stays valid for them, even a reserved one (the studio's own account). let problem = !name ? 'Add a display name.' : handle === user.handle.toLowerCase() ? null : handleProblem(handle); if (!problem && websiteRaw && !website) problem = 'The website must be an http or https address.'; if (!problem && handle !== user.handle.toLowerCase()) { if (!(await rateLimit(c.env, `handle:${user.id}`, 3, 604800))) problem = 'You changed your handle several times this week. Try again later.'; 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.'; } if (problem) { setFlash(c, 'error', problem); return c.redirect('/settings'); } 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(); setFlash(c, 'ok', 'Profile saved.'); return c.redirect('/settings'); }); app.post('/settings/notices', async (c) => { const user = requireUser(c); const form = await c.req.parseBody(); await c.env.DB.prepare('UPDATE users SET email_notices = ? WHERE id = ?').bind(form.email_notices ? 1 : 0, user.id).run(); setFlash(c, 'ok', form.email_notices ? 'Email notices are on.' : 'Email notices are off.'); return c.redirect('/settings'); }); // Avatar upload. The browser crops and resizes; the Worker re-checks type, size and dimensions. app.post('/api/me/avatar', async (c) => { const user = c.get('user'); if (!user) return c.json({ error: 'sign_in', message: 'Sign in first.' }, 401); 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); const len = parseInt(c.req.header('content-length') ?? '0', 10); if (len > MAX_AVATAR * 2 + 4096) return c.json({ error: 'too_large', message: 'Avatars can be up to 2 MB.' }, 413); try { const form = await c.req.formData(); const big = form.get('avatar') as unknown; const small = form.get('avatar_small') as unknown; if (!(big instanceof File)) throw new HttpError(400, 'No image was sent.'); const key = await storeAvatar(c, user, new Uint8Array(await big.arrayBuffer()), small instanceof File ? new Uint8Array(await small.arrayBuffer()) : null); return c.json({ ok: true, url: `/${key}` }); } catch (e) { if (e instanceof HttpError) return c.json({ error: 'refused', message: e.message }, e.status as 400); throw e; } }); app.post('/settings/avatar/remove', async (c) => { const user = requireUser(c); if (user.avatar_key) { await c.env.AVATARS.delete([user.avatar_key, user.avatar_key.replace(/(\.\w+)$/, '-128$1')]).catch(() => {}); await c.env.DB.prepare('UPDATE users SET avatar_key = NULL WHERE id = ?').bind(user.id).run(); } setFlash(c, 'ok', 'Avatar removed.'); return c.redirect('/settings'); }); app.get('/avatars/:uid/:file', async (c) => { const key = `avatars/${c.req.param('uid')}/${c.req.param('file')}`; if (!/^avatars\/[a-z0-9]{8,32}\/[a-f0-9]{20}(-128)?\.(webp|png|jpg)$/.test(key)) return c.notFound(); const obj = await c.env.AVATARS.get(key); if (!obj) return c.notFound(); return new Response(obj.body, { headers: { 'content-type': obj.httpMetadata?.contentType ?? 'image/webp', 'cache-control': 'public, max-age=31536000, immutable', 'x-content-type-options': 'nosniff', etag: obj.httpEtag }, }); }); app.post('/settings/unlink/:provider', async (c) => { const user = requireUser(c); const p = c.req.param('provider'); const count = await c.env.DB.prepare('SELECT COUNT(*) AS n FROM oauth_accounts WHERE user_id = ?').bind(user.id).first<{ n: number }>(); if ((count?.n ?? 0) < 2) { setFlash(c, 'error', 'You cannot unlink your only sign-in method.'); return c.redirect('/settings'); } await c.env.DB.prepare('DELETE FROM oauth_accounts WHERE user_id = ? AND provider = ?').bind(user.id, p).run(); setFlash(c, 'ok', 'Sign-in method unlinked.'); return c.redirect('/settings'); }); app.post('/settings/tokens', async (c) => { const user = requireUser(c); const form = await c.req.parseBody({ all: true }); const scopes = cleanScopes(([] as unknown[]).concat(form.scopes ?? []).filter((x): x is string => typeof x === 'string')); const name = String(form.name ?? '').trim().slice(0, 60); 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 }>(); if (!name || !scopes.length || (count?.n ?? 0) >= 10) { 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.'); return c.redirect('/settings#access'); } const { token } = await createToken(c.env, { userId: user.id, kind: 'pat', name, scopes }); // Shown once, on this response only. It is never stored in readable form. return render( c, { title: 'New token', noindex: true, narrow: true },

Copy your token now

This is the only time it is shown. Skillfarm keeps only a hash of it.

Name: {name}. Access: {scopes.join(', ')}.

Done
, ); }); app.post('/settings/tokens/:id/revoke', async (c) => { const user = requireUser(c); 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(); setFlash(c, 'ok', 'Token revoked.'); return c.redirect('/settings#access'); }); app.post('/settings/grants/:id/revoke', async (c) => { const user = requireUser(c); 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(); setFlash(c, 'ok', 'App disconnected.'); return c.redirect('/settings#access'); }); app.post('/settings/delete', async (c) => { const user = requireUser(c); const form = await c.req.parseBody(); if (String(form.confirm ?? '').trim().toLowerCase() !== user.handle.toLowerCase()) { setFlash(c, 'error', 'The handle you typed does not match.'); return c.redirect('/settings'); } if (user.is_admin) { setFlash(c, 'error', 'Admin accounts cannot be deleted from here.'); return c.redirect('/settings'); } const ts = now(); const skills = await c.env.DB.prepare("SELECT id FROM skills WHERE owner_id = ? AND state != 'removed'").bind(user.id).all<{ id: string }>(); const { reverseSkillPoints } = await import('../lib/points'); for (const s of skills.results) await reverseSkillPoints(c.env, s.id); if (user.avatar_key) await c.env.AVATARS.delete([user.avatar_key, user.avatar_key.replace(/(\.\w+)$/, '-128$1')]).catch(() => {}); await c.env.DB.batch([ c.env.DB.prepare("UPDATE skills SET state = 'removed', featured_at = NULL, updated_at = ? WHERE owner_id = ?").bind(ts, user.id), 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), c.env.DB.prepare('DELETE FROM oauth_accounts WHERE user_id = ?').bind(user.id), c.env.DB.prepare('DELETE FROM sessions WHERE user_id = ?').bind(user.id), c.env.DB.prepare('UPDATE api_tokens SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL').bind(ts, user.id), c.env.DB.prepare( "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 = ?", ).bind(`deleted-${newId(10)}`, user.id), ]); await destroySession(c); setFlash(c, 'ok', 'Your account was deleted.'); return c.redirect('/'); }); }