diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 109446db..bf94cd7b 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -792,7 +792,7 @@ export async function finishOwnClaudeLoginAction(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); - await finishOwnClaudeLogin(db, user, p, Number(str(f, "subscriptionId")), str(f, "code")); + await finishOwnClaudeLogin(db, user, p, Number(str(f, "subscriptionId")), str(f, "code"), str(f, "account")); }); } diff --git a/apps/web/app/(app)/subscriptions/actions.ts b/apps/web/app/(app)/subscriptions/actions.ts index 69106286..87ef4f74 100644 --- a/apps/web/app/(app)/subscriptions/actions.ts +++ b/apps/web/app/(app)/subscriptions/actions.ts @@ -1,7 +1,7 @@ "use server"; // «Подписки» (PEP-67): every action is superadmin-only (others get "not found"). -import { createPool, deletePool, getProject, lendSubscription, PeppaError, returnLoanNow, requireSuperadmin, setProjectPool, updatePool, updateSubscription, type SubscriptionProvider } from "@peppa/core"; +import { createPool, deletePool, getProject, lendSubscription, PeppaError, returnLoanNow, requireSuperadmin, setProjectPool, updatePool, updateSubscription, type SubscriptionProvider, setSubscriptionAccount } from "@peppa/core"; import { addPoolSubscription, addSubscription, cancelLogin, checkSubscription, finishClaudeLogin, removeSubscription, startClaudeLogin, startCodexLogin } from "@peppa/runner"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; @@ -72,7 +72,7 @@ export async function reconnectSubscription(f: FormData) { export async function submitLoginCode(f: FormData) { await attempt(f, async () => { const id = Number(str(f, "id")); - await finishClaudeLogin(db, id, str(f, "code")); + await finishClaudeLogin(db, id, str(f, "code"), str(f, "account")); return `${BASE}?added=${id}#s-${id}`; }); } @@ -95,6 +95,8 @@ export async function renameSubscription(f: FormData) { await attempt(f, async () => { if (!str(f, "name")) throw new PeppaError(m("Нужно название подписки")); await updateSubscription(db, Number(str(f, "id")), { name: str(f, "name") }); + // PEP-178: which account it is — the e-mail the person signed in with. + if (f.has("account")) await setSubscriptionAccount(db, Number(str(f, "id")), str(f, "account")); }); } diff --git a/apps/web/app/(app)/subscriptions/page.tsx b/apps/web/app/(app)/subscriptions/page.tsx index 14978795..c1ec4295 100644 --- a/apps/web/app/(app)/subscriptions/page.tsx +++ b/apps/web/app/(app)/subscriptions/page.tsx @@ -1,7 +1,7 @@ import { notFound } from "next/navigation"; import { ExternalLink, KeyRound, Plus, RefreshCw } from "lucide-react"; import { isSuperadmin, listSubscriptions, OPENCODE_KEY_ENV, PROVIDER_NAMES, poolOverviews, type PoolOverview, type SubscriptionView } from "@peppa/core"; -import { pendingLogin, pollCodexLogin, type PendingLogin } from "@peppa/runner"; +import { pendingLogin, pollCodexLogin, type PendingLogin, backfillCodexAccounts } from "@peppa/runner"; import { AutoRefresh } from "@/components/AutoRefresh"; import { PoolSubscriptions, PoolSummary, PoolSwitches } from "@/components/PoolSubscriptions"; import { Hidden } from "@/components/cards"; @@ -26,6 +26,7 @@ import { returnLoanAction, reconnectSubscription, submitLoginCode, + renameSubscription, updatePoolAction, } from "./actions"; @@ -53,6 +54,7 @@ function LoginSteps({ s, login, t }: { s: SubscriptionView; login: PendingLogin;
+ @@ -137,6 +139,22 @@ function SetCard({ o, subs, t }: { o: PoolOverview; subs: SubscriptionView[]; t: o={o} action={(s) => ( <> + {/* PEP-178: name and account of the subscription — which login it is. */} +
+ {t("Изменить")} +
+ + + + + +
diff --git a/packages/core/src/subscription-care.ts b/packages/core/src/subscription-care.ts index 095f5d60..543e4117 100644 --- a/packages/core/src/subscription-care.ts +++ b/packages/core/src/subscription-care.ts @@ -137,6 +137,8 @@ export interface PoolSubscriptionState { next: boolean; /** PEP-177: whose subscription (the person's name); null when the viewer must not see it. */ ownerName: string | null; + /** PEP-178: the account e-mail; null when the viewer must not see it. */ + accountEmail: string | null; /** «в работе: 2 агента» / «свободна» / «лимит до 15:40» / «ждёт входа» / «ошибка входа». */ label: string; } @@ -229,6 +231,7 @@ export async function poolOverviews(db: Db, poolIds?: number[], now = new Date() name: viewer ? visibleSubscriptionName(s, viewer) : s.name, // A neutral name for a non-admin hides whose it is too (PEP-121). ownerName: viewer && visibleSubscriptionName(s, viewer) !== s.name ? null : s.ownerName, + accountEmail: viewer && visibleSubscriptionName(s, viewer) !== s.name ? null : s.accountEmail, provider: s.provider, status: s.status, createdBy: s.createdBy, diff --git a/packages/core/src/subscriptions.ts b/packages/core/src/subscriptions.ts index 0cf43041..7142c5fb 100644 --- a/packages/core/src/subscriptions.ts +++ b/packages/core/src/subscriptions.ts @@ -31,6 +31,8 @@ export interface SubscriptionView extends Subscription { createdByLogin: string | null; /** PEP-177: whose subscription — the person's name (login when there is no name). */ ownerName: string | null; + /** PEP-178: which account it is (the e-mail the person signed in with) — Codex reports it, for Claude the person types it. */ + accountEmail: string | null; activeSessions: number; /** PEP-39: active sessions on it per project. */ projectSessions: Array<{ key: string; n: number }>; @@ -73,6 +75,20 @@ function countBySubscription(rows: ActiveRow[]): Map { return m; } +const accountKey = (id: number) => `subscription.account:${id}`; + +/** PEP-178: the account (e-mail) a subscription is signed in with; empty clears it. */ +export async function setSubscriptionAccount(db: Db, id: number, email: string | null | undefined): Promise { + const v = (email ?? "").trim(); + if (!v) return deleteSetting(db, accountKey(id)); + if (v.length > 200 || /\s/.test(v)) throw new PeppaError(tr("Почта аккаунта — одной строкой, без пробелов")); + await setSetting(db, accountKey(id), v); +} + +export async function subscriptionAccount(db: Db, id: number): Promise { + return (await getSetting(db, accountKey(id))) ?? null; +} + export async function listSubscriptions(db: Db): Promise { const rows = await db .select({ s: subscriptions, login: users.login, personName: users.name }) @@ -87,8 +103,14 @@ export async function listSubscriptions(db: Db): Promise { for (const a of active) if (a.subscriptionId === id) m.set(a.projectKey, (m.get(a.projectKey) ?? 0) + 1); return [...m].map(([key, n]) => ({ key, n })).sort((a, b) => a.key.localeCompare(b.key)); }; + const accounts = new Map(); + for (const r of rows) { + const a = await subscriptionAccount(db, r.s.id); + if (a) accounts.set(r.s.id, a); + } return rows.map((r) => ({ ...r.s, + accountEmail: accounts.get(r.s.id) ?? null, createdByLogin: r.login, ownerName: r.personName?.trim() || r.login, activeSessions: counts.get(r.s.id) ?? 0, diff --git a/packages/runner/src/project-subscription.ts b/packages/runner/src/project-subscription.ts index 1ac48c00..1963f673 100644 --- a/packages/runner/src/project-subscription.ts +++ b/packages/runner/src/project-subscription.ts @@ -175,10 +175,10 @@ async function ownPendingSubscription(db: Db, user: User, project: Project, subs } /** Step 3 of the Claude sign-in: the code Claude showed after the user signed in. */ -export async function finishOwnClaudeLogin(db: Db, user: User, project: Project, subscriptionId: number, code: string): Promise { +export async function finishOwnClaudeLogin(db: Db, user: User, project: Project, subscriptionId: number, code: string, account?: string | null): Promise { const sub = await ownPendingSubscription(db, user, project, subscriptionId); if (sub.provider !== "claude") throw new PeppaError(m("Код нужен только для Claude")); - await finishClaudeLogin(db, sub.id, code); + await finishClaudeLogin(db, sub.id, code, account); } /** «Отмена» of a sign-in that was not finished: the pending subscription goes away. */ diff --git a/packages/runner/src/subscription-login.ts b/packages/runner/src/subscription-login.ts index b3b4846f..a4fa6c89 100644 --- a/packages/runner/src/subscription-login.ts +++ b/packages/runner/src/subscription-login.ts @@ -6,19 +6,10 @@ // code; Codex itself writes auth.json there when the user confirms on their device. import { m } from "@peppa/shared/i18n"; import { execFile } from "node:child_process"; -import { existsSync, mkdirSync, rmSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; -import { - deleteSetting, - deleteSubscription, - getSetting, - getSubscription, - PeppaError, - setSetting, - updateSubscription, - type Subscription, -} from "@peppa/core"; +import { deleteSetting, deleteSubscription, getSetting, getSubscription, PeppaError, setSetting, updateSubscription, type Subscription, listSubscriptions, setSubscriptionAccount } from "@peppa/core"; import type { Db } from "@peppa/db"; import { peppaHome } from "@peppa/shared"; import * as tmux from "./tmux.ts"; @@ -119,7 +110,29 @@ export async function startClaudeLogin(db: Db, id: number): Promise { +/** PEP-178: the ChatGPT account of a Codex sign-in — the e-mail in auth.json's id_token. */ +export function codexAccountEmail(id: number): string | null { + try { + const auth = JSON.parse(readFileSync(join(codexHome(id), "auth.json"), "utf8")) as { tokens?: { id_token?: string } }; + const part = auth.tokens?.id_token?.split(".")[1]; + if (!part) return null; + const claims = JSON.parse(Buffer.from(part, "base64url").toString("utf8")) as { email?: string }; + return typeof claims.email === "string" && claims.email ? claims.email : null; + } catch { + return null; + } +} + +/** PEP-178: fills in the account of Codex subscriptions signed in before the e-mail was kept. */ +export async function backfillCodexAccounts(db: Db): Promise { + for (const s of await listSubscriptions(db)) { + if (s.provider !== "codex" || s.accountEmail) continue; + const email = codexAccountEmail(s.id); + if (email) await setSubscriptionAccount(db, s.id, email); + } +} + +export async function finishClaudeLogin(db: Db, id: number, code: string, account?: string | null): Promise { const c = code.trim(); if (!c || /\s/.test(c)) throw new PeppaError(m("Вставьте код целиком, без пробелов")); const login = await pendingLogin(db, id); @@ -133,6 +146,8 @@ export async function finishClaudeLogin(db: Db, id: number, code: string): Promi const token = TOKEN_RE.exec(screen)?.[0]; if (token) { await updateSubscription(db, id, { secret: token, authKind: "oauth", status: "active", checkedAt: new Date() }); + // PEP-178: Claude's token can't tell its account — the person says which one it is. + if (account?.trim()) await setSubscriptionAccount(db, id, account).catch(() => {}); await endLogin(db, id); // also wipes the token from the tmux scrollback return; } @@ -205,6 +220,8 @@ export async function pollCodexLogin(db: Db, id: number): Promise<"pending" | "a await endLogin(db, id); if (state.exitStatus === 0 && existsSync(join(codexHome(id), "auth.json"))) { await updateSubscription(db, id, { status: "active", checkedAt: new Date() }); + const email = codexAccountEmail(id); + if (email) await setSubscriptionAccount(db, id, email).catch(() => {}); return "active"; } const msg = screen.trim().split("\n").filter(Boolean).slice(-2).join(" ").slice(0, 200); diff --git a/packages/shared/src/i18n/en/admin.ts b/packages/shared/src/i18n/en/admin.ts index c78fe4fa..b6151fe5 100644 --- a/packages/shared/src/i18n/en/admin.ts +++ b/packages/shared/src/i18n/en/admin.ts @@ -346,4 +346,10 @@ export const admin: Dict = { "открыть": "open", "с {date}": "since {date}", "пароль": "password", + "Почта аккаунта Claude — по желанию": "Claude account e-mail — optional", + "Почта аккаунта Claude": "Claude account e-mail", + "Почта аккаунта": "Account e-mail", + "Изменить": "Edit", + "Аккаунт, под которым подключена подписка": "The account the subscription is signed in with", + "Почта аккаунта — одной строкой, без пробелов": "Account e-mail — one line, no spaces", }; diff --git a/packages/shared/src/i18n/kk/admin.ts b/packages/shared/src/i18n/kk/admin.ts index e2f049ce..47f544e9 100644 --- a/packages/shared/src/i18n/kk/admin.ts +++ b/packages/shared/src/i18n/kk/admin.ts @@ -306,4 +306,9 @@ export const admin: Dict = { "открыть": "ашу", "с {date}": "{date} бастап", "пароль": "құпиясөз", + "Почта аккаунта Claude — по желанию": "Claude аккаунтының поштасы — қаласаңыз", + "Почта аккаунта Claude": "Claude аккаунтының поштасы", + "Почта аккаунта": "Аккаунт поштасы", + "Аккаунт, под которым подключена подписка": "Жазылым қосылған аккаунт", + "Почта аккаунта — одной строкой, без пробелов": "Аккаунт поштасы — бір жолмен, бос орынсыз", }; diff --git a/packages/testkit/test/subscriptions.test.ts b/packages/testkit/test/subscriptions.test.ts index dc929f4f..65631649 100644 --- a/packages/testkit/test/subscriptions.test.ts +++ b/packages/testkit/test/subscriptions.test.ts @@ -402,3 +402,24 @@ describe("PEP-164: ещё одна подписка прямо в пул", () => await runner.cancelLogin(db, added.id); }); }); + +describe("PEP-178: под каким аккаунтом подписка", () => { + test("почта аккаунта: Claude — со слов человека, ChatGPT — из входа сам", async () => { + const c = await claudeSub("Claude — account test", "acct178"); + await core.setSubscriptionAccount(db, c.id, "work@example.com"); + assert.equal((await core.listSubscriptions(db)).find((x) => x.id === c.id)!.accountEmail, "work@example.com"); + await assert.rejects(core.setSubscriptionAccount(db, c.id, "two words"), /без пробелов/); + await core.setSubscriptionAccount(db, c.id, ""); + assert.equal((await core.listSubscriptions(db)).find((x) => x.id === c.id)!.accountEmail, null, "empty clears it"); + + const g = await runner.addSubscription(db, { provider: "codex", name: "ChatGPT — account test", method: "device", createdBy: asel.id }); + const claims = Buffer.from(JSON.stringify({ email: "chatgpt-user@example.com" })).toString("base64url"); + const { mkdirSync } = await import("node:fs"); + mkdirSync(runner.codexHome(g.id), { recursive: true }); + writeFileSync(join(runner.codexHome(g.id), "auth.json"), JSON.stringify({ tokens: { id_token: `x.${claims}.y` } })); + assert.equal(runner.codexAccountEmail(g.id), "chatgpt-user@example.com"); + await runner.backfillCodexAccounts(db); + assert.equal((await core.listSubscriptions(db)).find((x) => x.id === g.id)!.accountEmail, "chatgpt-user@example.com"); + await runner.cancelLogin(db, g.id).catch(() => {}); + }); +});