import { createSign } from "node:crypto"; export interface GoogleKey { client_email: string; private_key: string; } export type FetchFn = typeof fetch; const TOKEN_URL = "https://oauth2.googleapis.com/token"; const b64url = (b: Buffer | string): string => Buffer.from(b).toString("base64url"); /** Подписанный JWT (RS256) для обмена на access token сервисного аккаунта. */ export function buildServiceAccountJwt(key: GoogleKey, scopes: string[], subject: string | undefined, nowSec: number): string { const header = { alg: "RS256", typ: "JWT" }; const claims: Record = { iss: key.client_email, scope: scopes.join(" "), aud: TOKEN_URL, iat: nowSec, exp: nowSec + 3600, }; if (subject) claims.sub = subject; const unsigned = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`; const signature = createSign("RSA-SHA256").update(unsigned).sign(key.private_key); return `${unsigned}.${b64url(signature)}`; } /** Токены сервисного аккаунта Google с кэшем. subject - пользователь для делегирования на уровне домена (Gmail). */ export class GoogleAuth { private cache = new Map(); constructor( private key: GoogleKey, private opts: { fetchFn?: FetchFn; now?: () => Date } = {}, ) {} async getAccessToken(scopes: string[], subject?: string): Promise { const now = (this.opts.now ?? (() => new Date()))().getTime(); const ck = `${[...scopes].sort().join(" ")}|${subject ?? ""}`; const hit = this.cache.get(ck); if (hit && hit.expiresAtMs - 60_000 > now) return hit.token; const jwt = buildServiceAccountJwt(this.key, scopes, subject, Math.floor(now / 1000)); const body = new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: jwt }); const res = await (this.opts.fetchFn ?? fetch)(TOKEN_URL, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body, }); const text = await res.text(); if (!res.ok) throw new Error(`Google token ${res.status}: ${text.slice(0, 300)}`); const j = JSON.parse(text) as { access_token?: string; expires_in?: number }; if (!j.access_token) throw new Error("Google token: в ответе нет access_token"); this.cache.set(ck, { token: j.access_token, expiresAtMs: now + (j.expires_in ?? 3600) * 1000 }); return j.access_token; } }