// The Jobley API. One router for everything under /api/, called by functions/api/[[path]].js. // // Public: moderator access, passkey sign-in (src/passkeys.js) and backward compatibility for the retired job feed. // Admin (Authorization: Bearer ): everything under /api/admin/. // // People decide. Nothing here scores, ranks or filters a candidate or a job post; the only // automatic checks are spam controls (Turnstile, honeypot, rate limit) and field validation. import { APP, CATEGORIES, EMPLOYMENT_TYPES, HOURS_A_YEAR, LIMITS, MIN_HOURLY_USD, PAY_PERIODS, PERIODS_A_YEAR, WORKPLACES } from './config.js'; import { createEnrollment, finishRegistration, passkeyRoutes, registrationOptions, sessionPerson, signOut } from './passkeys.js'; import { Checker, allow, fail, ipHash, json, now, randomId, readJson, sha256, turnstile } from './util.js'; function historicalJob(row) { return { id: row.id, url: `${APP.site}/jobs/${row.id}`, title: row.title, company: row.company, company_url: row.company_url || null, location: row.location, workplace: row.workplace, employment_type: row.employment_type, category: row.category, pay: { min: row.pay_min, max: row.pay_max, currency: row.pay_currency, period: row.pay_period }, description: row.description, apply_url: row.apply_url || null, published_at: row.published_at, expires_at: row.expires_at, }; } function adminJob(row) { return { ...historicalJob(row), status: row.status, contact: { name: row.contact_name, email: row.contact_email }, review: { reason: row.review_reason || null, by: row.reviewed_by || null, at: row.reviewed_at || null }, created_at: row.created_at, updated_at: row.updated_at, }; } function adminCandidate(row) { return { id: row.id, job_id: row.job_id || null, status: row.status, name: row.name, email: row.email, location: row.location || null, headline: row.headline, looking_for: row.looking_for || null, about: row.about || null, links: safeList(row.links), resume_url: row.resume_url || null, note: row.note || null, created_at: row.created_at, updated_at: row.updated_at, }; } function safeList(text) { try { const v = JSON.parse(text); return Array.isArray(v) ? v : []; } catch { return []; } } export async function handle(request, env) { const url = new URL(request.url); const parts = url.pathname.replace(/^\/api\/?/, '').split('/').filter(Boolean).map(decodeURIComponent); const method = request.method.toUpperCase(); if (!env.DB) return fail(503, 'not_configured', 'The database is not connected yet.'); try { if (parts[0] === 'admin') return await admin(request, env, url, method, parts.slice(1)); if (parts[0] === 'passkeys') return await passkeyRoutes(request, env, method, parts.slice(1), tooMany); return await open(request, env, method, parts); } catch (err) { console.error('api error', err && err.stack ? err.stack : err); return fail(500, 'server_error', 'Something went wrong on our side. Please try again.'); } } // ------------------------------------------------------------------ public async function open(request, env, method, parts) { const [a, b, c] = parts; if (a === 'meta' && !b && method === 'GET') { return json({ ok: true, name: APP.name, site: APP.site, turnstile_site_key: env.TURNSTILE_SITE_KEY || null, mode: 'volunteer_only', volunteer_url: APP.site + '/volunteer/', public_job_submissions: false, candidate_applications: false, }, 200, { 'cache-control': 'public, max-age=300' }); } if (a === 'jobs' && !b) { if (method === 'GET') return json({ ok: true, jobs: [], next_cursor: null }, 200, { 'cache-control': 'no-store' }); if (method === 'POST') return volunteerOnly(); return notAllowed('GET'); } if (a === 'jobs' && b && !c) return method === 'GET' ? volunteerOnly() : notAllowed('GET'); if (a === 'jobs' && b && c === 'close' && parts.length === 3) return method === 'POST' ? closeJob(request, env, b) : notAllowed('POST'); if (a === 'candidates' && !b) return method === 'POST' ? volunteerOnly() : notAllowed('POST'); if (a === 'moderators' && !b) return method === 'POST' ? submitModerator(request, env) : notAllowed('POST'); return fail(404, 'not_found', 'No such endpoint.'); } const notAllowed = (allowHeader) => json({ ok: false, error: 'method_not_allowed', message: 'That method is not supported here.' }, 405, { allow: allowHeader }); const volunteerOnly = () => fail(410, 'volunteer_only', 'Choose an unpaid volunteer role and email us to join.', { volunteer_url: APP.site + '/volunteer/' }); // Shared by the public application forms. gate() runs first: honeypot, then Turnstile. Returns { stop } // with the response to send, or {} to carry on. tooMany() runs after validation, so a person fixing // a typo does not use up their hour; it counts only submissions that are about to be stored. async function gate(request, env, body, bucket) { // The hidden "website" field. A person never sees it, so anything in it is a bot: answer as // if it worked and store nothing. if (typeof body.website === 'string' && body.website.trim() !== '') return { stop: json({ ok: true, id: randomId({ jobs: 'j', candidates: 'c', moderators: 'a' }[bucket]), status: bucket === 'jobs' ? 'pending' : 'received' }, 201) }; const check = await turnstile(request, env, body.turnstile_token); if (!check.ok) return { stop: check.error }; return {}; } async function tooMany(request, env, bucket) { const hash = await ipHash(request, env); if (await allow(env, hash, bucket, LIMITS.rate[bucket])) return { hash }; return { hash, stop: json({ ok: false, error: 'rate_limited', message: 'That is a lot in one hour. Please try again a little later.' }, 429, { 'retry-after': '3600' }) }; } function jobFields(c, { partial = false } = {}) { const has = (name) => !partial || c.body[name] !== undefined; const out = {}; if (has('title')) out.title = c.text('title', { min: 4, max: 120, required: true, label: 'Job title' }); if (has('company')) out.company = c.text('company', { min: 2, max: 100, required: true, label: 'Company' }); if (has('company_url')) out.company_url = c.url('company_url', { max: 300, label: 'Company website' }); if (has('location')) out.location = c.text('location', { min: 2, max: 120, required: true, label: 'Location' }); if (has('workplace')) out.workplace = c.choice('workplace', WORKPLACES, { label: 'Workplace' }); if (has('employment_type')) out.employment_type = c.choice('employment_type', EMPLOYMENT_TYPES, { label: 'Job type' }); if (has('category')) out.category = c.choice('category', CATEGORIES, { label: 'Category' }); if (has('pay_min')) out.pay_min = c.int('pay_min', { min: 1, max: 10000000, label: 'Lowest pay' }); if (has('pay_max')) out.pay_max = c.int('pay_max', { min: 1, max: 10000000, label: 'Highest pay' }); if (has('pay_period')) out.pay_period = c.choice('pay_period', PAY_PERIODS, { label: 'Pay period' }); if (has('pay_currency')) { const cur = c.body.pay_currency === undefined || c.body.pay_currency === '' ? 'USD' : c.body.pay_currency; out.pay_currency = typeof cur === 'string' && /^[A-Z]{3}$/.test(cur) ? cur : c.bad('pay_currency', 'Currency must be a three-letter code such as USD.'); } if (has('description')) out.description = c.text('description', { min: 80, max: 8000, required: true, label: 'Description', multiline: true }); if (has('apply_url')) out.apply_url = c.url('apply_url', { max: 500, label: 'Apply link' }); return out; } // The pay floor (see PAY_FLOOR in config.js). Compared as a full-time year so the sums stay whole: // $100 an hour is $800 a day, $4,000 a week, $17,333 a month or $208,000 a year. const usd = (n) => `$${n.toLocaleString('en-US')}`; export const PAY_FLOOR_MESSAGE = `Pay must be at least ${usd(MIN_HOURLY_USD)} an hour, or ${usd(MIN_HOURLY_USD * HOURS_A_YEAR)} a year full time.`; export function belowPayFloor(min, period, currency) { if (PAY_FLOOR === 'off' || !Number.isInteger(min) || currency !== 'USD') return false; if (PAY_FLOOR === 'hourly' && period !== 'hour') return false; const perYear = PERIODS_A_YEAR[period]; return perYear ? min * perYear < MIN_HOURLY_USD * HOURS_A_YEAR : false; } async function closeJob(request, env, id) { const { body, error } = await readJson(request); if (error) return error; if (typeof body.manage_token !== 'string' || body.manage_token.length > 200) return fail(401, 'unauthorized', 'A manage token is required.'); const row = await env.DB.prepare(`SELECT id, status, manage_token_hash FROM jobs WHERE id = ?`).bind(id).first(); if (!row || row.manage_token_hash !== (await sha256(body.manage_token))) return fail(404, 'not_found', 'No job matches that id and token.'); if (row.status === 'closed') return json({ ok: true, id, status: 'closed' }); const at = now(); await env.DB.batch([ env.DB.prepare(`UPDATE jobs SET status = 'closed', updated_at = ? WHERE id = ?`).bind(at, id), env.DB.prepare(`INSERT INTO audit_log (actor, client, action, target_type, target_id, detail, created_at) VALUES ('poster', 'web', 'close', 'job', ?, ?, ?)`).bind(id, `was ${row.status}`, at), ]); return json({ ok: true, id, status: 'closed' }); } async function submitModerator(request, env) { const { body, error } = await readJson(request); if (error) return error; const g = await gate(request, env, body, 'moderators'); if (g.stop) return g.stop; const c = new Checker(body); const name = c.text('name', { min: 2, max: 100, required: true, label: 'Your name' }); const email = c.email('email'); const timezone = c.text('timezone', { max: 60, label: 'Time zone' }); const hours = c.int('hours_per_week', { min: 1, max: 40, required: false, label: 'Hours a week' }); // The public form sends name, email and message; older clients still send why. const why = c.text(c.body.message !== undefined ? 'message' : 'why', { min: 10, max: 3000, required: true, label: 'Message', multiline: true }); const experience = c.text('experience', { max: 3000, label: 'Experience', multiline: true }); const links = c.links('links'); if (!c.ok) return fail(422, 'invalid', 'Please fix the marked fields.', { fields: c.fields }); const rate = await tooMany(request, env, 'moderators'); if (rate.stop) return rate.stop; const id = randomId('a'); const at = now(); await env.DB.prepare( `INSERT INTO moderator_applications (id, status, name, email, timezone, hours_per_week, why, experience, links, ip_hash, created_at, updated_at) VALUES (?, 'new', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ).bind(id, name, email, timezone, hours, why, experience, JSON.stringify(links), rate.hash, at, at).run(); return json({ ok: true, id, status: 'received' }, 201); } // ------------------------------------------------------------------ admin // Who is calling: the curator or an active moderator, from the session token a passkey sign-in // issued. Nothing else signs a person in: ADMIN_TOKEN and the old pasted moderator tokens are refused. export async function whoIs(request, env) { const token = bearer(request); if (!token) return null; const client = (request.headers.get('x-client') || 'unknown').toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 20) || 'unknown'; const person = await sessionPerson(env, token); if (!person) return null; if (person.role === 'curator') return { role: 'curator', id: 'curator', name: 'Curator', actor: 'curator', canSeeCandidates: true, client, token }; await env.DB.prepare(`UPDATE moderators SET last_seen_at = ? WHERE id = ?`).bind(now(), person.userId).run(); return { role: 'moderator', id: person.userId, name: person.name, actor: `moderator:${person.userId}`, canSeeCandidates: person.canSeeCandidates, client, token }; } function bearer(request) { const header = request.headers.get('authorization') || ''; const token = header.startsWith('Bearer ') ? header.slice(7).trim() : ''; return token && token.length <= 200 ? token : null; } const log = (env, who, action, type, id, detail = null, at = now()) => env.DB.prepare(`INSERT INTO audit_log (actor, client, action, target_type, target_id, detail, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`) .bind(who.actor, who.client, action, type, id, detail, at); // What an agent (X-Client: mcp) may change: tidy a post's wording and leave a note for the // person reviewing. Agents never approve, reject, publish or unpublish a job, and never touch // a candidate. The apps enforce this too; the API does not rely on them. const AGENT_WRITES = new Set(['jobs.patch', 'jobs.notes']); async function admin(request, env, url, method, parts) { const who = await whoIs(request, env); if (!who) return json({ ok: false, error: 'unauthorized', message: 'Sign in with your passkey first.' }, 401, { 'www-authenticate': 'Bearer' }); const [a, b, c] = parts; const read = method === 'GET'; const guard = (name, { curator = false, candidates = false } = {}) => { if (!read && who.client === 'mcp' && !AGENT_WRITES.has(name)) return fail(403, 'people_only', 'Only a person can do that. Agents can tidy a post or leave a note.'); if (curator && who.role !== 'curator') return fail(403, 'forbidden', 'Only the curator can do that.'); if (candidates && who.client === 'mcp') return fail(403, 'people_only', 'Candidates are only shown to people.'); if (candidates && !who.canSeeCandidates) return fail(403, 'forbidden', 'You do not have access to candidates.'); return null; }; let body = {}; if (!read && method !== 'DELETE') { const parsed = await readJson(request); if (parsed.error) return parsed.error; body = parsed.body; } if (a === 'me' && !b && read) return json({ ok: true, role: who.role, id: who.id, name: who.name, can_see_candidates: who.canSeeCandidates }); if (a === 'stats' && !b && read) return stats(env, who); if (a === 'purge' && !b && method === 'POST') return guard('purge', { curator: true }) || purge(env, who); if (a === 'sign-out' && !b && method === 'POST') { await signOut(env, who.token); return json({ ok: true }); } if (a === 'passkeys') return guard('passkeys') || passkeys(env, who, method, parts.slice(1), body); if (a === 'jobs') { if (!b) { if (read) return adminListJobs(env, url); if (method === 'POST') return guard('jobs.create', { curator: true }) || volunteerOnly(); return notAllowed('GET, POST'); } const job = await env.DB.prepare(`SELECT * FROM jobs WHERE id = ?`).bind(b).first(); if (!job) return fail(404, 'not_found', 'No such job.'); if (!c) { if (read) return adminGetJob(env, job); if (method === 'PATCH') return guard('jobs.patch') || patchJob(env, who, job, body); return notAllowed('GET, PATCH'); } if (method !== 'POST' || parts.length !== 3) return fail(404, 'not_found', 'No such endpoint.'); if (c === 'notes') return guard('jobs.notes') || addNote(env, who, job, body); if (c === 'approve' || c === 'reject' || c === 'publish' || c === 'unpublish') return guard(`jobs.${c}`) || ((c === 'publish' || c === 'approve') ? volunteerOnly() : reviewJob(env, who, job, c, body)); return fail(404, 'not_found', 'No such endpoint.'); } if (a === 'candidates') { const stop = guard('candidates', { candidates: true }); if (stop) return stop; if (!b) return read ? adminListCandidates(env, url) : notAllowed('GET'); const cand = await env.DB.prepare(`SELECT * FROM candidates WHERE id = ?`).bind(b).first(); if (!cand) return fail(404, 'not_found', 'No such candidate.'); if (!c) return read ? adminGetCandidate(env, cand) : notAllowed('GET'); if (method !== 'POST' || parts.length !== 3) return fail(404, 'not_found', 'No such endpoint.'); if (c === 'introduce') return volunteerOnly(); if (c === 'status') return candidateStatus(env, who, cand, body); return fail(404, 'not_found', 'No such endpoint.'); } if (a === 'moderator-applications') { const stop = guard('applications', { curator: true }); if (stop) return stop; if (!b) return read ? listApplications(env, url) : notAllowed('GET'); const app = await env.DB.prepare(`SELECT * FROM moderator_applications WHERE id = ?`).bind(b).first(); if (!app) return fail(404, 'not_found', 'No such application.'); if (method === 'POST' && c === 'approve' && parts.length === 3) return approveModerator(env, who, app, body); if (method === 'POST' && c === 'decline' && parts.length === 3) return declineModerator(env, who, app, body); return fail(404, 'not_found', 'No such endpoint.'); } if (a === 'moderators') { const stop = guard('moderators', { curator: true }); if (stop) return stop; if (!b) { if (!read) return notAllowed('GET'); const { results } = await env.DB.prepare(`SELECT id, name, email, can_see_candidates, active, created_at, last_seen_at FROM moderators ORDER BY created_at DESC`).all(); return json({ ok: true, moderators: results.map((m) => ({ ...m, can_see_candidates: m.can_see_candidates === 1, active: m.active === 1 })) }); } const mod = await env.DB.prepare(`SELECT id FROM moderators WHERE id = ?`).bind(b).first(); if (!mod) return fail(404, 'not_found', 'No such moderator.'); if (method === 'POST' && c === 'revoke' && parts.length === 3) { await env.DB.batch([ env.DB.prepare(`UPDATE moderators SET active = 0 WHERE id = ?`).bind(b), env.DB.prepare(`DELETE FROM sessions WHERE role = 'moderator' AND user_id = ?`).bind(b), env.DB.prepare(`UPDATE passkey_enrollments SET used_at = ? WHERE role = 'moderator' AND user_id = ? AND used_at IS NULL`).bind(now(), b), log(env, who, 'revoke', 'moderator', b), ]); return json({ ok: true, id: b, active: false }); } // A new one-time setup link, for a moderator adding their first passkey (or one who lost theirs). if (method === 'POST' && c === 'setup-link' && parts.length === 3) { const active = await env.DB.prepare(`SELECT active FROM moderators WHERE id = ?`).bind(b).first(); if (active.active !== 1) return fail(409, 'wrong_state', 'This moderator was revoked.'); const link = await createEnrollment(env, 'moderator', b, who.actor); await log(env, who, 'setup_link', 'moderator', b, link.expires_at).run(); return json({ ok: true, id: b, setup: link }, 201); } if (method === 'POST' && c === 'access' && parts.length === 3) { if (typeof body.can_see_candidates !== 'boolean') return fail(422, 'invalid', 'can_see_candidates must be true or false.', { fields: { can_see_candidates: 'Must be true or false.' } }); await env.DB.batch([env.DB.prepare(`UPDATE moderators SET can_see_candidates = ? WHERE id = ?`).bind(body.can_see_candidates ? 1 : 0, b), log(env, who, 'access', 'moderator', b, `can_see_candidates=${body.can_see_candidates}`)]); return json({ ok: true, id: b, can_see_candidates: body.can_see_candidates }); } return fail(404, 'not_found', 'No such endpoint.'); } return fail(404, 'not_found', 'No such endpoint.'); } async function stats(env, who) { const jobs = await env.DB.prepare(`SELECT status, COUNT(*) AS n FROM jobs GROUP BY status`).all(); const out = { ok: true, jobs: Object.fromEntries(jobs.results.map((r) => [r.status, r.n])) }; if (who.canSeeCandidates && who.client !== 'mcp') { const cands = await env.DB.prepare(`SELECT status, COUNT(*) AS n FROM candidates GROUP BY status`).all(); out.candidates = Object.fromEntries(cands.results.map((r) => [r.status, r.n])); } if (who.role === 'curator') { const apps = await env.DB.prepare(`SELECT COUNT(*) AS n FROM moderator_applications WHERE status = 'new'`).first(); out.moderator_applications = { new: apps.n }; } return json(out); } // Deletes what the privacy page says we delete: posts that are off the board, candidates' notes and // moderator applications, once they are older than LIMITS.keepMonths. The Mac app calls this when the // curator opens it. Published jobs and their introductions are left alone until they come down. export async function purge(env, who, at = new Date()) { const cutoff = new Date(at); cutoff.setUTCMonth(cutoff.getUTCMonth() - LIMITS.keepMonths); const before = cutoff.toISOString(); const live = `status = 'published' AND expires_at > ?`; const out = await env.DB.batch([ env.DB.prepare(`DELETE FROM introductions WHERE candidate_id IN (SELECT id FROM candidates WHERE updated_at < ?)`).bind(before), env.DB.prepare(`DELETE FROM candidates WHERE updated_at < ?`).bind(before), env.DB.prepare(`DELETE FROM introductions WHERE job_id IN (SELECT id FROM jobs WHERE updated_at < ? AND NOT (${live}))`).bind(before, at.toISOString()), env.DB.prepare(`UPDATE candidates SET job_id = NULL WHERE job_id IN (SELECT id FROM jobs WHERE updated_at < ? AND NOT (${live}))`).bind(before, at.toISOString()), env.DB.prepare(`DELETE FROM jobs WHERE updated_at < ? AND NOT (${live})`).bind(before, at.toISOString()), env.DB.prepare(`DELETE FROM moderator_applications WHERE updated_at < ? AND id NOT IN (SELECT application_id FROM moderators WHERE application_id IS NOT NULL)`).bind(before), env.DB.prepare(`DELETE FROM rate_limits WHERE window_start < ?`).bind(at.getTime() - 2 * 3600000), ]); const n = (i) => out[i].meta.changes; const deleted = { candidates: n(1), jobs: n(4), moderator_applications: n(5) }; await log(env, who, 'purge', 'system', 'retention', JSON.stringify(deleted)).run(); return json({ ok: true, older_than: before, deleted }); } const JOB_STATUSES = { pending: 1, approved: 1, published: 1, rejected: 1, unpublished: 1, closed: 1 }; async function adminListJobs(env, url) { const status = url.searchParams.get('status') || 'pending'; if (status !== 'all' && !JOB_STATUSES[status]) return fail(422, 'invalid', 'Unknown status.', { fields: { status: 'Unknown status.' } }); const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '', 10) || 50, 1), 200); // The queue is oldest first, so the post that has waited longest is reviewed first. const order = status === 'pending' || status === 'approved' ? 'created_at ASC' : 'updated_at DESC'; const stmt = status === 'all' ? env.DB.prepare(`SELECT * FROM jobs ORDER BY ${order} LIMIT ?`).bind(limit) : env.DB.prepare(`SELECT * FROM jobs WHERE status = ? ORDER BY ${order} LIMIT ?`).bind(status, limit); const { results } = await stmt.all(); return json({ ok: true, jobs: results.map(adminJob) }); } async function adminGetJob(env, job) { const { results } = await env.DB.prepare(`SELECT actor, client, action, detail, created_at FROM audit_log WHERE target_type = 'job' AND target_id = ? ORDER BY id`).bind(job.id).all(); const count = await env.DB.prepare(`SELECT COUNT(*) AS n FROM candidates WHERE job_id = ?`).bind(job.id).first(); return json({ ok: true, job: adminJob(job), activity: results, candidate_count: count.n }); } async function patchJob(env, who, job, body) { const c = new Checker(body); const f = jobFields(c, { partial: true }); if ('company' in f || 'company_url' in f || 'apply_url' in f) { return fail(422, 'owned_board', 'Only Jobley lists roles on this board.'); } const names = Object.keys(f); if (!names.length) return fail(422, 'invalid', 'Nothing to change.', { fields: {} }); const min = f.pay_min ?? job.pay_min; const max = f.pay_max ?? job.pay_max; if (Number.isInteger(min) && Number.isInteger(max) && max < min) c.bad('pay_max', 'Highest pay must be at least the lowest pay.'); const payEdited = ['pay_min', 'pay_period', 'pay_currency'].some((n) => n in f); if (payEdited && !c.fields.pay_min && belowPayFloor(min, f.pay_period ?? job.pay_period, f.pay_currency ?? job.pay_currency)) c.bad('pay_min', PAY_FLOOR_MESSAGE); if (!c.ok) return fail(422, 'invalid', 'Please fix the marked fields.', { fields: c.fields }); const at = now(); await env.DB.batch([ env.DB.prepare(`UPDATE jobs SET ${names.map((n) => `${n} = ?`).join(', ')}, updated_at = ? WHERE id = ?`).bind(...names.map((n) => f[n]), at, job.id), log(env, who, 'edit', 'job', job.id, names.join(', '), at), ]); return json({ ok: true, job: adminJob(await env.DB.prepare(`SELECT * FROM jobs WHERE id = ?`).bind(job.id).first()) }); } async function addNote(env, who, job, body) { const c = new Checker(body); const note = c.text('note', { min: 1, max: 2000, required: true, label: 'Note', multiline: true }); if (!c.ok) return fail(422, 'invalid', 'Please fix the marked fields.', { fields: c.fields }); await log(env, who, 'note', 'job', job.id, note).run(); return json({ ok: true, id: job.id }, 201); } // Historical listings can be rejected or hidden, but never published again. const MOVES = { reject: { from: ['pending', 'approved'], to: 'rejected' }, unpublish: { from: ['published'], to: 'unpublished' }, }; async function reviewJob(env, who, job, action, body) { const move = MOVES[action]; if (!move.from.includes(job.status)) return fail(409, 'wrong_state', `This job is ${job.status}, so it cannot be ${move.to}.`, { status: job.status }); const c = new Checker(body); const reason = c.text('reason', { min: action === 'reject' ? 3 : 0, max: 1000, required: action === 'reject', label: 'Reason', multiline: true }); if (!c.ok) return fail(422, 'invalid', 'Please fix the marked fields.', { fields: c.fields }); const at = now(); await env.DB.batch([ env.DB.prepare('UPDATE jobs SET status = ?, updated_at = ?, review_reason = ?, reviewed_by = ?, reviewed_at = ? WHERE id = ?').bind(move.to, at, reason, who.actor, at, job.id), log(env, who, action, 'job', job.id, reason, at), ]); return json({ ok: true, job: adminJob(await env.DB.prepare('SELECT * FROM jobs WHERE id = ?').bind(job.id).first()) }); } async function adminListCandidates(env, url) { const where = []; const args = []; const jobId = url.searchParams.get('job_id'); if (jobId === 'none') where.push('job_id IS NULL'); else if (jobId) { where.push('job_id = ?'); args.push(jobId); } const status = url.searchParams.get('status'); if (status) { if (!CANDIDATE_STATUSES[status]) return fail(422, 'invalid', 'Unknown status.', { fields: { status: 'Unknown status.' } }); where.push('status = ?'); args.push(status); } const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '', 10) || 100, 1), 200); // Oldest first, always. People are never ranked or scored. const { results } = await env.DB.prepare(`SELECT * FROM candidates ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY created_at ASC LIMIT ?`).bind(...args, limit).all(); return json({ ok: true, candidates: results.map(adminCandidate) }); } async function adminGetCandidate(env, cand) { const { results } = await env.DB.prepare(`SELECT id, job_id, introduced_by, note, created_at FROM introductions WHERE candidate_id = ? ORDER BY created_at`).bind(cand.id).all(); return json({ ok: true, candidate: adminCandidate(cand), introductions: results }); } async function candidateStatus(env, who, cand, body) { const c = new Checker(body); const status = c.choice('status', { new: 1, reviewed: 1, declined: 1, withdrawn: 1 }, { label: 'Status' }); const note = c.text('note', { max: 2000, label: 'Note', multiline: true }); if (!c.ok) return fail(422, 'invalid', 'Please fix the marked fields.', { fields: c.fields }); const at = now(); await env.DB.batch([ env.DB.prepare(`UPDATE candidates SET status = ?, note = COALESCE(?, note), updated_at = ? WHERE id = ?`).bind(status, note, at, cand.id), log(env, who, `status:${status}`, 'candidate', cand.id, null, at), ]); return json({ ok: true, candidate: adminCandidate(await env.DB.prepare(`SELECT * FROM candidates WHERE id = ?`).bind(cand.id).first()) }); } async function listApplications(env, url) { const status = url.searchParams.get('status') || 'new'; if (!{ new: 1, approved: 1, declined: 1 }[status]) return fail(422, 'invalid', 'Unknown status.', { fields: { status: 'Unknown status.' } }); const { results } = await env.DB.prepare(`SELECT id, status, name, email, timezone, hours_per_week, why, experience, links, note, created_at, updated_at FROM moderator_applications WHERE status = ? ORDER BY created_at ASC LIMIT 200`).bind(status).all(); return json({ ok: true, applications: results.map((r) => ({ ...r, links: safeList(r.links) })) }); } async function approveModerator(env, who, app, body) { if (app.status === 'approved') return fail(409, 'wrong_state', 'This application was already approved.', { status: app.status }); const id = randomId('m'); const at = now(); await env.DB.batch([ // token_hash is a placeholder: moderators sign in with passkeys, never a token. env.DB.prepare(`INSERT INTO moderators (id, application_id, name, email, token_hash, can_see_candidates, active, created_at) VALUES (?, ?, ?, ?, ?, ?, 1, ?)`) .bind(id, app.id, app.name, app.email, `passkey:${id}`, body.can_see_candidates === true ? 1 : 0, at), env.DB.prepare(`UPDATE moderator_applications SET status = 'approved', updated_at = ? WHERE id = ?`).bind(at, app.id), log(env, who, 'approve', 'moderator_application', app.id, id, at), ]); // A one-time setup link, shown once. The curator hands it to the moderator, who opens it in the // app to add their passkey. It works once, within 15 minutes. const setup = await createEnrollment(env, 'moderator', id, who.actor); return json({ ok: true, moderator: { id, name: app.name, email: app.email, can_see_candidates: body.can_see_candidates === true }, setup }, 201); } async function declineModerator(env, who, app, body) { if (app.status !== 'new') return fail(409, 'wrong_state', `This application is already ${app.status}.`, { status: app.status }); const c = new Checker(body); const note = c.text('note', { max: 1000, label: 'Note', multiline: true }); if (!c.ok) return fail(422, 'invalid', 'Please fix the marked fields.', { fields: c.fields }); const at = now(); await env.DB.batch([ env.DB.prepare(`UPDATE moderator_applications SET status = 'declined', note = ?, updated_at = ? WHERE id = ?`).bind(note, at, app.id), log(env, who, 'decline', 'moderator_application', app.id, null, at), ]); return json({ ok: true, id: app.id, status: 'declined' }); } // The signed-in person's passkeys: list, add another, remove one (never the last). async function passkeys(env, who, method, parts, body) { const [id, extra] = parts; const person = { role: who.role, userId: who.id, name: who.name }; if (!id && method === 'GET') { const { results } = await env.DB.prepare(`SELECT id, name, created_at, last_used_at FROM passkeys WHERE role = ? AND user_id = ? ORDER BY created_at`).bind(who.role, who.id).all(); return json({ ok: true, passkeys: results }); } if (id === 'options' && !extra && method === 'POST') return registrationOptions(env, person); if (!id && method === 'POST') { const done = await finishRegistration(env, body, person); if (done.stop) return done.stop; await log(env, who, 'passkey_add', 'passkey', who.id, done.passkeyId).run(); return json({ ok: true, id: done.passkeyId }, 201); } if (id && id !== 'options' && !extra && method === 'DELETE') { const count = await env.DB.prepare(`SELECT COUNT(*) AS n FROM passkeys WHERE role = ? AND user_id = ?`).bind(who.role, who.id).first(); const mine = await env.DB.prepare(`SELECT id FROM passkeys WHERE id = ? AND role = ? AND user_id = ?`).bind(id, who.role, who.id).first(); if (!mine) return fail(404, 'not_found', 'No such passkey.'); if (count.n <= 1) return fail(409, 'last_passkey', 'Add another passkey before removing this one. It is your only way to sign in.'); await env.DB.batch([ env.DB.prepare(`DELETE FROM passkeys WHERE id = ? AND role = ? AND user_id = ?`).bind(id, who.role, who.id), env.DB.prepare(`DELETE FROM sessions WHERE passkey_id = ?`).bind(id), log(env, who, 'passkey_remove', 'passkey', who.id, id), ]); return json({ ok: true, id }); } return fail(404, 'not_found', 'No such endpoint.'); }