Skillfarm / website · skillfarm.ai / src / routes / auth.tsx
| 1 | import type { Hono } from 'hono'; |
| 2 | import type { AppEnv, Ctx, User } from '../env'; |
| 3 | import { finishRegistration, finishSignIn, startRegistration, startSignIn, type RegisterMode } from '../lib/biolock'; |
| 4 | import { ipKey, rateLimit } from '../lib/ratelimit'; |
| 5 | import { createSession, destroySession, setFlash } from '../lib/session'; |
| 6 | import { getUserById, handleProblem } from '../lib/users'; |
| 7 | import { HttpError, newId, now, safeNext } from '../lib/util'; |
| 8 | import { brandMark, icon } from '../views/art'; |
| 9 | import { render } from '../views/layout'; |
| 10 | |
| 11 | /** The BioLock buttons. public/js/biolock-page.js does the work; without a fingerprint or face reader it says so. */ |
| 12 | const BioLockButtons = ({ next }: { next: string }) => ( |
| 13 | <div class="signin-buttons" data-biolock data-next={next}> |
| 14 | <button type="button" class="btn btn-primary btn-provider" data-biolock-signin> |
| 15 | {icon('lock', 20)} |
| 16 | <span>Sign in with BioLock</span> |
| 17 | </button> |
| 18 | <button type="button" class="btn btn-ghost btn-provider" data-biolock-register="new"> |
| 19 | <span>New here? Create an account with BioLock</span> |
| 20 | </button> |
| 21 | <p class="fine biolock-status" data-biolock-status role="status" aria-live="polite"></p> |
| 22 | </div> |
| 23 | ); |
| 24 | |
| 25 | async function json(c: Ctx): Promise<Record<string, unknown>> { |
| 26 | try { |
| 27 | const v = await c.req.json(); |
| 28 | return v && typeof v === 'object' ? (v as Record<string, unknown>) : {}; |
| 29 | } catch { |
| 30 | return {}; |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | async function limit(c: Ctx, key: string, n: number, windowSec: number): Promise<void> { |
| 35 | const ip = await ipKey(c.env, c.req.header('cf-connecting-ip')); |
| 36 | if (!(await rateLimit(c.env, `${key}:${ip}`, n, windowSec))) throw new HttpError(429, 'Too many tries from this network. Try again later.'); |
| 37 | } |
| 38 | |
| 39 | export function registerAuth(app: Hono<AppEnv>) { |
| 40 | app.get('/signin', (c) => { |
| 41 | const next = safeNext(c.req.query('next')); |
| 42 | if (c.get('user')) return c.redirect(next); |
| 43 | return render( |
| 44 | c, |
| 45 | { title: 'Sign in', noindex: true, narrow: true }, |
| 46 | <section class="auth-card card"> |
| 47 | {brandMark(56)} |
| 48 | <h1>Sign in to Skillfarm</h1> |
| 49 | <p class="lede">Share skills, earn Seeds and build your portfolio. It is free.</p> |
| 50 | <BioLockButtons next={next} /> |
| 51 | <p class="fine"> |
| 52 | BioLock signs you in with the fingerprint or face reader built into your own device. There is no password to remember, steal or leak, and Skillfarm never sees your fingerprint or face: your device checks it and only proves the result. See the <a href="/privacy">privacy page</a>. |
| 53 | </p> |
| 54 | <p class="fine">Had an account from before BioLock? Create a new account with BioLock here. If you need your old skills moved to it, use Report on any skill page and tell us your old handle.</p> |
| 55 | {c.env.DEV_LOGIN === '1' && ['localhost', '127.0.0.1'].includes(new URL(c.req.url).hostname) ? ( |
| 56 | <p class="fine"> |
| 57 | Local development: <a href="/dev/login?as=dev-grower">sign in as a test member</a> or <a href="/dev/login?as=dev-admin&admin=1">as a test admin</a>. |
| 58 | </p> |
| 59 | ) : null} |
| 60 | </section>, |
| 61 | ); |
| 62 | }); |
| 63 | |
| 64 | app.get('/biolock/add', (c) => |
| 65 | render( |
| 66 | c, |
| 67 | { title: 'Add BioLock on this device', noindex: true, narrow: true }, |
| 68 | <section class="auth-card card"> |
| 69 | {brandMark(56)} |
| 70 | <h1>Add BioLock on this device</h1> |
| 71 | <p class="lede">This one-time link adds this device's fingerprint or face reader to your Skillfarm account. After that, this device signs you in on its own.</p> |
| 72 | <div class="signin-buttons" data-biolock data-next="/settings"> |
| 73 | <button type="button" class="btn btn-primary btn-provider" data-biolock-register="link"> |
| 74 | {icon('lock', 20)} |
| 75 | <span>Add BioLock on this device</span> |
| 76 | </button> |
| 77 | <p class="fine biolock-status" data-biolock-status role="status" aria-live="polite"></p> |
| 78 | </div> |
| 79 | <p class="fine">The link works once, for ten minutes. If it has expired, make a new one in Settings on a device that is signed in.</p> |
| 80 | </section>, |
| 81 | ), |
| 82 | ); |
| 83 | |
| 84 | app.post('/api/biolock/signin/options', async (c) => { |
| 85 | await limit(c, 'biolock-signin', 60, 3600); |
| 86 | const body = await json(c); |
| 87 | return c.json(await startSignIn(c, body.ids)); |
| 88 | }); |
| 89 | |
| 90 | app.post('/api/biolock/signin/verify', async (c) => { |
| 91 | await limit(c, 'biolock-signin', 60, 3600); |
| 92 | const body = await json(c); |
| 93 | const user = await finishSignIn(c, body.challengeId, body.response); |
| 94 | await createSession(c, user.id); |
| 95 | const next = safeNext(typeof body.next === 'string' ? body.next : '/'); |
| 96 | return c.json({ ok: true, next: user.onboarded ? next : `/welcome?next=${encodeURIComponent(next)}` }); |
| 97 | }); |
| 98 | |
| 99 | app.post('/api/biolock/register/options', async (c) => { |
| 100 | const body = await json(c); |
| 101 | const mode = (['new', 'add', 'link'] as RegisterMode[]).find((m) => m === body.mode); |
| 102 | if (!mode) throw new HttpError(400, 'Unknown request.'); |
| 103 | await limit(c, 'biolock-register', 30, 3600); |
| 104 | return c.json(await startRegistration(c, mode, body.token)); |
| 105 | }); |
| 106 | |
| 107 | app.post('/api/biolock/register/verify', async (c) => { |
| 108 | const body = await json(c); |
| 109 | const name = typeof body.name === 'string' ? body.name.replace(/[^\w .,'-]/g, '').trim() || 'Device' : 'Device'; |
| 110 | await limit(c, 'biolock-register', 30, 3600); |
| 111 | // A new account is only made once the device has proved it holds a working reader. |
| 112 | const peek = typeof body.challengeId === 'string' ? await c.env.DB.prepare('SELECT kind FROM biolock_challenges WHERE id = ?').bind(body.challengeId).first<{ kind: string }>() : null; |
| 113 | if (peek?.kind === 'new') await limit(c, 'signup', 5, 86400); |
| 114 | const { userId, created } = await finishRegistration(c, body.challengeId, body.response, name); |
| 115 | const signedIn = c.get('user'); |
| 116 | if (!signedIn || signedIn.id !== userId) await createSession(c, userId); |
| 117 | const next = safeNext(typeof body.next === 'string' ? body.next : '/'); |
| 118 | if (created) return c.json({ ok: true, next: `/welcome?next=${encodeURIComponent(next)}` }); |
| 119 | setFlash(c, 'ok', 'BioLock is now on this device.'); |
| 120 | return c.json({ ok: true, next: signedIn ? '/settings#biolock' : next }); |
| 121 | }); |
| 122 | |
| 123 | app.post('/signout', async (c) => { |
| 124 | await destroySession(c); |
| 125 | return c.redirect('/'); |
| 126 | }); |
| 127 | |
| 128 | app.get('/welcome', (c) => { |
| 129 | const user = c.get('user'); |
| 130 | const next = safeNext(c.req.query('next')); |
| 131 | if (!user) return c.redirect('/signin'); |
| 132 | return render( |
| 133 | c, |
| 134 | { title: 'Welcome', noindex: true, narrow: true }, |
| 135 | <section class="auth-card card"> |
| 136 | {brandMark(56)} |
| 137 | <h1>Welcome to the farm</h1> |
| 138 | <p class="lede">Pick the name and handle people will see on your skills. You can change both later in settings.</p> |
| 139 | <form method="post" action={`/welcome?next=${encodeURIComponent(next)}`} class="form"> |
| 140 | <label> |
| 141 | <span>Display name</span> |
| 142 | <input name="display_name" value={user.display_name === 'New grower' ? '' : user.display_name} required maxlength={60} autocomplete="nickname" /> |
| 143 | </label> |
| 144 | <label> |
| 145 | <span>Handle</span> |
| 146 | <div class="input-prefix"> |
| 147 | <span>skillfarm.ai/u/</span> |
| 148 | <input name="handle" value={user.handle} required minlength={2} maxlength={30} pattern="[a-z0-9][a-z0-9\-]{0,28}[a-z0-9]" autocapitalize="none" spellcheck={false} /> |
| 149 | </div> |
| 150 | </label> |
| 151 | <button class="btn btn-primary" type="submit">Start growing</button> |
| 152 | </form> |
| 153 | </section>, |
| 154 | ); |
| 155 | }); |
| 156 | |
| 157 | app.post('/welcome', async (c) => { |
| 158 | const user = c.get('user'); |
| 159 | if (!user) return c.redirect('/signin'); |
| 160 | const next = safeNext(c.req.query('next')); |
| 161 | const form = await c.req.parseBody(); |
| 162 | const name = String(form.display_name ?? '').trim().replace(/\s+/g, ' ').slice(0, 60); |
| 163 | const handle = String(form.handle ?? '').trim().toLowerCase(); |
| 164 | const problem = name.length < 1 ? 'Add a display name.' : handleProblem(handle); |
| 165 | if (problem) { |
| 166 | setFlash(c, 'error', problem); |
| 167 | return c.redirect(`/welcome?next=${encodeURIComponent(next)}`); |
| 168 | } |
| 169 | if (handle !== user.handle.toLowerCase()) { |
| 170 | const taken = await c.env.DB.prepare('SELECT 1 AS x FROM users WHERE handle = ? AND id != ?').bind(handle, user.id).first(); |
| 171 | if (taken) { |
| 172 | setFlash(c, 'error', 'That handle is taken. Try another.'); |
| 173 | return c.redirect(`/welcome?next=${encodeURIComponent(next)}`); |
| 174 | } |
| 175 | } |
| 176 | await c.env.DB.prepare('UPDATE users SET display_name = ?, handle = ?, onboarded = 1 WHERE id = ?').bind(name, handle, user.id).run(); |
| 177 | return c.redirect(next === '/' ? `/u/${handle}` : next); |
| 178 | }); |
| 179 | |
| 180 | // Local development only: lets the test suite sign in without a fingerprint or face reader. |
| 181 | app.get('/dev/login', async (c) => { |
| 182 | const host = new URL(c.req.url).hostname; |
| 183 | if (c.env.DEV_LOGIN !== '1' || !['localhost', '127.0.0.1'].includes(host)) throw new HttpError(404, 'Not found.'); |
| 184 | const handle = (c.req.query('as') ?? 'dev-grower').toLowerCase(); |
| 185 | const admin = c.req.query('admin') === '1' ? 1 : 0; |
| 186 | const age = parseInt(c.req.query('age_days') ?? '0', 10) || 0; |
| 187 | let user = await c.env.DB.prepare('SELECT * FROM users WHERE handle = ?').bind(handle).first<User>(); |
| 188 | if (user?.is_agent) throw new HttpError(404, 'Not found.'); |
| 189 | if (!user) { |
| 190 | const id = newId(); |
| 191 | await c.env.DB.prepare('INSERT INTO users (id, handle, display_name, email, is_admin, onboarded, created_at) VALUES (?,?,?,?,?,1,?)').bind(id, handle, handle.replace(/-/g, ' '), `${handle}@example.test`, admin, now() - age * 86400).run(); |
| 192 | user = (await getUserById(c.env, id))!; |
| 193 | } |
| 194 | await createSession(c, user.id); |
| 195 | return c.redirect(safeNext(c.req.query('next'))); |
| 196 | }); |
| 197 | } |