qbo_auth: discovery-документ, клиент API с разбором Fault, отключение с отзывом токена; анкета и требования Intuit
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { apiBase, authorizeUrl, exchangeCode, refreshTokens, TokenError, type FetchFn, type TokenSet } from "./oauth.js";
|
||||
import { apiBase, authorizeUrl, exchangeCode, refreshTokens, revokeToken, TokenError, type FetchFn, type TokenSet } from "./oauth.js";
|
||||
import { FALLBACK_ENDPOINTS, type Endpoints } from "./discovery.js";
|
||||
import type { Connection, Env, Store } from "./store.js";
|
||||
|
||||
export interface QboAuthDeps {
|
||||
@@ -13,6 +14,8 @@ export interface QboAuthDeps {
|
||||
keepAliveHours: number;
|
||||
now?: () => Date;
|
||||
notify?: (text: string) => Promise<void>;
|
||||
/** Адреса OAuth из discovery-документа (по умолчанию запасные константы). */
|
||||
endpoints?: () => Promise<Endpoints>;
|
||||
}
|
||||
|
||||
/** Человек должен заново авторизовать приложение (или подключение ещё не делали). */
|
||||
@@ -23,13 +26,14 @@ 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 ep = (): Promise<Endpoints> => (this.d.endpoints ? this.d.endpoints() : Promise.resolve(FALLBACK_ENDPOINTS));
|
||||
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 }) };
|
||||
return { url: authorizeUrl({ clientId: this.d.clientId, redirectUri: this.d.redirectUri, scope: this.d.scope, state, base: (await this.ep()).authorization }) };
|
||||
}
|
||||
|
||||
/** Возврат с Intuit: проверка state, обмен кода на токены, сохранение. */
|
||||
@@ -38,7 +42,7 @@ export class QboAuth {
|
||||
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 t = await exchangeCode(this.d.fetchFn, this.creds(), q.code, this.d.redirectUri, (await this.ep()).token);
|
||||
const conn = this.fromTokens(env, q.realmId, t, this.now());
|
||||
await this.d.store.withLock(env, (c) => c.save(conn));
|
||||
return { realmId: q.realmId };
|
||||
@@ -70,7 +74,7 @@ export class QboAuth {
|
||||
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 t = await refreshTokens(this.d.fetchFn, this.creds(), cur.refreshToken, (await this.ep()).token);
|
||||
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 };
|
||||
@@ -95,6 +99,23 @@ export class QboAuth {
|
||||
return "refreshed";
|
||||
}
|
||||
|
||||
/** Отключение: отзывает refresh token у Intuit и удаляет сохранённые токены. Если отзыв не удался (токен уже недействителен), токены всё равно удаляются. */
|
||||
async disconnect(): Promise<{ revoked: boolean; removed: boolean }> {
|
||||
return this.d.store.withLock(this.d.env, async (c) => {
|
||||
const cur = c.get();
|
||||
if (!cur) return { revoked: false, removed: false };
|
||||
let revoked = false;
|
||||
try {
|
||||
await revokeToken(this.d.fetchFn, this.creds(), cur.refreshToken, (await this.ep()).revocation);
|
||||
revoked = true;
|
||||
} catch {
|
||||
// токен мог быть уже отозван в QuickBooks (кнопка Disconnect): удаление ниже всё равно нужно
|
||||
}
|
||||
await c.remove();
|
||||
return { revoked, removed: true };
|
||||
});
|
||||
}
|
||||
|
||||
/** Состояние без секретов. */
|
||||
async status() {
|
||||
const c = await this.d.store.read(this.d.env);
|
||||
|
||||
Reference in New Issue
Block a user