peppa/packages/core/src/google.ts
peppa-bot d894f2d7cb PEP-195: привязка Gmail к учётке eGov объединяет учётки
Кто сначала вошёл через Google, получил отдельную учётку, и привязать
этот Google к учётке eGov было нельзя. Теперь привязка объединяет их:
проекты, участие в проектах, подключённые подписки, Telegram и свой бот
переходят в учётку eGov, старая отключается (core/merge-users.ts).
Учётка со своим eGov или Gitea не объединяется.

Ошибка привязки возвращается в «Настройки» (раньше уходила на /login,
откуда вошедшего перебрасывало на Главную, и текст терялся).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:10:18 +05:00

194 lines
9.6 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 { asIs, m as tr } from "@peppa/shared/i18n";
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";
import { announceNewUser } from "./new-users.ts";
import { mergeUserInto } from "./merge-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(tr("Вход через Google не настроен"));
if (purpose === "link" && !userId) throw new PeppaError(tr("Привязать 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(tr("Вход не удался — начните заново"));
const flow = await getSetting<Flow>(db, flowKey(state));
await deleteSetting(db, flowKey(state));
if (!flow || Date.now() >= flow.expiresAt) throw new PeppaError(tr("Вход устарел — начните заново"));
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(tr("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(tr("Google не вернул профиль"));
if (p.email_verified !== true) throw new PeppaError(tr("Почта в 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) {
await announceNewUser(db, row, "google");
return row;
}
const [same] = await db.select().from(users).where(eq(users.googleSub, identity.sub));
if (same) return same;
}
}
throw new PeppaError(tr("Не удалось создать пользователя"));
}
/** Which flow a Google callback belongs to, without spending it — so a failed link lands back in Settings. */
export async function googleFlowPurpose(db: Db, state: string): Promise<GooglePurpose | null> {
if (!state) return null;
return (await getSetting<Flow>(db, flowKey(state)))?.purpose ?? null;
}
/** 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) {
// PEP-195: the Google account already has its own Peppa account (the person logged in with Google
// before) — merge it into this one: for the platform it is one person. An account with its own
// eGov or Gitea identity is someone else's: never merged here.
if (other.egovIin || other.giteaId > 0) {
throw new PeppaError(tr("Этот Google-аккаунт уже входит в другую учётку ({login}). Чтобы объединить учётки, обратитесь к администратору.", { login: asIs(other.login) }));
}
await mergeUserInto(db, other.id, userId);
}
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(tr("Пользователь не найден"));
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(tr("Пользователь не найден"));
if (!user.egovIin && !user.passwordHash) throw new PeppaError(tr("Это единственный способ входа — сначала привяжите eGov"));
await db.update(users).set({ googleSub: null, googleEmail: null, googleLinkedAt: null }).where(eq(users.id, userId));
return (await getUser(db, userId))!;
}