import type { Hono } from 'hono'; import type { AppEnv, Ctx, User } from '../env'; import { finishRegistration, finishSignIn, startRegistration, startSignIn, type RegisterMode } from '../lib/biolock'; import { ipKey, rateLimit } from '../lib/ratelimit'; import { createSession, destroySession, setFlash } from '../lib/session'; import { getUserById, handleProblem } from '../lib/users'; import { HttpError, newId, now, safeNext } from '../lib/util'; import { brandMark, icon } from '../views/art'; import { render } from '../views/layout'; /** The BioLock buttons. public/js/biolock-page.js does the work; without a fingerprint or face reader it says so. */ const BioLockButtons = ({ next }: { next: string }) => (

); async function json(c: Ctx): Promise> { try { const v = await c.req.json(); return v && typeof v === 'object' ? (v as Record) : {}; } catch { return {}; } } async function limit(c: Ctx, key: string, n: number, windowSec: number): Promise { const ip = await ipKey(c.env, c.req.header('cf-connecting-ip')); if (!(await rateLimit(c.env, `${key}:${ip}`, n, windowSec))) throw new HttpError(429, 'Too many tries from this network. Try again later.'); } export function registerAuth(app: Hono) { app.get('/signin', (c) => { const next = safeNext(c.req.query('next')); if (c.get('user')) return c.redirect(next); return render( c, { title: 'Sign in', noindex: true, narrow: true },
{brandMark(56)}

Sign in to Skillfarm

Share skills, earn Seeds and build your portfolio. It is free.

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 privacy page.

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.

{c.env.DEV_LOGIN === '1' && ['localhost', '127.0.0.1'].includes(new URL(c.req.url).hostname) ? (

Local development: sign in as a test member or as a test admin.

) : null}
, ); }); app.get('/biolock/add', (c) => render( c, { title: 'Add BioLock on this device', noindex: true, narrow: true },
{brandMark(56)}

Add BioLock on this device

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.

The link works once, for ten minutes. If it has expired, make a new one in Settings on a device that is signed in.

, ), ); app.post('/api/biolock/signin/options', async (c) => { await limit(c, 'biolock-signin', 60, 3600); const body = await json(c); return c.json(await startSignIn(c, body.ids)); }); app.post('/api/biolock/signin/verify', async (c) => { await limit(c, 'biolock-signin', 60, 3600); const body = await json(c); const user = await finishSignIn(c, body.challengeId, body.response); await createSession(c, user.id); const next = safeNext(typeof body.next === 'string' ? body.next : '/'); return c.json({ ok: true, next: user.onboarded ? next : `/welcome?next=${encodeURIComponent(next)}` }); }); app.post('/api/biolock/register/options', async (c) => { const body = await json(c); const mode = (['new', 'add', 'link'] as RegisterMode[]).find((m) => m === body.mode); if (!mode) throw new HttpError(400, 'Unknown request.'); await limit(c, 'biolock-register', 30, 3600); return c.json(await startRegistration(c, mode, body.token)); }); app.post('/api/biolock/register/verify', async (c) => { const body = await json(c); const name = typeof body.name === 'string' ? body.name.replace(/[^\w .,'-]/g, '').trim() || 'Device' : 'Device'; await limit(c, 'biolock-register', 30, 3600); // A new account is only made once the device has proved it holds a working reader. 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; if (peek?.kind === 'new') await limit(c, 'signup', 5, 86400); const { userId, created } = await finishRegistration(c, body.challengeId, body.response, name); const signedIn = c.get('user'); if (!signedIn || signedIn.id !== userId) await createSession(c, userId); const next = safeNext(typeof body.next === 'string' ? body.next : '/'); if (created) return c.json({ ok: true, next: `/welcome?next=${encodeURIComponent(next)}` }); setFlash(c, 'ok', 'BioLock is now on this device.'); return c.json({ ok: true, next: signedIn ? '/settings#biolock' : next }); }); app.post('/signout', async (c) => { await destroySession(c); return c.redirect('/'); }); app.get('/welcome', (c) => { const user = c.get('user'); const next = safeNext(c.req.query('next')); if (!user) return c.redirect('/signin'); return render( c, { title: 'Welcome', noindex: true, narrow: true },
{brandMark(56)}

Welcome to the farm

Pick the name and handle people will see on your skills. You can change both later in settings.

, ); }); app.post('/welcome', async (c) => { const user = c.get('user'); if (!user) return c.redirect('/signin'); const next = safeNext(c.req.query('next')); 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 problem = name.length < 1 ? 'Add a display name.' : handleProblem(handle); if (problem) { setFlash(c, 'error', problem); return c.redirect(`/welcome?next=${encodeURIComponent(next)}`); } if (handle !== user.handle.toLowerCase()) { const taken = await c.env.DB.prepare('SELECT 1 AS x FROM users WHERE handle = ? AND id != ?').bind(handle, user.id).first(); if (taken) { setFlash(c, 'error', 'That handle is taken. Try another.'); return c.redirect(`/welcome?next=${encodeURIComponent(next)}`); } } await c.env.DB.prepare('UPDATE users SET display_name = ?, handle = ?, onboarded = 1 WHERE id = ?').bind(name, handle, user.id).run(); return c.redirect(next === '/' ? `/u/${handle}` : next); }); // Local development only: lets the test suite sign in without a fingerprint or face reader. app.get('/dev/login', async (c) => { const host = new URL(c.req.url).hostname; if (c.env.DEV_LOGIN !== '1' || !['localhost', '127.0.0.1'].includes(host)) throw new HttpError(404, 'Not found.'); const handle = (c.req.query('as') ?? 'dev-grower').toLowerCase(); const admin = c.req.query('admin') === '1' ? 1 : 0; const age = parseInt(c.req.query('age_days') ?? '0', 10) || 0; let user = await c.env.DB.prepare('SELECT * FROM users WHERE handle = ?').bind(handle).first(); if (user?.is_agent) throw new HttpError(404, 'Not found.'); if (!user) { const id = newId(); 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(); user = (await getUserById(c.env, id))!; } await createSession(c, user.id); return c.redirect(safeNext(c.req.query('next'))); }); }