Jobley / website / src / api.js
| 1 | // The Jobley API. One router for everything under /api/, called by functions/api/[[path]].js. |
| 2 | // |
| 3 | // Public: moderator access, passkey sign-in (src/passkeys.js) and backward compatibility for the retired job feed. |
| 4 | // Admin (Authorization: Bearer <session token from a passkey sign-in>): everything under /api/admin/. |
| 5 | // |
| 6 | // People decide. Nothing here scores, ranks or filters a candidate or a job post; the only |
| 7 | // automatic checks are spam controls (Turnstile, honeypot, rate limit) and field validation. |
| 8 | import { APP, CATEGORIES, EMPLOYMENT_TYPES, HOURS_A_YEAR, LIMITS, MIN_HOURLY_USD, PAY_PERIODS, PERIODS_A_YEAR, WORKPLACES } from './config.js'; |
| 9 | import { createEnrollment, finishRegistration, passkeyRoutes, registrationOptions, sessionPerson, signOut } from './passkeys.js'; |
| 10 | import { Checker, allow, fail, ipHash, json, now, randomId, readJson, sha256, turnstile } from './util.js'; |
| 11 | |
| 12 | function historicalJob(row) { |
| 13 | return { |
| 14 | id: row.id, |
| 15 | url: `${APP.site}/jobs/${row.id}`, |
| 16 | title: row.title, |
| 17 | company: row.company, |
| 18 | company_url: row.company_url || null, |
| 19 | location: row.location, |
| 20 | workplace: row.workplace, |
| 21 | employment_type: row.employment_type, |
| 22 | category: row.category, |
| 23 | pay: { min: row.pay_min, max: row.pay_max, currency: row.pay_currency, period: row.pay_period }, |
| 24 | description: row.description, |
| 25 | apply_url: row.apply_url || null, |
| 26 | published_at: row.published_at, |
| 27 | expires_at: row.expires_at, |
| 28 | }; |
| 29 | } |
| 30 | function adminJob(row) { |
| 31 | return { |
| 32 | ...historicalJob(row), |
| 33 | status: row.status, |
| 34 | contact: { name: row.contact_name, email: row.contact_email }, |
| 35 | review: { reason: row.review_reason || null, by: row.reviewed_by || null, at: row.reviewed_at || null }, |
| 36 | created_at: row.created_at, |
| 37 | updated_at: row.updated_at, |
| 38 | }; |
| 39 | } |
| 40 | function adminCandidate(row) { |
| 41 | return { |
| 42 | id: row.id, job_id: row.job_id || null, status: row.status, name: row.name, email: row.email, |
| 43 | location: row.location || null, headline: row.headline, looking_for: row.looking_for || null, about: row.about || null, |
| 44 | links: safeList(row.links), resume_url: row.resume_url || null, note: row.note || null, |
| 45 | created_at: row.created_at, updated_at: row.updated_at, |
| 46 | }; |
| 47 | } |
| 48 | function safeList(text) { try { const v = JSON.parse(text); return Array.isArray(v) ? v : []; } catch { return []; } } |
| 49 | |
| 50 | export async function handle(request, env) { |
| 51 | const url = new URL(request.url); |
| 52 | const parts = url.pathname.replace(/^\/api\/?/, '').split('/').filter(Boolean).map(decodeURIComponent); |
| 53 | const method = request.method.toUpperCase(); |
| 54 | if (!env.DB) return fail(503, 'not_configured', 'The database is not connected yet.'); |
| 55 | try { |
| 56 | if (parts[0] === 'admin') return await admin(request, env, url, method, parts.slice(1)); |
| 57 | if (parts[0] === 'passkeys') return await passkeyRoutes(request, env, method, parts.slice(1), tooMany); |
| 58 | return await open(request, env, method, parts); |
| 59 | } catch (err) { |
| 60 | console.error('api error', err && err.stack ? err.stack : err); |
| 61 | return fail(500, 'server_error', 'Something went wrong on our side. Please try again.'); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | // ------------------------------------------------------------------ public |
| 66 | |
| 67 | async function open(request, env, method, parts) { |
| 68 | const [a, b, c] = parts; |
| 69 | if (a === 'meta' && !b && method === 'GET') { |
| 70 | return json({ |
| 71 | ok: true, name: APP.name, site: APP.site, |
| 72 | turnstile_site_key: env.TURNSTILE_SITE_KEY || null, |
| 73 | mode: 'volunteer_only', volunteer_url: APP.site + '/volunteer/', |
| 74 | public_job_submissions: false, candidate_applications: false, |
| 75 | }, 200, { 'cache-control': 'public, max-age=300' }); |
| 76 | } |
| 77 | if (a === 'jobs' && !b) { |
| 78 | if (method === 'GET') return json({ ok: true, jobs: [], next_cursor: null }, 200, { 'cache-control': 'no-store' }); |
| 79 | if (method === 'POST') return volunteerOnly(); |
| 80 | return notAllowed('GET'); |
| 81 | } |
| 82 | if (a === 'jobs' && b && !c) return method === 'GET' ? volunteerOnly() : notAllowed('GET'); |
| 83 | if (a === 'jobs' && b && c === 'close' && parts.length === 3) return method === 'POST' ? closeJob(request, env, b) : notAllowed('POST'); |
| 84 | if (a === 'candidates' && !b) return method === 'POST' ? volunteerOnly() : notAllowed('POST'); |
| 85 | if (a === 'moderators' && !b) return method === 'POST' ? submitModerator(request, env) : notAllowed('POST'); |
| 86 | return fail(404, 'not_found', 'No such endpoint.'); |
| 87 | } |
| 88 | const notAllowed = (allowHeader) => json({ ok: false, error: 'method_not_allowed', message: 'That method is not supported here.' }, 405, { allow: allowHeader }); |
| 89 | |
| 90 | const volunteerOnly = () => fail(410, 'volunteer_only', 'Choose an unpaid volunteer role and email us to join.', { volunteer_url: APP.site + '/volunteer/' }); |
| 91 | |
| 92 | // Shared by the public application forms. gate() runs first: honeypot, then Turnstile. Returns { stop } |
| 93 | // with the response to send, or {} to carry on. tooMany() runs after validation, so a person fixing |
| 94 | // a typo does not use up their hour; it counts only submissions that are about to be stored. |
| 95 | async function gate(request, env, body, bucket) { |
| 96 | // The hidden "website" field. A person never sees it, so anything in it is a bot: answer as |
| 97 | // if it worked and store nothing. |
| 98 | 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) }; |
| 99 | const check = await turnstile(request, env, body.turnstile_token); |
| 100 | if (!check.ok) return { stop: check.error }; |
| 101 | return {}; |
| 102 | } |
| 103 | async function tooMany(request, env, bucket) { |
| 104 | const hash = await ipHash(request, env); |
| 105 | if (await allow(env, hash, bucket, LIMITS.rate[bucket])) return { hash }; |
| 106 | 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' }) }; |
| 107 | } |
| 108 | |
| 109 | function jobFields(c, { partial = false } = {}) { |
| 110 | const has = (name) => !partial || c.body[name] !== undefined; |
| 111 | const out = {}; |
| 112 | if (has('title')) out.title = c.text('title', { min: 4, max: 120, required: true, label: 'Job title' }); |
| 113 | if (has('company')) out.company = c.text('company', { min: 2, max: 100, required: true, label: 'Company' }); |
| 114 | if (has('company_url')) out.company_url = c.url('company_url', { max: 300, label: 'Company website' }); |
| 115 | if (has('location')) out.location = c.text('location', { min: 2, max: 120, required: true, label: 'Location' }); |
| 116 | if (has('workplace')) out.workplace = c.choice('workplace', WORKPLACES, { label: 'Workplace' }); |
| 117 | if (has('employment_type')) out.employment_type = c.choice('employment_type', EMPLOYMENT_TYPES, { label: 'Job type' }); |
| 118 | if (has('category')) out.category = c.choice('category', CATEGORIES, { label: 'Category' }); |
| 119 | if (has('pay_min')) out.pay_min = c.int('pay_min', { min: 1, max: 10000000, label: 'Lowest pay' }); |
| 120 | if (has('pay_max')) out.pay_max = c.int('pay_max', { min: 1, max: 10000000, label: 'Highest pay' }); |
| 121 | if (has('pay_period')) out.pay_period = c.choice('pay_period', PAY_PERIODS, { label: 'Pay period' }); |
| 122 | if (has('pay_currency')) { |
| 123 | const cur = c.body.pay_currency === undefined || c.body.pay_currency === '' ? 'USD' : c.body.pay_currency; |
| 124 | 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.'); |
| 125 | } |
| 126 | if (has('description')) out.description = c.text('description', { min: 80, max: 8000, required: true, label: 'Description', multiline: true }); |
| 127 | if (has('apply_url')) out.apply_url = c.url('apply_url', { max: 500, label: 'Apply link' }); |
| 128 | return out; |
| 129 | } |
| 130 | |
| 131 | // The pay floor (see PAY_FLOOR in config.js). Compared as a full-time year so the sums stay whole: |
| 132 | // $100 an hour is $800 a day, $4,000 a week, $17,333 a month or $208,000 a year. |
| 133 | const usd = (n) => `$${n.toLocaleString('en-US')}`; |
| 134 | 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.`; |
| 135 | export function belowPayFloor(min, period, currency) { |
| 136 | if (PAY_FLOOR === 'off' || !Number.isInteger(min) || currency !== 'USD') return false; |
| 137 | if (PAY_FLOOR === 'hourly' && period !== 'hour') return false; |
| 138 | const perYear = PERIODS_A_YEAR[period]; |
| 139 | return perYear ? min * perYear < MIN_HOURLY_USD * HOURS_A_YEAR : false; |
| 140 | } |
| 141 | |
| 142 | async function closeJob(request, env, id) { |
| 143 | const { body, error } = await readJson(request); |
| 144 | if (error) return error; |
| 145 | if (typeof body.manage_token !== 'string' || body.manage_token.length > 200) return fail(401, 'unauthorized', 'A manage token is required.'); |
| 146 | const row = await env.DB.prepare(`SELECT id, status, manage_token_hash FROM jobs WHERE id = ?`).bind(id).first(); |
| 147 | if (!row || row.manage_token_hash !== (await sha256(body.manage_token))) return fail(404, 'not_found', 'No job matches that id and token.'); |
| 148 | if (row.status === 'closed') return json({ ok: true, id, status: 'closed' }); |
| 149 | const at = now(); |
| 150 | await env.DB.batch([ |
| 151 | env.DB.prepare(`UPDATE jobs SET status = 'closed', updated_at = ? WHERE id = ?`).bind(at, id), |
| 152 | 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), |
| 153 | ]); |
| 154 | return json({ ok: true, id, status: 'closed' }); |
| 155 | } |
| 156 | |
| 157 | async function submitModerator(request, env) { |
| 158 | const { body, error } = await readJson(request); |
| 159 | if (error) return error; |
| 160 | const g = await gate(request, env, body, 'moderators'); |
| 161 | if (g.stop) return g.stop; |
| 162 | const c = new Checker(body); |
| 163 | const name = c.text('name', { min: 2, max: 100, required: true, label: 'Your name' }); |
| 164 | const email = c.email('email'); |
| 165 | const timezone = c.text('timezone', { max: 60, label: 'Time zone' }); |
| 166 | const hours = c.int('hours_per_week', { min: 1, max: 40, required: false, label: 'Hours a week' }); |
| 167 | // The public form sends name, email and message; older clients still send why. |
| 168 | const why = c.text(c.body.message !== undefined ? 'message' : 'why', { min: 10, max: 3000, required: true, label: 'Message', multiline: true }); |
| 169 | const experience = c.text('experience', { max: 3000, label: 'Experience', multiline: true }); |
| 170 | const links = c.links('links'); |
| 171 | if (!c.ok) return fail(422, 'invalid', 'Please fix the marked fields.', { fields: c.fields }); |
| 172 | const rate = await tooMany(request, env, 'moderators'); |
| 173 | if (rate.stop) return rate.stop; |
| 174 | const id = randomId('a'); |
| 175 | const at = now(); |
| 176 | await env.DB.prepare( |
| 177 | `INSERT INTO moderator_applications (id, status, name, email, timezone, hours_per_week, why, experience, links, ip_hash, created_at, updated_at) |
| 178 | VALUES (?, 'new', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, |
| 179 | ).bind(id, name, email, timezone, hours, why, experience, JSON.stringify(links), rate.hash, at, at).run(); |
| 180 | return json({ ok: true, id, status: 'received' }, 201); |
| 181 | } |
| 182 | |
| 183 | // ------------------------------------------------------------------ admin |
| 184 | |
| 185 | // Who is calling: the curator or an active moderator, from the session token a passkey sign-in |
| 186 | // issued. Nothing else signs a person in: ADMIN_TOKEN and the old pasted moderator tokens are refused. |
| 187 | export async function whoIs(request, env) { |
| 188 | const token = bearer(request); |
| 189 | if (!token) return null; |
| 190 | const client = (request.headers.get('x-client') || 'unknown').toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 20) || 'unknown'; |
| 191 | const person = await sessionPerson(env, token); |
| 192 | if (!person) return null; |
| 193 | if (person.role === 'curator') return { role: 'curator', id: 'curator', name: 'Curator', actor: 'curator', canSeeCandidates: true, client, token }; |
| 194 | await env.DB.prepare(`UPDATE moderators SET last_seen_at = ? WHERE id = ?`).bind(now(), person.userId).run(); |
| 195 | return { role: 'moderator', id: person.userId, name: person.name, actor: `moderator:${person.userId}`, canSeeCandidates: person.canSeeCandidates, client, token }; |
| 196 | } |
| 197 | function bearer(request) { |
| 198 | const header = request.headers.get('authorization') || ''; |
| 199 | const token = header.startsWith('Bearer ') ? header.slice(7).trim() : ''; |
| 200 | return token && token.length <= 200 ? token : null; |
| 201 | } |
| 202 | |
| 203 | const log = (env, who, action, type, id, detail = null, at = now()) => |
| 204 | env.DB.prepare(`INSERT INTO audit_log (actor, client, action, target_type, target_id, detail, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`) |
| 205 | .bind(who.actor, who.client, action, type, id, detail, at); |
| 206 | |
| 207 | // What an agent (X-Client: mcp) may change: tidy a post's wording and leave a note for the |
| 208 | // person reviewing. Agents never approve, reject, publish or unpublish a job, and never touch |
| 209 | // a candidate. The apps enforce this too; the API does not rely on them. |
| 210 | const AGENT_WRITES = new Set(['jobs.patch', 'jobs.notes']); |
| 211 | |
| 212 | async function admin(request, env, url, method, parts) { |
| 213 | const who = await whoIs(request, env); |
| 214 | if (!who) return json({ ok: false, error: 'unauthorized', message: 'Sign in with your passkey first.' }, 401, { 'www-authenticate': 'Bearer' }); |
| 215 | const [a, b, c] = parts; |
| 216 | const read = method === 'GET'; |
| 217 | const guard = (name, { curator = false, candidates = false } = {}) => { |
| 218 | 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.'); |
| 219 | if (curator && who.role !== 'curator') return fail(403, 'forbidden', 'Only the curator can do that.'); |
| 220 | if (candidates && who.client === 'mcp') return fail(403, 'people_only', 'Candidates are only shown to people.'); |
| 221 | if (candidates && !who.canSeeCandidates) return fail(403, 'forbidden', 'You do not have access to candidates.'); |
| 222 | return null; |
| 223 | }; |
| 224 | let body = {}; |
| 225 | if (!read && method !== 'DELETE') { |
| 226 | const parsed = await readJson(request); |
| 227 | if (parsed.error) return parsed.error; |
| 228 | body = parsed.body; |
| 229 | } |
| 230 | |
| 231 | if (a === 'me' && !b && read) return json({ ok: true, role: who.role, id: who.id, name: who.name, can_see_candidates: who.canSeeCandidates }); |
| 232 | if (a === 'stats' && !b && read) return stats(env, who); |
| 233 | if (a === 'purge' && !b && method === 'POST') return guard('purge', { curator: true }) || purge(env, who); |
| 234 | if (a === 'sign-out' && !b && method === 'POST') { await signOut(env, who.token); return json({ ok: true }); } |
| 235 | if (a === 'passkeys') return guard('passkeys') || passkeys(env, who, method, parts.slice(1), body); |
| 236 | |
| 237 | if (a === 'jobs') { |
| 238 | if (!b) { |
| 239 | if (read) return adminListJobs(env, url); |
| 240 | if (method === 'POST') return guard('jobs.create', { curator: true }) || volunteerOnly(); |
| 241 | return notAllowed('GET, POST'); |
| 242 | } |
| 243 | const job = await env.DB.prepare(`SELECT * FROM jobs WHERE id = ?`).bind(b).first(); |
| 244 | if (!job) return fail(404, 'not_found', 'No such job.'); |
| 245 | if (!c) { |
| 246 | if (read) return adminGetJob(env, job); |
| 247 | if (method === 'PATCH') return guard('jobs.patch') || patchJob(env, who, job, body); |
| 248 | return notAllowed('GET, PATCH'); |
| 249 | } |
| 250 | if (method !== 'POST' || parts.length !== 3) return fail(404, 'not_found', 'No such endpoint.'); |
| 251 | if (c === 'notes') return guard('jobs.notes') || addNote(env, who, job, body); |
| 252 | if (c === 'approve' || c === 'reject' || c === 'publish' || c === 'unpublish') return guard(`jobs.${c}`) || ((c === 'publish' || c === 'approve') ? volunteerOnly() : reviewJob(env, who, job, c, body)); |
| 253 | return fail(404, 'not_found', 'No such endpoint.'); |
| 254 | } |
| 255 | |
| 256 | if (a === 'candidates') { |
| 257 | const stop = guard('candidates', { candidates: true }); |
| 258 | if (stop) return stop; |
| 259 | if (!b) return read ? adminListCandidates(env, url) : notAllowed('GET'); |
| 260 | const cand = await env.DB.prepare(`SELECT * FROM candidates WHERE id = ?`).bind(b).first(); |
| 261 | if (!cand) return fail(404, 'not_found', 'No such candidate.'); |
| 262 | if (!c) return read ? adminGetCandidate(env, cand) : notAllowed('GET'); |
| 263 | if (method !== 'POST' || parts.length !== 3) return fail(404, 'not_found', 'No such endpoint.'); |
| 264 | if (c === 'introduce') return volunteerOnly(); |
| 265 | if (c === 'status') return candidateStatus(env, who, cand, body); |
| 266 | return fail(404, 'not_found', 'No such endpoint.'); |
| 267 | } |
| 268 | |
| 269 | if (a === 'moderator-applications') { |
| 270 | const stop = guard('applications', { curator: true }); |
| 271 | if (stop) return stop; |
| 272 | if (!b) return read ? listApplications(env, url) : notAllowed('GET'); |
| 273 | const app = await env.DB.prepare(`SELECT * FROM moderator_applications WHERE id = ?`).bind(b).first(); |
| 274 | if (!app) return fail(404, 'not_found', 'No such application.'); |
| 275 | if (method === 'POST' && c === 'approve' && parts.length === 3) return approveModerator(env, who, app, body); |
| 276 | if (method === 'POST' && c === 'decline' && parts.length === 3) return declineModerator(env, who, app, body); |
| 277 | return fail(404, 'not_found', 'No such endpoint.'); |
| 278 | } |
| 279 | |
| 280 | if (a === 'moderators') { |
| 281 | const stop = guard('moderators', { curator: true }); |
| 282 | if (stop) return stop; |
| 283 | if (!b) { |
| 284 | if (!read) return notAllowed('GET'); |
| 285 | 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(); |
| 286 | return json({ ok: true, moderators: results.map((m) => ({ ...m, can_see_candidates: m.can_see_candidates === 1, active: m.active === 1 })) }); |
| 287 | } |
| 288 | const mod = await env.DB.prepare(`SELECT id FROM moderators WHERE id = ?`).bind(b).first(); |
| 289 | if (!mod) return fail(404, 'not_found', 'No such moderator.'); |
| 290 | if (method === 'POST' && c === 'revoke' && parts.length === 3) { |
| 291 | await env.DB.batch([ |
| 292 | env.DB.prepare(`UPDATE moderators SET active = 0 WHERE id = ?`).bind(b), |
| 293 | env.DB.prepare(`DELETE FROM sessions WHERE role = 'moderator' AND user_id = ?`).bind(b), |
| 294 | env.DB.prepare(`UPDATE passkey_enrollments SET used_at = ? WHERE role = 'moderator' AND user_id = ? AND used_at IS NULL`).bind(now(), b), |
| 295 | log(env, who, 'revoke', 'moderator', b), |
| 296 | ]); |
| 297 | return json({ ok: true, id: b, active: false }); |
| 298 | } |
| 299 | // A new one-time setup link, for a moderator adding their first passkey (or one who lost theirs). |
| 300 | if (method === 'POST' && c === 'setup-link' && parts.length === 3) { |
| 301 | const active = await env.DB.prepare(`SELECT active FROM moderators WHERE id = ?`).bind(b).first(); |
| 302 | if (active.active !== 1) return fail(409, 'wrong_state', 'This moderator was revoked.'); |
| 303 | const link = await createEnrollment(env, 'moderator', b, who.actor); |
| 304 | await log(env, who, 'setup_link', 'moderator', b, link.expires_at).run(); |
| 305 | return json({ ok: true, id: b, setup: link }, 201); |
| 306 | } |
| 307 | if (method === 'POST' && c === 'access' && parts.length === 3) { |
| 308 | 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.' } }); |
| 309 | 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}`)]); |
| 310 | return json({ ok: true, id: b, can_see_candidates: body.can_see_candidates }); |
| 311 | } |
| 312 | return fail(404, 'not_found', 'No such endpoint.'); |
| 313 | } |
| 314 | return fail(404, 'not_found', 'No such endpoint.'); |
| 315 | } |
| 316 | |
| 317 | async function stats(env, who) { |
| 318 | const jobs = await env.DB.prepare(`SELECT status, COUNT(*) AS n FROM jobs GROUP BY status`).all(); |
| 319 | const out = { ok: true, jobs: Object.fromEntries(jobs.results.map((r) => [r.status, r.n])) }; |
| 320 | if (who.canSeeCandidates && who.client !== 'mcp') { |
| 321 | const cands = await env.DB.prepare(`SELECT status, COUNT(*) AS n FROM candidates GROUP BY status`).all(); |
| 322 | out.candidates = Object.fromEntries(cands.results.map((r) => [r.status, r.n])); |
| 323 | } |
| 324 | if (who.role === 'curator') { |
| 325 | const apps = await env.DB.prepare(`SELECT COUNT(*) AS n FROM moderator_applications WHERE status = 'new'`).first(); |
| 326 | out.moderator_applications = { new: apps.n }; |
| 327 | } |
| 328 | return json(out); |
| 329 | } |
| 330 | |
| 331 | // Deletes what the privacy page says we delete: posts that are off the board, candidates' notes and |
| 332 | // moderator applications, once they are older than LIMITS.keepMonths. The Mac app calls this when the |
| 333 | // curator opens it. Published jobs and their introductions are left alone until they come down. |
| 334 | export async function purge(env, who, at = new Date()) { |
| 335 | const cutoff = new Date(at); |
| 336 | cutoff.setUTCMonth(cutoff.getUTCMonth() - LIMITS.keepMonths); |
| 337 | const before = cutoff.toISOString(); |
| 338 | const live = `status = 'published' AND expires_at > ?`; |
| 339 | const out = await env.DB.batch([ |
| 340 | env.DB.prepare(`DELETE FROM introductions WHERE candidate_id IN (SELECT id FROM candidates WHERE updated_at < ?)`).bind(before), |
| 341 | env.DB.prepare(`DELETE FROM candidates WHERE updated_at < ?`).bind(before), |
| 342 | env.DB.prepare(`DELETE FROM introductions WHERE job_id IN (SELECT id FROM jobs WHERE updated_at < ? AND NOT (${live}))`).bind(before, at.toISOString()), |
| 343 | 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()), |
| 344 | env.DB.prepare(`DELETE FROM jobs WHERE updated_at < ? AND NOT (${live})`).bind(before, at.toISOString()), |
| 345 | 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), |
| 346 | env.DB.prepare(`DELETE FROM rate_limits WHERE window_start < ?`).bind(at.getTime() - 2 * 3600000), |
| 347 | ]); |
| 348 | const n = (i) => out[i].meta.changes; |
| 349 | const deleted = { candidates: n(1), jobs: n(4), moderator_applications: n(5) }; |
| 350 | await log(env, who, 'purge', 'system', 'retention', JSON.stringify(deleted)).run(); |
| 351 | return json({ ok: true, older_than: before, deleted }); |
| 352 | } |
| 353 | |
| 354 | const JOB_STATUSES = { pending: 1, approved: 1, published: 1, rejected: 1, unpublished: 1, closed: 1 }; |
| 355 | async function adminListJobs(env, url) { |
| 356 | const status = url.searchParams.get('status') || 'pending'; |
| 357 | if (status !== 'all' && !JOB_STATUSES[status]) return fail(422, 'invalid', 'Unknown status.', { fields: { status: 'Unknown status.' } }); |
| 358 | const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '', 10) || 50, 1), 200); |
| 359 | // The queue is oldest first, so the post that has waited longest is reviewed first. |
| 360 | const order = status === 'pending' || status === 'approved' ? 'created_at ASC' : 'updated_at DESC'; |
| 361 | const stmt = status === 'all' |
| 362 | ? env.DB.prepare(`SELECT * FROM jobs ORDER BY ${order} LIMIT ?`).bind(limit) |
| 363 | : env.DB.prepare(`SELECT * FROM jobs WHERE status = ? ORDER BY ${order} LIMIT ?`).bind(status, limit); |
| 364 | const { results } = await stmt.all(); |
| 365 | return json({ ok: true, jobs: results.map(adminJob) }); |
| 366 | } |
| 367 | async function adminGetJob(env, job) { |
| 368 | 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(); |
| 369 | const count = await env.DB.prepare(`SELECT COUNT(*) AS n FROM candidates WHERE job_id = ?`).bind(job.id).first(); |
| 370 | return json({ ok: true, job: adminJob(job), activity: results, candidate_count: count.n }); |
| 371 | } |
| 372 | |
| 373 | async function patchJob(env, who, job, body) { |
| 374 | const c = new Checker(body); |
| 375 | const f = jobFields(c, { partial: true }); |
| 376 | if ('company' in f || 'company_url' in f || 'apply_url' in f) { |
| 377 | return fail(422, 'owned_board', 'Only Jobley lists roles on this board.'); |
| 378 | } |
| 379 | const names = Object.keys(f); |
| 380 | if (!names.length) return fail(422, 'invalid', 'Nothing to change.', { fields: {} }); |
| 381 | const min = f.pay_min ?? job.pay_min; |
| 382 | const max = f.pay_max ?? job.pay_max; |
| 383 | if (Number.isInteger(min) && Number.isInteger(max) && max < min) c.bad('pay_max', 'Highest pay must be at least the lowest pay.'); |
| 384 | const payEdited = ['pay_min', 'pay_period', 'pay_currency'].some((n) => n in f); |
| 385 | 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); |
| 386 | if (!c.ok) return fail(422, 'invalid', 'Please fix the marked fields.', { fields: c.fields }); |
| 387 | const at = now(); |
| 388 | await env.DB.batch([ |
| 389 | env.DB.prepare(`UPDATE jobs SET ${names.map((n) => `${n} = ?`).join(', ')}, updated_at = ? WHERE id = ?`).bind(...names.map((n) => f[n]), at, job.id), |
| 390 | log(env, who, 'edit', 'job', job.id, names.join(', '), at), |
| 391 | ]); |
| 392 | return json({ ok: true, job: adminJob(await env.DB.prepare(`SELECT * FROM jobs WHERE id = ?`).bind(job.id).first()) }); |
| 393 | } |
| 394 | |
| 395 | async function addNote(env, who, job, body) { |
| 396 | const c = new Checker(body); |
| 397 | const note = c.text('note', { min: 1, max: 2000, required: true, label: 'Note', multiline: true }); |
| 398 | if (!c.ok) return fail(422, 'invalid', 'Please fix the marked fields.', { fields: c.fields }); |
| 399 | await log(env, who, 'note', 'job', job.id, note).run(); |
| 400 | return json({ ok: true, id: job.id }, 201); |
| 401 | } |
| 402 | |
| 403 | // Historical listings can be rejected or hidden, but never published again. |
| 404 | const MOVES = { |
| 405 | reject: { from: ['pending', 'approved'], to: 'rejected' }, |
| 406 | unpublish: { from: ['published'], to: 'unpublished' }, |
| 407 | }; |
| 408 | async function reviewJob(env, who, job, action, body) { |
| 409 | const move = MOVES[action]; |
| 410 | 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 }); |
| 411 | const c = new Checker(body); |
| 412 | const reason = c.text('reason', { min: action === 'reject' ? 3 : 0, max: 1000, required: action === 'reject', label: 'Reason', multiline: true }); |
| 413 | if (!c.ok) return fail(422, 'invalid', 'Please fix the marked fields.', { fields: c.fields }); |
| 414 | const at = now(); |
| 415 | await env.DB.batch([ |
| 416 | 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), |
| 417 | log(env, who, action, 'job', job.id, reason, at), |
| 418 | ]); |
| 419 | return json({ ok: true, job: adminJob(await env.DB.prepare('SELECT * FROM jobs WHERE id = ?').bind(job.id).first()) }); |
| 420 | } |
| 421 | |
| 422 | async function adminListCandidates(env, url) { |
| 423 | const where = []; |
| 424 | const args = []; |
| 425 | const jobId = url.searchParams.get('job_id'); |
| 426 | if (jobId === 'none') where.push('job_id IS NULL'); |
| 427 | else if (jobId) { where.push('job_id = ?'); args.push(jobId); } |
| 428 | const status = url.searchParams.get('status'); |
| 429 | if (status) { |
| 430 | if (!CANDIDATE_STATUSES[status]) return fail(422, 'invalid', 'Unknown status.', { fields: { status: 'Unknown status.' } }); |
| 431 | where.push('status = ?'); args.push(status); |
| 432 | } |
| 433 | const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '', 10) || 100, 1), 200); |
| 434 | // Oldest first, always. People are never ranked or scored. |
| 435 | 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(); |
| 436 | return json({ ok: true, candidates: results.map(adminCandidate) }); |
| 437 | } |
| 438 | async function adminGetCandidate(env, cand) { |
| 439 | 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(); |
| 440 | return json({ ok: true, candidate: adminCandidate(cand), introductions: results }); |
| 441 | } |
| 442 | |
| 443 | async function candidateStatus(env, who, cand, body) { |
| 444 | const c = new Checker(body); |
| 445 | const status = c.choice('status', { new: 1, reviewed: 1, declined: 1, withdrawn: 1 }, { label: 'Status' }); |
| 446 | const note = c.text('note', { max: 2000, label: 'Note', multiline: true }); |
| 447 | if (!c.ok) return fail(422, 'invalid', 'Please fix the marked fields.', { fields: c.fields }); |
| 448 | const at = now(); |
| 449 | await env.DB.batch([ |
| 450 | env.DB.prepare(`UPDATE candidates SET status = ?, note = COALESCE(?, note), updated_at = ? WHERE id = ?`).bind(status, note, at, cand.id), |
| 451 | log(env, who, `status:${status}`, 'candidate', cand.id, null, at), |
| 452 | ]); |
| 453 | return json({ ok: true, candidate: adminCandidate(await env.DB.prepare(`SELECT * FROM candidates WHERE id = ?`).bind(cand.id).first()) }); |
| 454 | } |
| 455 | |
| 456 | async function listApplications(env, url) { |
| 457 | const status = url.searchParams.get('status') || 'new'; |
| 458 | if (!{ new: 1, approved: 1, declined: 1 }[status]) return fail(422, 'invalid', 'Unknown status.', { fields: { status: 'Unknown status.' } }); |
| 459 | 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(); |
| 460 | return json({ ok: true, applications: results.map((r) => ({ ...r, links: safeList(r.links) })) }); |
| 461 | } |
| 462 | async function approveModerator(env, who, app, body) { |
| 463 | if (app.status === 'approved') return fail(409, 'wrong_state', 'This application was already approved.', { status: app.status }); |
| 464 | const id = randomId('m'); |
| 465 | const at = now(); |
| 466 | await env.DB.batch([ |
| 467 | // token_hash is a placeholder: moderators sign in with passkeys, never a token. |
| 468 | env.DB.prepare(`INSERT INTO moderators (id, application_id, name, email, token_hash, can_see_candidates, active, created_at) VALUES (?, ?, ?, ?, ?, ?, 1, ?)`) |
| 469 | .bind(id, app.id, app.name, app.email, `passkey:${id}`, body.can_see_candidates === true ? 1 : 0, at), |
| 470 | env.DB.prepare(`UPDATE moderator_applications SET status = 'approved', updated_at = ? WHERE id = ?`).bind(at, app.id), |
| 471 | log(env, who, 'approve', 'moderator_application', app.id, id, at), |
| 472 | ]); |
| 473 | // A one-time setup link, shown once. The curator hands it to the moderator, who opens it in the |
| 474 | // app to add their passkey. It works once, within 15 minutes. |
| 475 | const setup = await createEnrollment(env, 'moderator', id, who.actor); |
| 476 | return json({ ok: true, moderator: { id, name: app.name, email: app.email, can_see_candidates: body.can_see_candidates === true }, setup }, 201); |
| 477 | } |
| 478 | async function declineModerator(env, who, app, body) { |
| 479 | if (app.status !== 'new') return fail(409, 'wrong_state', `This application is already ${app.status}.`, { status: app.status }); |
| 480 | const c = new Checker(body); |
| 481 | const note = c.text('note', { max: 1000, label: 'Note', multiline: true }); |
| 482 | if (!c.ok) return fail(422, 'invalid', 'Please fix the marked fields.', { fields: c.fields }); |
| 483 | const at = now(); |
| 484 | await env.DB.batch([ |
| 485 | env.DB.prepare(`UPDATE moderator_applications SET status = 'declined', note = ?, updated_at = ? WHERE id = ?`).bind(note, at, app.id), |
| 486 | log(env, who, 'decline', 'moderator_application', app.id, null, at), |
| 487 | ]); |
| 488 | return json({ ok: true, id: app.id, status: 'declined' }); |
| 489 | } |
| 490 | |
| 491 | // The signed-in person's passkeys: list, add another, remove one (never the last). |
| 492 | async function passkeys(env, who, method, parts, body) { |
| 493 | const [id, extra] = parts; |
| 494 | const person = { role: who.role, userId: who.id, name: who.name }; |
| 495 | if (!id && method === 'GET') { |
| 496 | 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(); |
| 497 | return json({ ok: true, passkeys: results }); |
| 498 | } |
| 499 | if (id === 'options' && !extra && method === 'POST') return registrationOptions(env, person); |
| 500 | if (!id && method === 'POST') { |
| 501 | const done = await finishRegistration(env, body, person); |
| 502 | if (done.stop) return done.stop; |
| 503 | await log(env, who, 'passkey_add', 'passkey', who.id, done.passkeyId).run(); |
| 504 | return json({ ok: true, id: done.passkeyId }, 201); |
| 505 | } |
| 506 | if (id && id !== 'options' && !extra && method === 'DELETE') { |
| 507 | const count = await env.DB.prepare(`SELECT COUNT(*) AS n FROM passkeys WHERE role = ? AND user_id = ?`).bind(who.role, who.id).first(); |
| 508 | const mine = await env.DB.prepare(`SELECT id FROM passkeys WHERE id = ? AND role = ? AND user_id = ?`).bind(id, who.role, who.id).first(); |
| 509 | if (!mine) return fail(404, 'not_found', 'No such passkey.'); |
| 510 | if (count.n <= 1) return fail(409, 'last_passkey', 'Add another passkey before removing this one. It is your only way to sign in.'); |
| 511 | await env.DB.batch([ |
| 512 | env.DB.prepare(`DELETE FROM passkeys WHERE id = ? AND role = ? AND user_id = ?`).bind(id, who.role, who.id), |
| 513 | env.DB.prepare(`DELETE FROM sessions WHERE passkey_id = ?`).bind(id), |
| 514 | log(env, who, 'passkey_remove', 'passkey', who.id, id), |
| 515 | ]); |
| 516 | return json({ ok: true, id }); |
| 517 | } |
| 518 | return fail(404, 'not_found', 'No such endpoint.'); |
| 519 | } |