// PEP-252: the sign-in flow of a connection — like Google login (PEP-90): state and PKCE verifier // in `settings` (one-shot, 10 min), the state also in an httpOnly cookie of the starting browser, // and the callback must come to the same signed-in owner. Only then the code is exchanged; the // tokens go straight into the connection's sealed envelope (PEP-254). import { m as tr } from "@peppa/shared/i18n"; import { connectionGrants, connections, type Db } from "@peppa/db"; import { and, eq } from "drizzle-orm"; import { createHash, randomBytes } from "node:crypto"; import { logEvent } from "./audit.ts"; import { catalogService } from "./connection-catalog.ts"; import { cardScopes, exchangeCode, OAUTH_ERROR_TEXT, oauthClient, packTokens, scopesLevel, type OAuthLevel } from "./connection-oauth.ts"; import { CONNECTION_NAME_MAX, freeSlug, ownConnection, sealConnectionSecret } from "./connections.ts"; import { hashToken } from "./crypto.ts"; import { PeppaError } from "./errors.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; export const CONNECTION_OAUTH_TTL_MS = 10 * 60_000; /** The browser cookie of the flow (path /connections/oauth). */ export const CONNECTION_OAUTH_COOKIE = "peppa_conn_oauth"; interface Flow { userId: number; catalogId: string; level: OAuthLevel; /** «Войти заново»: the connection whose tokens are replaced. */ connectionId: number | null; verifier: string; redirectUri: string; scopes: string[]; expiresAt: number; } const flowKey = (state: string) => `conn.oauth.flow:${hashToken(state)}`; export interface ConnectionOAuthStart { url: string; /** Goes into the httpOnly cookie; the callback must bring it back. */ state: string; } /** Starts signing in for a catalog card (new connection) or for an own connection (`connectionId`, sign in again). */ export async function startConnectionOAuth(db: Db, userId: number, i: { catalogId?: string | null; connectionId?: number | null; level?: string | null; redirectUri: string }, env: NodeJS.ProcessEnv = process.env): Promise { let catalogId = i.catalogId ?? null; let level: OAuthLevel = i.level === "write" ? "write" : "read"; if (i.connectionId != null) { const c = await ownConnection(db, userId, i.connectionId); if (c.authKind !== "oauth") throw new PeppaError(tr("Это подключение работает по ключу доступа")); catalogId = c.catalogId; if (i.level !== "read" && i.level !== "write") level = scopesLevel(catalogService(c.catalogId), c.oauthScopes); } const card = catalogService(catalogId); if (!card?.oauth) throw new PeppaError(tr("У этого сервиса нет входа через сервис — подключите его ключом")); const client = oauthClient(card.oauth.provider, env); if (!client) throw new PeppaError(OAUTH_ERROR_TEXT.notConfigured); const scopes = cardScopes(card, level); const state = randomBytes(24).toString("base64url"); const verifier = randomBytes(32).toString("base64url"); await setSetting(db, flowKey(state), { userId, catalogId: card.id, level, connectionId: i.connectionId ?? null, verifier, redirectUri: i.redirectUri, scopes, expiresAt: Date.now() + CONNECTION_OAUTH_TTL_MS } satisfies Flow); const q = new URLSearchParams({ client_id: client.clientId, redirect_uri: i.redirectUri, response_type: "code", scope: scopes.join(" "), state, code_challenge: createHash("sha256").update(verifier).digest("base64url"), code_challenge_method: "S256", ...client.provider.authorizeParams, }); return { url: `${client.provider.authorize(client.base)}?${q}`, state }; } /** * The service sent the browser back. One-shot: the flow is removed before anything else. Refused * (and nothing created) when the state differs from the browser's cookie, the flow is gone or * stale, or another person is signed in now. */ export async function completeConnectionOAuth(db: Db, userId: number, i: { state: string; code: string; cookieState: string }, o: { now?: Date } = {}): Promise<{ connectionId: number; created: boolean }> { if (!i.state || !i.code || i.state !== i.cookieState) throw new PeppaError(OAUTH_ERROR_TEXT.stale); const flow = await getSetting(db, flowKey(i.state)); await deleteSetting(db, flowKey(i.state)); if (!flow || Date.now() >= flow.expiresAt) throw new PeppaError(OAUTH_ERROR_TEXT.stale); if (flow.userId !== userId) throw new PeppaError(OAUTH_ERROR_TEXT.stale); const card = catalogService(flow.catalogId); const client = card?.oauth ? oauthClient(card.oauth.provider) : null; if (!card?.oauth || !client) throw new PeppaError(OAUTH_ERROR_TEXT.notConfigured); const r = await exchangeCode(client, { code: i.code, redirectUri: flow.redirectUri, verifier: flow.verifier }, o.now); if (!r.ok) throw new PeppaError(OAUTH_ERROR_TEXT.failed); // Google lets a person untick scopes: without any of the asked ones the connection is useless. const granted = r.answer.scopes ?? flow.scopes; if (!flow.scopes.some((s) => granted.includes(s))) throw new PeppaError(OAUTH_ERROR_TEXT.noScopes); const patch = { ...sealConnectionSecret(packTokens(r.answer.tokens)), oauthProvider: card.oauth.provider, oauthScopes: granted, tokenExpiresAt: r.answer.expiresAt, status: "active" as const, revokedAt: null, checkStatus: null, checkedAt: null, checkAlertedAt: null, }; if (flow.connectionId != null) { // Sign in again: the same connection with its grants. Gone or not the owner's — refused. const c = await ownConnection(db, userId, flow.connectionId); if (c.authKind !== "oauth" || c.catalogId !== card.id) throw new PeppaError(OAUTH_ERROR_TEXT.stale); await db.update(connections).set(patch).where(and(eq(connections.id, c.id), eq(connections.ownerId, userId))); const grants = await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, c.id)); for (const projectId of new Set(grants.map((g) => g.projectId))) await logEvent(db, { projectId, type: "connection_signed_in", payload: { connectionId: c.id } }); return { connectionId: c.id, created: false }; } const taken = new Set((await db.select({ name: connections.name }).from(connections).where(eq(connections.ownerId, userId))).map((r) => r.name)); let name = card.name; for (let n = 2; taken.has(name); n++) name = `${card.name} ${n}`.slice(0, CONNECTION_NAME_MAX); const slug = await freeSlug(db, userId, card.id); const [row] = await db .insert(connections) .values({ ownerId: userId, name, baseUrl: card.baseUrl, authKind: "oauth", authHeader: null, catalogId: card.id, slug, ...patch }) .returning({ id: connections.id }); return { connectionId: row!.id, created: true }; }