import Fastify from "fastify"; import { RESOURCES, validate } from "./resources.js"; const SECRET_KEY = /token|secret|password|api[_-]?key/i; export function redact(value) { if (Array.isArray(value)) return value.map(redact); if (value && typeof value === "object") { return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, SECRET_KEY.test(k) ? "[redacted]" : redact(v)])); } return value; } async function audit(q, action, entity, before, after, actor = "owner") { await q.query("insert into audit_logs (actor, action, entity, before, after) values ($1,$2,$3,$4,$5)", [ actor, action, entity, before == null ? null : JSON.stringify(redact(before)), after == null ? null : JSON.stringify(redact(after)), ]); } export function buildApp({ db, apiToken }) { const app = Fastify(); app.get("/healthz", async () => ({ ok: true })); app.addHook("onRequest", async (req, reply) => { if (req.url === "/healthz") return; if (req.headers.authorization !== `Bearer ${apiToken}`) return reply.code(401).send({ error: "unauthorized" }); }); for (const res of RESOURCES) registerResource(app, db, res); app.get("/public-profile", async () => { const profile = await db.query("select * from person_profile where status = 'public_confirmed' order by id limit 1"); const roles = await db.query("select * from career_history where status = 'public_confirmed' order by start_year desc nulls last, id"); return { profile: profile[0] ?? null, current_roles: roles.filter((r) => r.is_current), past_roles: roles.filter((r) => !r.is_current) }; }); app.get("/audit", async () => db.query("select * from audit_logs order by id desc limit 200")); app.get("/approvals", async () => db.query("select * from approvals order by id desc")); app.post("/approvals/:id/decision", async (req, reply) => { const decision = req.body?.decision; if (decision !== "approved" && decision !== "rejected") return reply.code(422).send({ error: "decision must be approved or rejected" }); return db.tx(async (q) => { const [before] = await q.query("select * from approvals where id = $1 for update", [Number(req.params.id)]); if (!before) return reply.code(404).send({ error: "not found" }); if (before.status !== "pending") return reply.code(409).send({ error: "already decided" }); const [after] = await q.query("update approvals set status = $2, decided_at = now() where id = $1 returning *", [Number(req.params.id), decision]); await audit(q, "decide_approval", `approvals/${req.params.id}`, before, after); return after; }); }); app.get("/policy", async () => db.query("select * from action_policy order by action")); app.post("/actions/:action", async (req, reply) => { const action = req.params.action; const approvalId = req.body?.approval_id; const payload = req.body?.payload ?? null; return db.tx(async (q) => { const [policy] = await q.query("select * from action_policy where action = $1", [action]); if (!policy) return reply.code(404).send({ error: "unknown action" }); const needsApproval = policy.mode === "C" || (policy.mode === "B" && !policy.granted); if (needsApproval) { const [ap] = approvalId ? await q.query("select * from approvals where id = $1 and action = $2 and status = 'approved' for update", [approvalId, action]) : []; if (!ap) { const [created] = await q.query("insert into approvals (action, payload) values ($1, $2) returning *", [action, payload == null ? null : JSON.stringify(redact(payload))]); await audit(q, "request_approval", `approvals/${created.id}`, null, created); // Транзакция коммитится: согласование pending должно сохраниться. return reply.code(403).send({ error: "approval required", mode: policy.mode, approval_id: created.id }); } await q.query("update approvals set status = 'used' where id = $1", [ap.id]); } await audit(q, `action:${action}`, `actions/${action}`, null, { mode: policy.mode, approval_id: approvalId ?? null, payload }); return { ok: true, action, mode: policy.mode }; }); }); return app; } function registerResource(app, db, res) { const base = `/${res.route}`; app.get(base, async (req) => { if (req.query.audience === "public") { const where = ["status = 'public_confirmed'", res.publicWhere].filter(Boolean).join(" and "); return db.query(`select * from ${res.table} where ${where} order by id`); } return db.query(`select * from ${res.table} order by id`); }); app.get(`${base}/:id`, async (req, reply) => { const [row] = await db.query(`select * from ${res.table} where id = $1`, [Number(req.params.id)]); return row ?? reply.code(404).send({ error: "not found" }); }); app.post(base, async (req, reply) => { const v = validate(res, req.body, false); if ("error" in v) return reply.code(422).send({ error: v.error }); const cols = Object.keys(v.values); try { const row = await db.tx(async (q) => { const [created] = await q.query(cols.length ? `insert into ${res.table} (${cols.join(",")}) values (${cols.map((_, i) => `$${i + 1}`).join(",")}) returning *` : `insert into ${res.table} default values returning *`, Object.values(v.values)); await audit(q, "create", `${res.table}/${created.id}`, null, created); return created; }); return reply.code(201).send(row); } catch (e) { if (e.code === "23503") return reply.code(422).send({ error: "referenced record does not exist" }); throw e; } }); app.patch(`${base}/:id`, async (req, reply) => { const v = validate(res, req.body, true); if ("error" in v) return reply.code(422).send({ error: v.error }); const cols = Object.keys(v.values); if (!cols.length) return reply.code(422).send({ error: "nothing to update" }); const id = Number(req.params.id); try { return await db.tx(async (q) => { const [before] = await q.query(`select * from ${res.table} where id = $1 for update`, [id]); if (!before) return reply.code(404).send({ error: "not found" }); const [after] = await q.query(`update ${res.table} set ${cols.map((c, i) => `${c} = $${i + 1}`).join(",")}, updated_at = now() where id = $${cols.length + 1} returning *`, [...Object.values(v.values), id]); await audit(q, "update", `${res.table}/${id}`, before, after); return after; }); } catch (e) { if (e.code === "23503") return reply.code(422).send({ error: "referenced record does not exist" }); throw e; } }); }