peppa/packages/core/src/account-merge.ts
peppa-bot f3d10a4c25 PEP-243: платформа называется FORGE — название во всех текстах для людей и подсказках агентам, адрес forge.telecom.quest
«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках
агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя».
Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 11:18:49 +05:00

183 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.

// PEP-204: the superadmin merges two accounts of one person. People who started with the Gitea login
// kept their projects on accounts nobody can enter any more (PEP-71 removed that login); they now come in
// through eGov or Google under a new account. The superadmin sees what will move, confirms, and
// `mergeUserInto` (PEP-195) moves it; the old account is switched off, its history stays under its login.
import { and, eq, inArray, isNull, sql } from "drizzle-orm";
import { chats, projectInvites, projectMembers, projects, subscriptionPools, subscriptions, users, type Db } from "@peppa/db";
import { asIs, m as tr } from "@peppa/shared/i18n";
import { logEvent } from "./audit.ts";
import { addMasterMessage } from "./chats.ts";
import { PeppaError } from "./errors.ts";
import { mergeUserInto } from "./merge-users.ts";
import { isSuperadmin, platformAdmins } from "./monitor.ts";
import { deliverToUser } from "./notifications.ts";
import { platformProjectKey } from "./platform-channel.ts";
import type { User } from "./users.ts";
/** Can the account be entered at all: eGov, Google or a password (PEP-68/71/90). */
export const canLogIn = (u: Pick<User, "egovIin" | "googleSub" | "passwordHash">) => !!(u.egovIin || u.googleSub || u.passwordHash);
export interface MergeProject {
id: number;
key: string;
name: string;
/** owner/repo in Gitea. */
repo: string;
/** The repository sits in the old account's own Gitea space: it stays there, agents reach it through peppa-bot. */
personalRepo: boolean;
}
export interface MergePlan {
from: User;
to: User;
projects: MergeProject[];
memberships: { key: string; name: string }[];
invites: number;
subscriptions: string[];
pools: string[];
masterChat: boolean;
groups: number;
telegram: boolean;
bot: string | null;
egov: boolean;
google: string | null;
/** Why the merge is not possible; null — it is. */
refusal: string | null;
/** One of the two is a superadmin and the other is not: needs its own tick. */
adminConfirm: boolean;
}
/** What `mergeAccounts(from → to)` would move. Reads only. */
export async function mergePlan(db: Db, fromId: number, toId: number): Promise<MergePlan> {
const [from] = await db.select().from(users).where(eq(users.id, fromId));
const [to] = await db.select().from(users).where(eq(users.id, toId));
if (!from || !to) throw new PeppaError(tr("Пользователь не найден"));
const owned = await db.select().from(projects).where(and(eq(projects.ownerId, fromId), isNull(projects.deletedAt)));
const member = await db
.select({ key: projects.key, name: projects.name, ownerId: projects.ownerId })
.from(projectMembers)
.innerJoin(projects, eq(projects.id, projectMembers.projectId))
.where(and(eq(projectMembers.userId, fromId), isNull(projects.deletedAt)));
const [{ n: invites } = { n: 0 }] = await db.select({ n: sql<number>`count(*)` }).from(projectInvites).where(eq(projectInvites.invitedBy, fromId));
const subs = await db.select({ name: subscriptions.name }).from(subscriptions).where(eq(subscriptions.createdBy, fromId));
const pools = await db.select({ name: subscriptionPools.name }).from(subscriptionPools).where(eq(subscriptionPools.createdBy, fromId));
const [fromChat] = await db.select({ id: chats.id }).from(chats).where(and(eq(chats.userId, fromId), eq(chats.kind, "master")));
const [toChat] = await db.select({ id: chats.id }).from(chats).where(and(eq(chats.userId, toId), eq(chats.kind, "master")));
const moveBot = !to.telegramBotTokenEnc && !!from.telegramBotTokenEnc;
const [{ n: groups } = { n: 0 }] = moveBot ? await db.select({ n: sql<number>`count(*)` }).from(chats).where(eq(chats.tgBotUserId, fromId)) : [];
const admins = new Set((await platformAdmins(db)).map((l) => l.toLowerCase()));
const giteaLogin = from.giteaId > 0 ? from.login.toLowerCase() : null;
return {
from,
to,
projects: owned.map((p) => ({ id: p.id, key: p.key, name: p.name, repo: `${p.giteaOwner}/${p.giteaRepo}`, personalRepo: !!giteaLogin && p.giteaOwner.toLowerCase() === giteaLogin })),
memberships: member.filter((p) => p.ownerId !== toId).map(({ key, name }) => ({ key, name })),
invites,
subscriptions: subs.map((s) => s.name),
pools: pools.map((p) => p.name),
masterChat: !!fromChat && !toChat,
groups,
telegram: !to.telegramChatId && !!from.telegramChatId,
bot: moveBot ? from.telegramBotUsername : null,
egov: !to.egovIin && !!from.egovIin,
google: !to.googleSub && from.googleSub ? from.googleEmail : null,
refusal: refusal(from, to),
adminConfirm: admins.has(from.login.toLowerCase()) !== admins.has(to.login.toLowerCase()),
};
}
function refusal(from: User, to: User): string | null {
if (from.id === to.id) return tr("Нельзя объединить учётку саму с собой");
if (to.disabledAt) return tr("Главная учётка отключена — сначала включите её");
if (!canLogIn(to)) return tr("В главную учётку нельзя войти — выберите ту, через которую человек входит");
if (from.egovIin && to.egovIin && from.egovIin !== to.egovIin) return tr("У учёток разные ИИН eGov — это разные люди");
return null;
}
/** The superadmin merges `fromId` into `toId` after confirming the plan (PEP-204). */
export async function mergeAccounts(
db: Db,
actor: Pick<User, "id" | "login">,
fromId: number,
toId: number,
o: { confirm: boolean; confirmAdmin?: boolean },
): Promise<MergePlan> {
if (!(await isSuperadmin(db, actor))) throw new PeppaError(tr("Не найдено"));
const plan = await mergePlan(db, fromId, toId);
if (plan.refusal) throw new PeppaError(plan.refusal);
if (!o.confirm) throw new PeppaError(tr("Подтвердите объединение"));
if (plan.adminConfirm && !o.confirmAdmin) throw new PeppaError(tr("Одна из учёток — суперадмин: подтвердите это отдельно"));
await mergeUserInto(db, fromId, toId, { identities: true });
// Journal: one entry in every project that changed hands (and in the platform project when none did).
const payload = {
from: plan.from.login,
to: plan.to.login,
by: actor.login,
projects: plan.projects.map((p) => p.key),
memberships: plan.memberships.map((p) => p.key),
subscriptions: plan.subscriptions.length,
pools: plan.pools.length,
telegram: plan.telegram,
bot: plan.bot,
};
const keys = [...plan.projects.map((p) => p.key), ...plan.memberships.map((p) => p.key)];
const touched = keys.length ? await db.select({ id: projects.id }).from(projects).where(inArray(projects.key, keys)) : [];
const ids = touched.length ? touched.map((p) => p.id) : (await db.select({ id: projects.id }).from(projects).where(eq(projects.key, platformProjectKey()))).map((p) => p.id);
for (const projectId of ids) await logEvent(db, { projectId, type: "users_merged", payload });
if (plan.projects.length || plan.memberships.length) await tellOwner(db, plan);
return plan;
}
/** One message to the main account: which projects came over. */
async function tellOwner(db: Db, plan: MergePlan): Promise<void> {
const list = [...plan.projects, ...plan.memberships].map((p) => `${p.key} «${p.name}»`).join(", ");
const text = tr("Перенесли ваши проекты со старой учётки: {list}", { list: asIs(list) });
const key = `merge:${plan.from.id}:${plan.to.id}`;
await addMasterMessage(db, plan.to.id, { kind: "event", important: true, text, dedupeKey: `master:${key}`, url: "/projects" }).catch(() => null);
const [to] = await db.select().from(users).where(eq(users.id, plan.to.id));
if (!to) return;
await deliverToUser(db, to, {
event: "chat",
dedupeKey: `${key}:${to.telegramChatId}`,
pushKey: `${key}:u${to.id}`,
telegram: { params: { text } },
push: { title: tr("FORGE"), body: text, url: "/projects", tag: key },
}).catch(() => null);
}
export interface MergeHint {
/** Has projects, membership or subscriptions but nobody can log in. */
stranded: boolean;
/** A likely active account of the same person. */
candidate: Pick<User, "id" | "login"> | null;
}
/** Hints for the «Пользователи» page: stranded accounts and their likely main account. Merges nothing. */
export async function mergeHints(db: Db, all: User[]): Promise<Map<number, MergeHint>> {
const out = new Map<number, MergeHint>();
const holders = new Set<number>();
const rows = await db.all<{ id: number }>(sql`
SELECT owner_id AS id FROM projects WHERE deleted_at IS NULL
UNION SELECT user_id FROM project_members
UNION SELECT created_by FROM subscriptions WHERE created_by IS NOT NULL`);
for (const r of rows) holders.add(r.id);
const active = all.filter((u) => !u.disabledAt && canLogIn(u));
// Compared in JS: SQLite's lower() leaves Cyrillic alone.
const norm = (s: string | null | undefined) => (s ?? "").trim().toLowerCase();
for (const u of all) {
if (canLogIn(u) || !holders.has(u.id)) continue;
const mails = new Set([norm(u.email), norm(u.googleEmail)].filter(Boolean));
const login = norm(u.login);
const others = active.filter((v) => v.id !== u.id);
const candidate =
others.find((v) => [norm(v.email), norm(v.googleEmail)].some((e) => e && mails.has(e))) ??
others.find((v) => norm(u.name) && norm(v.name) === norm(u.name)) ??
(login.length >= 3 ? others.find((v) => norm(v.login).startsWith(login)) : undefined) ??
null;
out.set(u.id, { stranded: true, candidate: candidate ? { id: candidate.id, login: candidate.login } : null });
}
return out;
}