// PEP-204: the superadmin merges an old Gitea account (nobody can log in) into the person's eGov account: // projects, membership and subscriptions move, the old account is switched off, history stays; nothing // happens without confirmation; ordinary users are refused; two different eGov IINs never merge. import assert from "node:assert/strict"; import { after, describe, test } from "node:test"; import { core, db, teardown } from "./helpers.ts"; process.env.PEPPA_SECRET ??= "mock-secret-for-tests"; after(teardown); const { events, projectMembers, subscriptions, subscriptionPools, users } = await import("@peppa/db"); const { and, eq } = await import("drizzle-orm"); let seq = 0; async function giteaUser(login: string, extra: { email?: string; full_name?: string } = {}) { return core.upsertUserFromGitea(db, { id: 70_000 + ++seq, login, ...extra }, { access_token: "x" }); } async function proj(key: string, ownerId: number, giteaOwner = "peppa-bot") { return core.createProject(db, { slug: `mock-${key.toLowerCase()}`, key, name: `Проект ${key}`, giteaOwner, workspacePath: `/tmp/mock-${key}`, ownerId }); } describe("merge accounts (PEP-204)", () => { test("old Gitea account into the eGov account: plan, confirmation, move, journal, one message", async () => { const admin = await giteaUser("mock-merge-admin"); await core.setPlatformAdmins(db, [admin.login]); const old = await giteaUser("mock-dana", { email: "dana@example.com" }); const main = await core.registerEgovUser(db, { iin: "900101300126", name: "МЫРЗАТАЙ ДАНА" }); await db.update(users).set({ googleSub: "g-dana", googleEmail: "dana@example.com" }).where(eq(users.id, main.id)); const own = await proj("OLDA", old.id); const personal = await proj("OLDB", old.id, "mock-dana"); const other = await giteaUser("mock-merge-other"); const shared = await proj("OTHR", other.id); await db.insert(projectMembers).values({ projectId: shared.id, userId: old.id, addedBy: other.id }); const [sub] = await db.insert(subscriptions).values({ provider: "claude", name: "Claude — mock-dana", authKind: "oauth", status: "active", createdBy: old.id }).returning(); await db.insert(subscriptionPools).values({ name: "Подписки — mock-dana", createdBy: old.id }); await core.logEvent(db, { projectId: own.id, type: "pm_comment", payload: { text: "старый комментарий", login: "mock-dana" } }); // The Users page hints: stranded account, the main one by e-mail. const hints = await core.mergeHints(db, await core.listUsers(db)); assert.deepEqual(hints.get(old.id), { stranded: true, candidate: { id: main.id, login: main.login } }); assert.equal(hints.has(main.id), false); const plan = await core.mergePlan(db, old.id, main.id); assert.equal(plan.refusal, null); assert.deepEqual(plan.projects.map((p) => [p.key, p.personalRepo]), [["OLDA", false], ["OLDB", true]]); assert.deepEqual(plan.memberships.map((p) => p.key), ["OTHR"]); assert.deepEqual(plan.subscriptions, ["Claude — mock-dana"]); // Nothing without confirmation. await assert.rejects(core.mergeAccounts(db, admin, old.id, main.id, { confirm: false }), /Подтвердите/); assert.equal((await core.getProject(db, "OLDA"))!.ownerId, old.id); assert.equal((await db.select().from(events).where(eq(events.type, "users_merged"))).length, 0); await core.mergeAccounts(db, admin, old.id, main.id, { confirm: true }); assert.equal((await core.getProject(db, "OLDA"))!.ownerId, main.id); assert.equal((await core.getProject(db, "OLDB"))!.ownerId, main.id); assert.equal((await core.getProject(db, "OLDB"))!.giteaOwner, "mock-dana", "the repository is not moved between Gitea spaces"); const members = await db.select().from(projectMembers).where(eq(projectMembers.projectId, shared.id)); assert.deepEqual(members.map((m) => m.userId), [main.id]); assert.equal((await db.select().from(subscriptions).where(eq(subscriptions.id, sub!.id)))[0]!.createdBy, main.id); const gone = (await core.getUser(db, old.id))!; assert.ok(gone.disabledAt, "the old account is switched off"); assert.equal(gone.login, "mock-dana"); const history = await db.select().from(events).where(and(eq(events.projectId, own.id), eq(events.type, "pm_comment"))); assert.equal(history.length, 1, "history stays"); const journal = await db.select().from(events).where(eq(events.type, "users_merged")); assert.deepEqual(journal.map((e) => e.projectId).sort(), [own.id, personal.id, shared.id].sort()); const p = journal[0]!.payload as { from: string; to: string; by: string; projects: string[] }; assert.equal(p.from, "mock-dana"); assert.equal(p.to, main.login); assert.equal(p.by, admin.login); assert.deepEqual(p.projects, ["OLDA", "OLDB"]); const feed = await core.masterFeed(db, main); const told = feed.filter((m) => /Перенесли ваши проекты со старой учётки/.test(m.text)); assert.equal(told.length, 1, "one message to the owner"); assert.match(told[0]!.text, /OLDA/); assert.match(told[0]!.text, /OTHR/); // A stranded account no longer: nothing left to hint. assert.equal((await core.mergeHints(db, await core.listUsers(db))).has(old.id), false); }); test("an ordinary user is refused; self, different IINs and a superadmin need care", async () => { const admin = await giteaUser("mock-merge-admin2"); await core.setPlatformAdmins(db, [...(await core.platformAdmins(db)), admin.login]); const a = await core.registerEgovUser(db, { iin: "850505400008", name: "ИВАНОВА АЙГЕРИМ" }); const b = await core.registerEgovUser(db, { iin: "870707300011", name: "ИВАНОВА АЙГЕРИМ" }); const old = await giteaUser("mock-merge-stale"); await proj("STAL", old.id); await assert.rejects(core.mergeAccounts(db, a, old.id, a.id, { confirm: true }), /Не найдено/, "only the superadmin"); assert.equal((await core.getProject(db, "STAL"))!.ownerId, old.id); await assert.rejects(core.mergeAccounts(db, admin, a.id, a.id, { confirm: true }), /саму с собой/); await assert.rejects(core.mergeAccounts(db, admin, a.id, b.id, { confirm: true }), /разные ИИН/); assert.equal((await core.getUser(db, a.id))!.disabledAt, null); // Superadmin's own old account: a separate tick. const adminEgov = await core.registerEgovUser(db, { iin: "800101300014", name: "АДМИН" }); assert.equal((await core.mergePlan(db, admin.id, adminEgov.id)).adminConfirm, true); await assert.rejects(core.mergeAccounts(db, admin, old.id, admin.id, { confirm: true }), /нельзя войти/, "main account must be one you can enter"); await assert.rejects(core.mergeAccounts(db, admin, admin.id, adminEgov.id, { confirm: true }), /суперадмин/); }); });