Jobley / website / src / passkeys.js
| 1 | // Passkey sign-in for the curator and moderators. Passkeys are the only way a person signs in: |
| 2 | // no passwords, pasted tokens, email links or codes. Recovery is a second passkey. |
| 3 | // |
| 4 | // Public: |
| 5 | // POST /api/passkeys/setup x-setup-secret: JOBLEY_PASSKEY_SETUP_SECRET → the curator's one-time setup link (404 otherwise) |
| 6 | // POST /api/passkeys/register/options {code} from a setup link → registration options |
| 7 | // POST /api/passkeys/register {challenge_id, response, name?} → passkey saved, signed in |
| 8 | // POST /api/passkeys/login/options → authentication options (discoverable, user verification required) |
| 9 | // POST /api/passkeys/login {challenge_id, response} → session token |
| 10 | // Signed in (see src/api.js): list, add another, remove (never the last), sign out, and the |
| 11 | // curator's moderator setup links. |
| 12 | import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from '@simplewebauthn/server'; |
| 13 | import { isoBase64URL } from '@simplewebauthn/server/helpers'; |
| 14 | import { APP, PASSKEYS } from './config.js'; |
| 15 | import { fail, json, now, randomId, randomToken, readJson, sameSecret, sha256 } from './util.js'; |
| 16 | |
| 17 | const ALGORITHMS = [-7, -8, -257]; // ES256 (what Apple's passkeys use), EdDSA, RS256 |
| 18 | const minutesFromNow = (minutes, at = Date.now()) => new Date(at + minutes * 60000).toISOString(); |
| 19 | |
| 20 | export function relyingParty(env) { |
| 21 | const rpID = env.PASSKEY_RP_ID || PASSKEYS.rpID; |
| 22 | return { rpID, origins: [`https://${rpID}`, ...(env.PASSKEY_ORIGIN ? [env.PASSKEY_ORIGIN] : [])] }; |
| 23 | } |
| 24 | |
| 25 | // The file Apple fetches before an app may use passkeys for the domain. |
| 26 | export function appSiteAssociation() { |
| 27 | return new Response(JSON.stringify({ webcredentials: { apps: PASSKEYS.appIDs } }), { |
| 28 | headers: { 'content-type': 'application/json', 'cache-control': 'public, max-age=3600', 'x-content-type-options': 'nosniff' }, |
| 29 | }); |
| 30 | } |
| 31 | |
| 32 | // Where a setup link lands in a browser. The code stays in the fragment, so it is never sent here. |
| 33 | export function setupLinkPage() { |
| 34 | return new Response('This is a Jobley passkey setup link. Open Jobley, choose "Add a passkey" and paste the whole link. It works once, within 15 minutes of being made.\n', { |
| 35 | headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', 'x-robots-tag': 'noindex', 'x-content-type-options': 'nosniff' }, |
| 36 | }); |
| 37 | } |
| 38 | |
| 39 | // ------------------------------------------------------------------ setup links |
| 40 | |
| 41 | export async function createEnrollment(env, role, userId, createdBy, at = Date.now()) { |
| 42 | const code = randomToken('enroll'); |
| 43 | const expiresAt = minutesFromNow(PASSKEYS.enrollmentMinutes, at); |
| 44 | await env.DB.prepare(`INSERT INTO passkey_enrollments (code_hash, role, user_id, created_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)`) |
| 45 | .bind(await sha256(code), role, userId, createdBy, new Date(at).toISOString(), expiresAt).run(); |
| 46 | return { url: `${APP.site}/passkey/#${code}`, code, expires_at: expiresAt }; |
| 47 | } |
| 48 | |
| 49 | // The curator's first passkey. Answers exactly like an unknown endpoint unless the secret is set |
| 50 | // (at least 32 characters) and the header matches it. |
| 51 | async function setup(request, env) { |
| 52 | const secret = env.JOBLEY_PASSKEY_SETUP_SECRET; |
| 53 | const given = request.headers.get('x-setup-secret') || ''; |
| 54 | if (!secret || secret.length < 32 || !given || given.length > 500 || !(await sameSecret(given, secret))) return fail(404, 'not_found', 'No such endpoint.'); |
| 55 | const link = await createEnrollment(env, 'curator', 'curator', 'setup'); |
| 56 | await env.DB.prepare(`INSERT INTO audit_log (actor, client, action, target_type, target_id, detail, created_at) VALUES ('setup', 'web', 'setup_link', 'passkey', 'curator', ?, ?)`).bind(link.expires_at, now()).run(); |
| 57 | return json({ ok: true, ...link }); |
| 58 | } |
| 59 | |
| 60 | // "jl_enroll_…" or the whole link; the code is whatever follows the last '#'. |
| 61 | function enrollmentCode(value) { |
| 62 | if (typeof value !== 'string' || value.length > 500) return null; |
| 63 | const code = value.trim().split('#').pop(); |
| 64 | return /^[a-z]+_enroll_[0-9a-f]{64}$/.test(code) ? code : null; |
| 65 | } |
| 66 | |
| 67 | // ------------------------------------------------------------------ registration |
| 68 | |
| 69 | // Options to add a passkey for {role, userId}. enrollmentHash is set when a setup link is used. |
| 70 | export async function registrationOptions(env, { role, userId, name }, enrollmentHash = null) { |
| 71 | const { rpID } = relyingParty(env); |
| 72 | const { results: existing } = await env.DB.prepare(`SELECT id, user_handle, transports FROM passkeys WHERE role = ? AND user_id = ?`).bind(role, userId).all(); |
| 73 | const handle = existing[0]?.user_handle || isoBase64URL.fromBuffer(crypto.getRandomValues(new Uint8Array(32))); |
| 74 | const options = await generateRegistrationOptions({ |
| 75 | rpName: PASSKEYS.rpName, |
| 76 | rpID, |
| 77 | userID: isoBase64URL.toBuffer(handle), |
| 78 | userName: role === 'curator' ? 'Curator' : name, |
| 79 | userDisplayName: role === 'curator' ? 'Jobley curator' : name, |
| 80 | attestationType: 'none', |
| 81 | timeout: PASSKEYS.challengeMinutes * 60000, |
| 82 | excludeCredentials: existing.map((p) => ({ id: p.id, transports: safeList(p.transports) })), |
| 83 | authenticatorSelection: { residentKey: 'required', requireResidentKey: true, userVerification: 'required' }, |
| 84 | supportedAlgorithmIDs: ALGORITHMS, |
| 85 | }); |
| 86 | const id = await saveChallenge(env, { purpose: 'register', challenge: options.challenge, role, userId, handle, enrollmentHash }); |
| 87 | return json({ ok: true, challenge_id: id, options }); |
| 88 | } |
| 89 | |
| 90 | async function registrationOptionsFromCode(request, env) { |
| 91 | const { body, error } = await readJson(request); |
| 92 | if (error) return error; |
| 93 | const code = enrollmentCode(body.code); |
| 94 | if (!code) return badLink(); |
| 95 | const hash = await sha256(code); |
| 96 | const link = await env.DB.prepare(`SELECT role, user_id FROM passkey_enrollments WHERE code_hash = ? AND used_at IS NULL AND expires_at > ?`).bind(hash, now()).first(); |
| 97 | if (!link) return badLink(); |
| 98 | const person = await personFor(env, link.role, link.user_id); |
| 99 | if (!person) return badLink(); |
| 100 | return registrationOptions(env, person, hash); |
| 101 | } |
| 102 | const badLink = () => fail(410, 'link_expired', 'That setup link has been used or has expired. Ask for a new one.'); |
| 103 | |
| 104 | // Verifies a new passkey and saves it. A setup link is used up here, atomically, so it works once. |
| 105 | // Returns the saved person, or a response to send. |
| 106 | export async function finishRegistration(env, body, signedIn = null) { |
| 107 | const challenge = await takeChallenge(env, body.challenge_id, 'register'); |
| 108 | if (!challenge) return { stop: fail(400, 'challenge_expired', 'That request has expired. Please try again.') }; |
| 109 | if (signedIn && (challenge.role !== signedIn.role || challenge.user_id !== signedIn.userId || challenge.enrollment_hash)) return { stop: fail(400, 'challenge_expired', 'That request has expired. Please try again.') }; |
| 110 | if (!signedIn && !challenge.enrollment_hash) return { stop: fail(400, 'challenge_expired', 'That request has expired. Please try again.') }; |
| 111 | const { rpID, origins } = relyingParty(env); |
| 112 | let verification; |
| 113 | try { |
| 114 | verification = await verifyRegistrationResponse({ |
| 115 | response: body.response, expectedChallenge: challenge.challenge, expectedOrigin: origins, expectedRPID: rpID, |
| 116 | requireUserVerification: true, supportedAlgorithmIDs: ALGORITHMS, |
| 117 | }); |
| 118 | } catch { |
| 119 | return { stop: fail(400, 'passkey_failed', 'That passkey could not be checked. Please try again.') }; |
| 120 | } |
| 121 | if (!verification.verified) return { stop: fail(400, 'passkey_failed', 'That passkey could not be checked. Please try again.') }; |
| 122 | const at = now(); |
| 123 | if (challenge.enrollment_hash) { |
| 124 | const used = await env.DB.prepare(`UPDATE passkey_enrollments SET used_at = ? WHERE code_hash = ? AND used_at IS NULL AND expires_at > ? RETURNING role`).bind(at, challenge.enrollment_hash, at).first(); |
| 125 | if (!used) return { stop: badLink() }; |
| 126 | } |
| 127 | const person = await personFor(env, challenge.role, challenge.user_id); |
| 128 | if (!person) return { stop: badLink() }; |
| 129 | const { credential } = verification.registrationInfo; |
| 130 | const name = typeof body.name === 'string' ? body.name.replace(/[\u0000-\u001F\u007F]/g, ' ').trim().slice(0, 60) || null : null; |
| 131 | await env.DB.prepare(`INSERT INTO passkeys (id, role, user_id, user_handle, public_key, counter, transports, name, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`) |
| 132 | .bind(credential.id, challenge.role, challenge.user_id, challenge.user_handle, isoBase64URL.fromBuffer(credential.publicKey), credential.counter, JSON.stringify(credential.transports || []), name, at).run(); |
| 133 | return { person, passkeyId: credential.id }; |
| 134 | } |
| 135 | |
| 136 | async function register(request, env) { |
| 137 | const { body, error } = await readJson(request); |
| 138 | if (error) return error; |
| 139 | const done = await finishRegistration(env, body); |
| 140 | if (done.stop) return done.stop; |
| 141 | await audit(env, done.person, clientOf(request), 'passkey_add', done.passkeyId); |
| 142 | return signIn(env, request, done.person, done.passkeyId, 201); |
| 143 | } |
| 144 | |
| 145 | // ------------------------------------------------------------------ sign in |
| 146 | |
| 147 | async function loginOptions(env) { |
| 148 | const { rpID } = relyingParty(env); |
| 149 | const options = await generateAuthenticationOptions({ rpID, userVerification: 'required', timeout: PASSKEYS.challengeMinutes * 60000 }); |
| 150 | const id = await saveChallenge(env, { purpose: 'login', challenge: options.challenge }); |
| 151 | return json({ ok: true, challenge_id: id, options }); |
| 152 | } |
| 153 | |
| 154 | async function login(request, env) { |
| 155 | const { body, error } = await readJson(request); |
| 156 | if (error) return error; |
| 157 | const challenge = await takeChallenge(env, body.challenge_id, 'login'); |
| 158 | if (!challenge) return fail(400, 'challenge_expired', 'That request has expired. Please try again.'); |
| 159 | const credentialId = typeof body.response?.id === 'string' ? body.response.id : ''; |
| 160 | const passkey = credentialId && (await env.DB.prepare(`SELECT * FROM passkeys WHERE id = ?`).bind(credentialId).first()); |
| 161 | const person = passkey && (await personFor(env, passkey.role, passkey.user_id)); |
| 162 | if (!passkey || !person) return fail(401, 'unknown_passkey', 'That passkey is not set up for Jobley.'); |
| 163 | const { rpID, origins } = relyingParty(env); |
| 164 | let verification; |
| 165 | try { |
| 166 | verification = await verifyAuthenticationResponse({ |
| 167 | response: body.response, expectedChallenge: challenge.challenge, expectedOrigin: origins, expectedRPID: rpID, requireUserVerification: true, |
| 168 | credential: { id: passkey.id, publicKey: isoBase64URL.toBuffer(passkey.public_key), counter: passkey.counter, transports: safeList(passkey.transports) }, |
| 169 | }); |
| 170 | } catch { |
| 171 | return fail(401, 'passkey_failed', 'That passkey could not be checked. Please try again.'); |
| 172 | } |
| 173 | if (!verification.verified) return fail(401, 'passkey_failed', 'That passkey could not be checked. Please try again.'); |
| 174 | await env.DB.prepare(`UPDATE passkeys SET counter = ?, last_used_at = ? WHERE id = ?`).bind(verification.authenticationInfo.newCounter, now(), passkey.id).run(); |
| 175 | await audit(env, person, clientOf(request), 'sign_in', passkey.id); |
| 176 | return signIn(env, request, person, passkey.id); |
| 177 | } |
| 178 | |
| 179 | async function signIn(env, request, person, passkeyId, status = 200) { |
| 180 | const token = randomToken('session'); |
| 181 | const at = now(); |
| 182 | const expiresAt = minutesFromNow(PASSKEYS.sessionDays * 1440); |
| 183 | await env.DB.prepare(`INSERT INTO sessions (token_hash, role, user_id, passkey_id, created_at, expires_at, last_seen_at) VALUES (?, ?, ?, ?, ?, ?, ?)`) |
| 184 | .bind(await sha256(token), person.role, person.userId, passkeyId, at, expiresAt, at).run(); |
| 185 | return json({ ok: true, token, expires_at: expiresAt, role: person.role, id: person.userId, name: person.name, can_see_candidates: person.canSeeCandidates }, status); |
| 186 | } |
| 187 | |
| 188 | // The person behind a session token, or null. Sessions slide: each use keeps them for another |
| 189 | // PASSKEYS.sessionDays. Only sessions sign in; pasted curator and moderator tokens are not accepted. |
| 190 | export async function sessionPerson(env, token) { |
| 191 | const hash = await sha256(token); |
| 192 | const row = await env.DB.prepare(`SELECT role, user_id FROM sessions WHERE token_hash = ? AND expires_at > ?`).bind(hash, now()).first(); |
| 193 | if (!row) return null; |
| 194 | const person = await personFor(env, row.role, row.user_id); |
| 195 | if (!person) return null; |
| 196 | await env.DB.prepare(`UPDATE sessions SET last_seen_at = ?, expires_at = ? WHERE token_hash = ?`).bind(now(), minutesFromNow(PASSKEYS.sessionDays * 1440), hash).run(); |
| 197 | return person; |
| 198 | } |
| 199 | |
| 200 | export async function signOut(env, token) { |
| 201 | await env.DB.prepare(`DELETE FROM sessions WHERE token_hash = ?`).bind(await sha256(token)).run(); |
| 202 | } |
| 203 | |
| 204 | // ------------------------------------------------------------------ shared |
| 205 | |
| 206 | // The curator, or an active moderator. |
| 207 | async function personFor(env, role, userId) { |
| 208 | if (role === 'curator' && userId === 'curator') return { role, userId, name: 'Curator', canSeeCandidates: true }; |
| 209 | if (role !== 'moderator') return null; |
| 210 | const row = await env.DB.prepare(`SELECT id, name, can_see_candidates FROM moderators WHERE id = ? AND active = 1`).bind(userId).first(); |
| 211 | return row ? { role, userId: row.id, name: row.name, canSeeCandidates: row.can_see_candidates === 1 } : null; |
| 212 | } |
| 213 | |
| 214 | async function saveChallenge(env, { purpose, challenge, role = null, userId = null, handle = null, enrollmentHash = null }) { |
| 215 | const id = randomId('ch', 16); |
| 216 | await env.DB.batch([ |
| 217 | env.DB.prepare(`DELETE FROM passkey_challenges WHERE expires_at < ?`).bind(now()), |
| 218 | env.DB.prepare(`INSERT INTO passkey_challenges (id, purpose, challenge, role, user_id, user_handle, enrollment_hash, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`) |
| 219 | .bind(id, purpose, challenge, role, userId, handle, enrollmentHash, minutesFromNow(PASSKEYS.challengeMinutes)), |
| 220 | ]); |
| 221 | return id; |
| 222 | } |
| 223 | |
| 224 | // Deletes the challenge as it reads it, so each one is used at most once. |
| 225 | async function takeChallenge(env, id, purpose) { |
| 226 | if (typeof id !== 'string' || id.length > 40) return null; |
| 227 | const row = await env.DB.prepare(`DELETE FROM passkey_challenges WHERE id = ? AND purpose = ? RETURNING *`).bind(id, purpose).first(); |
| 228 | return row && row.expires_at > now() ? row : null; |
| 229 | } |
| 230 | |
| 231 | const audit = (env, person, client, action, detail) => |
| 232 | env.DB.prepare(`INSERT INTO audit_log (actor, client, action, target_type, target_id, detail, created_at) VALUES (?, ?, ?, 'passkey', ?, ?, ?)`) |
| 233 | .bind(person.role === 'curator' ? 'curator' : `moderator:${person.userId}`, client, action, person.userId, detail, now()).run(); |
| 234 | |
| 235 | const clientOf = (request) => (request.headers.get('x-client') || 'unknown').toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 20) || 'unknown'; |
| 236 | |
| 237 | function safeList(text) { try { const v = JSON.parse(text); return Array.isArray(v) ? v : []; } catch { return []; } } |
| 238 | |
| 239 | // ------------------------------------------------------------------ router |
| 240 | |
| 241 | export async function passkeyRoutes(request, env, method, parts, tooMany) { |
| 242 | const [a, b] = parts; |
| 243 | if (a === 'setup' && !b) return method === 'POST' ? setup(request, env) : fail(404, 'not_found', 'No such endpoint.'); |
| 244 | if (method !== 'POST') return fail(405, 'method_not_allowed', 'That method is not supported here.'); |
| 245 | if (a === 'register' && !b) return register(request, env); |
| 246 | if (a === 'login' && !b) return login(request, env); |
| 247 | if ((a === 'register' || a === 'login') && b === 'options' && parts.length === 2) { |
| 248 | const rate = await tooMany(request, env, 'passkeys'); |
| 249 | if (rate.stop) return rate.stop; |
| 250 | return a === 'login' ? loginOptions(env) : registrationOptionsFromCode(request, env); |
| 251 | } |
| 252 | return fail(404, 'not_found', 'No such endpoint.'); |
| 253 | } |