import Fastify from "fastify"; import type { DatabaseSync } from "node:sqlite"; import { listApplications } from "./applications.js"; import { pickLang, renderLanding } from "./landing.js"; import { COOKIE, readCookie, renderLogin, renderTeam, sameSecret, sessionValue } from "./team.js"; import { candidateList } from "./sourcing.js"; import { createLinkCode, getRecipient, lastDigestRun, pendingFinds, runDigestJob, sendTestMessage, sourceStatuses } from "./digest.js"; import type { ResumeSource } from "./resume-sources.js"; import type { TelegramApi } from "./telegram.js"; import { computePlan, dailyReport, validateConversions } from "./funnel.js"; import { createVacancy, getVacancy, listVacancies, validateVacancy, ValidationError } from "./vacancies.js"; export interface DigestOptions { sources: ResumeSource[]; configured: string[]; tg: () => TelegramApi | undefined } export interface AppOptions { db: DatabaseSync; apiToken: string; botUsername?: () => string | undefined; digest?: DigestOptions } function tokenOk(header: string | undefined, expected: string): boolean { return !!header?.startsWith("Bearer ") && sameSecret(header.slice(7), expected); } const HTML_HEADERS = { "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'", "x-content-type-options": "nosniff", "cache-control": "no-store", "referrer-policy": "no-referrer", }; export function buildApp({ db, apiToken, botUsername = () => undefined, digest = { sources: [], configured: [], tg: () => undefined } }: AppOptions) { const app = Fastify(); app.addContentTypeParser("application/x-www-form-urlencoded", { parseAs: "string", bodyLimit: 4096 }, (_req, body, done) => done(null, Object.fromEntries(new URLSearchParams(body as string)))); const teamOk = (cookie: string | undefined) => !!apiToken && sameSecret(readCookie(cookie, COOKIE) ?? "", sessionValue(apiToken)); const html = (reply: import("fastify").FastifyReply, body: string, code = 200) => reply.code(code).headers(HTML_HEADERS).type("text/html; charset=utf-8").send(body); app.get<{ Querystring: { lang?: string; office?: string } }>("/team", async (req, reply) => { const lang = pickLang(req.query.lang, req.headers["accept-language"]); if (!teamOk(req.headers.cookie)) return html(reply, renderLogin(lang, apiToken ? "form" : "nokey")); const office = req.query.office || undefined; return html(reply, renderTeam(lang, listApplications(db, { office }), office, botUsername(), digestView())); }); const digestView = (linkCode?: string) => ({ recipient: getRecipient(db), lastRun: lastDigestRun(db), pending: pendingFinds(db).length, statuses: sourceStatuses(db), configured: digest.configured, linkCode, }); let digestBusy = false; app.post<{ Querystring: { lang?: string }; Params: { action: string } }>("/team/digest/:action", async (req, reply) => { const lang = pickLang(req.query.lang, req.headers["accept-language"]); if (!teamOk(req.headers.cookie)) return html(reply, renderLogin(lang, apiToken ? "form" : "nokey"), 401); const action = req.params.action; if (action === "link") { if (!botUsername()) return reply.redirect(`/team?lang=${lang}`, 303); return html(reply, renderTeam(lang, listApplications(db), undefined, botUsername(), digestView(createLinkCode(db)))); } if (action !== "run" && action !== "test") return reply.code(404).send({ error: "not found" }); if (!digestBusy) { digestBusy = true; try { if (action === "run") await runDigestJob(db, digest.sources, digest.tg()); else await sendTestMessage(db, digest.tg()); } finally { digestBusy = false; } } return reply.redirect(`/team?lang=${lang}`, 303); }); app.post<{ Querystring: { lang?: string }; Body: { key?: string } | null }>("/team/login", async (req, reply) => { const lang = pickLang(req.query.lang, req.headers["accept-language"]); if (!apiToken) return html(reply, renderLogin(lang, "nokey"), 401); if (!sameSecret(String(req.body?.key ?? ""), apiToken)) return html(reply, renderLogin(lang, "bad"), 401); const secure = req.headers["x-forwarded-proto"] === "https" ? "; Secure" : ""; return reply .header("set-cookie", `${COOKIE}=${sessionValue(apiToken)}; Path=/; HttpOnly; SameSite=Strict; Max-Age=2592000${secure}`) .redirect(`/team?lang=${lang}`, 303); }); app.post("/team/logout", async (_req, reply) => reply.header("set-cookie", `${COOKIE}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`).redirect("/team", 303)); app.get<{ Querystring: { lang?: string } }>("/", async (req, reply) => { const lang = pickLang(req.query.lang, req.headers["accept-language"]); return reply .header("content-security-policy", "default-src 'none'; style-src 'unsafe-inline'") .header("x-content-type-options", "nosniff") .header("vary", "accept-language") .type("text/html; charset=utf-8") .send(renderLanding(lang)); }); app.get("/healthz", async () => ({ ok: true })); app.register(async (api) => { api.addHook("onRequest", async (req, reply) => { if (!tokenOk(req.headers.authorization, apiToken)) { return reply.code(401).send({ error: "unauthorized" }); } }); api.setErrorHandler((err, _req, reply) => { if (err instanceof ValidationError) return reply.code(400).send({ error: err.message }); reply.send(err); }); api.post("/vacancies", async (req, reply) => { const v = createVacancy(db, validateVacancy(req.body)); return reply.code(201).send(v); }); api.get("/vacancies", async () => listVacancies(db)); api.get<{ Querystring: { office?: string; source?: string } }>("/applications", async (req) => listApplications(db, { office: req.query.office || undefined, source: req.query.source || undefined })); api.get<{ Params: { id: string } }>("/vacancies/:id", async (req, reply) => { const v = getVacancy(db, Number(req.params.id)); return v ?? reply.code(404).send({ error: "not found" }); }); const vac = (id: string) => getVacancy(db, Number(id)); api.get<{ Params: { id: string } }>("/vacancies/:id/candidates", async (req, reply) => vac(req.params.id) ? candidateList(db, Number(req.params.id)) : reply.code(404).send({ error: "not found" })); api.get<{ Params: { id: string }; Querystring: { days?: string } }>("/vacancies/:id/plan", async (req, reply) => { const v = vac(req.params.id); if (!v) return reply.code(404).send({ error: "not found" }); return computePlan(v.targetCount, v.conversions, Number(req.query.days ?? 20)); }); api.get<{ Params: { id: string }; Querystring: { days?: string } }>("/vacancies/:id/report", async (req, reply) => { const v = vac(req.params.id); if (!v) return reply.code(404).send({ error: "not found" }); const plan = computePlan(v.targetCount, v.conversions, Number(req.query.days ?? 20)); return dailyReport(db, v.id, plan.perDay); }); api.put<{ Params: { id: string } }>("/vacancies/:id/conversions", async (req, reply) => { if (!vac(req.params.id)) return reply.code(404).send({ error: "not found" }); const c = validateConversions((req.body as { conversions?: unknown } | null)?.conversions); db.prepare("UPDATE vacancies SET conversions=? WHERE id=?").run(JSON.stringify(c), Number(req.params.id)); return vac(req.params.id); }); }, { prefix: "/api" }); return app; }