Сервис qbo_auth: OAuth-токены QuickBooks Online (callback services/api/qbo/callback), исследование и предложение quickbooks_bookkeeper (п.84)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
20
packages/khb_common/migrations/031_qbo_connection.sql
Normal file
20
packages/khb_common/migrations/031_qbo_connection.sql
Normal file
@@ -0,0 +1,20 @@
|
||||
-- Подключение к QuickBooks Online (сервис qbo_auth): токены приложения и одноразовые state авторизации.
|
||||
-- Токены хранятся зашифрованными (AES-256-GCM, ключ qbo_auth.encryptionKey в settings.json5), не в открытом виде.
|
||||
create table if not exists qbo_connection (
|
||||
environment text primary key check (environment in ('sandbox', 'production')),
|
||||
realm_id text not null, -- идентификатор компании QuickBooks
|
||||
access_token_enc text not null,
|
||||
refresh_token_enc text not null,
|
||||
access_expires_at timestamptz not null, -- access token живёт 60 минут
|
||||
refresh_expires_at timestamptz not null, -- refresh token скользящий, до 100 дней
|
||||
authorized_at timestamptz not null, -- когда администратор дал согласие
|
||||
refreshed_at timestamptz not null,
|
||||
status text not null default 'ok' check (status in ('ok', 'reauth_needed'))
|
||||
);
|
||||
create table if not exists qbo_oauth_state (
|
||||
state text primary key,
|
||||
environment text not null check (environment in ('sandbox', 'production')),
|
||||
created_at timestamptz not null default now()
|
||||
);
|
||||
alter table qbo_connection enable row level security;
|
||||
alter table qbo_oauth_state enable row level security;
|
||||
18
packages/qbo_auth/package.json
Normal file
18
packages/qbo_auth/package.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "qbo_auth",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"start": "node dist/main.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"fastify": "^5.2.0",
|
||||
"khb_common": "workspace:*",
|
||||
"zod": "3.25.76"
|
||||
}
|
||||
}
|
||||
24
packages/qbo_auth/src/crypto.ts
Normal file
24
packages/qbo_auth/src/crypto.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
|
||||
|
||||
/** Ключ: 64 hex-символа или base64 от 32 байт. */
|
||||
export function parseKey(raw: string): Buffer {
|
||||
const k = /^[0-9a-fA-F]{64}$/.test(raw) ? Buffer.from(raw, "hex") : Buffer.from(raw, "base64");
|
||||
if (k.length !== 32) throw new Error("encryptionKey: нужно 32 байта (hex 64 символа или base64)");
|
||||
return k;
|
||||
}
|
||||
|
||||
/** AES-256-GCM; формат: v1.<iv>.<tag>.<данные> (base64url). */
|
||||
export function encrypt(plain: string, key: Buffer): string {
|
||||
const iv = randomBytes(12);
|
||||
const c = createCipheriv("aes-256-gcm", key, iv);
|
||||
const data = Buffer.concat([c.update(plain, "utf8"), c.final()]);
|
||||
return ["v1", iv.toString("base64url"), c.getAuthTag().toString("base64url"), data.toString("base64url")].join(".");
|
||||
}
|
||||
|
||||
export function decrypt(token: string, key: Buffer): string {
|
||||
const [v, iv, tag, data] = token.split(".");
|
||||
if (v !== "v1" || !iv || !tag || !data) throw new Error("неизвестный формат зашифрованного значения");
|
||||
const d = createDecipheriv("aes-256-gcm", key, Buffer.from(iv, "base64url"));
|
||||
d.setAuthTag(Buffer.from(tag, "base64url"));
|
||||
return Buffer.concat([d.update(Buffer.from(data, "base64url")), d.final()]).toString("utf8");
|
||||
}
|
||||
49
packages/qbo_auth/src/http-api.ts
Normal file
49
packages/qbo_auth/src/http-api.ts
Normal 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;
|
||||
}
|
||||
34
packages/qbo_auth/src/main.ts
Normal file
34
packages/qbo_auth/src/main.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { createLogger, createPool, itNotify, loadServiceSettings } from "khb_common";
|
||||
import { parseKey } from "./crypto.js";
|
||||
import { buildApi } from "./http-api.js";
|
||||
import { QboAuth } from "./service.js";
|
||||
import { qboAuthSchema } from "./settings.js";
|
||||
import { PgStore } from "./store.js";
|
||||
|
||||
const { common, service: s } = loadServiceSettings("qbo_auth", qboAuthSchema);
|
||||
const log = createLogger("qbo_auth", common.logLevel);
|
||||
const pool = createPool(common.database.url, 3);
|
||||
const auth = new QboAuth({
|
||||
store: new PgStore(pool, parseKey(s.encryptionKey)),
|
||||
fetchFn: (url, init) => fetch(url, init),
|
||||
env: s.environment,
|
||||
clientId: s.clientId,
|
||||
clientSecret: s.clientSecret,
|
||||
redirectUri: s.redirectUri,
|
||||
scope: s.scope,
|
||||
keepAliveHours: s.keepAliveHours,
|
||||
notify: async (text) => {
|
||||
await itNotify(common, text).catch(() => false);
|
||||
},
|
||||
});
|
||||
|
||||
const app = buildApi(auth, s.http.token);
|
||||
await app.listen({ host: s.http.host, port: s.http.port });
|
||||
log.info({ port: s.http.port, environment: s.environment }, "qbo_auth запущен");
|
||||
|
||||
// поддержание токенов: раз в час проверяем, не пора ли обновить (скользящий refresh token)
|
||||
const timer = setInterval(() => void auth.keepAlive().catch((e) => log.error({ err: String(e) }, "keepalive")), 60 * 60_000);
|
||||
process.on("SIGTERM", () => {
|
||||
clearInterval(timer);
|
||||
void app.close();
|
||||
});
|
||||
53
packages/qbo_auth/src/oauth.ts
Normal file
53
packages/qbo_auth/src/oauth.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
export const AUTHORIZE_URL = "https://appcenter.intuit.com/connect/oauth2";
|
||||
export const TOKEN_URL = "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer";
|
||||
export const apiBase = (env: "sandbox" | "production"): string =>
|
||||
env === "sandbox" ? "https://sandbox-quickbooks.api.intuit.com" : "https://quickbooks.api.intuit.com";
|
||||
|
||||
export type FetchFn = (url: string, init: { method: string; headers: Record<string, string>; body: string }) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>;
|
||||
|
||||
export interface TokenSet {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
/** Через сколько секунд истекает access token (обычно 3600). */
|
||||
expiresIn: number;
|
||||
/** Через сколько секунд истекает refresh token (около 100 дней). */
|
||||
refreshExpiresIn: number;
|
||||
}
|
||||
|
||||
/** Ошибка обмена токена; `invalidGrant` - refresh token отозван/просрочен: нужна новая авторизация человеком. */
|
||||
export class TokenError extends Error {
|
||||
constructor(message: string, readonly status: number, readonly invalidGrant: boolean) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export function authorizeUrl(p: { clientId: string; redirectUri: string; scope: string; state: string }): string {
|
||||
const q = new URLSearchParams({ client_id: p.clientId, response_type: "code", scope: p.scope, redirect_uri: p.redirectUri, state: p.state });
|
||||
return `${AUTHORIZE_URL}?${q.toString()}`;
|
||||
}
|
||||
|
||||
async function tokenCall(fetchFn: FetchFn, creds: { clientId: string; clientSecret: string }, params: Record<string, string>): Promise<TokenSet> {
|
||||
const r = await fetchFn(TOKEN_URL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Basic " + Buffer.from(`${creds.clientId}:${creds.clientSecret}`).toString("base64"),
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
Accept: "application/json",
|
||||
},
|
||||
body: new URLSearchParams(params).toString(),
|
||||
});
|
||||
const j = (await r.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
if (!r.ok) {
|
||||
const err = typeof j.error === "string" ? j.error : "unknown";
|
||||
// в сообщение попадает только код ошибки Intuit, без тел с токенами
|
||||
throw new TokenError(`Intuit token endpoint: ${r.status} ${err}`, r.status, err === "invalid_grant");
|
||||
}
|
||||
const at = j.access_token, rt = j.refresh_token;
|
||||
if (typeof at !== "string" || typeof rt !== "string") throw new TokenError("в ответе Intuit нет токенов", r.status, false);
|
||||
return { accessToken: at, refreshToken: rt, expiresIn: Number(j.expires_in ?? 3600), refreshExpiresIn: Number(j.x_refresh_token_expires_in ?? 8640000) };
|
||||
}
|
||||
|
||||
export const exchangeCode = (f: FetchFn, c: { clientId: string; clientSecret: string }, code: string, redirectUri: string) =>
|
||||
tokenCall(f, c, { grant_type: "authorization_code", code, redirect_uri: redirectUri });
|
||||
export const refreshTokens = (f: FetchFn, c: { clientId: string; clientSecret: string }, refreshToken: string) =>
|
||||
tokenCall(f, c, { grant_type: "refresh_token", refresh_token: refreshToken });
|
||||
174
packages/qbo_auth/src/service.test.ts
Normal file
174
packages/qbo_auth/src/service.test.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildApi } from "./http-api.js";
|
||||
import { decrypt, encrypt, parseKey } from "./crypto.js";
|
||||
import type { FetchFn } from "./oauth.js";
|
||||
import { QboAuth, ReauthNeeded } from "./service.js";
|
||||
import { MemoryStore } from "./store.js";
|
||||
|
||||
const T0 = new Date("2026-11-16T12:00:00.000Z");
|
||||
|
||||
/** Заглушка token endpoint: отдаёт заданные ответы по очереди и запоминает тела запросов. */
|
||||
function fakeFetch(responses: Array<{ status?: number; body: Record<string, unknown> }>) {
|
||||
const calls: Array<{ url: string; body: URLSearchParams; auth: string }> = [];
|
||||
const fn: FetchFn = async (url, init) => {
|
||||
calls.push({ url, body: new URLSearchParams(init.body), auth: init.headers.Authorization ?? "" });
|
||||
const r = responses.shift() ?? { status: 500, body: {} };
|
||||
const status = r.status ?? 200;
|
||||
return { ok: status < 400, status, json: async () => r.body };
|
||||
};
|
||||
return { fn, calls };
|
||||
}
|
||||
|
||||
const tokens = (n: number) => ({ access_token: `at${n}`, refresh_token: `rt${n}`, expires_in: 3600, x_refresh_token_expires_in: 8726400 });
|
||||
|
||||
function mk(responses: Array<{ status?: number; body: Record<string, unknown> }>, clock = { t: T0 }) {
|
||||
const store = new MemoryStore();
|
||||
const f = fakeFetch(responses);
|
||||
const notes: string[] = [];
|
||||
const auth = new QboAuth({
|
||||
store, fetchFn: f.fn, env: "sandbox", clientId: "cid", clientSecret: "csec", redirectUri: "https://x/api/qbo/callback",
|
||||
scope: "com.intuit.quickbooks.accounting", keepAliveHours: 20, now: () => clock.t, notify: async (t) => { notes.push(t); },
|
||||
});
|
||||
return { auth, store, f, notes, clock };
|
||||
}
|
||||
|
||||
describe("подключение", () => {
|
||||
it("startConnect: ссылка Intuit с redirect_uri и одноразовым state", async () => {
|
||||
const { auth, store } = mk([]);
|
||||
const { url } = await auth.startConnect();
|
||||
const u = new URL(url);
|
||||
expect(u.origin + u.pathname).toBe("https://appcenter.intuit.com/connect/oauth2");
|
||||
expect(u.searchParams.get("redirect_uri")).toBe("https://x/api/qbo/callback");
|
||||
expect(u.searchParams.get("client_id")).toBe("cid");
|
||||
expect(store.states.has(u.searchParams.get("state")!)).toBe(true);
|
||||
});
|
||||
|
||||
it("callback: обмен кода, сохранение токенов; повтор того же state отклоняется", async () => {
|
||||
const { auth, store, f } = mk([{ body: tokens(1) }]);
|
||||
const state = new URL((await auth.startConnect()).url).searchParams.get("state")!;
|
||||
expect(await auth.handleCallback({ code: "c1", state, realmId: "R1" })).toEqual({ realmId: "R1" });
|
||||
expect(f.calls[0]!.body.get("grant_type")).toBe("authorization_code");
|
||||
expect(f.calls[0]!.body.get("code")).toBe("c1");
|
||||
expect(f.calls[0]!.auth).toBe("Basic " + Buffer.from("cid:csec").toString("base64"));
|
||||
expect(store.conns.get("sandbox")).toMatchObject({ realmId: "R1", accessToken: "at1", refreshToken: "rt1", status: "ok" });
|
||||
await expect(auth.handleCallback({ code: "c1", state, realmId: "R1" })).rejects.toThrow(/state/);
|
||||
});
|
||||
|
||||
it("callback: чужой state и просроченный state отклоняются без обращения к Intuit", async () => {
|
||||
const { auth, store, f } = mk([]);
|
||||
store.now = () => T0.getTime();
|
||||
await expect(auth.handleCallback({ code: "c", state: "bad", realmId: "R" })).rejects.toThrow(/state/);
|
||||
const state = new URL((await auth.startConnect()).url).searchParams.get("state")!;
|
||||
store.now = () => T0.getTime() + 11 * 60_000;
|
||||
await expect(auth.handleCallback({ code: "c", state, realmId: "R" })).rejects.toThrow(/state/);
|
||||
expect(f.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("callback: ошибка Intuit (access_denied) не сохраняет токены", async () => {
|
||||
const { auth, store } = mk([]);
|
||||
const state = new URL((await auth.startConnect()).url).searchParams.get("state")!;
|
||||
await expect(auth.handleCallback({ state, error: "access_denied" })).rejects.toThrow(/access_denied/);
|
||||
expect(store.conns.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("токены", () => {
|
||||
async function connected(extra: Array<{ status?: number; body: Record<string, unknown> }> = []) {
|
||||
const ctx = mk([{ body: tokens(1) }, ...extra]);
|
||||
const state = new URL((await ctx.auth.startConnect()).url).searchParams.get("state")!;
|
||||
await ctx.auth.handleCallback({ code: "c", state, realmId: "R1" });
|
||||
return ctx;
|
||||
}
|
||||
|
||||
it("действующий токен отдаётся без обращения к Intuit; за 5 минут до конца - обновляется и сохраняется новый refresh token", async () => {
|
||||
const ctx = await connected([{ body: tokens(2) }]);
|
||||
expect((await ctx.auth.getAccessToken()).accessToken).toBe("at1");
|
||||
expect(ctx.f.calls).toHaveLength(1);
|
||||
ctx.clock.t = new Date(T0.getTime() + 56 * 60_000);
|
||||
const t = await ctx.auth.getAccessToken();
|
||||
expect(t).toMatchObject({ accessToken: "at2", realmId: "R1", apiBase: "https://sandbox-quickbooks.api.intuit.com" });
|
||||
expect(ctx.f.calls[1]!.body.get("grant_type")).toBe("refresh_token");
|
||||
expect(ctx.f.calls[1]!.body.get("refresh_token")).toBe("rt1");
|
||||
expect(ctx.store.conns.get("sandbox")!.refreshToken).toBe("rt2");
|
||||
});
|
||||
|
||||
it("invalid_grant: статус reauth_needed, уведомление, дальше 409 без обращения к Intuit", async () => {
|
||||
const ctx = await connected([{ status: 400, body: { error: "invalid_grant" } }]);
|
||||
ctx.clock.t = new Date(T0.getTime() + 2 * 3600_000);
|
||||
await expect(ctx.auth.getAccessToken()).rejects.toBeInstanceOf(ReauthNeeded);
|
||||
expect(ctx.notes).toHaveLength(1);
|
||||
const calls = ctx.f.calls.length;
|
||||
await expect(ctx.auth.getAccessToken()).rejects.toBeInstanceOf(ReauthNeeded);
|
||||
expect(ctx.f.calls).toHaveLength(calls);
|
||||
expect((await ctx.auth.status()).connected).toBe(false);
|
||||
});
|
||||
|
||||
it("прочие ошибки Intuit не переводят подключение в reauth_needed", async () => {
|
||||
const ctx = await connected([{ status: 500, body: { error: "server_error" } }]);
|
||||
ctx.clock.t = new Date(T0.getTime() + 2 * 3600_000);
|
||||
await expect(ctx.auth.getAccessToken()).rejects.toThrow(/500/);
|
||||
expect(ctx.store.conns.get("sandbox")!.status).toBe("ok");
|
||||
});
|
||||
|
||||
it("keepAlive: свежие токены не трогает, старые обновляет", async () => {
|
||||
const ctx = await connected([{ body: tokens(2) }]);
|
||||
expect(await ctx.auth.keepAlive()).toBe("fresh");
|
||||
ctx.clock.t = new Date(T0.getTime() + 21 * 3600_000);
|
||||
expect(await ctx.auth.keepAlive()).toBe("refreshed");
|
||||
expect(ctx.store.conns.get("sandbox")!.refreshToken).toBe("rt2");
|
||||
});
|
||||
|
||||
it("keepAlive без подключения", async () => {
|
||||
expect(await mk([]).auth.keepAlive()).toBe("not_connected");
|
||||
});
|
||||
});
|
||||
|
||||
describe("HTTP", () => {
|
||||
it("служебные ручки требуют токен; /healthz и /callback открыты; в status нет секретов", async () => {
|
||||
const ctx = mk([{ body: tokens(1) }]);
|
||||
const app = buildApi(ctx.auth, "tok");
|
||||
expect((await app.inject({ url: "/healthz" })).statusCode).toBe(200);
|
||||
expect((await app.inject({ url: "/status" })).statusCode).toBe(401);
|
||||
expect((await app.inject({ method: "POST", url: "/token" })).statusCode).toBe(401);
|
||||
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("подключён");
|
||||
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");
|
||||
expect(st.body).not.toContain("rt1");
|
||||
});
|
||||
|
||||
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");
|
||||
});
|
||||
|
||||
it("/token: без подключения - 409 reauth_needed; с подключением - токен", async () => {
|
||||
const ctx = mk([{ body: tokens(1) }]);
|
||||
const app = buildApi(ctx.auth, "tok");
|
||||
const h = { authorization: "Bearer tok" };
|
||||
expect((await app.inject({ method: "POST", url: "/token", headers: h })).statusCode).toBe(409);
|
||||
const state = new URL((await ctx.auth.startConnect()).url).searchParams.get("state")!;
|
||||
await ctx.auth.handleCallback({ code: "c", state, realmId: "R1" });
|
||||
const r = await app.inject({ method: "POST", url: "/token", headers: h });
|
||||
expect(r.statusCode).toBe(200);
|
||||
expect(r.json()).toMatchObject({ accessToken: "at1", realmId: "R1" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("шифрование", () => {
|
||||
it("туда-обратно; разные шифртексты; подмена ломает расшифровку; плохой ключ отклоняется", () => {
|
||||
const key = parseKey("00".repeat(32));
|
||||
const a = encrypt("secret", key), b = encrypt("secret", key);
|
||||
expect(a).not.toBe(b);
|
||||
expect(a).not.toContain("secret");
|
||||
expect(decrypt(a, key)).toBe("secret");
|
||||
expect(() => decrypt(a.slice(0, -2) + "AA", key)).toThrow();
|
||||
expect(() => parseKey("short")).toThrow();
|
||||
});
|
||||
});
|
||||
114
packages/qbo_auth/src/service.ts
Normal file
114
packages/qbo_auth/src/service.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { apiBase, authorizeUrl, exchangeCode, refreshTokens, TokenError, type FetchFn, type TokenSet } from "./oauth.js";
|
||||
import type { Connection, Env, Store } from "./store.js";
|
||||
|
||||
export interface QboAuthDeps {
|
||||
store: Store;
|
||||
fetchFn: FetchFn;
|
||||
env: Env;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
redirectUri: string;
|
||||
scope: string;
|
||||
keepAliveHours: number;
|
||||
now?: () => Date;
|
||||
notify?: (text: string) => Promise<void>;
|
||||
}
|
||||
|
||||
/** Человек должен заново авторизовать приложение (или подключение ещё не делали). */
|
||||
export class ReauthNeeded extends Error {}
|
||||
|
||||
const SKEW_MS = 5 * 60_000;
|
||||
|
||||
export class QboAuth {
|
||||
constructor(private readonly d: QboAuthDeps) {}
|
||||
private now = () => (this.d.now ? this.d.now() : new Date());
|
||||
private creds = () => ({ clientId: this.d.clientId, clientSecret: this.d.clientSecret });
|
||||
|
||||
/** Ссылка авторизации для администратора компании QuickBooks. State одноразовый, живёт 10 минут. */
|
||||
async startConnect(): Promise<{ url: string }> {
|
||||
const state = randomBytes(24).toString("base64url");
|
||||
await this.d.store.saveState(state, this.d.env);
|
||||
return { url: authorizeUrl({ clientId: this.d.clientId, redirectUri: this.d.redirectUri, scope: this.d.scope, state }) };
|
||||
}
|
||||
|
||||
/** Возврат с Intuit: проверка state, обмен кода на токены, сохранение. */
|
||||
async handleCallback(q: { code?: string; state?: string; realmId?: string; error?: string }): Promise<{ realmId: string }> {
|
||||
const env = q.state ? await this.d.store.consumeState(q.state) : null;
|
||||
if (!env) throw new Error("неизвестный или просроченный state: начните подключение заново");
|
||||
if (q.error) throw new Error(`Intuit вернул ошибку: ${q.error}`);
|
||||
if (!q.code || !q.realmId) throw new Error("в ответе Intuit нет code или realmId");
|
||||
const t = await exchangeCode(this.d.fetchFn, this.creds(), q.code, this.d.redirectUri);
|
||||
const conn = this.fromTokens(env, q.realmId, t, this.now());
|
||||
await this.d.store.withLock(env, (c) => c.save(conn));
|
||||
return { realmId: q.realmId };
|
||||
}
|
||||
|
||||
private fromTokens(env: Env, realmId: string, t: TokenSet, at: Date, authorizedAt = at): Connection {
|
||||
return {
|
||||
environment: env,
|
||||
realmId,
|
||||
accessToken: t.accessToken,
|
||||
refreshToken: t.refreshToken,
|
||||
accessExpiresAt: new Date(at.getTime() + t.expiresIn * 1000),
|
||||
refreshExpiresAt: new Date(at.getTime() + t.refreshExpiresIn * 1000),
|
||||
authorizedAt,
|
||||
refreshedAt: at,
|
||||
status: "ok",
|
||||
};
|
||||
}
|
||||
|
||||
/** Действующий access token; при необходимости (или force) обновляет его под блокировкой и сразу сохраняет новый refresh token. */
|
||||
async getAccessToken(opts: { force?: boolean } = {}): Promise<{ accessToken: string; realmId: string; apiBase: string; expiresAt: Date }> {
|
||||
const env = this.d.env;
|
||||
return this.d.store.withLock(env, async (c) => {
|
||||
const cur = c.get();
|
||||
if (!cur) throw new ReauthNeeded("QuickBooks не подключён: выполните подключение (POST /connect)");
|
||||
if (cur.status === "reauth_needed") throw new ReauthNeeded("нужна новая авторизация QuickBooks (POST /connect)");
|
||||
const at = this.now();
|
||||
if (!opts.force && cur.accessExpiresAt.getTime() - at.getTime() > SKEW_MS) {
|
||||
return { accessToken: cur.accessToken, realmId: cur.realmId, apiBase: apiBase(env), expiresAt: cur.accessExpiresAt };
|
||||
}
|
||||
try {
|
||||
const t = await refreshTokens(this.d.fetchFn, this.creds(), cur.refreshToken);
|
||||
const next = this.fromTokens(env, cur.realmId, t, at, cur.authorizedAt);
|
||||
await c.save(next);
|
||||
return { accessToken: next.accessToken, realmId: next.realmId, apiBase: apiBase(env), expiresAt: next.accessExpiresAt };
|
||||
} catch (e) {
|
||||
if (e instanceof TokenError && e.invalidGrant) {
|
||||
await c.save({ ...cur, status: "reauth_needed" });
|
||||
await this.d.notify?.("QuickBooks: refresh token недействителен, нужна новая авторизация (POST /connect у qbo_auth)").catch(() => undefined);
|
||||
throw new ReauthNeeded("refresh token недействителен: нужна новая авторизация QuickBooks");
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Поддержание: обновляет токены, если последнее обновление старше keepAliveHours (скользящий refresh token не должен простаивать). */
|
||||
async keepAlive(): Promise<"refreshed" | "fresh" | "not_connected" | "reauth_needed"> {
|
||||
const cur = await this.d.store.read(this.d.env);
|
||||
if (!cur) return "not_connected";
|
||||
if (cur.status === "reauth_needed") return "reauth_needed";
|
||||
if (this.now().getTime() - cur.refreshedAt.getTime() < this.d.keepAliveHours * 3600_000) return "fresh";
|
||||
await this.getAccessToken({ force: true });
|
||||
return "refreshed";
|
||||
}
|
||||
|
||||
/** Состояние без секретов. */
|
||||
async status() {
|
||||
const c = await this.d.store.read(this.d.env);
|
||||
if (!c) return { environment: this.d.env, connected: false as const };
|
||||
return {
|
||||
environment: c.environment,
|
||||
connected: c.status === "ok",
|
||||
status: c.status,
|
||||
realmId: c.realmId,
|
||||
apiBase: apiBase(c.environment),
|
||||
accessExpiresAt: c.accessExpiresAt.toISOString(),
|
||||
refreshExpiresAt: c.refreshExpiresAt.toISOString(),
|
||||
authorizedAt: c.authorizedAt.toISOString(),
|
||||
refreshedAt: c.refreshedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
20
packages/qbo_auth/src/settings.ts
Normal file
20
packages/qbo_auth/src/settings.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* Секция `qbo_auth` в settings.json5. Секреты (clientSecret, encryptionKey, token) - только здесь, не в Git.
|
||||
* Ключи приложения Intuit: development-ключи работают только с sandbox, production - после проверки Intuit.
|
||||
*/
|
||||
export const qboAuthSchema = z.object({
|
||||
http: z.object({ host: z.string().default("0.0.0.0"), port: z.number().default(8095), token: z.string().min(1) }),
|
||||
environment: z.enum(["sandbox", "production"]).default("sandbox"),
|
||||
clientId: z.string().min(1),
|
||||
clientSecret: z.string().min(1),
|
||||
/** Должен совпадать со значением в разделе Redirect URIs приложения Intuit. */
|
||||
redirectUri: z.string().url(),
|
||||
scope: z.string().default("com.intuit.quickbooks.accounting"),
|
||||
/** 32 байта в hex (64 символа) или base64: ключ шифрования токенов в БД (AES-256-GCM). */
|
||||
encryptionKey: z.string().min(32),
|
||||
/** Обновлять токены, если последнее обновление старше, часов (refresh token скользящий, до 100 дней). */
|
||||
keepAliveHours: z.number().default(20),
|
||||
});
|
||||
export type QboAuthSettings = z.infer<typeof qboAuthSchema>;
|
||||
119
packages/qbo_auth/src/store.ts
Normal file
119
packages/qbo_auth/src/store.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { withTx, type Pool } from "khb_common";
|
||||
import { decrypt, encrypt } from "./crypto.js";
|
||||
|
||||
export type Env = "sandbox" | "production";
|
||||
|
||||
export interface Connection {
|
||||
environment: Env;
|
||||
realmId: string;
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
accessExpiresAt: Date;
|
||||
refreshExpiresAt: Date;
|
||||
authorizedAt: Date;
|
||||
refreshedAt: Date;
|
||||
/** ok | reauth_needed (refresh token отозван или просрочен: нужна новая авторизация человеком) */
|
||||
status: "ok" | "reauth_needed";
|
||||
}
|
||||
|
||||
/** Операции над соединением внутри блокировки (одно обновление токена за раз: refresh token одноразовый). */
|
||||
export interface LockedConn {
|
||||
get(): Connection | null;
|
||||
save(c: Connection): Promise<void>;
|
||||
}
|
||||
|
||||
export interface Store {
|
||||
saveState(state: string, env: Env): Promise<void>;
|
||||
/** Одноразово: возвращает окружение, если state есть и моложе 10 минут; затем удаляет. */
|
||||
consumeState(state: string): Promise<Env | null>;
|
||||
withLock<T>(env: Env, fn: (c: LockedConn) => Promise<T>): Promise<T>;
|
||||
read(env: Env): Promise<Connection | null>;
|
||||
}
|
||||
|
||||
export class PgStore implements Store {
|
||||
constructor(
|
||||
private readonly pool: Pool,
|
||||
private readonly key: Buffer,
|
||||
) {}
|
||||
|
||||
async saveState(state: string, env: Env): Promise<void> {
|
||||
await this.pool.query("delete from qbo_oauth_state where created_at < now() - interval '1 hour'");
|
||||
await this.pool.query("insert into qbo_oauth_state (state, environment) values ($1, $2)", [state, env]);
|
||||
}
|
||||
|
||||
async consumeState(state: string): Promise<Env | null> {
|
||||
const r = await this.pool.query(
|
||||
"delete from qbo_oauth_state where state = $1 returning environment, created_at > now() - interval '10 minutes' as fresh",
|
||||
[state],
|
||||
);
|
||||
const row = r.rows[0] as { environment: Env; fresh: boolean } | undefined;
|
||||
return row && row.fresh ? row.environment : null;
|
||||
}
|
||||
|
||||
private toConn(row: Record<string, unknown>): Connection {
|
||||
return {
|
||||
environment: row.environment as Env,
|
||||
realmId: 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,
|
||||
refreshExpiresAt: row.refresh_expires_at as Date,
|
||||
authorizedAt: row.authorized_at as Date,
|
||||
refreshedAt: row.refreshed_at as Date,
|
||||
status: row.status as Connection["status"],
|
||||
};
|
||||
}
|
||||
|
||||
async read(env: Env): Promise<Connection | null> {
|
||||
const r = await this.pool.query("select * from qbo_connection where environment = $1", [env]);
|
||||
return r.rows[0] ? this.toConn(r.rows[0]) : null;
|
||||
}
|
||||
|
||||
async withLock<T>(env: Env, fn: (c: LockedConn) => Promise<T>): Promise<T> {
|
||||
return withTx(this.pool, async (client) => {
|
||||
await client.query("select pg_advisory_xact_lock(hashtext($1))", [`qbo_connection:${env}`]);
|
||||
const r = await client.query("select * from qbo_connection where environment = $1 for update", [env]);
|
||||
const current = r.rows[0] ? this.toConn(r.rows[0]) : null;
|
||||
return fn({
|
||||
get: () => current,
|
||||
save: async (c) => {
|
||||
await client.query(
|
||||
`insert into qbo_connection (environment, realm_id, access_token_enc, refresh_token_enc, access_expires_at, refresh_expires_at, authorized_at, refreshed_at, status)
|
||||
values ($1,$2,$3,$4,$5,$6,$7,$8,$9)
|
||||
on conflict (environment) do update set realm_id = excluded.realm_id, access_token_enc = excluded.access_token_enc,
|
||||
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],
|
||||
);
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Хранилище в памяти (тесты). */
|
||||
export class MemoryStore implements Store {
|
||||
states = new Map<string, { env: Env; at: number }>();
|
||||
conns = new Map<Env, Connection>();
|
||||
now = () => Date.now();
|
||||
async saveState(state: string, env: Env) {
|
||||
this.states.set(state, { env, at: this.now() });
|
||||
}
|
||||
async consumeState(state: string) {
|
||||
const s = this.states.get(state);
|
||||
this.states.delete(state);
|
||||
return s && this.now() - s.at < 10 * 60_000 ? s.env : null;
|
||||
}
|
||||
async read(env: Env) {
|
||||
return this.conns.get(env) ?? null;
|
||||
}
|
||||
async withLock<T>(env: Env, fn: (c: LockedConn) => Promise<T>) {
|
||||
return fn({
|
||||
get: () => this.conns.get(env) ?? null,
|
||||
save: async (c) => {
|
||||
this.conns.set(env, c);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
6
packages/qbo_auth/tsconfig.json
Normal file
6
packages/qbo_auth/tsconfig.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": { "outDir": "dist", "rootDir": "src" },
|
||||
"include": ["src"],
|
||||
"exclude": ["src/**/*.test.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user