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