import { AUTHORIZE_URL, TOKEN_URL } from "./oauth.js"; import type { Env } from "./store.js"; export interface Endpoints { authorization: string; token: string; revocation: string; } export const DISCOVERY_URL: Record = { sandbox: "https://developer.api.intuit.com/.well-known/openid_sandbox_configuration", production: "https://developer.api.intuit.com/.well-known/openid_configuration", }; /** Запасные адреса на случай, если discovery-документ недоступен. */ export const FALLBACK_ENDPOINTS: Endpoints = { authorization: AUTHORIZE_URL, token: TOKEN_URL, revocation: "https://developer.api.intuit.com/v2/oauth2/tokens/revoke" }; const TTL_MS = 24 * 3600_000; const trusted = (u: unknown): u is string => { if (typeof u !== "string") return false; try { const x = new URL(u); return x.protocol === "https:" && (x.hostname === "intuit.com" || x.hostname.endsWith(".intuit.com")); } catch { return false; } }; /** Адреса OAuth из discovery-документа Intuit: кэш на сутки, при ошибке или чужом домене - запасные адреса. */ export function discoveryEndpoints( env: Env, getJson: (url: string) => Promise, now: () => number = Date.now, log?: (msg: string, extra?: Record) => void, ): () => Promise { let cached: { at: number; v: Endpoints } | undefined; return async () => { if (cached && now() - cached.at < TTL_MS) return cached.v; try { const j = (await getJson(DISCOVERY_URL[env])) as Record; if (!trusted(j.authorization_endpoint) || !trusted(j.token_endpoint)) throw new Error("в discovery-документе нет доверенных адресов"); const v: Endpoints = { authorization: j.authorization_endpoint, token: j.token_endpoint, revocation: trusted(j.revocation_endpoint) ? j.revocation_endpoint : FALLBACK_ENDPOINTS.revocation, }; cached = { at: now(), v }; return v; } catch (e) { log?.("discovery-документ Intuit недоступен, используются запасные адреса", { err: String(e) }); return cached?.v ?? FALLBACK_ENDPOINTS; } }; }