qbo_auth: realmId шифруется, /callback отвечает 302, no-cache; требования Intuit: раздел E по оригиналу, ручные тесты через /tests
All checks were successful
ci / test (push) Successful in 38s
ci / deploy (push) Successful in 2m38s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 09:21:39 +03:00
parent b0a68930b1
commit e90b9f352d
7 changed files with 65 additions and 34 deletions

View File

@@ -36,8 +36,9 @@ const notify = async (text: string): Promise<void> => {
/** Компания QuickBooks берётся из подключения qbo_auth. */
async function realmId(): Promise<string> {
const { rows } = await pool.query("select realm_id from qbo_connection order by refreshed_at desc limit 1");
if (!rows[0]) throw new Error("QuickBooks не подключён (нет строки в qbo_connection)");
// realm_id в qbo_connection зашифрован (требование Intuit); компания берётся из последней успешной загрузки зеркала
const { rows } = await pool.query("select realm_id from qbo_sync_run where status = 'ok' and realm_id is not null order by started_at desc limit 1");
if (!rows[0]) throw new Error("QuickBooks не подключён или зеркало ещё не загружено (нет успешной загрузки в qbo_sync_run)");
return rows[0].realm_id as string;
}

View File

@@ -30,14 +30,14 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?:
});
// требования Intuit: ответы с токенами и страницы действий не кэшируются, адрес с code/state не уходит в Referer
app.addHook("onSend", async (_req, reply) => {
reply.header("Cache-Control", "no-store");
reply.header("Cache-Control", "no-cache, no-store");
reply.header("Pragma", "no-cache");
reply.header("Referrer-Policy", "no-referrer");
reply.header("X-Content-Type-Options", "nosniff");
});
app.addHook("onRequest", async (req, reply) => {
const path = req.url.split("?")[0];
if (path === "/healthz" || path === "/callback" || path === "/webhook" || path === "/tests") return;
if (path === "/healthz" || path === "/callback" || path === "/webhook" || path === "/tests" || path === "/connected") return;
if (req.headers.authorization !== `Bearer ${token}`) return reply.code(401).send({ error: "unauthorized" });
});
@@ -82,12 +82,19 @@ 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);
return reply.type("text/html").send(page("QuickBooks подключён", "Авторизация сохранена. Эту вкладку можно закрыть."));
return reply.redirect("/api/qbo/connected?ok=1", 302);
} catch (e) {
req.log.warn({ err: String(e) }, "callback отклонён");
return reply.code(400).type("text/html").send(page("Не удалось подключить QuickBooks", "Начните подключение заново. Причина записана в журнал сервиса."));
return reply.redirect("/api/qbo/connected?ok=0", 302);
}
});
/** Итоговая страница после возврата с Intuit. /callback отвечает 302 сюда (требование Intuit: адрес с code не отдаёт HTML-тело). */
app.get("/connected", async (req, reply) => {
const ok = (req.query as { ok?: string }).ok === "1";
return ok
? reply.type("text/html").send(page("QuickBooks подключён", "Авторизация сохранена. Эту вкладку можно закрыть."))
: reply.code(400).type("text/html").send(page("Не удалось подключить QuickBooks", "Начните подключение заново. Причина записана в журнал сервиса."));
});
/** Ссылка авторизации (для администратора компании QuickBooks). */
app.post("/connect", async () => auth.startConnect());

View File

@@ -11,8 +11,9 @@ import { QboSync } from "./sync.js";
const { common, service: s } = loadServiceSettings("qbo_auth", qboAuthSchema);
const log = createLogger("qbo_auth", common.logLevel);
const pool = createPool(common.database.url, 3);
const store = new PgStore(pool, parseKey(s.encryptionKey));
const auth = new QboAuth({
store: new PgStore(pool, parseKey(s.encryptionKey)),
store,
fetchFn: (url, init) => fetch(url, init),
env: s.environment,
clientId: s.clientId,
@@ -48,6 +49,10 @@ const app = buildApi(auth, s.http.token, sync, {
trigger.poke();
},
});
{
const n = await store.encryptExistingRealms().catch((e) => (log.error({ err: String(e) }, "шифрование realm_id"), 0));
if (n) log.info({ rows: n }, "realm_id зашифрован в существующих записях");
}
await app.listen({ host: s.http.host, port: s.http.port });
log.info({ port: s.http.port, environment: s.environment }, "qbo_auth запущен");

View File

@@ -133,8 +133,10 @@ describe("HTTP", () => {
const url = (await app.inject({ method: "POST", url: "/connect", headers: { authorization: "Bearer tok" } })).json().url as string;
const state = new URL(url).searchParams.get("state")!;
const cb = await app.inject({ url: `/callback?code=c&state=${state}&realmId=R1` });
expect(cb.statusCode).toBe(200);
expect(cb.body).toContain("подключён");
expect(cb.statusCode).toBe(302);
expect(cb.headers.location).toBe("/api/qbo/connected?ok=1");
expect(cb.body).not.toContain("html");
expect((await app.inject({ url: "/connected?ok=1" })).body).toContain("подключён");
const st = await app.inject({ url: "/status", headers: { authorization: "Bearer tok" } });
expect(st.json()).toMatchObject({ connected: true, realmId: "R1" });
expect(st.body).not.toContain("at1");
@@ -144,8 +146,9 @@ describe("HTTP", () => {
it("/callback с плохим state: 400 и страница без подробностей", async () => {
const app = buildApi(mk([]).auth, "tok");
const r = await app.inject({ url: "/callback?code=c&state=bad&realmId=R" });
expect(r.statusCode).toBe(400);
expect(r.body).not.toContain("state");
expect(r.statusCode).toBe(302);
expect(r.headers.location).toBe("/api/qbo/connected?ok=0");
expect((await app.inject({ url: "/connected?ok=0" })).statusCode).toBe(400);
});
it("/token: без подключения - 409 reauth_needed; с подключением - токен", async () => {

View File

@@ -52,10 +52,24 @@ export class PgStore implements Store {
return row && row.fresh ? row.environment : null;
}
/** realmId хранится зашифрованным (требование Intuit); открытое значение из старых записей читается как есть. */
private readRealm(v: string): string {
return v.startsWith("v1.") ? decrypt(v, this.key) : v;
}
/** Однократно шифрует realm_id в уже существующих записях (вызывается при старте). */
async encryptExistingRealms(): Promise<number> {
const r = await this.pool.query("select environment, realm_id from qbo_connection where realm_id not like 'v1.%'");
for (const row of r.rows as Array<{ environment: string; realm_id: string }>) {
await this.pool.query("update qbo_connection set realm_id = $2 where environment = $1", [row.environment, encrypt(row.realm_id, this.key)]);
}
return r.rows.length;
}
private toConn(row: Record<string, unknown>): Connection {
return {
environment: row.environment as Env,
realmId: row.realm_id as string,
realmId: this.readRealm(row.realm_id as string),
accessToken: decrypt(row.access_token_enc as string, this.key),
refreshToken: decrypt(row.refresh_token_enc as string, this.key),
accessExpiresAt: row.access_expires_at as Date,
@@ -86,7 +100,7 @@ export class PgStore implements Store {
refresh_token_enc = excluded.refresh_token_enc, access_expires_at = excluded.access_expires_at,
refresh_expires_at = excluded.refresh_expires_at, authorized_at = excluded.authorized_at,
refreshed_at = excluded.refreshed_at, status = excluded.status`,
[c.environment, c.realmId, encrypt(c.accessToken, this.key), encrypt(c.refreshToken, this.key), c.accessExpiresAt, c.refreshExpiresAt, c.authorizedAt, c.refreshedAt, c.status],
[c.environment, encrypt(c.realmId, this.key), encrypt(c.accessToken, this.key), encrypt(c.refreshToken, this.key), c.accessExpiresAt, c.refreshExpiresAt, c.authorizedAt, c.refreshedAt, c.status],
);
},
remove: async () => {

View File

@@ -35,7 +35,7 @@ describe("вебхук Intuit", () => {
const app = buildApi({} as QboAuth, "svc");
const page = await app.inject({ url: "/tests" });
expect(page.statusCode).toBe(200);
expect(page.headers["cache-control"]).toBe("no-store");
expect(page.headers["cache-control"]).toBe("no-cache, no-store");
expect(page.headers["referrer-policy"]).toBe("no-referrer");
expect((await app.inject({ url: "/tests/status" })).statusCode).toBe(401);
expect((await app.inject({ method: "POST", url: "/tests/disconnect" })).statusCode).toBe(401);