Skillfarm / website · skillfarm.ai / src / routes / auth.tsx
| 1 | import type { Hono } from 'hono'; |
| 2 | import type { AppEnv, Ctx, User } from '../env'; |
| 3 | import { mail } from '../lib/email'; |
| 4 | import { ipKey, rateLimit } from '../lib/ratelimit'; |
| 5 | import { clearCookie, createSession, destroySession, getSigned, setFlash, setSigned } from '../lib/session'; |
| 6 | import { getUserById, handleProblem, isAdminGithubId, uniqueHandle } from '../lib/users'; |
| 7 | import { SPROUT_ID } from '../lib/skills'; |
| 8 | import { HttpError, newId, now, randomToken, safeEqual, safeNext, sha256B64url } from '../lib/util'; |
| 9 | import { brandMark, icon } from '../views/art'; |
| 10 | import { render } from '../views/layout'; |
| 11 | |
| 12 | type Provider = 'github' | 'google'; |
| 13 | type Tx = { provider: Provider; state: string; verifier: string; next: string; link: boolean }; |
| 14 | type Identity = { provider: Provider; id: string; login: string | null; name: string | null; email: string | null; emailVerified: boolean; avatar: string | null }; |
| 15 | type PendingLink = Identity & { existingProviders: string[] }; |
| 16 | |
| 17 | const PROVIDER_NAME: Record<Provider, string> = { github: 'GitHub', google: 'Google' }; |
| 18 | |
| 19 | export function providerReady(c: Ctx, p: Provider): boolean { |
| 20 | return p === 'github' ? !!(c.env.GITHUB_CLIENT_ID && c.env.GITHUB_CLIENT_SECRET) : !!(c.env.GOOGLE_CLIENT_ID && c.env.GOOGLE_CLIENT_SECRET); |
| 21 | } |
| 22 | |
| 23 | function callbackUrl(c: Ctx, p: Provider): string { |
| 24 | return `${new URL(c.req.url).origin}/auth/${p}/callback`; |
| 25 | } |
| 26 | |
| 27 | async function exchange(c: Ctx, p: Provider, code: string, verifier: string): Promise<Identity> { |
| 28 | if (p === 'github') { |
| 29 | const tokenRes = await fetch('https://github.com/login/oauth/access_token', { |
| 30 | method: 'POST', |
| 31 | headers: { accept: 'application/json', 'content-type': 'application/json', 'user-agent': 'skillfarm' }, |
| 32 | body: JSON.stringify({ client_id: c.env.GITHUB_CLIENT_ID, client_secret: c.env.GITHUB_CLIENT_SECRET, code, redirect_uri: callbackUrl(c, p), code_verifier: verifier }), |
| 33 | }); |
| 34 | const tok = (await tokenRes.json()) as { access_token?: string }; |
| 35 | if (!tok.access_token) throw new HttpError(400, 'GitHub did not complete the sign-in. Try again.'); |
| 36 | const h = { authorization: `Bearer ${tok.access_token}`, accept: 'application/vnd.github+json', 'user-agent': 'skillfarm' }; |
| 37 | const [uRes, eRes] = await Promise.all([fetch('https://api.github.com/user', { headers: h }), fetch('https://api.github.com/user/emails', { headers: h })]); |
| 38 | if (!uRes.ok) throw new HttpError(502, 'Could not read your GitHub profile. Try again.'); |
| 39 | const u = (await uRes.json()) as { id: number; login: string; name: string | null; avatar_url: string | null }; |
| 40 | const emails = eRes.ok ? ((await eRes.json()) as { email: string; primary: boolean; verified: boolean }[]) : []; |
| 41 | const primary = Array.isArray(emails) ? emails.find((e) => e.primary && e.verified) : undefined; |
| 42 | return { provider: p, id: String(u.id), login: u.login, name: u.name, email: primary?.email.toLowerCase() ?? null, emailVerified: !!primary, avatar: u.avatar_url ? `https://avatars.githubusercontent.com/u/${u.id}?s=256&v=4` : null }; |
| 43 | } |
| 44 | const tokenRes = await fetch('https://oauth2.googleapis.com/token', { |
| 45 | method: 'POST', |
| 46 | headers: { 'content-type': 'application/x-www-form-urlencoded' }, |
| 47 | body: new URLSearchParams({ client_id: c.env.GOOGLE_CLIENT_ID!, client_secret: c.env.GOOGLE_CLIENT_SECRET!, code, code_verifier: verifier, grant_type: 'authorization_code', redirect_uri: callbackUrl(c, p) }), |
| 48 | }); |
| 49 | const tok = (await tokenRes.json()) as { access_token?: string }; |
| 50 | if (!tok.access_token) throw new HttpError(400, 'Google did not complete the sign-in. Try again.'); |
| 51 | const uRes = await fetch('https://openidconnect.googleapis.com/v1/userinfo', { headers: { authorization: `Bearer ${tok.access_token}` } }); |
| 52 | if (!uRes.ok) throw new HttpError(502, 'Could not read your Google profile. Try again.'); |
| 53 | const u = (await uRes.json()) as { sub: string; email?: string; email_verified?: boolean }; |
| 54 | // Only the id and verified email are kept from Google. The name and photo are not stored. |
| 55 | return { provider: p, id: u.sub, login: null, name: null, email: u.email?.toLowerCase() ?? null, emailVerified: !!u.email_verified, avatar: null }; |
| 56 | } |
| 57 | |
| 58 | async function linkIdentity(c: Ctx, userId: string, id: Identity): Promise<void> { |
| 59 | await c.env.DB.prepare('INSERT OR IGNORE INTO oauth_accounts (provider, provider_user_id, user_id, login, email, email_verified, created_at) VALUES (?,?,?,?,?,?,?)') |
| 60 | .bind(id.provider, id.id, userId, id.login, id.emailVerified ? id.email : null, id.emailVerified ? 1 : 0, now()) |
| 61 | .run(); |
| 62 | } |
| 63 | |
| 64 | async function afterSignIn(c: Ctx, user: User, id: Identity, next: string): Promise<Response> { |
| 65 | const sets: string[] = []; |
| 66 | const args: unknown[] = []; |
| 67 | if (id.emailVerified && id.email && !user.email) { sets.push('email = ?'); args.push(id.email); } |
| 68 | if (id.provider === 'github') { |
| 69 | if (isAdminGithubId(c.env, id.id) && !user.is_admin) sets.push('is_admin = 1'); |
| 70 | if (id.avatar && !user.is_agent && user.avatar_fallback !== id.avatar) { sets.push('avatar_fallback = ?'); args.push(id.avatar); } |
| 71 | await c.env.DB.prepare("UPDATE oauth_accounts SET login = ?, email = COALESCE(?, email), email_verified = MAX(email_verified, ?) WHERE provider = 'github' AND provider_user_id = ?") |
| 72 | .bind(id.login, id.emailVerified ? id.email : null, id.emailVerified ? 1 : 0, id.id) |
| 73 | .run(); |
| 74 | } |
| 75 | if (sets.length) await c.env.DB.prepare(`UPDATE users SET ${sets.join(', ')} WHERE id = ?`).bind(...args, user.id).run(); |
| 76 | |
| 77 | // Finish a link that was waiting for proof of control of the existing account. |
| 78 | const pending = await getSigned<PendingLink>(c, 'sf_link'); |
| 79 | if (pending) { |
| 80 | clearCookie(c, 'sf_link'); |
| 81 | if (pending.provider !== id.provider) { |
| 82 | const taken = await c.env.DB.prepare('SELECT user_id FROM oauth_accounts WHERE provider = ? AND provider_user_id = ?').bind(pending.provider, pending.id).first(); |
| 83 | if (!taken) { |
| 84 | await linkIdentity(c, user.id, pending); |
| 85 | setFlash(c, 'ok', `${PROVIDER_NAME[pending.provider]} is now linked to your account.`); |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | await createSession(c, user.id); |
| 90 | return c.redirect(user.onboarded ? next : `/welcome?next=${encodeURIComponent(next)}`); |
| 91 | } |
| 92 | |
| 93 | const SignInButtons = ({ c, next, link }: { c: Ctx; next: string; link?: boolean }) => ( |
| 94 | <div class="signin-buttons"> |
| 95 | {(['github', 'google'] as Provider[]).map((p) => |
| 96 | providerReady(c, p) ? ( |
| 97 | <a class={`btn btn-provider btn-${p}`} href={`/auth/${p}/start?next=${encodeURIComponent(next)}${link ? '&link=1' : ''}`}> |
| 98 | {icon(p, 20)} |
| 99 | <span>Continue with {PROVIDER_NAME[p]}</span> |
| 100 | </a> |
| 101 | ) : ( |
| 102 | <span class={`btn btn-provider btn-${p} is-disabled`} aria-disabled="true"> |
| 103 | {icon(p, 20)} |
| 104 | <span>{PROVIDER_NAME[p]} sign-in is being set up</span> |
| 105 | </span> |
| 106 | ), |
| 107 | )} |
| 108 | </div> |
| 109 | ); |
| 110 | |
| 111 | export function registerAuth(app: Hono<AppEnv>) { |
| 112 | app.get('/signin', (c) => { |
| 113 | const next = safeNext(c.req.query('next')); |
| 114 | if (c.get('user')) return c.redirect(next); |
| 115 | return render( |
| 116 | c, |
| 117 | { title: 'Sign in', noindex: true, narrow: true }, |
| 118 | <section class="auth-card card"> |
| 119 | {brandMark(56)} |
| 120 | <h1>Sign in to Skillfarm</h1> |
| 121 | <p class="lede">Share skills, earn Seeds and build your portfolio. It is free.</p> |
| 122 | <SignInButtons c={c} next={next} /> |
| 123 | <p class="fine"> |
| 124 | No passwords. Skillfarm keeps your provider account id and verified email, and uses the email only for notices about your skills. See the <a href="/privacy">privacy page</a>. |
| 125 | </p> |
| 126 | {c.env.DEV_LOGIN === '1' && ['localhost', '127.0.0.1'].includes(new URL(c.req.url).hostname) ? ( |
| 127 | <p class="fine"> |
| 128 | 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>. |
| 129 | </p> |
| 130 | ) : null} |
| 131 | </section>, |
| 132 | ); |
| 133 | }); |
| 134 | |
| 135 | app.get('/auth/:provider/start', async (c) => { |
| 136 | const p = c.req.param('provider') as Provider; |
| 137 | if (p !== 'github' && p !== 'google') throw new HttpError(404, 'Unknown sign-in provider.'); |
| 138 | if (!providerReady(c, p)) throw new HttpError(503, `${PROVIDER_NAME[p]} sign-in is not set up yet.`); |
| 139 | const ip = await ipKey(c.env, c.req.header('cf-connecting-ip')); |
| 140 | if (!(await rateLimit(c.env, `auth:${ip}`, 30, 3600))) throw new HttpError(429, 'Too many sign-in attempts. Try again later.'); |
| 141 | const tx: Tx = { provider: p, state: randomToken(24), verifier: randomToken(48), next: safeNext(c.req.query('next')), link: c.req.query('link') === '1' }; |
| 142 | await setSigned(c, 'sf_oauth', tx, 600); |
| 143 | const challenge = await sha256B64url(tx.verifier); |
| 144 | const u = new URL(p === 'github' ? 'https://github.com/login/oauth/authorize' : 'https://accounts.google.com/o/oauth2/v2/auth'); |
| 145 | u.searchParams.set('client_id', (p === 'github' ? c.env.GITHUB_CLIENT_ID : c.env.GOOGLE_CLIENT_ID)!); |
| 146 | u.searchParams.set('redirect_uri', callbackUrl(c, p)); |
| 147 | u.searchParams.set('state', tx.state); |
| 148 | u.searchParams.set('code_challenge', challenge); |
| 149 | u.searchParams.set('code_challenge_method', 'S256'); |
| 150 | if (p === 'github') { |
| 151 | u.searchParams.set('scope', 'read:user user:email'); |
| 152 | } else { |
| 153 | u.searchParams.set('response_type', 'code'); |
| 154 | u.searchParams.set('scope', 'openid email'); |
| 155 | u.searchParams.set('prompt', 'select_account'); |
| 156 | } |
| 157 | return c.redirect(u.toString()); |
| 158 | }); |
| 159 | |
| 160 | app.get('/auth/:provider/callback', async (c) => { |
| 161 | const p = c.req.param('provider') as Provider; |
| 162 | const tx = await getSigned<Tx>(c, 'sf_oauth'); |
| 163 | clearCookie(c, 'sf_oauth'); |
| 164 | const state = c.req.query('state') ?? ''; |
| 165 | const code = c.req.query('code'); |
| 166 | if (c.req.query('error')) { |
| 167 | setFlash(c, 'error', 'Sign-in was cancelled.'); |
| 168 | return c.redirect('/signin'); |
| 169 | } |
| 170 | if (!tx || tx.provider !== p || !code || !safeEqual(tx.state, state)) throw new HttpError(400, 'That sign-in link expired. Start again from the sign-in page.'); |
| 171 | const id = await exchange(c, p, code, tx.verifier); |
| 172 | const current = c.get('user'); |
| 173 | const existing = await c.env.DB.prepare('SELECT user_id FROM oauth_accounts WHERE provider = ? AND provider_user_id = ?').bind(p, id.id).first<{ user_id: string }>(); |
| 174 | |
| 175 | if (existing) { |
| 176 | if (current && existing.user_id !== current.id) { |
| 177 | setFlash(c, 'error', `That ${PROVIDER_NAME[p]} account is already linked to a different Skillfarm account.`); |
| 178 | return c.redirect('/settings'); |
| 179 | } |
| 180 | const user = await getUserById(c.env, existing.user_id); |
| 181 | if (!user || user.status !== 'active') throw new HttpError(403, 'This account is not active.'); |
| 182 | return afterSignIn(c, user, id, tx.next); |
| 183 | } |
| 184 | |
| 185 | if (current) { |
| 186 | // Signed in and adding a second provider from settings. |
| 187 | await linkIdentity(c, current.id, id); |
| 188 | setFlash(c, 'ok', `${PROVIDER_NAME[p]} is now linked to your account.`); |
| 189 | return c.redirect('/settings'); |
| 190 | } |
| 191 | |
| 192 | if (p === 'github' && isAdminGithubId(c.env, id.id)) { |
| 193 | // The site owner runs Skillfarm as Sprout and keeps no member account of their own. |
| 194 | const sprout = await getUserById(c.env, SPROUT_ID); |
| 195 | if (sprout && sprout.status === 'active') { |
| 196 | await linkIdentity(c, sprout.id, id); |
| 197 | return afterSignIn(c, sprout, id, tx.next); |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | if (id.emailVerified && id.email) { |
| 202 | // Same verified email as an existing member: never merge silently. Ask for proof of control of that account first. |
| 203 | const match = await c.env.DB.prepare( |
| 204 | `SELECT u.id FROM users u WHERE u.status = 'active' AND (u.email = ?1 OR u.id IN (SELECT user_id FROM oauth_accounts WHERE email = ?1 AND email_verified = 1)) LIMIT 1`, |
| 205 | ).bind(id.email).first<{ id: string }>(); |
| 206 | if (match) { |
| 207 | const provs = await c.env.DB.prepare('SELECT provider FROM oauth_accounts WHERE user_id = ?').bind(match.id).all<{ provider: Provider }>(); |
| 208 | const existingProviders = provs.results.map((r) => r.provider); |
| 209 | await setSigned(c, 'sf_link', { ...id, existingProviders } satisfies PendingLink, 600); |
| 210 | const other = existingProviders[0] ?? 'github'; |
| 211 | return render( |
| 212 | c, |
| 213 | { title: 'Link your accounts', noindex: true, narrow: true }, |
| 214 | <section class="auth-card card"> |
| 215 | {brandMark(56)} |
| 216 | <h1>This email already has a Skillfarm account</h1> |
| 217 | <p class="lede"> |
| 218 | Sign in with {PROVIDER_NAME[other]} to link {PROVIDER_NAME[p]} to it. After that, either one signs you in. |
| 219 | </p> |
| 220 | <div class="signin-buttons"> |
| 221 | <a class={`btn btn-provider btn-${other}`} href={`/auth/${other}/start?next=${encodeURIComponent(tx.next)}`}> |
| 222 | {icon(other, 20)} |
| 223 | <span>Continue with {PROVIDER_NAME[other]}</span> |
| 224 | </a> |
| 225 | </div> |
| 226 | <p class="fine">Skillfarm does not merge accounts on a matching email alone, so nobody can take over an account by adding your address elsewhere.</p> |
| 227 | </section>, |
| 228 | ); |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | const ip = await ipKey(c.env, c.req.header('cf-connecting-ip')); |
| 233 | if (!(await rateLimit(c.env, `signup:${ip}`, 5, 86400))) throw new HttpError(429, 'Too many new accounts from this network today.'); |
| 234 | const userId = newId(); |
| 235 | const handle = await uniqueHandle(c.env, id.login ?? `grower-${newId(5)}`); |
| 236 | const displayName = (id.name || id.login || 'New grower').slice(0, 60); |
| 237 | const admin = p === 'github' && isAdminGithubId(c.env, id.id) ? 1 : 0; |
| 238 | await c.env.DB.batch([ |
| 239 | c.env.DB.prepare('INSERT INTO users (id, handle, display_name, avatar_fallback, email, is_admin, created_at) VALUES (?,?,?,?,?,?,?)').bind(userId, handle, displayName, id.avatar, id.emailVerified ? id.email : null, admin, now()), |
| 240 | c.env.DB.prepare('INSERT INTO oauth_accounts (provider, provider_user_id, user_id, login, email, email_verified, created_at) VALUES (?,?,?,?,?,?,?)').bind(p, id.id, userId, id.login, id.emailVerified ? id.email : null, id.emailVerified ? 1 : 0, now()), |
| 241 | ]); |
| 242 | const user = (await getUserById(c.env, userId))!; |
| 243 | c.executionCtx.waitUntil(mail.welcome(c.env, user, handle).catch(() => false)); |
| 244 | await createSession(c, userId); |
| 245 | return c.redirect(`/welcome?next=${encodeURIComponent(tx.next)}`); |
| 246 | }); |
| 247 | |
| 248 | app.post('/signout', async (c) => { |
| 249 | await destroySession(c); |
| 250 | return c.redirect('/'); |
| 251 | }); |
| 252 | |
| 253 | app.get('/welcome', (c) => { |
| 254 | const user = c.get('user'); |
| 255 | const next = safeNext(c.req.query('next')); |
| 256 | if (!user) return c.redirect('/signin'); |
| 257 | return render( |
| 258 | c, |
| 259 | { title: 'Welcome', noindex: true, narrow: true }, |
| 260 | <section class="auth-card card"> |
| 261 | {brandMark(56)} |
| 262 | <h1>Welcome to the farm</h1> |
| 263 | <p class="lede">Pick the name and handle people will see on your skills. You can change both later in settings.</p> |
| 264 | <form method="post" action={`/welcome?next=${encodeURIComponent(next)}`} class="form"> |
| 265 | <label> |
| 266 | <span>Display name</span> |
| 267 | <input name="display_name" value={user.display_name === 'New grower' ? '' : user.display_name} required maxlength={60} autocomplete="nickname" /> |
| 268 | </label> |
| 269 | <label> |
| 270 | <span>Handle</span> |
| 271 | <div class="input-prefix"> |
| 272 | <span>skillfarm.ai/u/</span> |
| 273 | <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} /> |
| 274 | </div> |
| 275 | </label> |
| 276 | <button class="btn btn-primary" type="submit">Start growing</button> |
| 277 | </form> |
| 278 | </section>, |
| 279 | ); |
| 280 | }); |
| 281 | |
| 282 | app.post('/welcome', async (c) => { |
| 283 | const user = c.get('user'); |
| 284 | if (!user) return c.redirect('/signin'); |
| 285 | const next = safeNext(c.req.query('next')); |
| 286 | const form = await c.req.parseBody(); |
| 287 | const name = String(form.display_name ?? '').trim().replace(/\s+/g, ' ').slice(0, 60); |
| 288 | const handle = String(form.handle ?? '').trim().toLowerCase(); |
| 289 | const problem = name.length < 1 ? 'Add a display name.' : handleProblem(handle); |
| 290 | if (problem) { |
| 291 | setFlash(c, 'error', problem); |
| 292 | return c.redirect(`/welcome?next=${encodeURIComponent(next)}`); |
| 293 | } |
| 294 | if (handle !== user.handle.toLowerCase()) { |
| 295 | const taken = await c.env.DB.prepare('SELECT 1 AS x FROM users WHERE handle = ? AND id != ?').bind(handle, user.id).first(); |
| 296 | if (taken) { |
| 297 | setFlash(c, 'error', 'That handle is taken. Try another.'); |
| 298 | return c.redirect(`/welcome?next=${encodeURIComponent(next)}`); |
| 299 | } |
| 300 | } |
| 301 | await c.env.DB.prepare('UPDATE users SET display_name = ?, handle = ?, onboarded = 1 WHERE id = ?').bind(name, handle, user.id).run(); |
| 302 | return c.redirect(next === '/' ? `/u/${handle}` : next); |
| 303 | }); |
| 304 | |
| 305 | // Local development only: lets the test suite sign in without a real OAuth provider. |
| 306 | app.get('/dev/login', async (c) => { |
| 307 | const host = new URL(c.req.url).hostname; |
| 308 | if (c.env.DEV_LOGIN !== '1' || !['localhost', '127.0.0.1'].includes(host)) throw new HttpError(404, 'Not found.'); |
| 309 | const handle = (c.req.query('as') ?? 'dev-grower').toLowerCase(); |
| 310 | const admin = c.req.query('admin') === '1' ? 1 : 0; |
| 311 | const age = parseInt(c.req.query('age_days') ?? '0', 10) || 0; |
| 312 | let user = await c.env.DB.prepare('SELECT * FROM users WHERE handle = ?').bind(handle).first<User>(); |
| 313 | if (user?.is_agent) throw new HttpError(404, 'Not found.'); |
| 314 | if (!user) { |
| 315 | const id = newId(); |
| 316 | await c.env.DB.batch([ |
| 317 | 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), |
| 318 | c.env.DB.prepare("INSERT INTO oauth_accounts (provider, provider_user_id, user_id, login, email, email_verified, created_at) VALUES ('github',?,?,?,?,1,?)").bind(`dev-${id}`, id, handle, `${handle}@example.test`, now()), |
| 319 | ]); |
| 320 | user = (await getUserById(c.env, id))!; |
| 321 | } |
| 322 | await createSession(c, user.id); |
| 323 | return c.redirect(safeNext(c.req.query('next'))); |
| 324 | }); |
| 325 | } |
| 326 | |
| 327 | export { SignInButtons }; |