peppa/packages/core/src/google.ts
Асель 3159e888d2 PEP-90: sign in and register with Google (OAuth code + PKCE), link with eGov in Settings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:40:26 +05:00

174 lines
8.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Google login (PEP-90): OAuth 2.0 authorization code + PKCE. Identity is the Google account's
// stable `sub`; the e-mail (must be verified) only names a new account and is shown in Settings —
// accounts are never merged by e-mail. State lives in `settings` (one-shot, 10 min) and in an
// httpOnly cookie of the starting browser, so a forged or replayed callback is refused before
// Google is contacted. Tokens are not stored.
import { createHash, randomBytes, randomInt } from "node:crypto";
import { eq, sql } from "drizzle-orm";
import { users, type Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { hashToken } from "./crypto.ts";
import { PeppaError } from "./errors.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import { getUser, type User } from "./users.ts";
export const GOOGLE_FLOW_TTL_MS = 10 * 60_000;
export type GooglePurpose = "login" | "link";
interface Flow {
purpose: GooglePurpose;
userId: number | null;
verifier: string;
redirectUri: string;
expiresAt: number;
}
export interface GoogleIdentity {
sub: string;
email: string;
name: string | null;
}
export type GoogleResult =
| { purpose: "login"; user: User; identity: GoogleIdentity; created: boolean }
| { purpose: "link"; user: User; identity: GoogleIdentity };
const flowKey = (state: string) => `google.flow:${hashToken(state)}`;
export function googleEnabled(env = loadEnv()): boolean {
return !!env.GOOGLE_CLIENT_ID && !!env.GOOGLE_CLIENT_SECRET;
}
function endpoints() {
const b = loadEnv().GOOGLE_OAUTH_BASE?.replace(/\/$/, "");
return b
? { auth: `${b}/auth`, token: `${b}/token`, userinfo: `${b}/userinfo` }
: {
auth: "https://accounts.google.com/o/oauth2/v2/auth",
token: "https://oauth2.googleapis.com/token",
userinfo: "https://openidconnect.googleapis.com/v1/userinfo",
};
}
export interface GoogleStart {
/** Where to send the browser. */
url: string;
/** Kept by the browser in an httpOnly cookie; the callback must bring the same value back. */
state: string;
}
export async function startGoogleFlow(db: Db, purpose: GooglePurpose, redirectUri: string, userId: number | null = null): Promise<GoogleStart> {
const env = loadEnv();
if (!googleEnabled(env)) throw new PeppaError("Вход через Google не настроен");
if (purpose === "link" && !userId) throw new PeppaError("Привязать Google можно только после входа");
const state = randomBytes(24).toString("base64url");
const verifier = randomBytes(32).toString("base64url");
await setSetting(db, flowKey(state), { purpose, userId, verifier, redirectUri, expiresAt: Date.now() + GOOGLE_FLOW_TTL_MS } satisfies Flow);
const q = new URLSearchParams({
client_id: env.GOOGLE_CLIENT_ID!,
redirect_uri: redirectUri,
response_type: "code",
scope: "openid email profile",
state,
code_challenge: createHash("sha256").update(verifier).digest("base64url"),
code_challenge_method: "S256",
prompt: "select_account",
});
return { url: `${endpoints().auth}?${q}`, state };
}
async function post<T>(url: string, body: URLSearchParams): Promise<T> {
const res = await fetch(url, { method: "POST", body, headers: { "Content-Type": "application/x-www-form-urlencoded" }, signal: AbortSignal.timeout(15_000) });
const json = (await res.json().catch(() => ({}))) as T & { error?: string };
if (!res.ok) throw new PeppaError(`Google: ${json.error ?? `HTTP ${res.status}`}`);
return json;
}
/**
* Finishes the flow (one-shot: removed before anything else, whatever happens). `cookieState` is the
* state the starting browser kept; it must equal the callback's `state`.
*/
export async function completeGoogleFlow(db: Db, input: { state: string; code: string; cookieState: string }): Promise<GoogleResult> {
const { state, code, cookieState } = input;
if (!state || !code || state !== cookieState) throw new PeppaError("Вход не удался — начните заново");
const flow = await getSetting<Flow>(db, flowKey(state));
await deleteSetting(db, flowKey(state));
if (!flow || Date.now() >= flow.expiresAt) throw new PeppaError("Вход устарел — начните заново");
const env = loadEnv();
const ep = endpoints();
const tok = await post<{ access_token?: string }>(
ep.token,
new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: flow.redirectUri,
client_id: env.GOOGLE_CLIENT_ID ?? "",
client_secret: env.GOOGLE_CLIENT_SECRET ?? "",
code_verifier: flow.verifier,
}),
);
if (!tok.access_token) throw new PeppaError("Google не выдал токен");
const res = await fetch(ep.userinfo, { headers: { Authorization: `Bearer ${tok.access_token}` }, signal: AbortSignal.timeout(15_000) });
const p = (await res.json().catch(() => ({}))) as { sub?: string; email?: string; email_verified?: boolean; name?: string };
if (!res.ok || !p.sub || !p.email) throw new PeppaError("Google не вернул профиль");
if (p.email_verified !== true) throw new PeppaError("Почта в Google не подтверждена");
const identity: GoogleIdentity = { sub: p.sub, email: p.email.toLowerCase(), name: p.name?.trim() || null };
if (flow.purpose === "link") {
const user = await linkGoogle(db, flow.userId!, identity);
return { purpose: "link", user, identity };
}
const [found] = await db.select().from(users).where(eq(users.googleSub, identity.sub));
const account = found ?? (await registerGoogleUser(db, identity));
await db.update(users).set({ googleEmail: identity.email, lastLoginAt: new Date() }).where(eq(users.id, account.id));
return { purpose: "login", user: (await getUser(db, account.id))!, identity, created: !found };
}
/** "Anna.Petrova+work@x.com" → "anna.petrova"; nothing usable → "user-<last 4 of sub>". */
export function googleLoginBase(identity: GoogleIdentity): string {
const local = identity.email.split("@")[0]!.split("+")[0]!.toLowerCase().replace(/[^a-z0-9._-]/g, "");
const login = local.slice(0, 39).replace(/^[._-]+/, "");
return /^[a-z0-9][a-z0-9._-]{1,38}$/.test(login) ? login : `user-${identity.sub.slice(-4)}`;
}
/** First Google login: a Peppa account without Gitea and password (negative gitea_id), like eGov's. */
export async function registerGoogleUser(db: Db, identity: GoogleIdentity): Promise<User> {
const base = googleLoginBase(identity);
for (let n = 1; n < 1000; n++) {
const suffix = n === 1 ? "" : `-${n}`;
const login = base.slice(0, 39 - suffix.length).replace(/[._-]+$/, "") + suffix;
const [taken] = await db.select({ id: users.id }).from(users).where(sql`lower(${users.login}) = ${login}`);
if (taken) continue;
for (let i = 0; i < 5; i++) {
const [row] = await db
.insert(users)
.values({ giteaId: -1 - randomInt(2 ** 47), login, name: identity.name, googleSub: identity.sub, googleEmail: identity.email, googleLinkedAt: new Date() })
.onConflictDoNothing()
.returning();
if (row) return row;
const [same] = await db.select().from(users).where(eq(users.googleSub, identity.sub));
if (same) return same;
}
}
throw new PeppaError("Не удалось создать пользователя");
}
/** Links a Google account to `userId`. One Google account — one Peppa account. */
export async function linkGoogle(db: Db, userId: number, identity: GoogleIdentity): Promise<User> {
const [other] = await db.select().from(users).where(eq(users.googleSub, identity.sub));
if (other && other.id !== userId) throw new PeppaError("Этот Google-аккаунт уже привязан к другой учётке");
await db.update(users).set({ googleSub: identity.sub, googleEmail: identity.email, googleLinkedAt: new Date() }).where(eq(users.id, userId));
const user = await getUser(db, userId);
if (!user) throw new PeppaError("Пользователь не найден");
return user;
}
/** Unlinks Google, unless it is the account's only way in. */
export async function unlinkGoogle(db: Db, userId: number): Promise<User> {
const user = await getUser(db, userId);
if (!user) throw new PeppaError("Пользователь не найден");
if (!user.egovIin && !user.passwordHash) throw new PeppaError("Это единственный способ входа — сначала привяжите eGov");
await db.update(users).set({ googleSub: null, googleEmail: null, googleLinkedAt: null }).where(eq(users.id, userId));
return (await getUser(db, userId))!;
}