Сервис qbo_auth: OAuth-токены QuickBooks Online (callback services/api/qbo/callback), исследование и предложение quickbooks_bookkeeper (п.84)
All checks were successful
ci / test (push) Successful in 36s
ci / deploy (push) Successful in 5m18s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 22:19:06 +03:00
parent 6c4767c806
commit d8926bc6dc
19 changed files with 880 additions and 1 deletions

View File

@@ -0,0 +1,49 @@
import Fastify, { type FastifyInstance } from "fastify";
import { QboAuth, ReauthNeeded } from "./service.js";
const page = (title: string, text: string) =>
`<!doctype html><html lang="ru"><meta charset="utf-8"><meta name="robots" content="noindex"><title>${title}</title><body style="font-family:system-ui;max-width:32rem;margin:4rem auto;padding:0 1rem"><h1>${title}</h1><p>${text}</p></body></html>`;
/**
* Служебные ручки закрыты токеном (settings.json5 `qbo_auth.http.token`); открыты /healthz и /callback.
* /callback защищён одноразовым state; наружу (nginx services) публикуется только он: /api/qbo/callback.
*/
export function buildApi(auth: QboAuth, token: string): FastifyInstance {
const app = Fastify();
app.addHook("onRequest", async (req, reply) => {
const path = req.url.split("?")[0];
if (path === "/healthz" || path === "/callback") return;
if (req.headers.authorization !== `Bearer ${token}`) return reply.code(401).send({ error: "unauthorized" });
});
app.get("/healthz", async () => ({ ok: true, time: new Date().toISOString() }));
app.get("/callback", async (req, reply) => {
const q = req.query as { code?: string; state?: string; realmId?: string; error?: string };
try {
await auth.handleCallback(q);
return reply.type("text/html").send(page("QuickBooks подключён", "Авторизация сохранена. Эту вкладку можно закрыть."));
} catch (e) {
req.log.warn({ err: String(e) }, "callback отклонён");
return reply.code(400).type("text/html").send(page("Не удалось подключить QuickBooks", "Начните подключение заново. Причина записана в журнал сервиса."));
}
});
/** Ссылка авторизации (для администратора компании QuickBooks). */
app.post("/connect", async () => auth.startConnect());
app.get("/status", async () => auth.status());
/** Действующий access token для других сервисов (только docker-сеть и токен сервиса). `?force=true` - обновить принудительно. */
app.post("/token", async (req, reply) => {
try {
const force = (req.query as { force?: string }).force === "true";
const t = await auth.getAccessToken({ force });
return { accessToken: t.accessToken, realmId: t.realmId, apiBase: t.apiBase, expiresAt: t.expiresAt.toISOString() };
} catch (e) {
if (e instanceof ReauthNeeded) return reply.code(409).send({ error: "reauth_needed", message: e.message });
req.log.error({ err: String(e) }, "получение токена");
return reply.code(502).send({ error: "token_error" });
}
});
app.post("/keepalive", async () => ({ result: await auth.keepAlive() }));
return app;
}