75 lines
4.3 KiB
TypeScript
75 lines
4.3 KiB
TypeScript
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>; headers?: { get(name: string): string | null } }>;
|
||
|
||
/** Идентификатор запроса Intuit (заголовок intuit_tid): нужен поддержке Intuit для разбора ошибок. */
|
||
export const intuitTid = (r: { headers?: { get(name: string): string | null } }): string | undefined => r.headers?.get("intuit_tid") ?? undefined;
|
||
|
||
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; base?: string }): string {
|
||
const q = new URLSearchParams({ client_id: p.clientId, response_type: "code", scope: p.scope, redirect_uri: p.redirectUri, state: p.state });
|
||
return `${p.base ?? AUTHORIZE_URL}?${q.toString()}`;
|
||
}
|
||
|
||
async function tokenCall(fetchFn: FetchFn, creds: { clientId: string; clientSecret: string }, params: Record<string, string>, tokenUrl: string): Promise<TokenSet> {
|
||
const r = await fetchFn(tokenUrl, {
|
||
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, без тел с токенами
|
||
const tid = intuitTid(r);
|
||
throw new TokenError(`Intuit token endpoint: ${r.status} ${err}${tid ? ` intuit_tid=${tid}` : ""}`, 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, tokenUrl: string = TOKEN_URL) =>
|
||
tokenCall(f, c, { grant_type: "authorization_code", code, redirect_uri: redirectUri }, tokenUrl);
|
||
export const refreshTokens = (f: FetchFn, c: { clientId: string; clientSecret: string }, refreshToken: string, tokenUrl: string = TOKEN_URL) =>
|
||
tokenCall(f, c, { grant_type: "refresh_token", refresh_token: refreshToken }, tokenUrl);
|
||
|
||
/** Отзыв токена у Intuit (revocation endpoint из discovery-документа). Успех: 200. */
|
||
export async function revokeToken(fetchFn: FetchFn, creds: { clientId: string; clientSecret: string }, token: string, revokeUrl: string): Promise<void> {
|
||
const r = await fetchFn(revokeUrl, {
|
||
method: "POST",
|
||
headers: {
|
||
Authorization: "Basic " + Buffer.from(`${creds.clientId}:${creds.clientSecret}`).toString("base64"),
|
||
"Content-Type": "application/json",
|
||
Accept: "application/json",
|
||
},
|
||
body: JSON.stringify({ token }),
|
||
});
|
||
if (!r.ok) {
|
||
const tid = intuitTid(r);
|
||
throw new Error(`Intuit revoke: ${r.status}${tid ? ` intuit_tid=${tid}` : ""}`);
|
||
}
|
||
}
|