qbo_auth: журнал действий страницы ручных тестов (ручной тест: действие и результат)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -18,7 +18,11 @@ const page = (title: string, text: string) =>
|
||||
* Служебные ручки закрыты токеном (settings.json5 `qbo_auth.http.token`); открыты /healthz и /callback.
|
||||
* /callback защищён одноразовым state; наружу (nginx services) публикуется только он: /api/qbo/callback.
|
||||
*/
|
||||
export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?: WebhookOptions): FastifyInstance {
|
||||
export interface AuditLog {
|
||||
info(obj: Record<string, unknown>, msg: string): void;
|
||||
}
|
||||
|
||||
export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?: WebhookOptions, audit?: AuditLog): FastifyInstance {
|
||||
const app = Fastify();
|
||||
// тело вебхука нужно целиком (подпись считается по сырой строке)
|
||||
app.addContentTypeParser("application/json", { parseAs: "string" }, (req, body, done) => {
|
||||
@@ -62,18 +66,38 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?:
|
||||
*/
|
||||
const tests = (req: { params: unknown }): boolean => (req.params as { slug?: string }).slug === slug;
|
||||
app.get("/tests/:slug", async (req, reply) => (tests(req) ? reply.type("text/html").send(TESTS_PAGE) : reply.code(404).send({ error: "not_found" })));
|
||||
app.get("/tests/:slug/status", async (req, reply) => (tests(req) ? auth.status() : reply.code(404).send({ error: "not_found" })));
|
||||
app.post("/tests/:slug/connect", async (req, reply) => (tests(req) ? auth.startConnect() : reply.code(404).send({ error: "not_found" })));
|
||||
app.post("/tests/:slug/disconnect", async (req, reply) => (tests(req) ? auth.disconnect() : reply.code(404).send({ error: "not_found" })));
|
||||
app.get("/tests/:slug/status", async (req, reply) => {
|
||||
if (!tests(req)) return reply.code(404).send({ error: "not_found" });
|
||||
const st = await auth.status();
|
||||
audit?.info({ action: "status", connected: st.connected, status: "status" in st ? st.status : "not_connected" }, "ручной тест");
|
||||
return st;
|
||||
});
|
||||
app.post("/tests/:slug/connect", async (req, reply) => {
|
||||
if (!tests(req)) return reply.code(404).send({ error: "not_found" });
|
||||
const r = await auth.startConnect();
|
||||
audit?.info({ action: "connect", result: "ссылка авторизации выдана" }, "ручной тест");
|
||||
return r;
|
||||
});
|
||||
app.post("/tests/:slug/disconnect", async (req, reply) => {
|
||||
if (!tests(req)) return reply.code(404).send({ error: "not_found" });
|
||||
const r = await auth.disconnect();
|
||||
audit?.info({ action: "disconnect", ...r }, "ручной тест");
|
||||
return r;
|
||||
});
|
||||
app.post("/tests/:slug/sync", async (req, reply) => {
|
||||
if (!tests(req)) return reply.code(404).send({ error: "not_found" });
|
||||
if (!sync) return reply.code(501).send({ error: "sync_not_configured" });
|
||||
if (sync.isRunning) return reply.code(409).send({ error: "already_running" });
|
||||
try {
|
||||
const r = await sync.run({ full: false });
|
||||
audit?.info({ action: "sync", result: r.status, http: r.status === "ok" ? 200 : 502 }, "ручной тест");
|
||||
return reply.code(r.status === "ok" ? 200 : 502).send(r);
|
||||
} catch (e) {
|
||||
if (e instanceof ReauthNeeded) return reply.code(409).send({ error: "reauth_needed", message: e.message });
|
||||
if (e instanceof ReauthNeeded) {
|
||||
audit?.info({ action: "sync", result: "reauth_needed", http: 409 }, "ручной тест");
|
||||
return reply.code(409).send({ error: "reauth_needed", message: e.message });
|
||||
}
|
||||
audit?.info({ action: "sync", result: "sync_failed", http: 502 }, "ручной тест");
|
||||
req.log.error({ err: String(e) }, "sync (tests)");
|
||||
return reply.code(502).send({ error: "sync_failed" });
|
||||
}
|
||||
@@ -83,7 +107,7 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?:
|
||||
if (!tests(req)) return reply.code(404).send({ error: "not_found" });
|
||||
const text = String((req.body as { text?: string } | undefined)?.text ?? "").slice(0, 500).trim();
|
||||
if (!text) return reply.code(400).send({ error: "empty" });
|
||||
req.log.info({ note: text }, "заметка ручного теста");
|
||||
audit?.info({ action: "note", note: text }, "ручной тест");
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
@@ -93,8 +117,10 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?:
|
||||
const q = req.query as { code?: string; state?: string; realmId?: string; error?: string };
|
||||
try {
|
||||
await auth.handleCallback(q);
|
||||
audit?.info({ action: "callback", result: "подключено" }, "ручной тест");
|
||||
return reply.redirect("/api/qbo/connected?ok=1", 302);
|
||||
} catch (e) {
|
||||
audit?.info({ action: "callback", result: "отклонено", reason: String(e).slice(0, 160) }, "ручной тест");
|
||||
req.log.warn({ err: String(e) }, "callback отклонён");
|
||||
return reply.redirect("/api/qbo/connected?ok=0", 302);
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ const app = buildApi(auth, s.http.token, sync, {
|
||||
log.info({ count: events.length, entities: [...new Set(events.map((e) => `${e.name}:${e.operation}`))].slice(0, 20) }, "вебхук QuickBooks");
|
||||
trigger.poke();
|
||||
},
|
||||
});
|
||||
}, log);
|
||||
{
|
||||
const n = await store.encryptExistingRealms().catch((e) => (log.error({ err: String(e) }, "шифрование realm_id"), 0));
|
||||
if (n) log.info({ rows: n }, "realm_id зашифрован в существующих записях");
|
||||
|
||||
@@ -32,7 +32,8 @@ describe("вебхук Intuit", () => {
|
||||
});
|
||||
|
||||
it("страница тестов: только по секретному адресу, заголовки без кэша, заметка принимается", async () => {
|
||||
const app = buildApi({} as QboAuth, "svc");
|
||||
const audit = { info: vi.fn() };
|
||||
const app = buildApi({} as QboAuth, "svc", undefined, undefined, audit);
|
||||
const slug = testsSlug("svc");
|
||||
expect(slug).toMatch(/^[0-9a-f]{32}$/);
|
||||
expect((await app.inject({ url: "/tests/wrong" })).statusCode).toBe(404);
|
||||
@@ -46,6 +47,7 @@ describe("вебхук Intuit", () => {
|
||||
const h = { "content-type": "application/json" };
|
||||
expect((await app.inject({ method: "POST", url: `/tests/${slug}/note`, headers: h, payload: { text: "Bill 12.50" } })).statusCode).toBe(200);
|
||||
expect((await app.inject({ method: "POST", url: `/tests/${slug}/note`, headers: h, payload: { text: " " } })).statusCode).toBe(400);
|
||||
expect(audit.info).toHaveBeenCalledWith({ action: "note", note: "Bill 12.50" }, "ручной тест");
|
||||
});
|
||||
|
||||
it("вебхук с типом application/cloudevents+json принимается (раньше было 415)", async () => {
|
||||
|
||||
Reference in New Issue
Block a user