/** * The mock API of Team Tasks (an extension of the previous version's backend). The harness starts it outside the app directory: the agent only sees the front end and apps/team-tasks/API.md. * * node apps/mock-api/server.mjs --port 5701 [--scenario scenarios/x.json] [--public-url http://127.0.0.1:5701] * * Data is in memory, read from seed.json when the server starts; POST /__reset restores it (sessions and SSE connections are cleared too). * Fields of tasks, members and labels are not whitelisted: whatever fields the front end adds are stored and returned as they are. * * Scenario. Default {}: behaves like the previous version's backend (no sign-in required, the current user is the Owner). * latency / search / slow / fail as in the previous version: delay, out-of-order search, slow down by parameter, fail by route * auth: "required" every endpoint except /api/auth/* needs a sign-in first (cookie session), otherwise 401 * role: "viewer" the default user when not signed in becomes a read-only member (Sam Carter); any change by a read-only member is a 403 * sessionTtlMs: N the session expires N milliseconds after sign-in, then 401 { code: "session_expired" } * maxUploadBytes: N attachment size limit, 1 MB by default, 413 above it * fixtures: ["many-tasks", "long-thread", "long-task"] extra data (added once when the scenario is set) * Control endpoints: POST /__reset, POST /__scenario, GET /__state, POST /__notify {title, body?, taskId?} (pushes a notification), * POST /__sse/drop (drops every SSE connection), POST /__sessions/expire (expires every current session). * * The checkout /pay/:id is not under /api: this server serves the page itself, at --public-url (default http://127.0.0.1:port), * a different origin from the app (localhost:vite port), like an external payment page. After payment it answers 303 back to the returnUrl given with the order. */ import { createServer } from "node:http"; import { readFileSync } from "node:fs"; import { randomBytes } from "node:crypto"; import { parseArgs } from "node:util"; const { values } = parseArgs({ options: { port: { type: "string", default: "5701" }, scenario: { type: "string" }, "public-url": { type: "string" } }, }); const PORT = Number(values.port); const PUBLIC_URL = values["public-url"] ?? `http://127.0.0.1:${PORT}`; const SEED = readFileSync(new URL("./seed.json", import.meta.url), "utf8"); const PASSWORD = "teamtasks"; const COOKIE = "tt_session"; const PACKS = { 100: 1000, 500: 4000, 1000: 7000 }; // credits → price (cents) let db, files, sessions; const streams = new Set(); function load() { db = JSON.parse(SEED); // Attachment contents are kept out of /__state: stored separately files = new Map(Object.entries(db.attachmentFiles ?? {}).map(([id, f]) => [Number(id), Buffer.from(f.text, "utf8")])); delete db.attachmentFiles; sessions = new Map(); for (const s of streams) s.end(); streams.clear(); } load(); let scenario = {}; setScenario(values.scenario ? JSON.parse(readFileSync(values.scenario, "utf8")) : {}); const nextId = (xs) => Math.max(0, ...xs.map((x) => Number(String(x.id).replace(/\D/g, "")) || 0)) + 1; const now = () => new Date().toISOString(); class HttpError extends Error { constructor(status, message, extra = {}) { super(message); this.status = status; this.extra = extra; } } const need = (x, what) => { if (!x) throw new HttpError(404, `${what} not found`); return x; }; const raw = (status, headers, body) => ({ __raw: { status, headers, body } }); const withCount = (t) => ({ ...t, commentCount: db.comments.filter((c) => c.taskId === t.id).length }); const member = (id) => db.members.find((m) => m.id === id); const taskById = (id) => db.tasks.find((t) => t.id === Number(id)); function findTask(id) { const t = taskById(id); if (t) return t; const gone = db.deletedTasks.find((d) => d.id === Number(id)); if (gone) throw new HttpError(410, "task was deleted", { taskId: gone.id, title: gone.title, deletedAt: gone.deletedAt, deletedBy: gone.deletedBy }); throw new HttpError(404, "task not found"); } // ───────────── Scenarios and extra data ───────────── function setScenario(s) { scenario = s ?? {}; db.fixtures ??= []; for (const f of scenario.fixtures ?? []) { if (db.fixtures.includes(f)) continue; FIXTURES[f]?.(); db.fixtures.push(f); } } const VERBS = ["Audit", "Fix", "Document", "Migrate", "Review", "Update", "Test", "Clean up", "Investigate", "Draft", "Ship", "Triage"]; const THINGS = ["billing emails", "CSV import", "search ranking", "mobile header", "invoice PDFs", "SSO settings", "webhook retries", "onboarding checklist", "dark theme colors", "audit log export", "rate limits", "file previews"]; const FIXTURES = { // 120 older tasks: for pagination, infinite scroll and long lists "many-tasks": () => { let id = nextId([...db.tasks, ...db.deletedTasks]); for (let i = 0; i < 120; i++) { const day = new Date(Date.UTC(2026, 8, 30) - i * 6 * 3600 * 1000); db.tasks.push({ id: id++, title: `${VERBS[i % VERBS.length]} ${THINGS[(i * 5) % THINGS.length]} (#${1100 + i})`, priority: ["low", "medium", "high"][(i * 7) % 3], done: i % 4 === 0, description: "", createdAt: day.toISOString().replace(".000", ""), }); } }, // 24 comments under "Relocate staging database": the comment area has to scroll "long-thread": () => { const who = ["m2", "m3", "m4", "m1"]; const lines = [ "Snapshot of staging taken, 42 GB.", "Do we keep the old read replica around for a week?", "Yes, until the freeze ends.", "DNS TTL lowered to 60s.", "Migration dry run took 38 minutes.", "Can we do it on Thursday morning?", "Thursday works for me.", "I'll post in #eng-announce.", "Found two cron jobs still pointing at the old host.", "Fixed the cron jobs.", "Feature flags service needs the new connection string.", "Updated the flags service config.", "Dry run #2: 31 minutes.", "Backups verified in the new region.", "Monitoring dashboards cloned.", "Alert thresholds copied over.", "Load test passed.", "Rollback plan written up in the wiki.", "QA signed off on staging.", "Scheduled for Thursday 9:00.", "Started.", "Data copied, switching traffic.", "Traffic switched, watching errors.", "All green. Closing this out tomorrow.", ]; let id = nextId(db.comments); lines.forEach((body, i) => db.comments.push({ id: id++, taskId: 10, authorId: who[i % who.length], body, createdAt: new Date(Date.UTC(2026, 9, 10, 10 + Math.floor(i / 4), (i * 13) % 60)).toISOString() }), ); }, // "Relocate staging database" filled in: a long description and every field, so the edit page scrolls a long way "long-task": () => { const t = taskById(10); if (!t) return; t.description = Array.from({ length: 14 }, (_, i) => `Step ${i + 1}: ${["Freeze writes", "Snapshot the primary", "Copy the snapshot", "Restore in the new region", "Replay the WAL", "Verify row counts", "Switch the read replicas", "Point the app at the new primary", "Run smoke tests", "Lift the freeze", "Watch error rates", "Update runbooks", "Remove the old instance", "Close the change ticket"][i]}.`).join("\n\n"); Object.assign(t, { assigneeId: "m3", dueDate: "2026-11-20", estimateHours: 16, notes: "Coordinate with the data team before freezing writes.\nKeep the old instance for 7 days." }); }, }; // ───────────── Sessions ───────────── function cookies(req) { return Object.fromEntries((req.headers.cookie ?? "").split(/;\s*/).filter(Boolean).map((c) => [c.slice(0, c.indexOf("=")), decodeURIComponent(c.slice(c.indexOf("=") + 1))])); } function sessionOf(req) { const sid = cookies(req)[COOKIE]; return sid ? { sid, ...sessions.get(sid) } : null; } const defaultMe = () => (scenario.role === "viewer" ? db.members.find((m) => m.role === "Viewer") : member(db.me)) ?? db.members[0]; /** Who this request is from. Throws 401 when a sign-in is required and missing (or the session expired). */ function currentMember(req) { const s = sessionOf(req); if (s?.memberId) { if (s.expiresAt <= Date.now()) { sessions.delete(s.sid); throw new HttpError(401, "Your session has expired. Please sign in again.", { code: "session_expired" }); } const m = member(s.memberId); if (m) return m; } if (scenario.auth === "required") throw new HttpError(401, "Please sign in.", { code: "unauthenticated" }); return defaultMe(); } // ───────────── Activity log, notifications, SSE ───────────── function log(type, actor, extra = {}) { db.activity.push({ id: nextId(db.activity), at: now(), actorId: actor?.id ?? null, type, ...extra }); } function broadcast(event, data) { for (const s of streams) s.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); } function notify(n) { const item = { id: nextId(db.notifications), title: n.title, body: n.body ?? "", taskId: n.taskId ?? null, read: false, createdAt: now() }; db.notifications.push(item); broadcast("notification", item); return item; } // ───────────── Filtering, sorting and CSV of the task list ───────────── const RANK = { high: 0, medium: 1, low: 2 }; function queryTasks(q) { let ts = db.tasks; if (q.get("q")) ts = ts.filter((t) => t.title.toLowerCase().includes(q.get("q").toLowerCase())); const status = q.get("status"); if (status === "active") ts = ts.filter((t) => !t.done); else if (status === "done") ts = ts.filter((t) => t.done); if (q.get("seriesId")) ts = ts.filter((t) => String(t.seriesId) === q.get("seriesId")); const sort = q.get("sort") ?? (q.has("page") ? "newest" : null); const out = [...ts]; if (sort === "newest") out.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id - a.id); else if (sort === "oldest") out.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id - b.id); else if (sort === "priority") out.sort((a, b) => RANK[a.priority] - RANK[b.priority] || a.id - b.id); else if (sort === "title") out.sort((a, b) => a.title.localeCompare(b.title)); return out; } function page(items, q, map = (x) => x) { const p = Math.max(1, Number(q.get("page")) || 1); const limit = Math.min(100, Math.max(1, Number(q.get("limit")) || 20)); return { items: items.slice((p - 1) * limit, p * limit).map(map), total: items.length, page: p, limit, hasMore: p * limit < items.length }; } const csvCell = (v) => (/[",\n]/.test(String(v)) ? `"${String(v).replaceAll('"', '""')}"` : String(v)); // ───────────── Attachments ───────────── function parseMultipart(buf, contentType) { const boundary = /boundary=(?:"([^"]+)"|([^;]+))/.exec(contentType); if (!boundary) throw new HttpError(400, "multipart boundary missing"); const sep = Buffer.from(`--${boundary[1] ?? boundary[2]}`); const parts = {}; let at = buf.indexOf(sep); while (at !== -1) { const start = at + sep.length; if (buf.slice(start, start + 2).toString() === "--") break; const next = buf.indexOf(sep, start); if (next === -1) break; const part = buf.slice(start + 2, next - 2); // drop the leading \r\n and the trailing \r\n const headEnd = part.indexOf("\r\n\r\n"); const head = part.slice(0, headEnd).toString(); const name = /name="([^"]*)"/.exec(head)?.[1]; const filename = /filename="([^"]*)"/.exec(head)?.[1]; const type = /content-type:\s*([^\r\n]+)/i.exec(head)?.[1] ?? "application/octet-stream"; const data = part.slice(headEnd + 4); if (name) parts[name] = filename !== undefined ? { filename, type, data } : data.toString(); at = next; } return parts; } const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); const isText = (a) => /^text\/|json|xml|javascript|csv|markdown/.test(a.type) || /\.(txt|md|csv|json|log|ya?ml)$/i.test(a.name); function previewPage(a) { const blob = files.get(a.id) ?? Buffer.alloc(0); let body; if (a.type.startsWith("image/")) body = `${esc(a.name)}`; else if (isText(a)) body = `
${esc(blob.toString("utf8"))}
`; else body = `

No preview for this file type. Download ${esc(a.name)}

`; return `${esc(a.name)}
${esc(a.name)} · ${a.size.toLocaleString("en-US")} bytes
${body}`; } // ───────────── Checkout page ───────────── const money = (cents) => `$${(cents / 100).toFixed(2)}`; function back(order, status) { const u = new URL(order.returnUrl); u.searchParams.set("order", String(order.id)); u.searchParams.set("status", status); return u.toString(); } function checkoutPage(o) { const open = o.status === "pending"; return `Checkout · Payline
Payline

${open ? "Complete your purchase" : `This order is ${o.status}`}

Team Tasks credits${o.credits}
Order#${o.id}
Total${money(o.amount)}
${open ? `
Cancel and return to Team Tasks` : `Return to Team Tasks`}

Test mode — no card is charged.

`; } // ───────────── Routes ───────────── const forbidViewer = (me) => { if (me.role === "Viewer") throw new HttpError(403, "Viewers can't make changes to this team."); }; /** [method, path template, handler(params, body, query, ctx)]. ctx = { me, req }; auth routes do not resolve the current user first. */ const ROUTES = [ // Sign-in and sessions ["GET", "/api/auth/session", (_, __, ___, { req }) => ({ member: currentMember(req), authRequired: scenario.auth === "required" })], ["POST", "/api/auth/login", (_, b) => { const m = db.members.find((x) => x.email.toLowerCase() === String(b.email ?? "").trim().toLowerCase()); if (!m || b.password !== PASSWORD) throw new HttpError(401, "Wrong email or password.", { code: "bad_credentials" }); const sid = randomBytes(16).toString("hex"); sessions.set(sid, { memberId: m.id, expiresAt: Date.now() + (scenario.sessionTtlMs ?? 8 * 3600 * 1000) }); return raw(200, { "content-type": "application/json", "set-cookie": `${COOKIE}=${sid}; Path=/; HttpOnly; SameSite=Lax` }, JSON.stringify({ member: m })); }], ["POST", "/api/auth/logout", (_, __, ___, { req }) => { const s = sessionOf(req); if (s) sessions.delete(s.sid); return raw(200, { "content-type": "application/json", "set-cookie": `${COOKIE}=; Path=/; Max-Age=0` }, JSON.stringify({ ok: true })); }], // Team and members ["GET", "/api/me", (_, __, ___, { me }) => me], ["GET", "/api/team", () => ({ name: db.team, memberCount: db.members.length })], ["GET", "/api/members", () => db.members], ["POST", "/api/members", (_, b, __, { me }) => { forbidViewer(me); if (!b.name || !b.email) throw new HttpError(400, "name and email are required"); const m = { ...b, id: `m${nextId(db.members)}`, role: b.role ?? "Member" }; db.members.push(m); return m; }], ["DELETE", "/api/members/:id", (p, _, __, { me }) => { forbidViewer(me); const m = need(member(p.id), "member"); db.members = db.members.filter((x) => x.id !== p.id); log("member.removed", me, { summary: m.name }); return { ok: true }; }], ["GET", "/api/labels", () => db.labels], ["POST", "/api/labels", (_, b, __, { me }) => { forbidViewer(me); if (!b.name) throw new HttpError(400, "name is required"); if (db.labels.some((l) => l.name.toLowerCase() === String(b.name).toLowerCase())) throw new HttpError(409, "a label with that name exists"); const l = { color: "gray", ...b, id: nextId(db.labels) }; db.labels.push(l); return l; }], ["PATCH", "/api/labels/:id", (p, b, __, { me }) => { forbidViewer(me); return Object.assign(need(db.labels.find((l) => l.id === Number(p.id)), "label"), b, { id: Number(p.id) }); }], ["DELETE", "/api/labels/:id", (p, _, __, { me }) => { forbidViewer(me); db.labels = db.labels.filter((l) => l.id !== Number(p.id)); return { ok: true }; }], ["GET", "/api/invites", () => db.invites], ["DELETE", "/api/invites/:id", (p, _, __, { me }) => { forbidViewer(me); need(db.invites.find((i) => i.id === Number(p.id)), "invite"); db.invites = db.invites.filter((i) => i.id !== Number(p.id)); return { ok: true }; }], ["POST", "/api/invites", (_, b, __, { me }) => { forbidViewer(me); if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(b.email ?? "")) throw new HttpError(400, "a valid email is required"); const i = { id: nextId(db.invites), email: b.email, createdAt: now() }; db.invites.push(i); log("invite.sent", me, { summary: b.email }); return i; }], // Tasks ["GET", "/api/tasks/export.csv", (_, __, q) => { const head = ["id", "title", "priority", "status", "created_at"]; const rows = queryTasks(q).map((t) => [t.id, t.title, t.priority, t.done ? "done" : "active", t.createdAt]); const csv = [head, ...rows].map((r) => r.map(csvCell).join(",")).join("\r\n") + "\r\n"; const name = `tasks${q.get("status") && q.get("status") !== "all" ? `-${q.get("status")}` : ""}.csv`; return raw(200, { "content-type": "text/csv; charset=utf-8", "content-disposition": `attachment; filename="${name}"` }, csv); }], ["GET", "/api/tasks", (_, __, q) => { const ts = queryTasks(q); return q.has("page") ? page(ts, q, withCount) : ts.map(withCount); }], ["GET", "/api/tasks/:id", (p) => withCount(findTask(p.id))], ["POST", "/api/tasks", (_, b, __, { me }) => { forbidViewer(me); if (!String(b.title ?? "").trim()) throw new HttpError(400, "title is required"); const t = { priority: "medium", done: false, description: "", ...b, id: nextId([...db.tasks, ...db.deletedTasks]), createdAt: now() }; db.tasks.push(t); log("task.created", me, { taskId: t.id, summary: t.title }); return withCount(t); }], ["PATCH", "/api/tasks/:id", (p, b, __, { me }) => { forbidViewer(me); const t = findTask(p.id); const wasDone = t.done; Object.assign(t, b, { id: t.id, createdAt: t.createdAt }); const type = !wasDone && t.done ? "task.completed" : wasDone && t.done === false ? "task.reopened" : "task.updated"; log(type, me, { taskId: t.id, summary: t.title, fields: Object.keys(b) }); return withCount(t); }], ["DELETE", "/api/tasks/:id", (p, _, __, { me }) => { forbidViewer(me); const t = findTask(p.id); db.tasks = db.tasks.filter((x) => x.id !== t.id); db.comments = db.comments.filter((c) => c.taskId !== t.id); for (const a of db.attachments.filter((a) => a.taskId === t.id)) files.delete(a.id); db.attachments = db.attachments.filter((a) => a.taskId !== t.id); db.deletedTasks.push({ id: t.id, title: t.title, deletedAt: now(), deletedBy: me.id }); log("task.deleted", me, { taskId: t.id, summary: t.title }); return { ok: true }; }], ["GET", "/api/tasks/:id/comments", (p) => db.comments.filter((c) => c.taskId === Number(p.id))], ["POST", "/api/tasks/:id/comments", (p, b, __, { me }) => { forbidViewer(me); const t = findTask(p.id); if (!String(b.body ?? "").trim()) throw new HttpError(400, "body is required"); const c = { id: nextId(db.comments), taskId: t.id, authorId: me.id, body: b.body, createdAt: now() }; db.comments.push(c); log("comment.added", me, { taskId: t.id, summary: t.title }); return c; }], // Attachments ["GET", "/api/tasks/:id/attachments", (p) => db.attachments.filter((a) => a.taskId === Number(p.id))], ["POST", "/api/tasks/:id/attachments", (p, b, __, { me }) => { forbidViewer(me); const t = findTask(p.id); const f = b.file; if (!f || typeof f !== "object") throw new HttpError(400, "send the file as multipart/form-data in a field named \"file\""); const max = scenario.maxUploadBytes ?? 1024 * 1024; if (f.data.length > max) throw new HttpError(413, `File is too large (max ${max >= 1024 * 1024 ? `${max / 1024 / 1024} MB` : `${Math.round(max / 1024)} KB`}).`); const d = new Date(); const a = { id: nextId(db.attachments), taskId: t.id, name: f.filename || "file", size: f.data.length, type: f.type, path: `team-files/acme-product/tasks/${t.id}/${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}/${f.filename || "file"}`, uploadedBy: me.id, createdAt: now(), }; db.attachments.push(a); files.set(a.id, f.data); log("attachment.added", me, { taskId: t.id, summary: a.name }); return a; }], ["GET", "/api/attachments/:id/preview", (p) => raw(200, { "content-type": "text/html; charset=utf-8" }, previewPage(need(db.attachments.find((a) => a.id === Number(p.id)), "attachment")))], ["GET", "/api/attachments/:id/download", (p, _, q) => { const a = need(db.attachments.find((x) => x.id === Number(p.id)), "attachment"); return raw(200, { "content-type": a.type, "content-disposition": `${q.get("inline") ? "inline" : "attachment"}; filename="${a.name}"` }, files.get(a.id) ?? Buffer.alloc(0)); }], ["DELETE", "/api/attachments/:id", (p, _, __, { me }) => { forbidViewer(me); need(db.attachments.find((a) => a.id === Number(p.id)), "attachment"); db.attachments = db.attachments.filter((a) => a.id !== Number(p.id)); files.delete(Number(p.id)); return { ok: true }; }], // Old-style links (such as /browse/TT-1002) ["GET", "/api/legacy/:key", (p) => { const id = db.legacyKeys[String(p.key).toUpperCase()]; if (!id) throw new HttpError(404, "no task with that key"); return { taskId: findTask(id).id }; }], // Credits and orders ["GET", "/api/credits", () => ({ balance: db.credits })], ["GET", "/api/orders", () => [...db.orders].sort((a, b) => b.id - a.id)], ["POST", "/api/orders", (_, b, __, { me }) => { const credits = Number(b.credits); if (!PACKS[credits]) throw new HttpError(400, `credits must be one of ${Object.keys(PACKS).join(", ")}`); let returnUrl; try { returnUrl = new URL(b.returnUrl).toString(); } catch { throw new HttpError(400, "returnUrl must be an absolute URL"); } const o = { id: nextId(db.orders), credits, amount: PACKS[credits], currency: "USD", status: "pending", createdAt: now(), createdBy: me.id, returnUrl }; db.orders.push(o); log("order.created", me, { summary: `${credits} credits` }); return { ...o, checkoutUrl: `${PUBLIC_URL}/pay/${o.id}` }; }], ["POST", "/api/orders/:id/cancel", (p, _, __, { me }) => { const o = need(db.orders.find((x) => x.id === Number(p.id)), "order"); if (o.status === "paid") throw new HttpError(409, "this order is already paid"); if (o.status === "pending") { o.status = "cancelled"; o.cancelledAt = now(); log("order.cancelled", me, { summary: `#${o.id}` }); broadcast("order", o); } return o; }], // Notifications ["GET", "/api/notifications", () => [...db.notifications].sort((a, b) => b.id - a.id)], ["POST", "/api/notifications/read-all", () => { for (const n of db.notifications) n.read = true; return { ok: true }; }], ["POST", "/api/notifications/:id/read", (p) => { const n = need(db.notifications.find((x) => x.id === Number(p.id)), "notification"); n.read = true; return n; }], // Activity log ["GET", "/api/activity", (_, __, q) => { let xs = [...db.activity].sort((a, b) => b.at.localeCompare(a.at) || b.id - a.id); if (q.get("type")) xs = xs.filter((a) => a.type === q.get("type") || a.type.startsWith(`${q.get("type")}.`)); if (q.get("actorId")) xs = xs.filter((a) => a.actorId === q.get("actorId")); if (q.get("taskId")) xs = xs.filter((a) => a.taskId === Number(q.get("taskId"))); return page(xs, q); }], ["DELETE", "/api/activity/:id", (p, _, __, { me }) => { forbidViewer(me); need(db.activity.find((a) => a.id === Number(p.id)), "activity entry"); db.activity = db.activity.filter((a) => a.id !== Number(p.id)); return { ok: true }; }], ]; function match(method, path) { for (const [m, tpl, fn] of ROUTES) { if (m !== method) continue; const a = tpl.split("/"), b = path.split("/"); if (a.length !== b.length) continue; const params = {}; if (a.every((s, i) => (s.startsWith(":") ? ((params[s.slice(1)] = decodeURIComponent(b[i])), true) : s === b[i]))) return { route: `${m} ${tpl}`, fn, params }; } return null; } function delayFor(route, query, params, body) { if (route === "GET /api/tasks" && query.get("q") && scenario.search === "short-is-slow") return Math.max(60, 1000 - 220 * query.get("q").length); const slow = (scenario.slow ?? []).find((x) => x.route === route && Object.entries(x.when ?? {}).every(([k, v]) => String(params[k] ?? query.get(k) ?? body?.[k]) === String(v))); if (slow) return slow.ms; return scenario.latency?.[route] ?? scenario.latency?.default ?? 80; } function failFor(route, params, body, query) { const f = (scenario.fail ?? []).find((f) => f.route === route && (f.times ?? Infinity) > 0 && Object.entries(f.when ?? {}).every(([k, v]) => String(params[k] ?? query.get(k) ?? body?.[k]) === String(v))); if (f && f.times) f.times--; return f; } const send = (res, status, data, headers = {}) => { res.writeHead(status, { "content-type": "application/json", ...headers }); res.end(JSON.stringify(data)); }; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); function parseBody(buf, type = "") { if (!buf.length) return {}; if (type.startsWith("multipart/form-data")) return parseMultipart(buf, type); if (type.startsWith("application/x-www-form-urlencoded")) return Object.fromEntries(new URLSearchParams(buf.toString())); return JSON.parse(buf.toString()); } async function handlePay(req, res, url) { const m = /^\/pay\/(\d+)$/.exec(url.pathname); const o = m && db.orders.find((x) => x.id === Number(m[1])); const route = `${req.method} /pay/:id`; await sleep(delayFor(route, url.searchParams, {}, {})); if (!o) { res.writeHead(404, { "content-type": "text/html; charset=utf-8" }); return res.end("Not found

This checkout link is not valid.

"); } if (req.method === "POST" && o.status === "pending") { const f = failFor(route, { id: m[1] }, {}, url.searchParams); if (f) { res.writeHead(f.status ?? 502, { "content-type": "text/html; charset=utf-8" }); return res.end(`Payment failed

The payment could not be processed. Try again

`); } o.status = "paid"; o.paidAt = now(); db.credits += o.credits; log("order.paid", member(o.createdBy), { summary: `${o.credits} credits` }); notify({ title: `Payment received: ${o.credits} credits added`, body: `Order #${o.id} · ${money(o.amount)}` }); broadcast("order", o); broadcast("credits", { balance: db.credits }); res.writeHead(303, { location: back(o, "paid") }); return res.end(); } res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }); res.end(checkoutPage(o)); } function openStream(req, res) { res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive", "x-accel-buffering": "no" }); res.write("retry: 2000\n\n"); const ping = setInterval(() => res.write(": ping\n\n"), 15000); const s = { write: (x) => res.write(x), end: () => res.end() }; streams.add(s); req.on("close", () => { clearInterval(ping); streams.delete(s); }); } createServer(async (req, res) => { const url = new URL(req.url, "http://x"); const chunks = []; for await (const c of req) chunks.push(c); let body = {}; try { // Bodies of control requests are always read as JSON (the harness sends them without a content-type) body = parseBody(Buffer.concat(chunks), url.pathname.startsWith("/__") ? "application/json" : req.headers["content-type"]); } catch (e) { return send(res, 400, { error: e instanceof HttpError ? e.message : "invalid JSON" }); } // Control endpoints (for the harness and the judges) if (url.pathname === "/__reset") { load(); setScenario(scenario); return send(res, 200, { ok: true }); } if (url.pathname === "/__scenario") { setScenario(body); return send(res, 200, { ok: true }); } if (url.pathname === "/__state") return send(res, 200, db); if (url.pathname === "/__notify") return send(res, 200, notify({ title: body.title ?? "Something happened", body: body.body, taskId: body.taskId })); if (url.pathname === "/__sse/drop") { for (const s of streams) s.end(); streams.clear(); return send(res, 200, { ok: true }); } if (url.pathname === "/__sessions/expire") { for (const s of sessions.values()) s.expiresAt = 0; return send(res, 200, { ok: true }); } if (url.pathname.startsWith("/pay/")) return handlePay(req, res, url); if (url.pathname === "/api/events" && req.method === "GET") { await sleep(delayFor("GET /api/events", url.searchParams, {}, {})); try { currentMember(req); } catch (e) { return send(res, e.status ?? 500, { error: e.message, ...e.extra }); } return openStream(req, res); } const m = match(req.method, url.pathname); if (!m) return send(res, 404, { error: "no such endpoint" }); await sleep(delayFor(m.route, url.searchParams, m.params, body)); const f = failFor(m.route, m.params, body, url.searchParams); if (f) return send(res, f.status ?? 500, { error: f.message ?? "internal error" }); try { const ctx = { req, me: m.route.startsWith(`${req.method} /api/auth/`) ? null : currentMember(req) }; const out = m.fn(m.params, body, url.searchParams, ctx); if (out?.__raw) { res.writeHead(out.__raw.status, out.__raw.headers); return res.end(out.__raw.body); } send(res, req.method === "POST" ? 201 : 200, out); } catch (e) { if (!(e instanceof HttpError)) console.error(e); send(res, e.status ?? 500, { error: e.message, ...e.extra }); } }).listen(PORT, () => console.log(`api on http://localhost:${PORT} (checkout at ${PUBLIC_URL}/pay/:id)`));