PEP-178: every subscription shows its account — ChatGPT's e-mail is read from the sign-in, Claude's is typed at sign-in or in «Изменить»

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-16 21:26:51 +05:00
parent 186310a42b
commit 5524348974
12 changed files with 117 additions and 18 deletions

View File

@ -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"));
});
}

View File

@ -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"));
});
}

View File

@ -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;
<form action={submitLoginCode} className="flex gap-2">
<Hidden fields={{ id: s.id }} />
<Input name="code" placeholder={t("Код из Claude")} aria-label={t("Код из Claude")} autoComplete="off" required className="font-mono" />
<Input name="account" type="email" autoComplete="email" placeholder={t("Почта аккаунта Claude — по желанию")} aria-label={t("Почта аккаунта Claude")} />
<Button variant="default">{t("Подключить")}</Button>
</form>
</>
@ -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. */}
<details className="relative" data-edit-subscription={s.id}>
<summary className="cursor-pointer list-none rounded px-2 py-1 text-xs text-muted-foreground hover:text-foreground">{t("Изменить")}</summary>
<form action={renameSubscription} className="absolute right-0 z-20 mt-1 flex w-72 flex-col gap-2 rounded-lg border bg-card p-3 shadow-lg">
<Hidden fields={{ id: s.id, back: `/subscriptions#pool-${o.pool.id}` }} />
<Label>
{t("Название")}
<Input name="name" required defaultValue={s.name} className="h-8" />
</Label>
<Label>
{t("Почта аккаунта")}
<Input name="account" type="email" defaultValue={s.accountEmail ?? ""} placeholder="name@example.com" className="h-8" />
</Label>
<Button size="sm" variant="default" className="self-start">{t("Сохранить")}</Button>
</form>
</details>
<form action={checkSubscriptionAction}>
<Hidden fields={{ id: s.id }} />
<Button size="xs" variant="ghost" title={t("Проверить")} aria-label={t("Проверить")} className="text-muted-foreground">
@ -205,6 +223,8 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr
const t = await getT();
if (!(await isSuperadmin(db, user))) notFound();
const { error, added } = await searchParams;
// PEP-178: ChatGPT logins carry their account — fill in the ones signed in before it was kept.
await backfillCodexAccounts(db).catch(() => {});
let subs = await listSubscriptions(db);
// Codex device sign-ins finish on the user's device: look whether they are done.
let polled = false;

View File

@ -29,6 +29,7 @@ export async function PoolSubscriptions({ o, action }: { o: PoolOverview; action
<li key={s.id} className="flex flex-wrap items-center gap-x-2 gap-y-1 py-2 text-sm first:pt-0 last:pb-0" data-pool-subscription={s.id}>
<span className="font-medium">{s.name}</span>
{s.ownerName && !s.name.includes(s.ownerName) && <span className="text-xs text-muted-foreground" data-subscription-owner>· {s.ownerName}</span>}
{s.accountEmail && <span className="font-mono text-xs text-muted-foreground" data-subscription-account title={t("Аккаунт, под которым подключена подписка")}>· {s.accountEmail}</span>}
{!s.name.includes(KIND[s.provider]) && <span className="text-xs text-muted-foreground">{KIND[s.provider]}</span>}
<Badge variant={tone(s)}>{t.text(s.label)}</Badge>
{s.next && <Badge variant="info">{t("следующая")}</Badge>}

View File

@ -60,6 +60,8 @@ export async function SubscriptionSetup({ projectId, back, logins, shared = fals
<form action={finishOwnClaudeLoginAction} className="flex min-w-0 flex-1 flex-wrap items-center gap-2">
<Hidden fields={{ projectId, subscriptionId: l.subscriptionId, back }} />
<Input name="code" required autoComplete="off" placeholder={t("Вставьте код сюда")} aria-label={t("Код от Claude")} className="h-9 min-w-48 flex-1 font-mono" />
{/* PEP-178: Claude does not tell which account this is — the person may say it. */}
<Input name="account" type="email" autoComplete="email" placeholder={t("Почта аккаунта Claude — по желанию")} aria-label={t("Почта аккаунта Claude")} className="h-9 min-w-48 flex-1" />
<Button variant="default">{t("Готово")}</Button>
</form>
</div>

View File

@ -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,

View File

@ -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<number, number> {
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<void> {
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<string | null> {
return (await getSetting<string>(db, accountKey(id))) ?? null;
}
export async function listSubscriptions(db: Db): Promise<SubscriptionView[]> {
const rows = await db
.select({ s: subscriptions, login: users.login, personName: users.name })
@ -87,8 +103,14 @@ export async function listSubscriptions(db: Db): Promise<SubscriptionView[]> {
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<number, string>();
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,

View File

@ -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<void> {
export async function finishOwnClaudeLogin(db: Db, user: User, project: Project, subscriptionId: number, code: string, account?: string | null): Promise<void> {
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. */

View File

@ -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<PendingLogin
}
/** Types the code into setup-token and stores the token it prints on the subscription. */
export async function finishClaudeLogin(db: Db, id: number, code: string): Promise<void> {
/** 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<void> {
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<void> {
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);

View File

@ -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",
};

View File

@ -306,4 +306,9 @@ export const admin: Dict = {
"открыть": "ашу",
"с {date}": "{date} бастап",
"пароль": "құпиясөз",
"Почта аккаунта Claude — по желанию": "Claude аккаунтының поштасы — қаласаңыз",
"Почта аккаунта Claude": "Claude аккаунтының поштасы",
"Почта аккаунта": "Аккаунт поштасы",
"Аккаунт, под которым подключена подписка": "Жазылым қосылған аккаунт",
"Почта аккаунта — одной строкой, без пробелов": "Аккаунт поштасы — бір жолмен, бос орынсыз",
};

View File

@ -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(() => {});
});
});