import type { Hono } from 'hono'; import type { AppEnv, Ctx, User } from '../env'; import { mail } from '../lib/email'; import { ipKey, rateLimit } from '../lib/ratelimit'; import { clearCookie, createSession, destroySession, getSigned, setFlash, setSigned } from '../lib/session'; import { getUserById, handleProblem, isAdminGithubId, uniqueHandle } from '../lib/users'; import { SPROUT_ID } from '../lib/skills'; import { HttpError, newId, now, randomToken, safeEqual, safeNext, sha256B64url } from '../lib/util'; import { brandMark, icon } from '../views/art'; import { render } from '../views/layout'; type Provider = 'github' | 'google'; type Tx = { provider: Provider; state: string; verifier: string; next: string; link: boolean }; type Identity = { provider: Provider; id: string; login: string | null; name: string | null; email: string | null; emailVerified: boolean; avatar: string | null }; type PendingLink = Identity & { existingProviders: string[] }; const PROVIDER_NAME: Record = { github: 'GitHub', google: 'Google' }; export function providerReady(c: Ctx, p: Provider): boolean { return p === 'github' ? !!(c.env.GITHUB_CLIENT_ID && c.env.GITHUB_CLIENT_SECRET) : !!(c.env.GOOGLE_CLIENT_ID && c.env.GOOGLE_CLIENT_SECRET); } function callbackUrl(c: Ctx, p: Provider): string { return `${new URL(c.req.url).origin}/auth/${p}/callback`; } async function exchange(c: Ctx, p: Provider, code: string, verifier: string): Promise { if (p === 'github') { const tokenRes = await fetch('https://github.com/login/oauth/access_token', { method: 'POST', headers: { accept: 'application/json', 'content-type': 'application/json', 'user-agent': 'skillfarm' }, 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 }), }); const tok = (await tokenRes.json()) as { access_token?: string }; if (!tok.access_token) throw new HttpError(400, 'GitHub did not complete the sign-in. Try again.'); const h = { authorization: `Bearer ${tok.access_token}`, accept: 'application/vnd.github+json', 'user-agent': 'skillfarm' }; const [uRes, eRes] = await Promise.all([fetch('https://api.github.com/user', { headers: h }), fetch('https://api.github.com/user/emails', { headers: h })]); if (!uRes.ok) throw new HttpError(502, 'Could not read your GitHub profile. Try again.'); const u = (await uRes.json()) as { id: number; login: string; name: string | null; avatar_url: string | null }; const emails = eRes.ok ? ((await eRes.json()) as { email: string; primary: boolean; verified: boolean }[]) : []; const primary = Array.isArray(emails) ? emails.find((e) => e.primary && e.verified) : undefined; 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 }; } const tokenRes = await fetch('https://oauth2.googleapis.com/token', { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, 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) }), }); const tok = (await tokenRes.json()) as { access_token?: string }; if (!tok.access_token) throw new HttpError(400, 'Google did not complete the sign-in. Try again.'); const uRes = await fetch('https://openidconnect.googleapis.com/v1/userinfo', { headers: { authorization: `Bearer ${tok.access_token}` } }); if (!uRes.ok) throw new HttpError(502, 'Could not read your Google profile. Try again.'); const u = (await uRes.json()) as { sub: string; email?: string; email_verified?: boolean }; // Only the id and verified email are kept from Google. The name and photo are not stored. return { provider: p, id: u.sub, login: null, name: null, email: u.email?.toLowerCase() ?? null, emailVerified: !!u.email_verified, avatar: null }; } async function linkIdentity(c: Ctx, userId: string, id: Identity): Promise { await c.env.DB.prepare('INSERT OR IGNORE INTO oauth_accounts (provider, provider_user_id, user_id, login, email, email_verified, created_at) VALUES (?,?,?,?,?,?,?)') .bind(id.provider, id.id, userId, id.login, id.emailVerified ? id.email : null, id.emailVerified ? 1 : 0, now()) .run(); } async function afterSignIn(c: Ctx, user: User, id: Identity, next: string): Promise { const sets: string[] = []; const args: unknown[] = []; if (id.emailVerified && id.email && !user.email) { sets.push('email = ?'); args.push(id.email); } if (id.provider === 'github') { if (isAdminGithubId(c.env, id.id) && !user.is_admin) sets.push('is_admin = 1'); if (id.avatar && !user.is_agent && user.avatar_fallback !== id.avatar) { sets.push('avatar_fallback = ?'); args.push(id.avatar); } 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 = ?") .bind(id.login, id.emailVerified ? id.email : null, id.emailVerified ? 1 : 0, id.id) .run(); } if (sets.length) await c.env.DB.prepare(`UPDATE users SET ${sets.join(', ')} WHERE id = ?`).bind(...args, user.id).run(); // Finish a link that was waiting for proof of control of the existing account. const pending = await getSigned(c, 'sf_link'); if (pending) { clearCookie(c, 'sf_link'); if (pending.provider !== id.provider) { 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(); if (!taken) { await linkIdentity(c, user.id, pending); setFlash(c, 'ok', `${PROVIDER_NAME[pending.provider]} is now linked to your account.`); } } } await createSession(c, user.id); return c.redirect(user.onboarded ? next : `/welcome?next=${encodeURIComponent(next)}`); } const SignInButtons = ({ c, next, link }: { c: Ctx; next: string; link?: boolean }) => ( ); 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.

No passwords. Skillfarm keeps your provider account id and verified email, and uses the email only for notices about your skills. See the privacy page.

{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('/auth/:provider/start', async (c) => { const p = c.req.param('provider') as Provider; if (p !== 'github' && p !== 'google') throw new HttpError(404, 'Unknown sign-in provider.'); if (!providerReady(c, p)) throw new HttpError(503, `${PROVIDER_NAME[p]} sign-in is not set up yet.`); const ip = await ipKey(c.env, c.req.header('cf-connecting-ip')); if (!(await rateLimit(c.env, `auth:${ip}`, 30, 3600))) throw new HttpError(429, 'Too many sign-in attempts. Try again later.'); const tx: Tx = { provider: p, state: randomToken(24), verifier: randomToken(48), next: safeNext(c.req.query('next')), link: c.req.query('link') === '1' }; await setSigned(c, 'sf_oauth', tx, 600); const challenge = await sha256B64url(tx.verifier); const u = new URL(p === 'github' ? 'https://github.com/login/oauth/authorize' : 'https://accounts.google.com/o/oauth2/v2/auth'); u.searchParams.set('client_id', (p === 'github' ? c.env.GITHUB_CLIENT_ID : c.env.GOOGLE_CLIENT_ID)!); u.searchParams.set('redirect_uri', callbackUrl(c, p)); u.searchParams.set('state', tx.state); u.searchParams.set('code_challenge', challenge); u.searchParams.set('code_challenge_method', 'S256'); if (p === 'github') { u.searchParams.set('scope', 'read:user user:email'); } else { u.searchParams.set('response_type', 'code'); u.searchParams.set('scope', 'openid email'); u.searchParams.set('prompt', 'select_account'); } return c.redirect(u.toString()); }); app.get('/auth/:provider/callback', async (c) => { const p = c.req.param('provider') as Provider; const tx = await getSigned(c, 'sf_oauth'); clearCookie(c, 'sf_oauth'); const state = c.req.query('state') ?? ''; const code = c.req.query('code'); if (c.req.query('error')) { setFlash(c, 'error', 'Sign-in was cancelled.'); return c.redirect('/signin'); } 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.'); const id = await exchange(c, p, code, tx.verifier); const current = c.get('user'); 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 }>(); if (existing) { if (current && existing.user_id !== current.id) { setFlash(c, 'error', `That ${PROVIDER_NAME[p]} account is already linked to a different Skillfarm account.`); return c.redirect('/settings'); } const user = await getUserById(c.env, existing.user_id); if (!user || user.status !== 'active') throw new HttpError(403, 'This account is not active.'); return afterSignIn(c, user, id, tx.next); } if (current) { // Signed in and adding a second provider from settings. await linkIdentity(c, current.id, id); setFlash(c, 'ok', `${PROVIDER_NAME[p]} is now linked to your account.`); return c.redirect('/settings'); } if (p === 'github' && isAdminGithubId(c.env, id.id)) { // The site owner runs Skillfarm as Sprout and keeps no member account of their own. const sprout = await getUserById(c.env, SPROUT_ID); if (sprout && sprout.status === 'active') { await linkIdentity(c, sprout.id, id); return afterSignIn(c, sprout, id, tx.next); } } if (id.emailVerified && id.email) { // Same verified email as an existing member: never merge silently. Ask for proof of control of that account first. const match = await c.env.DB.prepare( `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`, ).bind(id.email).first<{ id: string }>(); if (match) { const provs = await c.env.DB.prepare('SELECT provider FROM oauth_accounts WHERE user_id = ?').bind(match.id).all<{ provider: Provider }>(); const existingProviders = provs.results.map((r) => r.provider); await setSigned(c, 'sf_link', { ...id, existingProviders } satisfies PendingLink, 600); const other = existingProviders[0] ?? 'github'; return render( c, { title: 'Link your accounts', noindex: true, narrow: true },
{brandMark(56)}

This email already has a Skillfarm account

Sign in with {PROVIDER_NAME[other]} to link {PROVIDER_NAME[p]} to it. After that, either one signs you in.

Skillfarm does not merge accounts on a matching email alone, so nobody can take over an account by adding your address elsewhere.

, ); } } const ip = await ipKey(c.env, c.req.header('cf-connecting-ip')); if (!(await rateLimit(c.env, `signup:${ip}`, 5, 86400))) throw new HttpError(429, 'Too many new accounts from this network today.'); const userId = newId(); const handle = await uniqueHandle(c.env, id.login ?? `grower-${newId(5)}`); const displayName = (id.name || id.login || 'New grower').slice(0, 60); const admin = p === 'github' && isAdminGithubId(c.env, id.id) ? 1 : 0; await c.env.DB.batch([ 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()), 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()), ]); const user = (await getUserById(c.env, userId))!; c.executionCtx.waitUntil(mail.welcome(c.env, user, handle).catch(() => false)); await createSession(c, userId); return c.redirect(`/welcome?next=${encodeURIComponent(tx.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 real OAuth provider. 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.batch([ 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), 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()), ]); user = (await getUserById(c.env, id))!; } await createSession(c, user.id); return c.redirect(safeNext(c.req.query('next'))); }); } export { SignInButtons };