Сервис 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:
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(),
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user