Merge branch 'main' into task/pep-181

This commit is contained in:
peppa-bot 2026-11-16 23:36:58 +05:00
commit 2deacd6747
18 changed files with 185 additions and 23 deletions

View File

@ -810,7 +810,7 @@ export async function finishOwnClaudeLoginAction(f: FormData) {
const user = asWebActor(await requireUser()); const user = asWebActor(await requireUser());
await attempt(f, async () => { await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); 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"; "use server";
// «Подписки» (PEP-67): every action is superadmin-only (others get "not found"). // «Подписки» (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, switchAgents, cancelLogin, checkSubscription, finishClaudeLogin, removeSubscription, startClaudeLogin, startCodexLogin } from "@peppa/runner"; import { addPoolSubscription, addSubscription, switchAgents, cancelLogin, checkSubscription, finishClaudeLogin, removeSubscription, startClaudeLogin, startCodexLogin } from "@peppa/runner";
import { revalidatePath } from "next/cache"; import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
@ -82,7 +82,7 @@ export async function reconnectSubscription(f: FormData) {
export async function submitLoginCode(f: FormData) { export async function submitLoginCode(f: FormData) {
await attempt(f, async () => { await attempt(f, async () => {
const id = Number(str(f, "id")); 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}`; return `${BASE}?added=${id}#s-${id}`;
}); });
} }
@ -105,6 +105,8 @@ export async function renameSubscription(f: FormData) {
await attempt(f, async () => { await attempt(f, async () => {
if (!str(f, "name")) throw new PeppaError(m("Нужно название подписки")); if (!str(f, "name")) throw new PeppaError(m("Нужно название подписки"));
await updateSubscription(db, Number(str(f, "id")), { name: str(f, "name") }); 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 { notFound } from "next/navigation";
import { ExternalLink, KeyRound, Plus, RefreshCw } from "lucide-react"; 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 { 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 { AutoRefresh } from "@/components/AutoRefresh";
import { PoolSubscriptions, PoolSummary, PoolSwitches } from "@/components/PoolSubscriptions"; import { PoolSubscriptions, PoolSummary, PoolSwitches } from "@/components/PoolSubscriptions";
import { Hidden } from "@/components/cards"; import { Hidden } from "@/components/cards";
@ -27,6 +27,7 @@ import {
returnLoanAction, returnLoanAction,
reconnectSubscription, reconnectSubscription,
submitLoginCode, submitLoginCode,
renameSubscription,
updatePoolAction, updatePoolAction,
} from "./actions"; } from "./actions";
@ -54,6 +55,7 @@ function LoginSteps({ s, login, t }: { s: SubscriptionView; login: PendingLogin;
<form action={submitLoginCode} className="flex gap-2"> <form action={submitLoginCode} className="flex gap-2">
<Hidden fields={{ id: s.id }} /> <Hidden fields={{ id: s.id }} />
<Input name="code" placeholder={t("Код из Claude")} aria-label={t("Код из Claude")} autoComplete="off" required className="font-mono" /> <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> <Button variant="default">{t("Подключить")}</Button>
</form> </form>
</> </>
@ -100,6 +102,7 @@ function Problem({ s, login, t }: { s: SubscriptionView; login: PendingLogin | n
<Card id={`s-${s.id}`} className="gap-2"> <Card id={`s-${s.id}`} className="gap-2">
<div className="flex flex-wrap items-center gap-2 text-sm"> <div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{s.name}</span> <span className="font-medium">{s.name}</span>
{s.ownerName && !s.name.includes(s.ownerName) && <span className="text-xs text-muted-foreground">· {s.ownerName}</span>}
<span className="text-xs text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span> <span className="text-xs text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span>
{s.status === "auth_error" ? <Badge variant="danger">{t("ошибка входа")}</Badge> : <Badge variant="muted">{t("вход не закончен · {ago}", { ago: ago(s.createdAt, t) })}</Badge>} {s.status === "auth_error" ? <Badge variant="danger">{t("ошибка входа")}</Badge> : <Badge variant="muted">{t("вход не закончен · {ago}", { ago: ago(s.createdAt, t) })}</Badge>}
</div> </div>
@ -148,6 +151,7 @@ function SetCard({ o, subs, t }: { o: PoolOverview; subs: SubscriptionView[]; t:
.map((x) => ( .map((x) => (
<option key={x.id} value={x.id}> <option key={x.id} value={x.id}>
{x.name} {x.name}
{x.accountEmail ? ` · ${x.accountEmail}` : x.ownerName && !x.name.includes(x.ownerName) ? ` · ${x.ownerName}` : ""}
</option> </option>
))} ))}
</NativeSelect> </NativeSelect>
@ -156,6 +160,22 @@ function SetCard({ o, subs, t }: { o: PoolOverview; subs: SubscriptionView[]; t:
</Button> </Button>
</form> </form>
)} )}
{/* 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}> <form action={checkSubscriptionAction}>
<Hidden fields={{ id: s.id }} /> <Hidden fields={{ id: s.id }} />
<Button size="xs" variant="ghost" title={t("Проверить")} aria-label={t("Проверить")} className="text-muted-foreground"> <Button size="xs" variant="ghost" title={t("Проверить")} aria-label={t("Проверить")} className="text-muted-foreground">
@ -185,7 +205,7 @@ function SetCard({ o, subs, t }: { o: PoolOverview; subs: SubscriptionView[]; t:
<NativeSelect name="subscription" aria-label={t("Добавить подписку")} className="h-8 max-w-xs text-sm" required defaultValue=""> <NativeSelect name="subscription" aria-label={t("Добавить подписку")} className="h-8 max-w-xs text-sm" required defaultValue="">
<option value="" disabled>{t("Добавить подписку…")}</option> <option value="" disabled>{t("Добавить подписку…")}</option>
{addable.map((s) => ( {addable.map((s) => (
<option key={s.id} value={s.id}>{s.name} ({PROVIDER_NAMES[s.provider]})</option> <option key={s.id} value={s.id}>{s.name}{s.ownerName && !s.name.includes(s.ownerName) ? ` · ${s.ownerName}` : ""} ({PROVIDER_NAMES[s.provider]})</option>
))} ))}
</NativeSelect> </NativeSelect>
<Button size="sm">{t("Добавить")}</Button> <Button size="sm">{t("Добавить")}</Button>
@ -224,6 +244,8 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr
const t = await getT(); const t = await getT();
if (!(await isSuperadmin(db, user))) notFound(); if (!(await isSuperadmin(db, user))) notFound();
const { error, added, switched, left } = await searchParams; const { error, added, switched, left } = 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); let subs = await listSubscriptions(db);
// Codex device sign-ins finish on the user's device: look whether they are done. // Codex device sign-ins finish on the user's device: look whether they are done.
let polled = false; let polled = false;
@ -287,6 +309,7 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr
{loose.map((s) => ( {loose.map((s) => (
<li key={s.id} className="flex flex-wrap items-center gap-2 py-2 text-sm first:pt-0 last:pb-0"> <li key={s.id} className="flex flex-wrap items-center gap-2 py-2 text-sm first:pt-0 last:pb-0">
<span className="font-medium">{s.name}</span> <span className="font-medium">{s.name}</span>
{s.ownerName && !s.name.includes(s.ownerName) && <span className="text-xs text-muted-foreground">· {s.ownerName}</span>}
<span className="text-xs text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span> <span className="text-xs text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span>
<form action={deleteSubscriptionAction} className="ml-auto"> <form action={deleteSubscriptionAction} className="ml-auto">
<Hidden fields={{ id: s.id }} /> <Hidden fields={{ id: s.id }} />

View File

@ -28,6 +28,8 @@ export async function PoolSubscriptions({ o, action }: { o: PoolOverview; action
{o.subscriptions.map((s) => ( {o.subscriptions.map((s) => (
<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}> <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> <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>} {!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> <Badge variant={tone(s)}>{t.text(s.label)}</Badge>
{s.next && <Badge variant="info">{t("следующая")}</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"> <form action={finishOwnClaudeLoginAction} className="flex min-w-0 flex-1 flex-wrap items-center gap-2">
<Hidden fields={{ projectId, subscriptionId: l.subscriptionId, back }} /> <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" /> <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> <Button variant="default">{t("Готово")}</Button>
</form> </form>
</div> </div>

View File

@ -0,0 +1 @@
Почта хранится в `settings` `subscription.account:<id>` (без миграции). `codexAccountEmail` читает email из id_token. Видимость — как у имени (`visibleSubscriptionName`).

View File

@ -0,0 +1,7 @@
## Why
У двух подписок «Claude — asel» и «Claude 2 — asel» непонятно, какая под каким логином. Токен Claude не даёт узнать аккаунт (API профиля отвечает 403).
## What Changes
- ChatGPT: почта берётся из входа сама (id_token в auth.json); уже подключённые заполняются при открытии «Подписок».
- Claude: поле «Почта аккаунта Claude — по желанию» при подключении (мастер проекта и «Подписки») и «Изменить» (название и почта) у каждой подписки суперадмина.
- Почта показывается рядом с названием; обычным пользователям у чужих подписок — нет.

View File

@ -0,0 +1,18 @@
## ADDED Requirements
### Requirement: Подписка показывает аккаунт
Система SHALL показывать рядом с названием подписки почту аккаунта, если она известна, и скрывать её от тех, кто не видит имя подписки.
#### Scenario: ChatGPT определяет почту сам
- **GIVEN** подписка ChatGPT, вход завершён
- **WHEN** суперадмин открывает «Подписки»
- **THEN** рядом с названием видна почта из входа
#### Scenario: Claude — со слов человека
- **GIVEN** вход в Claude, человек ввёл код и почту «a@b.kz»
- **WHEN** вход завершён
- **THEN** рядом с названием видна «a@b.kz»
#### Scenario: Чужая подписка у обычного пользователя
- **GIVEN** подписка с почтой, пользователь не суперадмин и не автор
- **WHEN** он открывает настройки проекта
- **THEN** почты нет

View File

@ -0,0 +1,4 @@
- [x] Хранение и показ почты аккаунта
- [x] Чтение почты ChatGPT из входа и дозаполнение
- [x] Поле почты при подключении Claude и «Изменить»
- [x] Тест и переводы

View File

@ -183,3 +183,21 @@ Claude и делать пул с этой подпиской пулом по у
- **GIVEN** агент проекта «BS» упёрся в лимит на подписке «Claude — tatyana.saifarova 5», в пуле есть свободная «Claude — timur 2» - **GIVEN** агент проекта «BS» упёрся в лимит на подписке «Claude — tatyana.saifarova 5», в пуле есть свободная «Claude — timur 2»
- **WHEN** Peppa FACTORY переключает агента и пишет участникам проекта - **WHEN** Peppa FACTORY переключает агента и пишет участникам проекта
- **THEN** в сообщении нет текстов «tatyana.saifarova» и «timur» - **THEN** в сообщении нет текстов «tatyana.saifarova» и «timur»
### Requirement: Подписка показывает аккаунт
Система SHALL показывать рядом с названием подписки почту аккаунта, если она известна, и скрывать её от тех, кто не видит имя подписки.
#### Scenario: ChatGPT определяет почту сам
- **GIVEN** подписка ChatGPT, вход завершён
- **WHEN** суперадмин открывает «Подписки»
- **THEN** рядом с названием видна почта из входа
#### Scenario: Claude — со слов человека
- **GIVEN** вход в Claude, человек ввёл код и почту «a@b.kz»
- **WHEN** вход завершён
- **THEN** рядом с названием видна «a@b.kz»
#### Scenario: Чужая подписка у обычного пользователя
- **GIVEN** подписка с почтой, пользователь не суперадмин и не автор
- **WHEN** он открывает настройки проекта
- **THEN** почты нет

View File

@ -135,6 +135,10 @@ export interface PoolSubscriptionState {
loan: Loan | null; loan: Loan | null;
/** PEP-170: the free subscription an agent of this pool moves to when its own runs out. */ /** PEP-170: the free subscription an agent of this pool moves to when its own runs out. */
next: boolean; 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» / «ждёт входа» / «ошибка входа». */ /** «в работе: 2 агента» / «свободна» / «лимит до 15:40» / «ждёт входа» / «ошибка входа». */
label: string; label: string;
} }
@ -225,6 +229,9 @@ export async function poolOverviews(db: Db, poolIds?: number[], now = new Date()
const base = { const base = {
id: s.id, id: s.id,
name: viewer ? visibleSubscriptionName(s, viewer) : s.name, 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, provider: s.provider,
status: s.status, status: s.status,
createdBy: s.createdBy, createdBy: s.createdBy,

View File

@ -29,6 +29,10 @@ export const OPENCODE_KEY_ENV: Record<string, string> = {
export interface SubscriptionView extends Subscription { export interface SubscriptionView extends Subscription {
createdByLogin: string | null; 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; activeSessions: number;
/** PEP-39: active sessions on it per project. */ /** PEP-39: active sessions on it per project. */
projectSessions: Array<{ key: string; n: number }>; projectSessions: Array<{ key: string; n: number }>;
@ -71,9 +75,23 @@ function countBySubscription(rows: ActiveRow[]): Map<number, number> {
return m; 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[]> { export async function listSubscriptions(db: Db): Promise<SubscriptionView[]> {
const rows = await db const rows = await db
.select({ s: subscriptions, login: users.login }) .select({ s: subscriptions, login: users.login, personName: users.name })
.from(subscriptions) .from(subscriptions)
.leftJoin(users, eq(subscriptions.createdBy, users.id)) .leftJoin(users, eq(subscriptions.createdBy, users.id))
.orderBy(asc(subscriptions.id)); .orderBy(asc(subscriptions.id));
@ -85,9 +103,16 @@ 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); 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)); 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) => ({ return rows.map((r) => ({
...r.s, ...r.s,
accountEmail: accounts.get(r.s.id) ?? null,
createdByLogin: r.login, createdByLogin: r.login,
ownerName: r.personName?.trim() || r.login,
activeSessions: counts.get(r.s.id) ?? 0, activeSessions: counts.get(r.s.id) ?? 0,
projectSessions: perProject(r.s.id), projectSessions: perProject(r.s.id),
poolIds: members.filter((m) => m.subscriptionId === r.s.id).map((m) => m.poolId), poolIds: members.filter((m) => m.subscriptionId === r.s.id).map((m) => m.poolId),

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. */ /** 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); const sub = await ownPendingSubscription(db, user, project, subscriptionId);
if (sub.provider !== "claude") throw new PeppaError(m("Код нужен только для Claude")); 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. */ /** «Отмена» 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. // code; Codex itself writes auth.json there when the user confirms on their device.
import { m } from "@peppa/shared/i18n"; import { m } from "@peppa/shared/i18n";
import { execFile } from "node:child_process"; 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 { homedir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { import { deleteSetting, deleteSubscription, getSetting, getSubscription, PeppaError, setSetting, updateSubscription, type Subscription, listSubscriptions, setSubscriptionAccount } from "@peppa/core";
deleteSetting,
deleteSubscription,
getSetting,
getSubscription,
PeppaError,
setSetting,
updateSubscription,
type Subscription,
} from "@peppa/core";
import type { Db } from "@peppa/db"; import type { Db } from "@peppa/db";
import { peppaHome } from "@peppa/shared"; import { peppaHome } from "@peppa/shared";
import * as tmux from "./tmux.ts"; import * as tmux from "./tmux.ts";
@ -118,8 +109,30 @@ export async function startClaudeLogin(db: Db, id: number): Promise<PendingLogin
} }
} }
/** 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);
}
}
/** Types the code into setup-token and stores the token it prints on the subscription. */ /** 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> { export async function finishClaudeLogin(db: Db, id: number, code: string, account?: string | null): Promise<void> {
const c = code.trim(); const c = code.trim();
if (!c || /\s/.test(c)) throw new PeppaError(m("Вставьте код целиком, без пробелов")); if (!c || /\s/.test(c)) throw new PeppaError(m("Вставьте код целиком, без пробелов"));
const login = await pendingLogin(db, id); 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]; const token = TOKEN_RE.exec(screen)?.[0];
if (token) { if (token) {
await updateSubscription(db, id, { secret: token, authKind: "oauth", status: "active", checkedAt: new Date() }); 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 await endLogin(db, id); // also wipes the token from the tmux scrollback
return; return;
} }
@ -205,6 +220,8 @@ export async function pollCodexLogin(db: Db, id: number): Promise<"pending" | "a
await endLogin(db, id); await endLogin(db, id);
if (state.exitStatus === 0 && existsSync(join(codexHome(id), "auth.json"))) { if (state.exitStatus === 0 && existsSync(join(codexHome(id), "auth.json"))) {
await updateSubscription(db, id, { status: "active", checkedAt: new Date() }); await updateSubscription(db, id, { status: "active", checkedAt: new Date() });
const email = codexAccountEmail(id);
if (email) await setSubscriptionAccount(db, id, email).catch(() => {});
return "active"; return "active";
} }
const msg = screen.trim().split("\n").filter(Boolean).slice(-2).join(" ").slice(0, 200); const msg = screen.trim().split("\n").filter(Boolean).slice(-2).join(" ").slice(0, 200);

View File

@ -5,7 +5,7 @@ import { spawn } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs"; import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { createSubscription, getSubscription, OPENCODE_KEY_ENV, PeppaError, subscriptionSecret, updateSubscription, type Subscription, getPool, listSubscriptions, poolSubscriptions, updatePool } from "@peppa/core"; import { createSubscription, getSubscription, OPENCODE_KEY_ENV, PeppaError, subscriptionSecret, updateSubscription, type Subscription, getPool, listSubscriptions, poolSubscriptions, updatePool, getUser } from "@peppa/core";
import type { Db } from "@peppa/db"; import type { Db } from "@peppa/db";
import { parseResetTime } from "./limits.ts"; import { parseResetTime } from "./limits.ts";
import { codexHome, mask, removeSubscription, setClaudeSubscriptionToken, setCodexApiKey, startClaudeLogin, startCodexLogin } from "./subscription-login.ts"; import { codexHome, mask, removeSubscription, setClaudeSubscriptionToken, setCodexApiKey, startClaudeLogin, startCodexLogin } from "./subscription-login.ts";
@ -73,7 +73,9 @@ export async function addPoolSubscription(db: Db, o: { poolId: number; provider:
const taken = new Set((await listSubscriptions(db)).map((x) => x.name)); const taken = new Set((await listSubscriptions(db)).map((x) => x.name));
let n = members.filter((x) => x.provider === o.provider).length + 1; let n = members.filter((x) => x.provider === o.provider).length + 1;
while (taken.has(`${label} ${n} — ${pool.name}`)) n++; while (taken.has(`${label} ${n} — ${pool.name}`)) n++;
const s = await addSubscription(db, { provider: o.provider, name: `${label} ${n} — ${pool.name}`, method: o.provider === "codex" ? "device" : "oauth", createdBy: o.createdBy }); // PEP-177: the name says whose it is — «Claude 2 — asel», not the pool's name.
const who = (await getUser(db, o.createdBy).catch(() => null))?.login ?? pool.name;
const s = await addSubscription(db, { provider: o.provider, name: `${label} ${n} — ${who}`, method: o.provider === "codex" ? "device" : "oauth", createdBy: o.createdBy });
await updatePool(db, pool.id, { subscriptionIds: [...members.map((m) => m.id), s.id] }); await updatePool(db, pool.id, { subscriptionIds: [...members.map((m) => m.id), s.id] });
return s; return s;
} }

View File

@ -346,6 +346,12 @@ export const admin: Dict = {
"открыть": "open", "открыть": "open",
"с {date}": "since {date}", "с {date}": "since {date}",
"пароль": "password", "пароль": "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",
// Team picture (PEP-179) // Team picture (PEP-179)
"Работают: {n}": "At work: {n}", "Работают: {n}": "At work: {n}",

View File

@ -306,6 +306,11 @@ export const admin: Dict = {
"открыть": "ашу", "открыть": "ашу",
"с {date}": "{date} бастап", "с {date}": "{date} бастап",
"пароль": "құпиясөз", "пароль": "құпиясөз",
"Почта аккаунта Claude — по желанию": "Claude аккаунтының поштасы — қаласаңыз",
"Почта аккаунта Claude": "Claude аккаунтының поштасы",
"Почта аккаунта": "Аккаунт поштасы",
"Аккаунт, под которым подключена подписка": "Жазылым қосылған аккаунт",
"Почта аккаунта — одной строкой, без пробелов": "Аккаунт поштасы — бір жолмен, бос орынсыз",
// Team picture (PEP-179) // Team picture (PEP-179)
"Работают: {n}": "Жұмыста: {n}", "Работают: {n}": "Жұмыста: {n}",

View File

@ -392,11 +392,34 @@ describe("PEP-164: ещё одна подписка прямо в пул", () =>
const pool = await core.createPool(db, { name: "Пул ротации PEP-164", subscriptionIds: [first.id] }); const pool = await core.createPool(db, { name: "Пул ротации PEP-164", subscriptionIds: [first.id] });
const added = await runner.addPoolSubscription(db, { poolId: pool.id, provider: "claude", createdBy: asel.id }); const added = await runner.addPoolSubscription(db, { poolId: pool.id, provider: "claude", createdBy: asel.id });
assert.equal(added.status, "pending", "waits for the sign-in"); assert.equal(added.status, "pending", "waits for the sign-in");
assert.match(added.name, /^Claude 2 — Пул ротации PEP-164$/); assert.match(added.name, /^Claude 2 — asel$/, "PEP-177: the name says whose it is");
const members = (await core.poolSubscriptions(db, pool.id)).map((s) => s.id); const members = (await core.poolSubscriptions(db, pool.id)).map((s) => s.id);
assert.deepEqual(members, [first.id, added.id], "already a member of the pool, the first one stays"); assert.deepEqual(members, [first.id, added.id], "already a member of the pool, the first one stays");
const row = (await core.listSubscriptions(db)).find((x) => x.id === added.id)!;
assert.equal(row.ownerName, "asel", "PEP-177: the owner is shown next to the name");
const login = await runner.pendingLogin(db, added.id); const login = await runner.pendingLogin(db, added.id);
assert.ok(login?.url, "the sign-in link is ready"); assert.ok(login?.url, "the sign-in link is ready");
await runner.cancelLogin(db, added.id); 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(() => {});
});
});