acc_invoices: журнал без зависания (Proxy вместо подмены query), общий журнал /api/log, MCP-инструменты acc_inv_* (все функции WebUI и анализ журнала)
All checks were successful
ci / test (push) Successful in 55s
ci / deploy (push) Successful in 3m23s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-04 20:29:00 +03:00
parent 76eafc995a
commit 798580a908
11 changed files with 301 additions and 15 deletions

View File

@@ -34,14 +34,18 @@ export function withAudit(pool: Pool): Pool {
}) as Pool["query"];
wrapped.connect = (async () => {
const c = await pool.connect();
const orig = c.query.bind(c) as (t: unknown, p?: unknown[]) => Promise<unknown>;
c.query = (async (text: unknown, params?: unknown[]) => {
const r = await orig(text, params);
const a = auditStore.getStore();
if (a?.actorId && typeof text === "string" && /^\s*begin\b/i.test(text)) await orig(SET_SQL, setArgs(a));
return r;
}) as typeof c.query;
return c;
// прокси, а не подмена метода: клиент возвращается в пул и должен остаться нетронутым
return new Proxy(c, {
get(target, prop) {
if (prop !== "query") { const v = Reflect.get(target, prop, target) as unknown; return typeof v === "function" ? (v as (...x: unknown[]) => unknown).bind(target) : v; }
return async (text: unknown, params?: unknown[]) => {
const r = await (target.query as (t: unknown, p?: unknown[]) => Promise<unknown>).call(target, text, params);
const st = auditStore.getStore();
if (st?.actorId && typeof text === "string" && /^\s*begin/i.test(text)) await target.query(SET_SQL, setArgs(st));
return r;
};
},
});
}) as Pool["connect"];
return wrapped;
}

View File

@@ -25,7 +25,7 @@ export interface Actor {
acting: ActingRole;
}
const safeEqual = (a: string, b: string): boolean => {
export const safeEqual = (a: string, b: string): boolean => {
const x = Buffer.from(a);
const y = Buffer.from(b);
return x.length === y.length && timingSafeEqual(x, y);
@@ -67,7 +67,7 @@ export function effectiveRoles(real: string[], requested?: string): { roles: Rol
return { roles: acting === "employee" ? [] : [acting], canSwitch, acting };
}
async function actorOf(pool: Pool, personId: string, requested?: string): Promise<Actor> {
export async function actorOf(pool: Pool, personId: string, requested?: string): Promise<Actor> {
const p = (await pool.query("select id, display_name from person where id = $1 and is_active", [personId])).rows[0];
if (!p) throw new AuthError("человек не найден или неактивен", 403);
const realRoles = await loadRoles(pool, personId);

View File

@@ -3,7 +3,7 @@ import { extname, join, normalize } from "node:path";
import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify";
import { withTx, type Logger, type Pool } from "khb_common";
import { z } from "zod";
import { AuthError, createAuth, type Actor, type JwtVerifier } from "./auth.js";
import { AuthError, actorOf, createAuth, safeEqual, type Actor, type JwtVerifier } from "./auth.js";
import { LOOKUP, getApproves, getContractPanel, getDetails, getInvoice, listInvoices, recomputeApproved, type ListItem } from "./repo.js";
import {
QUICK_FILTERS, STATUS_LABELS, canCancel, canMarkPaid, canReturnToDraft, canSendToBank, canView, dayInTz, editableFields, errorsOf, isStaff, matchesFilter, normResult, statusOf, submitProblems,
@@ -100,9 +100,19 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
// контекст автора для журнала: в каждом запросе свой, заполняется после входа
app.addHook("onRequest", (_req, _reply, done) => { auditStore.run({}, done); });
const need = async (req: FastifyRequest): Promise<Actor> => {
const a = await authenticate(req.headers.authorization, typeof req.headers["x-acting-role"] === "string" ? req.headers["x-acting-role"] : undefined);
const acting = typeof req.headers["x-acting-role"] === "string" ? req.headers["x-acting-role"] : undefined;
const internal = req.headers["x-internal-token"];
let a: Actor;
let via = "";
if (typeof internal === "string" && settings.auth.internalToken) {
// MCP (accounting_automation): уже аутентифицированный человек, его id передаётся заголовком
const pid = req.headers["x-person-id"];
if (!safeEqual(internal, settings.auth.internalToken) || typeof pid !== "string" || !uuid.safeParse(pid).success) throw new AuthError("внутренний токен не принят", 401);
a = await actorOf(rawPool, pid, acting);
via = ` via ${String(req.headers["x-via"] ?? "mcp").slice(0, 60)}`;
} else a = await authenticate(req.headers.authorization, acting);
const st = auditStore.getStore();
if (st) Object.assign(st, { actorId: a.personId, actorName: a.displayName, actingRole: a.acting, action: `${req.method} ${req.routeOptions?.url ?? req.url}` });
if (st) Object.assign(st, { actorId: a.personId, actorName: a.displayName, actingRole: a.acting, action: `${req.method} ${req.routeOptions?.url ?? req.url}${via}` });
return a;
};
const fail = (reply: FastifyReply, status: number, error: string) => reply.code(status).send({ error });
@@ -171,6 +181,39 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
return { items: rows };
});
/** Общий журнал и его разбор (бухгалтерия): фильтры по инвойсу, автору, действию, таблице, полю, периоду; group - счётчики вместо строк. */
app.get("/api/log", async (req, reply) => {
const a = await need(req);
if (!isStaff(a)) return fail(reply, 403, "журнал доступен бухгалтерии");
const q = z.object({
invoice_id: uuid.optional(), actor: z.string().max(100).optional(), action: z.string().max(100).optional(),
tbl: z.enum(["acc_invoices", "acc_invoices_details", "acc_invoices_approves"]).optional(), field: z.string().max(60).optional(),
since: z.string().max(40).optional(), until: z.string().max(40).optional(), system_only: z.enum(["true", "false"]).optional(),
group: z.enum(["actor", "action", "invoice", "day"]).optional(), limit: z.coerce.number().int().min(1).max(500).default(100),
}).parse(req.query);
const w: string[] = [];
const v: unknown[] = [];
const add = (sql: string, val: unknown) => { v.push(val); w.push(sql.replace("?", "$" + v.length)); };
if (q.invoice_id) add("l.invoice_id = ?", q.invoice_id);
if (q.actor) add("l.actor_name ilike ?", "%" + q.actor + "%");
if (q.action) add("l.action ilike ?", "%" + q.action + "%");
if (q.tbl) add("l.tbl = ?", q.tbl);
if (q.field) add("jsonb_exists(l.changes, ?)", q.field);
if (q.since) add("l.at >= ?::timestamptz", q.since);
if (q.until) add("l.at < ?::timestamptz", q.until);
if (q.system_only === "true") w.push("l.actor_id is null");
const where = w.length ? "where " + w.join(" and ") : "";
if (q.group) {
const key = { actor: "coalesce(l.actor_name, 'система (' || l.db_user || ')')", action: "coalesce(l.action, 'вне WebUI')", invoice: "l.invoice_id::text", day: "(l.at at time zone 'America/New_York')::date::text" }[q.group];
const rows = (await pool.query(`select ${key} as key, count(*)::int as events, min(l.at) as first_at, max(l.at) as last_at from acc_invoices_log l ${where} group by 1 order by events desc limit ${q.limit}`, v)).rows;
return { items: rows };
}
const rows = (await pool.query(
`select l.id, l.at, l.invoice_id, i.vendor_name, i.invoice_number, l.tbl, l.op, l.actor_name, l.acting_role, l.action, l.db_user, l.changes
from acc_invoices_log l left join acc_invoices i on i.id = l.invoice_id ${where} order by l.id desc limit ${q.limit}`, v)).rows;
return { items: rows };
});
/* ------------------------------------------------------------- создание */
app.post("/api/invoices", async (req, reply) => {
const a = await need(req);

View File

@@ -12,6 +12,8 @@ export const accInvoicesSchema = z.object({
/** Пускаются только адреса этого домена (вход Keycloak через Google). */
emailDomain: z.string().default("khbuild.pro"),
/** Статические токены (человек -> токен): для тестов и сотрудников без Keycloak. */
/** Внутренний токен: сервис accounting_automation (MCP) ходит с ним от имени человека (заголовки x-internal-token, x-person-id). */
internalToken: z.string().min(24).optional(),
staticTokens: z.array(z.object({ token: z.string().min(16), personId: z.string() })).default([]),
})
.default({}),