peppa/apps/web/app/(app)/settings/page.tsx
Асель 414e4500e4 PEP-68: local users without Gitea — password login, superadmin management
- users.password_hash/password_set_at/disabled_at (migration 0002_local_users)
- core/local-users.ts: scrypt, passwordLogin with attempt limits, create/reset/disable
- isSuperadmin(db, user) = platform.admins; isUserAllowed honours disabled_at
- web: /auth/password + login form, /users for superadmins, Settings → password
- Gitea login with a local user's login is refused (giteaLoginRefusal)
- local users: projects in peppa-bot namespace, members without Gitea collaboration
- CLI: peppa user add|passwd|disable|enable; tests in testkit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 03:20:21 +05:00

222 lines
11 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.

import { ExternalLink } from "lucide-react";
import { connectedApps, isLocalUser, isSuperadmin, maskIin, MIN_PASSWORD } from "@peppa/core";
import { pendingClaudeSetup } from "@peppa/runner";
import { Hidden } from "@/components/cards";
import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input, Label } from "@/components/ui/input";
import { EgovSign } from "@/components/EgovSign";
import { Workspace } from "@/components/Workspace";
import { publicOrigin, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { changePasswordAction, cancelClaude, connectClaude, disconnectClaude, pairTelegram, revokeConnectedApp, submitClaudeCode, unlinkEgov, unpairTelegramAction } from "../actions";
const back = { back: "/settings" };
/** A connected thing: title + details on the left, actions on the right. */
function Row({ title, children, actions }: { title: React.ReactNode; children?: React.ReactNode; actions?: React.ReactNode }) {
return (
<Card className="flex-row flex-wrap items-center gap-3">
<div className="min-w-0 flex-[1_1_16rem]">
<div className="font-medium">{title}</div>
{children && <div className="text-sm text-muted-foreground">{children}</div>}
</div>
{actions && <div className="flex gap-2">{actions}</div>}
</Card>
);
}
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string; egov?: string; password?: string }> }) {
const user = await requireUser();
const { error, claude, egov, password } = await searchParams;
const local = isLocalUser(user);
const superadmin = await isSuperadmin(db, user);
const setup = await pendingClaudeSetup(db, user.id);
const apps = await connectedApps(db, user.id);
const origin = await publicOrigin();
return (
<Workspace>
<div className="max-w-2xl">
<Flash error={error} />
<PageHeader title="Настройки" />
<Section title="Учётная запись">
{password === "changed" && <Notice>Пароль изменён</Notice>}
{local ? (
<Card>
<p className="m-0 text-sm">
<span className="font-mono">{user.login}</span> — локальный пользователь Пеппы, <b>нет аккаунта Gitea</b>. Доступ к коду проектов — только через Пеппу
(агенты, PR, проверки); соавтором репозитория в Gitea вас добавить нельзя, новые проекты создаются в пространстве{" "}
<span className="font-mono">peppa-bot</span>.
</p>
<form action={changePasswordAction} className="flex flex-col gap-3" aria-label="Смена пароля">
<Hidden fields={back} />
<input type="text" name="username" value={user.login} autoComplete="username" readOnly hidden />
<div className="flex flex-wrap gap-3">
<Label className="min-w-40 flex-1">
Текущий пароль
<Input name="current" type="password" required autoComplete="current-password" />
</Label>
<Label className="min-w-40 flex-1">
Новый пароль
<Input name="newPassword" type="password" required minLength={MIN_PASSWORD} autoComplete="new-password" />
</Label>
<Label className="min-w-40 flex-1">
Повтор
<Input name="confirm" type="password" required minLength={MIN_PASSWORD} autoComplete="new-password" />
</Label>
</div>
<Button variant="default" className="self-start">Сменить пароль</Button>
</form>
</Card>
) : (
<Row title={`Gitea: ${user.login}`}>Вы входите через Gitea{user.egovIin ? " или eGov" : ""}; пароль Пеппы не нужен.</Row>
)}
{superadmin && (
<Row
title="Суперадмин"
actions={
<Button asChild size="sm">
<a href="/users">Пользователи</a>
</Button>
}
>
Локальные пользователи без Gitea: создать, сбросить пароль, отключить.
</Row>
)}
</Section>
<Section title="Claude">
{claude === "connected" && <Notice>Claude подключён</Notice>}
{setup ? (
<Card>
<p className="m-0 text-sm">1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude (нужна подписка):</p>
<Button asChild variant="default" className="self-start">
<a href={setup.url} target="_blank" rel="noreferrer">
Войти в Claude <ExternalLink />
</a>
</Button>
<p className="m-0 text-sm">2. Claude покажет код — вставьте его сюда:</p>
<form action={submitClaudeCode} className="flex gap-2">
<Hidden fields={back} />
<Input name="code" placeholder="Код из Claude" aria-label="Код из Claude" autoComplete="off" required className="font-mono" />
<Button variant="default">Подключить</Button>
</form>
<form action={cancelClaude}>
<Hidden fields={back} />
<Button variant="link" className="text-muted-foreground">Отменить</Button>
</form>
</Card>
) : user.claudeTokenEnc ? (
<Row
title="Claude подключён"
actions={
<>
<form action={connectClaude}>
<Hidden fields={back} />
<Button size="sm">Переподключить</Button>
</form>
<form action={disconnectClaude}>
<Hidden fields={back} />
<Button size="sm" variant="destructive">Отключить</Button>
</form>
</>
}
>
с {user.claudeTokenSetAt?.toLocaleDateString("ru-RU")} · сессии ваших проектов работают на вашей подписке
</Row>
) : (
<Row
title="Claude не подключён"
actions={
<form action={connectClaude}>
<Hidden fields={back} />
<Button variant="default" size="sm">Подключить Claude</Button>
</form>
}
>
Агенты ваших проектов запускаются как Claude Code. Подключите свой аккаунт Claude — Пеппа получит годовой токен через{" "}
<span className="font-mono">claude setup-token</span>, вход делаете вы сами по ссылке.
</Row>
)}
</Section>
<Section title="eGov">
{egov === "linked" && <Notice>eGov привязан — теперь можно входить по QR</Notice>}
{user.egovIin ? (
<Card>
<p className="m-0 text-sm">
Привязан ИИН <span className="font-mono">{maskIin(user.egovIin)}</span> — на странице входа можно войти через eGov QR.
</p>
<form action={unlinkEgov}>
<Hidden fields={back} />
<Button variant="destructive" size="sm">Отвязать</Button>
</form>
</Card>
) : (
<Card>
<p className="m-0 text-sm">Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. После этого можно входить в Пеппу через eGov.</p>
<div className="max-w-xs">
<EgovSign purpose="link" label="Привязать eGov" />
</div>
</Card>
)}
</Section>
<Section title="Telegram">
{user.telegramChatId ? (
<Row
title={`Telegram привязан${user.telegramUsername ? ` (@${user.telegramUsername})` : ""}`}
actions={
<form action={unpairTelegramAction}>
<Hidden fields={back} />
<Button size="sm" variant="destructive">Отвязать</Button>
</form>
}
>
Вопросы агентов из ваших и общих проектов приходят в этот чат.
</Row>
) : (
<Row
title="Telegram не привязан"
actions={
<form action={pairTelegram}>
<Hidden fields={back} />
<Button variant="default" size="sm">Привязать Telegram</Button>
</form>
}
>
Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start.
</Row>
)}
</Section>
<Section title="MCP для ChatGPT и других клиентов">
<p className="m-0 text-sm">Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Пеппы.</p>
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 font-mono text-sm">{origin}/mcp</code>
<p className="m-0 text-sm text-muted-foreground">
Как подключить и что спрашивать — в <a href="/help" className="text-primary">Помощи</a>.
</p>
</Section>
<Section title="Подключённые приложения">
{apps.length === 0 ? (
<Empty>Нет подключённых приложений.</Empty>
) : (
apps.map((a) => (
<Row
key={a.clientId}
title={a.name}
actions={
<form action={revokeConnectedApp}>
<Hidden fields={{ clientId: a.clientId, ...back }} />
<Button size="sm" variant="destructive">Отозвать</Button>
</form>
}
>
с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}
</Row>
))
)}
</Section>
</div>
</Workspace>
);
}