// PEP-252 Access Hub: connecting a service by signing in (OAuth 2.0 authorization code + PKCE S256). // This file knows the providers — their endpoints, FORGE's client settings and the token calls // (code exchange, refresh, revoke) — and nothing about the database. The flow (state in settings, // the browser cookie, the owner) is in connection-oauth-flow.ts; the gateway's refresh is in // connections.ts (`connectionCredential`). Tokens never leave these functions except into the // connection's sealed envelope (PEP-254) and the outgoing Authorization header. import { m as tr } from "@peppa/shared/i18n"; import { catalogService, type CatalogService, type OAuthProviderId } from "./connection-catalog.ts"; export type { OAuthProviderId } from "./connection-catalog.ts"; export const OAUTH_TIMEOUT_MS = 15_000; export const OAUTH_REVOKE_TIMEOUT_MS = 5_000; /** A token that expires within this window is refreshed before the call. */ export const OAUTH_REFRESH_EARLY_MS = 60_000; export interface OAuthProvider { id: OAuthProviderId; /** Brand name for «Войти через …». */ name: string; /** Env names of FORGE's client; `fallback` — another client of the same provider (Google login, PEP-90). */ env: { id: string; secret: string; base: string; fallbackId?: string; fallbackSecret?: string }; authorize: (base: string | null) => string; token: (base: string | null) => string; /** Extra authorize parameters (Google: offline access, so a refresh token comes). */ authorizeParams: Record; } export const OAUTH_PROVIDERS: Record = { google: { id: "google", name: "Google", env: { id: "PEPPA_OAUTH_GOOGLE_CLIENT_ID", secret: "PEPPA_OAUTH_GOOGLE_CLIENT_SECRET", base: "PEPPA_OAUTH_GOOGLE_BASE", fallbackId: "GOOGLE_CLIENT_ID", fallbackSecret: "GOOGLE_CLIENT_SECRET" }, authorize: (b) => (b ? `${b}/auth` : "https://accounts.google.com/o/oauth2/v2/auth"), token: (b) => (b ? `${b}/token` : "https://oauth2.googleapis.com/token"), // prompt=consent: Google sends a refresh token only on a consent screen. authorizeParams: { access_type: "offline", prompt: "consent", include_granted_scopes: "false" }, }, github: { id: "github", name: "GitHub", env: { id: "PEPPA_OAUTH_GITHUB_CLIENT_ID", secret: "PEPPA_OAUTH_GITHUB_CLIENT_SECRET", base: "PEPPA_OAUTH_GITHUB_BASE" }, authorize: (b) => `${b ?? "https://github.com"}/login/oauth/authorize`, token: (b) => `${b ?? "https://github.com"}/login/oauth/access_token`, authorizeParams: { allow_signup: "false" }, }, }; export interface ServiceOAuthClient { provider: OAuthProvider; clientId: string; clientSecret: string; /** Test/mock base of the provider's endpoints, null — the real ones. */ base: string | null; } /** FORGE's client of a provider, or null — the sign-in way is hidden. */ export function oauthClient(id: OAuthProviderId | string | null | undefined, env: NodeJS.ProcessEnv = process.env): ServiceOAuthClient | null { const provider = id ? OAUTH_PROVIDERS[id as OAuthProviderId] : undefined; if (!provider) return null; const own = env[provider.env.id] && env[provider.env.secret]; const clientId = own ? env[provider.env.id] : provider.env.fallbackId ? env[provider.env.fallbackId] : undefined; const clientSecret = own ? env[provider.env.secret] : provider.env.fallbackSecret ? env[provider.env.fallbackSecret] : undefined; if (!clientId || !clientSecret) return null; const base = env[provider.env.base]?.replace(/\/+$/, "") || null; return { provider, clientId, clientSecret, base }; } export const oauthEnabled = (id: OAuthProviderId | string | null | undefined, env: NodeJS.ProcessEnv = process.env) => !!oauthClient(id, env); export type OAuthLevel = "read" | "write"; /** Scopes FORGE asks for one level of a card. */ export function cardScopes(card: CatalogService, level: OAuthLevel): string[] { return card.oauth ? (level === "write" ? card.oauth.write : card.oauth.read) : []; } /** What a card offers for signing in, for the page: null — no sign-in for it (or no client). */ export function oauthOffer(catalogId: string | null | undefined, env: NodeJS.ProcessEnv = process.env): { provider: OAuthProviderId; providerName: string; read: string[]; write: string[]; note: string | null } | null { const card = catalogService(catalogId); if (!card?.oauth || !oauthEnabled(card.oauth.provider, env)) return null; return { provider: card.oauth.provider, providerName: OAUTH_PROVIDERS[card.oauth.provider].name, read: card.oauth.read, write: card.oauth.write, note: card.oauth.note ?? null }; } /** «https://www.googleapis.com/auth/spreadsheets.readonly» → «spreadsheets.readonly». */ export const scopeLabel = (scope: string) => scope.replace(/^https:\/\/www\.googleapis\.com\/auth\//, ""); /** Level of saved scopes: all write scopes of the card granted → write. */ export function scopesLevel(card: CatalogService | null, scopes: string[] | null | undefined): OAuthLevel { if (!card?.oauth || !scopes?.length) return "read"; const read = new Set(card.oauth.read); const extra = card.oauth.write.filter((s) => !read.has(s)); if (!extra.length) return "read"; return extra.every((s) => scopes.includes(s)) ? "write" : "read"; } // ---------- tokens ---------- /** What the sealed envelope of a sign-in connection holds (JSON). */ export interface ServiceTokens { access: string; refresh: string | null; } export const packTokens = (t: ServiceTokens) => JSON.stringify({ v: 1, access: t.access, refresh: t.refresh }); export function unpackTokens(raw: string): ServiceTokens | null { try { const j = JSON.parse(raw) as { v?: number; access?: unknown; refresh?: unknown }; if (j.v !== 1 || typeof j.access !== "string" || !j.access) return null; return { access: j.access, refresh: typeof j.refresh === "string" && j.refresh ? j.refresh : null }; } catch { return null; } } export interface TokenAnswer { tokens: ServiceTokens; /** null — the token does not expire (GitHub OAuth app). */ expiresAt: Date | null; /** What the service says it granted; null — it didn't say. */ scopes: string[] | null; } /** rejected — the service refused (revoked, wrong code); failed — no answer / 5xx (try later). */ export type TokenFailure = { ok: false; rejected: boolean }; const TOKEN_SHAPE = /^[\x21-\x7e]{1,4096}$/; async function tokenCall(c: ServiceOAuthClient, body: Record, now: Date): Promise<{ ok: true; answer: TokenAnswer } | TokenFailure> { let res: Response; try { res = await fetch(c.provider.token(c.base), { method: "POST", // GitHub answers form-encoded without Accept. headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json", "user-agent": "PeppaFactory-AccessHub/1" }, body: new URLSearchParams({ ...body, client_id: c.clientId, client_secret: c.clientSecret }), redirect: "error", signal: AbortSignal.timeout(OAUTH_TIMEOUT_MS), }); } catch { return { ok: false, rejected: false }; } if (res.status >= 500) return { ok: false, rejected: false }; const j = (await res.json().catch(() => null)) as { access_token?: unknown; refresh_token?: unknown; expires_in?: unknown; scope?: unknown; error?: unknown } | null; // GitHub reports errors with 200 and `error`; Google with 400/401. if (!j || j.error || !res.ok || typeof j.access_token !== "string" || !TOKEN_SHAPE.test(j.access_token)) return { ok: false, rejected: res.status < 500 && !!j }; const refresh = typeof j.refresh_token === "string" && TOKEN_SHAPE.test(j.refresh_token) ? j.refresh_token : null; const sec = Number(j.expires_in); const scopes = typeof j.scope === "string" ? j.scope.split(/[\s,]+/).filter(Boolean) : null; return { ok: true, answer: { tokens: { access: j.access_token, refresh }, expiresAt: Number.isFinite(sec) && sec > 0 ? new Date(now.getTime() + sec * 1000) : null, scopes } }; } export function exchangeCode(c: ServiceOAuthClient, i: { code: string; redirectUri: string; verifier: string }, now = new Date()) { return tokenCall(c, { grant_type: "authorization_code", code: i.code, redirect_uri: i.redirectUri, code_verifier: i.verifier }, now); } export function refreshTokens(c: ServiceOAuthClient, refresh: string, now = new Date()) { return tokenCall(c, { grant_type: "refresh_token", refresh_token: refresh }, now); } /** * Revokes FORGE's access in the service itself. Google: POST /revoke (the refresh token revokes * the whole grant); GitHub: DELETE /applications/{client_id}/grant (basic client auth). Never * throws: the revoke in FORGE happens whatever the service answers. */ export async function revokeAtService(providerId: string | null | undefined, tokens: ServiceTokens, env: NodeJS.ProcessEnv = process.env): Promise<"revoked" | "failed" | "unsupported"> { const c = oauthClient(providerId, env); if (!c) return "unsupported"; try { let res: Response; if (c.provider.id === "google") { res = await fetch(c.base ? `${c.base}/revoke` : "https://oauth2.googleapis.com/revoke", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ token: tokens.refresh ?? tokens.access }), redirect: "error", signal: AbortSignal.timeout(OAUTH_REVOKE_TIMEOUT_MS), }); } else { res = await fetch(`${c.base ?? "https://api.github.com"}/applications/${encodeURIComponent(c.clientId)}/grant`, { method: "DELETE", headers: { authorization: `Basic ${Buffer.from(`${c.clientId}:${c.clientSecret}`).toString("base64")}`, accept: "application/vnd.github+json", "content-type": "application/json", "user-agent": "PeppaFactory-AccessHub/1" }, body: JSON.stringify({ access_token: tokens.access }), redirect: "error", signal: AbortSignal.timeout(OAUTH_REVOKE_TIMEOUT_MS), }); } await res.arrayBuffer().catch(() => null); // Already revoked/unknown token: nothing left to revoke. return res.ok || res.status === 400 || res.status === 404 ? "revoked" : "failed"; } catch { return "failed"; } } export const OAUTH_ERROR_TEXT = { notConfigured: tr("Вход через этот сервис в FORGE пока не настроен — подключите его ключом"), denied: tr("Вход отменён: подключение не создано"), stale: tr("Вход устарел или уже использован — начните заново"), failed: tr("Сервис не подтвердил вход — попробуйте ещё раз"), noScopes: tr("Вы не дали FORGE нужный доступ — начните заново и отметьте все пункты"), };