PEP-90: sign in and register with Google (OAuth code + PKCE), link with eGov in Settings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b86874e409
commit
3159e888d2
@ -28,3 +28,7 @@ PEPPA_ROOT=/Users/telecom/Dev/Peppa
|
||||
# Gitea OAuth2 app for web login (scripts/create-oauth-app.sh)
|
||||
GITEA_OAUTH_CLIENT_ID=
|
||||
GITEA_OAUTH_CLIENT_SECRET=
|
||||
|
||||
# Вход через Google (PEP-90): OAuth-клиент из Google Cloud, redirect URI <PEPPA_WEB_URL>/auth/google/callback
|
||||
# GOOGLE_CLIENT_ID=
|
||||
# GOOGLE_CLIENT_SECRET=
|
||||
|
||||
@ -12,3 +12,4 @@
|
||||
- Репозитории платформы — в организации Gitea `peppa` (PEP-4): `peppa/peppa`, `peppa/template`; старые адреса `peppa-bot/…` живут редиректом — не создавать `peppa-bot/peppa|template` заново. Проект переносит `peppa project transfer <KEY> <owner>`.
|
||||
- Чаты (PEP-62) — проекция: новое событие для чата = строка в EVENT_TEXT (core/chats.ts), код источников не трогать; сообщения короткоживущие (TTL), источник правды — events/questions/releases/incidents.
|
||||
- tmux-сервер по умолчанию: newSession чистит его глобальное окружение от GITEA_*/PEPPA_*/MOCK_*/DATABASE_URL (PEP-69; при PEPPA_TMUX_SOCKET не трогает); агенту нужное — только через new-session -e.
|
||||
- Вход через Google (PEP-90): идентичность — google_sub, по почте учётки не склеиваем; без GOOGLE_CLIENT_ID/SECRET кнопки нет; в тестах эндпоинты подменяет GOOGLE_OAUTH_BASE (mock-google). `pnpm typecheck` в apps/web может падать на устаревших .next/types (auth/callback, auth/start) — не от правок.
|
||||
|
||||
@ -48,6 +48,7 @@
|
||||
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `<KEY>-web`/`<KEY>-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/<hook_secret>` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i:<id>:backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
|
||||
- **Вход через eGov QR (PEP-65)**: relay KazEDS `sign.aitu.uz` (`KAZEDS_RELAY_BASE`, уже доверенный в eGov), `EGOV_ORGANISATION_NAME`/`EGOV_ORGANISATION_BIN` (БИН сгенерирован). `core/egov.ts`: `startEgovFlow` (документ `<auth><challenge/><nonce/></auth>`, поток в `settings` `egov.flow:<hash>`, 5 мин) → `egovFlowStatus` → `completeEgovFlow` (сверка challenge+nonce, ИИН из сертификата — свой разбор DER, `users.egov_iin`). **Подпись XMLDSig не проверяется — доверяем relay (решение PM)**. Веб: `/auth/egov/{start,status,complete}`, handle только в httpOnly cookie `peppa_egov`; `EgovSign` на странице входа и в «Настройках → eGov» (привязать/отвязать). Войти может только пользователь с привязанным ИИН и доступом (PEP-16). CLI `peppa user egov <login> <ИИН|->`. Мок `mock-kazeds-relay` (testkit; подписывает на 3-м опросе поддельным сертификатом). Пример интеграции от PM — `docs/egov-reference/`
|
||||
- **Вход только eGov (PEP-71)**: Gitea-вход и пароль убраны из веба (маршрутов `/auth/start|callback|password` нет). Неизвестный ИИН → `registerEgovUser` (core/egov.ts): учётка `gitea_id < 0` без пароля, логин `egovLoginBase` из имени сертификата («ИВАНОВА АЙГЕРИМ» → `aigerim.ivanova`, дубль `-2`, без имени `user-<4 цифры>`). Самозарегистрированный владелец (без Gitea и пароля, не админ/allowlist) без пула не получает вход машины для агентов — `mayUseMachineLogin` (core/access.ts) в `startSession`. Старым учёткам ИИН — «Настройки» (пока залогинен) или `peppa user egov`; аварийный вход — `peppa web login-link`
|
||||
- **Вход через Google (PEP-90)**: `core/google.ts` — OAuth code + PKCE; идентичность `users.google_sub` (+ `google_email`, миграция 0017), по почте учётки не склеиваются; поток `settings` `google.flow:<hash(state)>` (10 мин, одноразовый) + cookie `peppa_google` (state, привязка к браузеру; путь `/auth/google`); регистрация как у eGov (`gitea_id < 0`, логин из почты); `/auth/google/start` (POST-форма, `purpose=login|link`) и `/auth/google/callback`; включено при `GOOGLE_CLIENT_ID`+`GOOGLE_CLIENT_SECRET` (`googleEnabled`), `GOOGLE_OAUTH_BASE` подменяет эндпоинты моком `mock-google`; «Настройки → Google» (привязать/отвязать, отвязка единственного способа входа запрещена). Нужно от PM: OAuth-клиент Google Cloud, redirect URI `<PEPPA_WEB_URL>/auth/google/callback`
|
||||
- **Локальные пользователи (PEP-68)**: `users.gitea_id < 0`, вход по логину и паролю (`POST /auth/password` → `passwordLogin` в `core/local-users.ts`: scrypt `users.password_hash`, одна ошибка «Неверный логин или пароль», 5 неудач на логин / 20 на IP за 15 мин → пауза 15 мин, счётчики в `settings` `auth.fail:*`). Суперадмин = `platform.admins` (`isSuperadmin(db, user)` в core/monitor.ts): раздел `/users` — создать (временный пароль), сбросить пароль, отключить/включить (`users.disabled_at`: `isUserAllowed` → false для любого пользователя, сессии веба и MCP гаснут сразу); смена своего пароля — «Настройки». Вход через Gitea с логином локального пользователя отклоняется (`giteaLoginRefusal`), привязки Gitea к локальному аккаунту нет. Проект локального — в пространстве peppa-bot (`projectNamespace` в runner/provision.ts), участником он добавляется без соавторства в Gitea. CLI `peppa user add <login> [--admin] [--name]`, `peppa user passwd|disable|enable <login>` (пароль из stdin или сгенерированный)
|
||||
- **Секреты (PEP-54/19)**: секреты проекта — таблица `project_secrets` (имя env, `value_enc` = `encrypt`, кто менял, `last_used_at`), `core/secrets.ts` (`setProjectSecret`/`deleteProjectSecret` через `projectForUser`, имена `^[A-Z][A-Z0-9_]*$` без зарезервированных `PATH`/`PEPPA_*`/`CLAUDE_*`…, `projectSecretEnv`, `projectSecretMasker`); веб «⋯ Настройки проекта → Секреты» (значение только на запись). Раннер (`launch` в runner/sessions.ts) пишет `secrets.env` (0600) в каталог поколения, `launch.sh` его читает и сразу удаляет — значений нет в argv tmux; событие `secrets_issued {names}`. Маскировка `••••` — `TerminalFeed` (`mask`, из `terminalSse`) и `recordStep`. MCP `list_secrets` (агент — проект своей сессии; PM — доступный проект), только имена. Ревизия (core/secrets-audit.ts `secretsAudit`): секреты платформы `PLATFORM_SECRETS` (задан ли, возраст от `settings` `secrets.rotated:<NAME>`, кто использует, шаги ротации), шифрование по колонкам, MCP-токены по клиентам, подписки, секреты проектов — `/secrets` (суперадмин) и `peppa secrets audit|new-key|reencrypt|rotated|revoke-client|check-gitea|list`. Ротация `PEPPA_SECRET` двумя ключами: `PEPPA_SECRET_PREVIOUS` принимается для `decrypt`/`verify`/хэшей OAuth (`hashTokenCandidates`)/подписей вебхуков, пишется только текущим; `reencryptAll` переводит все `*_enc`. Новые зашифрованные колонки — добавлять в `encryptedColumns` (secrets-audit.ts), иначе ротация их потеряет
|
||||
- **Подписки (PEP-67)**: раздел `/subscriptions` только для суперадмина (`isSuperadmin(db, user)` в core/monitor.ts = логин из `platform.admins`; остальным пункта меню нет, URL → 404, actions в `app/(app)/subscriptions/actions.ts` через `requireSuperadmin`). Таблицы `subscriptions` (claude|codex|opencode, статус pending/active/limited/auth_error), `subscription_pools` + `subscription_pool_members`, `projects.subscription_pool_id` (пул проекта, «⋯ Настройки проекта»), `sessions.subscription_id`. Вход — runner/subscription-login.ts в tmux `peppa-auth-sub<id>`: Claude `claude setup-token` (ссылка → код → токен в `secret_enc`) или готовый токен; Codex `codex login --device-auth` (ссылка + код, страница опрашивает) или `--with-api-key`, вход живёт в своём `CODEX_HOME` = `$PEPPA_HOME/subscriptions/s<id>/codex` (0700); OpenCode — ключ провайдера (anthropic/openai/openrouter) зашифрован. «Проверить» — `checkSubscription` (runner/subscriptions.ts: `claude -p` / `codex exec` / `opencode run`). Раннер: `startSession(…, { subscriptionIds, poolId, provider })` → `pickSubscription` (отмеченные → пул → пул проекта; первая свободная активная, иначе наименее занятая; нет пула — вход машины), провайдер сессии = провайдер подписки, env подписки (`CLAUDE_CODE_OAUTH_TOKEN` / `CODEX_HOME` / ключ), resume — на той же. **Ротация (PEP-39)**: лимит (StopFailure/баннер) помечает подписку «лимит до …» (`markSubscriptionLimited`), `recordLimit` при свободной подписке того же провайдера в пуле (`rotationCandidate`: пул проекта, иначе пулы текущей подписки; наименее занятая) ставит `sessions.rotate_reason=limit` вместо пинга PM, вачдог (runner/rotation.ts `tryRotate`/`rotateSession`) убивает tmux и `resumeSession` на новой подписке — Claude/OpenCode тот же разговор, Codex заново (`conversation_id` сбрасывается, история в `CODEX_HOME` аккаунта не переносится); событие `subscription_switched` + сообщение в Telegram (`sendProjectMessage`). Порог: баннер «N% of your … limit» (≥ `PEPPA_ROTATE_THRESHOLD_PCT`, 85) → `rotate_reason=threshold`, Stop-хук не подталкивает, после хода — на подписку без сессий. Свободных нет — ждёт сброса (PEP-56); освободилась раньше — переключит. Предел `PEPPA_ROTATE_MAX_PER_HOUR` (3), выключение `PEPPA_ROTATE=off`. Справедливость: проект с ≥ `PEPPA_POOL_PROJECT_MAX` (2) подписками пула не получает свободную, пока сессия другого проекта ждёт сброса на этом пуле (`poolRestricted`). Мок: `limit.credential` в сценарии — лимит только на входе с этой подстрокой, `{warn: N}` — баннер порога. Провайдер OpenCode (`providers.ts`): `opencode <dir> --prompt`, правила и MCP из `OPENCODE_CONFIG` (opencode.json в каталоге запуска), хуков нет — статус по процессу. Миграция 0003 перенесла токены `users.claude_token_enc` (PEP-13, колонки больше не читаются) в подписки «Claude — <login>» и пулы проектов владельца. Моки: `mock-claude setup-token|-p`, `mock-codex login|exec`, `mock-opencode`
|
||||
|
||||
@ -10,6 +10,7 @@ import {
|
||||
getQuestion,
|
||||
getSession,
|
||||
PeppaError,
|
||||
unlinkGoogle,
|
||||
projectForUser,
|
||||
resolveTask,
|
||||
revokeApp,
|
||||
@ -428,6 +429,13 @@ export async function pairTelegram(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
export async function unlinkGoogleAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await unlinkGoogle(db, user.id);
|
||||
});
|
||||
}
|
||||
|
||||
export async function unpairTelegramAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
|
||||
@ -75,7 +75,7 @@ export default async function Help() {
|
||||
<li><b>Telegram</b> — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда <span className="font-mono">/newbot</span>), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Не хотите создавать — там же можно выбрать общего бота Пеппы.</li>
|
||||
<li><b>Продакт и аналитик</b> — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено.</li>
|
||||
<li><b>Команда</b> — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.</li>
|
||||
<li><b>Вход</b> — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, <span className="font-mono">aigerim.ivanova</span>). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.</li>
|
||||
<li><b>Вход</b> — через eGov QR (с телефона — кнопка «Открыть в eGov Mobile») или через Google (кнопка есть, когда суперадмин задал <span className="font-mono">GOOGLE_CLIENT_ID/SECRET</span>); в «Настройках» их можно связать в одну учётку. Первый вход сам создаёт учётку по ИИН или Google-почте: логин из имени в сертификате (например, <span className="font-mono">aigerim.ivanova</span>). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.</li>
|
||||
<li><b>Раннер</b> — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе <Link href="/runners">Раннеры</Link>: статус, стори, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и <b>живой терминал</b>: экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.</li>
|
||||
<li><b>Новый терминал</b> — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выбери проект, имя, агента и напиши промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляешь ты в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать.</li>
|
||||
<li><b>Раннеры и стори</b> — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка <code>task/…</code>, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь.</li>
|
||||
|
||||
@ -1,15 +1,16 @@
|
||||
import { connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
|
||||
import { googleEnabled, connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { ago, Disclosure, 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 { GoogleSignIn } from "@/components/GoogleSignIn";
|
||||
import { EgovSign } from "@/components/EgovSign";
|
||||
import { OwnBotSteps } from "@/components/OwnBotSteps";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { publicOrigin, requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { disconnectOwnBotAction, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
|
||||
import { unlinkGoogleAction, disconnectOwnBotAction, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
|
||||
import { PushNotifications } from "@/components/PushNotifications";
|
||||
import { TimezoneField } from "@/components/TimezoneField";
|
||||
|
||||
@ -28,9 +29,9 @@ function Row({ title, children, actions }: { title: React.ReactNode; children?:
|
||||
);
|
||||
}
|
||||
|
||||
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; notify?: string; bot?: string }> }) {
|
||||
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; google?: string; notify?: string; bot?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { error, egov, notify, bot } = await searchParams;
|
||||
const { error, egov, google, notify, bot } = await searchParams;
|
||||
const hasBot = !!user.telegramBotUsername;
|
||||
const local = isLocalUser(user);
|
||||
const superadmin = await isSuperadmin(db, user);
|
||||
@ -50,13 +51,13 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
<Card>
|
||||
<p className="m-0 text-sm">
|
||||
Логин <span className="font-mono">{user.login}</span>
|
||||
{user.name ? <> · {user.name}</> : null}. Вход в Пеппу — только через eGov QR
|
||||
{user.name ? <> · {user.name}</> : null}. Вход в Пеппу — через eGov QR или Google
|
||||
{user.egovIin ? (
|
||||
<>
|
||||
, ИИН <span className="font-mono">{maskIin(user.egovIin)}</span>.
|
||||
</>
|
||||
) : (
|
||||
<>. <b>ИИН ещё не привязан</b> — привяжите его ниже, иначе после выхода вы не сможете войти.</>
|
||||
<>. <b>ИИН ещё не привязан</b>{user.googleSub ? "." : " — привяжите его ниже или Google, иначе после выхода вы не сможете войти."}</>
|
||||
)}
|
||||
</p>
|
||||
{local && (
|
||||
@ -113,6 +114,32 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
)}
|
||||
{user.egovIin && egov === "linked" && <Notice>eGov привязан — теперь можно входить по QR</Notice>}
|
||||
|
||||
{(googleEnabled() || user.googleSub) && (
|
||||
<Section title="Google" id="google">
|
||||
{google === "linked" && <Notice>Google привязан — теперь можно входить через него</Notice>}
|
||||
{user.googleSub ? (
|
||||
<Row
|
||||
title="Google привязан"
|
||||
actions={
|
||||
<form action={unlinkGoogleAction}>
|
||||
<Hidden fields={{ back: "/settings#google" }} />
|
||||
<Button size="sm" variant="destructive">Отвязать</Button>
|
||||
</form>
|
||||
}
|
||||
>
|
||||
{user.googleEmail}. Войти через Google можно в ту же учётку.
|
||||
</Row>
|
||||
) : (
|
||||
<Card>
|
||||
<p className="m-0 text-sm">Привяжите Google-аккаунт — и в эту учётку можно будет входить и через него.</p>
|
||||
<div className="max-w-xs">
|
||||
<GoogleSignIn purpose="link" label="Привязать Google" />
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<Section title="Telegram" id="telegram">
|
||||
{bot === "connected" && <Notice>Бот @{user.telegramBotUsername} подключён — остался последний шаг: откройте его и нажмите Start.</Notice>}
|
||||
{user.telegramChatId ? (
|
||||
|
||||
@ -39,7 +39,9 @@ export default async function Users({ searchParams }: { searchParams: Promise<{
|
||||
{!local && <Badge variant="muted">Gitea</Badge>}
|
||||
{admins.has(u.login.toLowerCase()) && <Badge variant="primary">суперадмин</Badge>}
|
||||
{u.disabledAt && <Badge variant="danger">отключён</Badge>}
|
||||
{u.egovIin ? <Badge variant="muted">eGov {maskIin(u.egovIin)}</Badge> : <Badge variant="warn">без eGov — не войдёт</Badge>}
|
||||
{u.egovIin && <Badge variant="muted">eGov {maskIin(u.egovIin)}</Badge>}
|
||||
{u.googleSub && <Badge variant="muted">Google {u.googleEmail}</Badge>}
|
||||
{!u.egovIin && !u.googleSub && !u.passwordHash && <Badge variant="warn">без eGov и Google — не войдёт</Badge>}
|
||||
<span className="ml-auto text-xs text-muted-foreground">{u.lastLoginAt ? `вход ${ago(u.lastLoginAt)}` : "ещё не входил"}</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
|
||||
32
apps/web/app/auth/google/callback/route.ts
Normal file
32
apps/web/app/auth/google/callback/route.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import { completeGoogleFlow, isUserAllowed, PeppaError } from "@peppa/core";
|
||||
import { cookies } from "next/headers";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { GOOGLE_COOKIE, googleCookieOptions, publicOrigin, safeNext, sessionCookie } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
/** Google redirects here (PEP-90): checks state against the browser's cookie, then logs in, registers or links. */
|
||||
export async function GET(req: NextRequest) {
|
||||
const origin = await publicOrigin();
|
||||
const jar = await cookies();
|
||||
const cookieState = jar.get(GOOGLE_COOKIE)?.value ?? "";
|
||||
const next = safeNext(jar.get(`${GOOGLE_COOKIE}_next`)?.value);
|
||||
const q = req.nextUrl.searchParams;
|
||||
const done = (path: string, error?: string) => {
|
||||
const res = NextResponse.redirect(`${origin}${path}${error ? `${path.includes("?") ? "&" : "?"}error=${encodeURIComponent(error)}` : ""}`, 303);
|
||||
res.cookies.set(GOOGLE_COOKIE, "", googleCookieOptions(0));
|
||||
res.cookies.set(`${GOOGLE_COOKIE}_next`, "", googleCookieOptions(0));
|
||||
return res;
|
||||
};
|
||||
if (q.get("error")) return done("/login", q.get("error") === "access_denied" ? "Вход через Google отменён" : "Google отказал во входе");
|
||||
try {
|
||||
const r = await completeGoogleFlow(db, { state: q.get("state") ?? "", code: q.get("code") ?? "", cookieState });
|
||||
if (r.purpose === "link") return done("/settings?google=linked");
|
||||
if (!(await isUserAllowed(db, r.user))) return done("/login", "Учётка отключена — обратитесь к администратору");
|
||||
const res = done(next);
|
||||
const c = sessionCookie(r.user.id);
|
||||
res.cookies.set(c.name, c.value, c.options);
|
||||
return res;
|
||||
} catch (e) {
|
||||
return done("/login", e instanceof PeppaError ? e.message : "Не удалось войти через Google");
|
||||
}
|
||||
}
|
||||
25
apps/web/app/auth/google/start/route.ts
Normal file
25
apps/web/app/auth/google/start/route.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import { PeppaError, startGoogleFlow } from "@peppa/core";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { currentUser, GOOGLE_COOKIE, googleCookieOptions, publicOrigin, safeNext } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
/** Starts a Google login (PEP-90) or, from Settings (`purpose=link`, needs a session), linking. POST form → 303 to Google. */
|
||||
export async function POST(req: NextRequest) {
|
||||
const origin = await publicOrigin();
|
||||
const form = await req.formData().catch(() => null);
|
||||
const purpose = form?.get("purpose") === "link" ? "link" : "login";
|
||||
const next = safeNext(String(form?.get("next") ?? ""));
|
||||
const fail = (msg: string) => NextResponse.redirect(`${origin}${purpose === "link" ? "/settings" : "/login"}?error=${encodeURIComponent(msg)}`, 303);
|
||||
try {
|
||||
const user = purpose === "link" ? await currentUser() : null;
|
||||
if (purpose === "link" && !user) return fail("Войдите, чтобы привязать Google");
|
||||
const flow = await startGoogleFlow(db, purpose, `${origin}/auth/google/callback`, user?.id ?? null);
|
||||
const res = NextResponse.redirect(flow.url, 303);
|
||||
res.cookies.set(GOOGLE_COOKIE, flow.state, googleCookieOptions(600));
|
||||
// Where to go after login: a separate cookie value would leak into the URL, so keep it beside the state.
|
||||
res.cookies.set(`${GOOGLE_COOKIE}_next`, next, googleCookieOptions(600));
|
||||
return res;
|
||||
} catch (e) {
|
||||
return fail(e instanceof PeppaError ? e.message : "Не удалось начать вход через Google");
|
||||
}
|
||||
}
|
||||
@ -1,7 +1,9 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { Check, Laptop, MessageCircle, ShieldCheck, Sparkles } from "lucide-react";
|
||||
import { googleEnabled } from "@peppa/core";
|
||||
import { currentUser, safeNext } from "@/lib/auth";
|
||||
import { Brand } from "@/components/Brand";
|
||||
import { GoogleSignIn } from "@/components/GoogleSignIn";
|
||||
import { Flash } from "@/components/common";
|
||||
import { EgovSign } from "@/components/EgovSign";
|
||||
import { Footer } from "@/components/Footer";
|
||||
@ -16,7 +18,7 @@ const WHY = [
|
||||
];
|
||||
|
||||
const STEPS = [
|
||||
{ title: "Войдите с ноутбука", text: "Через eGov QR — учётка создаётся сама, пароль не нужен." },
|
||||
{ title: "Войдите с ноутбука", text: "Через eGov QR или Google — учётка создаётся сама, пароль не нужен." },
|
||||
{ title: "Привяжите Telegram-бота", text: "Он на телефоне позовёт вас, когда агенту нужен ответ или работа готова." },
|
||||
{ title: "Создайте проект и подключите подписку", text: "Свою Claude или ChatGPT — на ней агенты пишут код. Это одна минута." },
|
||||
{ title: "Опишите задачу словами", text: "«Страница с каталогом: фото, цена, кнопка „Купить“». Агент возьмёт её сам." },
|
||||
@ -48,9 +50,10 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
|
||||
<aside className="flex flex-col items-center gap-4 rounded-2xl border bg-card p-6 text-center lg:sticky lg:top-10 lg:col-start-2 lg:row-span-2 lg:row-start-1">
|
||||
<PugMascot mood="alert" size={112} />
|
||||
<h2 className="m-0 text-xl font-semibold">Начать — одна минута</h2>
|
||||
<p className="m-0 text-sm text-muted-foreground">Вход через eGov. Первый вход сам создаёт учётку — регистрироваться отдельно не нужно.</p>
|
||||
<p className="m-0 text-sm text-muted-foreground">Вход через eGov или Google. Первый вход сам создаёт учётку — регистрироваться отдельно не нужно.</p>
|
||||
<Flash error={error} />
|
||||
<EgovSign purpose="login" next={safeNext(next)} label="Войти через eGov" />
|
||||
{googleEnabled() && <GoogleSignIn purpose="login" next={safeNext(next)} label="Войти через Google" />}
|
||||
<p className="m-0 text-xs text-muted-foreground lg:hidden">Вы с телефона? Войти можно и отсюда, но управлять фабрикой удобнее с ноутбука.</p>
|
||||
</aside>
|
||||
|
||||
|
||||
20
apps/web/components/GoogleSignIn.tsx
Normal file
20
apps/web/components/GoogleSignIn.tsx
Normal file
@ -0,0 +1,20 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
/** «Войти через Google» / «Привязать Google» (PEP-90): обычная форма, браузер уходит на Google. */
|
||||
export function GoogleSignIn({ purpose, next, label }: { purpose: "login" | "link"; next?: string; label: string }) {
|
||||
return (
|
||||
<form method="post" action="/auth/google/start" className="w-full">
|
||||
<input type="hidden" name="purpose" value={purpose} />
|
||||
{next && <input type="hidden" name="next" value={next} />}
|
||||
<Button type="submit" variant="outline" size="lg" className="w-full">
|
||||
<svg aria-hidden viewBox="0 0 48 48" className="size-4">
|
||||
<path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9.1 3.6l6.8-6.8C35.8 2.4 30.3 0 24 0 14.6 0 6.5 5.4 2.6 13.2l7.9 6.1C12.4 13.6 17.7 9.5 24 9.5z" />
|
||||
<path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.7c-.6 3-2.3 5.5-4.8 7.2l7.5 5.8c4.4-4.1 7.1-10.1 7.1-17.5z" />
|
||||
<path fill="#FBBC05" d="M10.5 28.7c-.5-1.5-.8-3-.8-4.7s.3-3.2.8-4.7l-7.9-6.1C.9 16.4 0 20.1 0 24s.9 7.6 2.6 10.8l7.9-6.1z" />
|
||||
<path fill="#34A853" d="M24 48c6.5 0 11.9-2.1 15.9-5.8l-7.5-5.8c-2.1 1.4-4.9 2.3-8.4 2.3-6.3 0-11.6-4.1-13.5-9.8l-7.9 6.1C6.5 42.6 14.6 48 24 48z" />
|
||||
</svg>
|
||||
{label}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@ -54,6 +54,10 @@ export function sessionCookie(uid: number) {
|
||||
|
||||
export const egovCookieOptions = (maxAgeSec: number) => ({ httpOnly: true, sameSite: "lax" as const, secure: isHttps(), path: "/auth/egov", maxAge: maxAgeSec });
|
||||
|
||||
/** Google OAuth state (PEP-90): binds the callback to the browser that started the flow. */
|
||||
export const GOOGLE_COOKIE = "peppa_google";
|
||||
export const googleCookieOptions = (maxAgeSec: number) => ({ httpOnly: true, sameSite: "lax" as const, secure: isHttps(), path: "/auth/google", maxAge: maxAgeSec });
|
||||
|
||||
const isHttps = () => loadEnv().PEPPA_WEB_URL.startsWith("https://");
|
||||
|
||||
/**
|
||||
|
||||
@ -0,0 +1,8 @@
|
||||
# Design: PEP-90
|
||||
|
||||
- Новые колонки `users.google_sub` (unique), `users.google_email`, `users.google_linked_at` (миграция 0017). Идентичность — только `sub`; почта показывается и даёт логин, но по ней учётки **не склеиваются** (иначе чужая почта угоняет учётку).
|
||||
- `core/google.ts`: `startGoogleFlow` (state и PKCE verifier, поток в `settings` `google.flow:<hash(state)>`, 10 мин; state ещё и в httpOnly cookie `peppa_google` — привязка к браузеру), `completeGoogleFlow` (поток удаляется до обмена: одноразовый; сверка cookie-state; обмен code на токены; профиль через `userinfo`; требуем `email_verified`). Токены не храним.
|
||||
- Эндпоинты Google берутся из `GOOGLE_OAUTH_BASE` (по умолчанию настоящие `accounts.google.com`/`oauth2.googleapis.com`), чтобы подменять моком. Включено, только если заданы `GOOGLE_CLIENT_ID` и `GOOGLE_CLIENT_SECRET` (`googleEnabled`).
|
||||
- Регистрация: логин из локальной части почты (латиница/цифры, дубль `-2`), `gitea_id < 0`, без пароля; подписки и `mayUseMachineLogin` работают как у eGov (по `gitea_id < 0`).
|
||||
- Привязка (`purpose: link`) — только вошедшим; Google-аккаунт, занятый другой учёткой, отклоняется. Отвязать нельзя, если это единственный способ входа.
|
||||
- Маршруты: `/auth/google/start` (редирект на Google), `/auth/google/callback`.
|
||||
@ -0,0 +1,14 @@
|
||||
# PEP-90: Вход и регистрация через Google-почту
|
||||
|
||||
## Зачем
|
||||
Сейчас в Пеппу входят только через eGov QR (PEP-71). Нужен и обычный вход «через Google»: не у всех под рукой eGov Mobile.
|
||||
|
||||
## Что меняется
|
||||
- На странице входа рядом с eGov — кнопка «Войти через Google» (OAuth 2.0 authorization code + PKCE).
|
||||
- Первый вход создаёт учётку как у eGov: без Gitea и пароля, логин из адреса почты; следующий находит её по Google-аккаунту (`sub`).
|
||||
- В «Настройках» можно привязать Google к учётке eGov, а eGov — к учётке Google (оба способа ведут в одну учётку).
|
||||
- Отключённый пользователь войти не может; state/code одноразовые и привязаны к браузеру.
|
||||
- Мок Google OAuth (`mock-google`) для тестов и работы до выдачи OAuth-клиента.
|
||||
|
||||
## Нужно от PM
|
||||
OAuth-клиент в Google Cloud (Web application): redirect URI `https://peppa.telecom.quest/auth/google/callback`, `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` в `.env`. Без них кнопки Google нет.
|
||||
@ -0,0 +1,43 @@
|
||||
# Spec Delta: web-auth
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Вход через Google
|
||||
Страница входа SHALL предлагать «Войти через Google», если на платформе настроен OAuth-клиент Google. Первый вход SHALL создавать учётку без Gitea и пароля, последующие — находить её по идентификатору Google-аккаунта. Отключённый пользователь SHALL не входить. Ответ Google SHALL приниматься только один раз и только в браузере, начавшем вход.
|
||||
|
||||
#### Scenario: Первый вход через Google
|
||||
- **GIVEN** Google подтвердил почту «anna.petrova@example.com» аккаунта с идентификатором «g-1001», учётки с ним нет
|
||||
- **WHEN** пользователь возвращается с Google с верными state и code
|
||||
- **THEN** создаётся учётка с логином «anna.petrova» без пароля и Gitea
|
||||
- **AND** открывается сессия веба
|
||||
|
||||
#### Scenario: Повторный вход
|
||||
- **GIVEN** учётка «anna.petrova» создана входом через Google «g-1001»
|
||||
- **WHEN** тот же Google-аккаунт входит снова
|
||||
- **THEN** открывается сессия той же учётки, новая не создаётся
|
||||
|
||||
#### Scenario: Отключённый пользователь
|
||||
- **GIVEN** учётка «anna.petrova» отключена администратором
|
||||
- **WHEN** она входит через Google
|
||||
- **THEN** вход отклонён и сессия не открывается
|
||||
|
||||
#### Scenario: Подделанный или повторный ответ
|
||||
- **WHEN** в callback приходит чужой или повторно использованный state, либо state без cookie начавшего браузера
|
||||
- **THEN** вход отклонён без обращения к Google и без создания учётки
|
||||
|
||||
#### Scenario: Непотверждённая почта
|
||||
- **WHEN** Google отвечает `email_verified: false`
|
||||
- **THEN** вход отклонён
|
||||
|
||||
### Requirement: Связка eGov и Google
|
||||
Вошедший пользователь SHALL привязывать Google к учётке eGov и eGov к учётке Google в «Настройках»; один Google-аккаунт — одна учётка.
|
||||
|
||||
#### Scenario: Привязка Google к учётке eGov
|
||||
- **GIVEN** пользователь вошёл через eGov
|
||||
- **WHEN** он привязывает Google-аккаунт «g-2002» в «Настройках»
|
||||
- **THEN** вход через Google ведёт в ту же учётку
|
||||
|
||||
#### Scenario: Google-аккаунт занят
|
||||
- **GIVEN** Google-аккаунт «g-1001» привязан к учётке «anna.petrova»
|
||||
- **WHEN** другой пользователь пытается привязать «g-1001»
|
||||
- **THEN** привязка отклонена с сообщением, что аккаунт уже привязан
|
||||
@ -0,0 +1,11 @@
|
||||
# Tasks: PEP-90
|
||||
|
||||
## 1. Данные и ядро
|
||||
- [x] 1.1 Колонки `users.google_*`, миграция 0017, env `GOOGLE_CLIENT_ID/SECRET/OAUTH_BASE`
|
||||
- [x] 1.2 `core/google.ts`: start/complete/link/unlink, регистрация, `googleEnabled`
|
||||
- [x] 1.3 `mock-google` в testkit
|
||||
## 2. Веб
|
||||
- [x] 2.1 Маршруты `/auth/google/start|callback`
|
||||
- [x] 2.2 Кнопка на странице входа; «Настройки» (привязать/отвязать Google, привязать eGov учётке Google); `/users`
|
||||
## 3. Проверка
|
||||
- [x] 3.1 e2e `google.test.ts`, typecheck, документация (`/help`, AGENTS.md)
|
||||
@ -193,3 +193,43 @@ nonce, созданные сервером для этого потока; по
|
||||
#### Scenario: Посторонний
|
||||
- **WHEN** пользователь, не владелец и не суперадмин, пытается добавить участника в «PAY»
|
||||
- **THEN** действие отклонено
|
||||
|
||||
### Requirement: Вход через Google
|
||||
Страница входа SHALL предлагать «Войти через Google», если на платформе настроен OAuth-клиент Google. Первый вход SHALL создавать учётку без Gitea и пароля, последующие — находить её по идентификатору Google-аккаунта. Отключённый пользователь SHALL не входить. Ответ Google SHALL приниматься только один раз и только в браузере, начавшем вход.
|
||||
|
||||
#### Scenario: Первый вход через Google
|
||||
- **GIVEN** Google подтвердил почту «anna.petrova@example.com» аккаунта с идентификатором «g-1001», учётки с ним нет
|
||||
- **WHEN** пользователь возвращается с Google с верными state и code
|
||||
- **THEN** создаётся учётка с логином «anna.petrova» без пароля и Gitea
|
||||
- **AND** открывается сессия веба
|
||||
|
||||
#### Scenario: Повторный вход
|
||||
- **GIVEN** учётка «anna.petrova» создана входом через Google «g-1001»
|
||||
- **WHEN** тот же Google-аккаунт входит снова
|
||||
- **THEN** открывается сессия той же учётки, новая не создаётся
|
||||
|
||||
#### Scenario: Отключённый пользователь
|
||||
- **GIVEN** учётка «anna.petrova» отключена администратором
|
||||
- **WHEN** она входит через Google
|
||||
- **THEN** вход отклонён и сессия не открывается
|
||||
|
||||
#### Scenario: Подделанный или повторный ответ
|
||||
- **WHEN** в callback приходит чужой или повторно использованный state, либо state без cookie начавшего браузера
|
||||
- **THEN** вход отклонён без обращения к Google и без создания учётки
|
||||
|
||||
#### Scenario: Непотверждённая почта
|
||||
- **WHEN** Google отвечает `email_verified: false`
|
||||
- **THEN** вход отклонён
|
||||
|
||||
### Requirement: Связка eGov и Google
|
||||
Вошедший пользователь SHALL привязывать Google к учётке eGov и eGov к учётке Google в «Настройках»; один Google-аккаунт — одна учётка.
|
||||
|
||||
#### Scenario: Привязка Google к учётке eGov
|
||||
- **GIVEN** пользователь вошёл через eGov
|
||||
- **WHEN** он привязывает Google-аккаунт «g-2002» в «Настройках»
|
||||
- **THEN** вход через Google ведёт в ту же учётку
|
||||
|
||||
#### Scenario: Google-аккаунт занят
|
||||
- **GIVEN** Google-аккаунт «g-1001» привязан к учётке «anna.petrova»
|
||||
- **WHEN** другой пользователь пытается привязать «g-1001»
|
||||
- **THEN** привязка отклонена с сообщением, что аккаунт уже привязан
|
||||
|
||||
173
packages/core/src/google.ts
Normal file
173
packages/core/src/google.ts
Normal file
@ -0,0 +1,173 @@
|
||||
// Google login (PEP-90): OAuth 2.0 authorization code + PKCE. Identity is the Google account's
|
||||
// stable `sub`; the e-mail (must be verified) only names a new account and is shown in Settings —
|
||||
// accounts are never merged by e-mail. State lives in `settings` (one-shot, 10 min) and in an
|
||||
// httpOnly cookie of the starting browser, so a forged or replayed callback is refused before
|
||||
// Google is contacted. Tokens are not stored.
|
||||
import { createHash, randomBytes, randomInt } from "node:crypto";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { users, type Db } from "@peppa/db";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { hashToken } from "./crypto.ts";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
import { getUser, type User } from "./users.ts";
|
||||
|
||||
export const GOOGLE_FLOW_TTL_MS = 10 * 60_000;
|
||||
export type GooglePurpose = "login" | "link";
|
||||
|
||||
interface Flow {
|
||||
purpose: GooglePurpose;
|
||||
userId: number | null;
|
||||
verifier: string;
|
||||
redirectUri: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export interface GoogleIdentity {
|
||||
sub: string;
|
||||
email: string;
|
||||
name: string | null;
|
||||
}
|
||||
|
||||
export type GoogleResult =
|
||||
| { purpose: "login"; user: User; identity: GoogleIdentity; created: boolean }
|
||||
| { purpose: "link"; user: User; identity: GoogleIdentity };
|
||||
|
||||
const flowKey = (state: string) => `google.flow:${hashToken(state)}`;
|
||||
|
||||
export function googleEnabled(env = loadEnv()): boolean {
|
||||
return !!env.GOOGLE_CLIENT_ID && !!env.GOOGLE_CLIENT_SECRET;
|
||||
}
|
||||
|
||||
function endpoints() {
|
||||
const b = loadEnv().GOOGLE_OAUTH_BASE?.replace(/\/$/, "");
|
||||
return b
|
||||
? { auth: `${b}/auth`, token: `${b}/token`, userinfo: `${b}/userinfo` }
|
||||
: {
|
||||
auth: "https://accounts.google.com/o/oauth2/v2/auth",
|
||||
token: "https://oauth2.googleapis.com/token",
|
||||
userinfo: "https://openidconnect.googleapis.com/v1/userinfo",
|
||||
};
|
||||
}
|
||||
|
||||
export interface GoogleStart {
|
||||
/** Where to send the browser. */
|
||||
url: string;
|
||||
/** Kept by the browser in an httpOnly cookie; the callback must bring the same value back. */
|
||||
state: string;
|
||||
}
|
||||
|
||||
export async function startGoogleFlow(db: Db, purpose: GooglePurpose, redirectUri: string, userId: number | null = null): Promise<GoogleStart> {
|
||||
const env = loadEnv();
|
||||
if (!googleEnabled(env)) throw new PeppaError("Вход через Google не настроен");
|
||||
if (purpose === "link" && !userId) throw new PeppaError("Привязать Google можно только после входа");
|
||||
const state = randomBytes(24).toString("base64url");
|
||||
const verifier = randomBytes(32).toString("base64url");
|
||||
await setSetting(db, flowKey(state), { purpose, userId, verifier, redirectUri, expiresAt: Date.now() + GOOGLE_FLOW_TTL_MS } satisfies Flow);
|
||||
const q = new URLSearchParams({
|
||||
client_id: env.GOOGLE_CLIENT_ID!,
|
||||
redirect_uri: redirectUri,
|
||||
response_type: "code",
|
||||
scope: "openid email profile",
|
||||
state,
|
||||
code_challenge: createHash("sha256").update(verifier).digest("base64url"),
|
||||
code_challenge_method: "S256",
|
||||
prompt: "select_account",
|
||||
});
|
||||
return { url: `${endpoints().auth}?${q}`, state };
|
||||
}
|
||||
|
||||
async function post<T>(url: string, body: URLSearchParams): Promise<T> {
|
||||
const res = await fetch(url, { method: "POST", body, headers: { "Content-Type": "application/x-www-form-urlencoded" }, signal: AbortSignal.timeout(15_000) });
|
||||
const json = (await res.json().catch(() => ({}))) as T & { error?: string };
|
||||
if (!res.ok) throw new PeppaError(`Google: ${json.error ?? `HTTP ${res.status}`}`);
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes the flow (one-shot: removed before anything else, whatever happens). `cookieState` is the
|
||||
* state the starting browser kept; it must equal the callback's `state`.
|
||||
*/
|
||||
export async function completeGoogleFlow(db: Db, input: { state: string; code: string; cookieState: string }): Promise<GoogleResult> {
|
||||
const { state, code, cookieState } = input;
|
||||
if (!state || !code || state !== cookieState) throw new PeppaError("Вход не удался — начните заново");
|
||||
const flow = await getSetting<Flow>(db, flowKey(state));
|
||||
await deleteSetting(db, flowKey(state));
|
||||
if (!flow || Date.now() >= flow.expiresAt) throw new PeppaError("Вход устарел — начните заново");
|
||||
const env = loadEnv();
|
||||
const ep = endpoints();
|
||||
const tok = await post<{ access_token?: string }>(
|
||||
ep.token,
|
||||
new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
code,
|
||||
redirect_uri: flow.redirectUri,
|
||||
client_id: env.GOOGLE_CLIENT_ID ?? "",
|
||||
client_secret: env.GOOGLE_CLIENT_SECRET ?? "",
|
||||
code_verifier: flow.verifier,
|
||||
}),
|
||||
);
|
||||
if (!tok.access_token) throw new PeppaError("Google не выдал токен");
|
||||
const res = await fetch(ep.userinfo, { headers: { Authorization: `Bearer ${tok.access_token}` }, signal: AbortSignal.timeout(15_000) });
|
||||
const p = (await res.json().catch(() => ({}))) as { sub?: string; email?: string; email_verified?: boolean; name?: string };
|
||||
if (!res.ok || !p.sub || !p.email) throw new PeppaError("Google не вернул профиль");
|
||||
if (p.email_verified !== true) throw new PeppaError("Почта в Google не подтверждена");
|
||||
const identity: GoogleIdentity = { sub: p.sub, email: p.email.toLowerCase(), name: p.name?.trim() || null };
|
||||
|
||||
if (flow.purpose === "link") {
|
||||
const user = await linkGoogle(db, flow.userId!, identity);
|
||||
return { purpose: "link", user, identity };
|
||||
}
|
||||
const [found] = await db.select().from(users).where(eq(users.googleSub, identity.sub));
|
||||
const account = found ?? (await registerGoogleUser(db, identity));
|
||||
await db.update(users).set({ googleEmail: identity.email, lastLoginAt: new Date() }).where(eq(users.id, account.id));
|
||||
return { purpose: "login", user: (await getUser(db, account.id))!, identity, created: !found };
|
||||
}
|
||||
|
||||
/** "Anna.Petrova+work@x.com" → "anna.petrova"; nothing usable → "user-<last 4 of sub>". */
|
||||
export function googleLoginBase(identity: GoogleIdentity): string {
|
||||
const local = identity.email.split("@")[0]!.split("+")[0]!.toLowerCase().replace(/[^a-z0-9._-]/g, "");
|
||||
const login = local.slice(0, 39).replace(/^[._-]+/, "");
|
||||
return /^[a-z0-9][a-z0-9._-]{1,38}$/.test(login) ? login : `user-${identity.sub.slice(-4)}`;
|
||||
}
|
||||
|
||||
/** First Google login: a Peppa account without Gitea and password (negative gitea_id), like eGov's. */
|
||||
export async function registerGoogleUser(db: Db, identity: GoogleIdentity): Promise<User> {
|
||||
const base = googleLoginBase(identity);
|
||||
for (let n = 1; n < 1000; n++) {
|
||||
const suffix = n === 1 ? "" : `-${n}`;
|
||||
const login = base.slice(0, 39 - suffix.length).replace(/[._-]+$/, "") + suffix;
|
||||
const [taken] = await db.select({ id: users.id }).from(users).where(sql`lower(${users.login}) = ${login}`);
|
||||
if (taken) continue;
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const [row] = await db
|
||||
.insert(users)
|
||||
.values({ giteaId: -1 - randomInt(2 ** 47), login, name: identity.name, googleSub: identity.sub, googleEmail: identity.email, googleLinkedAt: new Date() })
|
||||
.onConflictDoNothing()
|
||||
.returning();
|
||||
if (row) return row;
|
||||
const [same] = await db.select().from(users).where(eq(users.googleSub, identity.sub));
|
||||
if (same) return same;
|
||||
}
|
||||
}
|
||||
throw new PeppaError("Не удалось создать пользователя");
|
||||
}
|
||||
|
||||
/** Links a Google account to `userId`. One Google account — one Peppa account. */
|
||||
export async function linkGoogle(db: Db, userId: number, identity: GoogleIdentity): Promise<User> {
|
||||
const [other] = await db.select().from(users).where(eq(users.googleSub, identity.sub));
|
||||
if (other && other.id !== userId) throw new PeppaError("Этот Google-аккаунт уже привязан к другой учётке");
|
||||
await db.update(users).set({ googleSub: identity.sub, googleEmail: identity.email, googleLinkedAt: new Date() }).where(eq(users.id, userId));
|
||||
const user = await getUser(db, userId);
|
||||
if (!user) throw new PeppaError("Пользователь не найден");
|
||||
return user;
|
||||
}
|
||||
|
||||
/** Unlinks Google, unless it is the account's only way in. */
|
||||
export async function unlinkGoogle(db: Db, userId: number): Promise<User> {
|
||||
const user = await getUser(db, userId);
|
||||
if (!user) throw new PeppaError("Пользователь не найден");
|
||||
if (!user.egovIin && !user.passwordHash) throw new PeppaError("Это единственный способ входа — сначала привяжите eGov");
|
||||
await db.update(users).set({ googleSub: null, googleEmail: null, googleLinkedAt: null }).where(eq(users.id, userId));
|
||||
return (await getUser(db, userId))!;
|
||||
}
|
||||
@ -20,6 +20,7 @@ export * from "./repo-info.ts";
|
||||
export * from "./incidents.ts";
|
||||
export * from "./ci.ts";
|
||||
export * from "./egov.ts";
|
||||
export * from "./google.ts";
|
||||
export * from "./team.ts";
|
||||
export * from "./progress.ts";
|
||||
export * from "./intake.ts";
|
||||
|
||||
4
packages/db/migrations/0017_lowly_ghost_rider.sql
Normal file
4
packages/db/migrations/0017_lowly_ghost_rider.sql
Normal file
@ -0,0 +1,4 @@
|
||||
ALTER TABLE `users` ADD `google_sub` text;--> statement-breakpoint
|
||||
ALTER TABLE `users` ADD `google_email` text;--> statement-breakpoint
|
||||
ALTER TABLE `users` ADD `google_linked_at` integer;--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `users_google_sub_unique` ON `users` (`google_sub`);
|
||||
4148
packages/db/migrations/meta/0017_snapshot.json
Normal file
4148
packages/db/migrations/meta/0017_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -120,6 +120,13 @@
|
||||
"when": 1794678698233,
|
||||
"tag": "0016_user_telegram_bot",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 17,
|
||||
"version": "6",
|
||||
"when": 1794727874686,
|
||||
"tag": "0017_lowly_ghost_rider",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -38,6 +38,10 @@ export const users = sqliteTable("users", {
|
||||
// eGov login (PEP-65): the signer's IIN from the certificate, one account per IIN.
|
||||
egovIin: text("egov_iin").unique(),
|
||||
egovLinkedAt: integer("egov_linked_at", { mode: "timestamp_ms" }),
|
||||
// Google login (PEP-90): the Google account's stable `sub` (identity) and its verified e-mail (display only).
|
||||
googleSub: text("google_sub").unique(),
|
||||
googleEmail: text("google_email"),
|
||||
googleLinkedAt: integer("google_linked_at", { mode: "timestamp_ms" }),
|
||||
// Local login (PEP-68): scrypt hash "scrypt$N$r$p$salt$hash" (core/local-users.ts).
|
||||
passwordHash: text("password_hash"),
|
||||
passwordSetAt: integer("password_set_at", { mode: "timestamp_ms" }),
|
||||
|
||||
@ -26,6 +26,11 @@ const schema = z.object({
|
||||
// eGov QR login (PEP-65) through the KazEDS relay, already trusted by eGov Mobile.
|
||||
KAZEDS_RELAY_BASE: z.string().url().default("https://sign.aitu.uz/relay/v1"),
|
||||
EGOV_ORGANISATION_NAME: z.string().default("Peppa"),
|
||||
// Google login (PEP-90): OAuth client from Google Cloud; without both the button is hidden.
|
||||
GOOGLE_CLIENT_ID: z.string().optional(),
|
||||
GOOGLE_CLIENT_SECRET: z.string().optional(),
|
||||
// Test override of accounts.google.com / oauth2.googleapis.com (mock-google).
|
||||
GOOGLE_OAUTH_BASE: z.string().url().optional(),
|
||||
EGOV_ORGANISATION_BIN: z.string().regex(/^\d{12}$/).default("241140100000"),
|
||||
});
|
||||
|
||||
|
||||
3
packages/testkit/bin/mock-google
Executable file
3
packages/testkit/bin/mock-google
Executable file
@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env bash
|
||||
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
|
||||
exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-google.ts" "$@"
|
||||
89
packages/testkit/src/mock-google.ts
Normal file
89
packages/testkit/src/mock-google.ts
Normal file
@ -0,0 +1,89 @@
|
||||
// Mock Google OAuth (PEP-90) for tests and checks without a Google Cloud client: GET /auth (the
|
||||
// "user" consents at once and is redirected back with code+state), POST /token (checks client,
|
||||
// redirect_uri, PKCE S256 and that the code is used once), GET /userinfo (OIDC profile).
|
||||
// Standalone: `mock-google [port]` → GOOGLE_OAUTH_BASE=<printed url>.
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
|
||||
export interface MockGoogleAccount {
|
||||
sub: string;
|
||||
email: string;
|
||||
email_verified?: boolean;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
interface Grant {
|
||||
account: MockGoogleAccount;
|
||||
redirectUri: string;
|
||||
challenge: string;
|
||||
}
|
||||
|
||||
export class MockGoogle {
|
||||
/** Who consents on the next /auth. */
|
||||
account: MockGoogleAccount = { sub: "g-1001", email: "anna.petrova@example.com", email_verified: true, name: "Anna Petrova" };
|
||||
readonly codes = new Map<string, Grant>();
|
||||
readonly tokens = new Map<string, MockGoogleAccount>();
|
||||
/** What the platform sent to /auth and /token — for assertions. */
|
||||
readonly seen: { auth: URLSearchParams[]; token: URLSearchParams[] } = { auth: [], token: [] };
|
||||
clientId = "mock-google-client";
|
||||
clientSecret = "mock-google-secret";
|
||||
private server: Server | null = null;
|
||||
|
||||
async start(port = 0): Promise<string> {
|
||||
this.server = createServer((req, res) => void this.handle(req.method ?? "GET", req.url ?? "/", req, res));
|
||||
await new Promise<void>((r) => this.server!.listen(port, "127.0.0.1", r));
|
||||
return `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
await new Promise<void>((r) => (this.server ? this.server.close(() => r()) : r()));
|
||||
}
|
||||
|
||||
private async handle(method: string, url: string, req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) {
|
||||
const u = new URL(url, "http://mock");
|
||||
const send = (code: number, body: unknown) => {
|
||||
res.writeHead(code, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(body));
|
||||
};
|
||||
if (method === "GET" && u.pathname === "/auth") {
|
||||
const q = u.searchParams;
|
||||
this.seen.auth.push(q);
|
||||
if (q.get("client_id") !== this.clientId || q.get("response_type") !== "code" || q.get("code_challenge_method") !== "S256" || !q.get("redirect_uri") || !q.get("state")) {
|
||||
return send(400, { error: "invalid_request" });
|
||||
}
|
||||
const code = randomUUID();
|
||||
this.codes.set(code, { account: { ...this.account }, redirectUri: q.get("redirect_uri")!, challenge: q.get("code_challenge") ?? "" });
|
||||
const back = new URL(q.get("redirect_uri")!);
|
||||
back.searchParams.set("code", code);
|
||||
back.searchParams.set("state", q.get("state")!);
|
||||
res.writeHead(302, { Location: back.toString() });
|
||||
return res.end();
|
||||
}
|
||||
if (method === "POST" && u.pathname === "/token") {
|
||||
let raw = "";
|
||||
for await (const chunk of req) raw += chunk;
|
||||
const f = new URLSearchParams(raw);
|
||||
this.seen.token.push(f);
|
||||
const grant = this.codes.get(f.get("code") ?? "");
|
||||
this.codes.delete(f.get("code") ?? ""); // one use
|
||||
if (f.get("client_id") !== this.clientId || f.get("client_secret") !== this.clientSecret) return send(401, { error: "invalid_client" });
|
||||
if (!grant || f.get("grant_type") !== "authorization_code" || f.get("redirect_uri") !== grant.redirectUri) return send(400, { error: "invalid_grant" });
|
||||
if (createHash("sha256").update(f.get("code_verifier") ?? "").digest("base64url") !== grant.challenge) return send(400, { error: "invalid_grant" });
|
||||
const token = randomUUID();
|
||||
this.tokens.set(token, grant.account);
|
||||
return send(200, { access_token: token, token_type: "Bearer", expires_in: 3600 });
|
||||
}
|
||||
if (method === "GET" && u.pathname === "/userinfo") {
|
||||
const account = this.tokens.get((req.headers.authorization ?? "").replace(/^Bearer /, ""));
|
||||
return account ? send(200, account) : send(401, { error: "invalid_token" });
|
||||
}
|
||||
send(404, { error: "not_found" });
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
const g = new MockGoogle();
|
||||
const url = await g.start(Number(process.argv[2] ?? process.env.MOCK_PORT ?? 3104));
|
||||
console.log(`mock-google (TEST ONLY): GOOGLE_OAUTH_BASE=${url} GOOGLE_CLIENT_ID=${g.clientId} GOOGLE_CLIENT_SECRET=${g.clientSecret}`);
|
||||
}
|
||||
139
packages/testkit/test/google.test.ts
Normal file
139
packages/testkit/test/google.test.ts
Normal file
@ -0,0 +1,139 @@
|
||||
// PEP-90: Google login against mock-google: first login registers, repeat finds the account,
|
||||
// disabled user refused, forged/replayed/foreign-browser state refused, unverified e-mail, link/unlink.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { core, db, teardown } from "./helpers.ts";
|
||||
import { MockGoogle } from "../src/mock-google.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
const google = new MockGoogle();
|
||||
const REDIRECT = "https://peppa.test/auth/google/callback";
|
||||
|
||||
before(async () => {
|
||||
process.env.GOOGLE_OAUTH_BASE = await google.start();
|
||||
process.env.GOOGLE_CLIENT_ID = google.clientId;
|
||||
process.env.GOOGLE_CLIENT_SECRET = google.clientSecret;
|
||||
});
|
||||
after(async () => {
|
||||
await google.stop();
|
||||
await teardown();
|
||||
});
|
||||
|
||||
/** The "browser": opens Google's authorize URL, which consents and redirects back with code+state. */
|
||||
async function consent(url: string) {
|
||||
const res = await fetch(url, { redirect: "manual" });
|
||||
assert.equal(res.status, 302);
|
||||
const back = new URL(res.headers.get("location")!);
|
||||
return { code: back.searchParams.get("code")!, state: back.searchParams.get("state")! };
|
||||
}
|
||||
async function login(purpose: "login" | "link" = "login", userId: number | null = null) {
|
||||
const f = await core.startGoogleFlow(db, purpose, REDIRECT, userId);
|
||||
const { code, state } = await consent(f.url);
|
||||
return { f, code, state };
|
||||
}
|
||||
|
||||
describe("Google login", () => {
|
||||
test("disabled without a client", async () => {
|
||||
delete process.env.GOOGLE_CLIENT_SECRET;
|
||||
assert.equal(core.googleEnabled(), false);
|
||||
await assert.rejects(core.startGoogleFlow(db, "login", REDIRECT), /не настроен/);
|
||||
process.env.GOOGLE_CLIENT_SECRET = google.clientSecret;
|
||||
assert.equal(core.googleEnabled(), true);
|
||||
});
|
||||
|
||||
test("first login registers, the next one finds the same account", async () => {
|
||||
const a = await login();
|
||||
const r = await core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state });
|
||||
assert.ok(r.purpose === "login" && r.created);
|
||||
assert.equal(r.user.login, "anna.petrova");
|
||||
assert.equal(r.user.name, "Anna Petrova");
|
||||
assert.equal(r.user.googleSub, "g-1001");
|
||||
assert.ok(r.user.giteaId < 0 && !r.user.passwordHash, "no Gitea, no password");
|
||||
assert.ok(core.isLocalUser(r.user));
|
||||
assert.equal(await core.mayUseMachineLogin(db, r.user.id), false, "no pool → no machine login, like eGov");
|
||||
assert.ok(google.seen.auth[0]!.get("code_challenge"), "PKCE");
|
||||
|
||||
const b = await login();
|
||||
const r2 = await core.completeGoogleFlow(db, { state: b.state, code: b.code, cookieState: b.f.state });
|
||||
assert.ok(r2.purpose === "login" && !r2.created);
|
||||
assert.equal(r2.user.id, r.user.id);
|
||||
});
|
||||
|
||||
test("same e-mail local part, other Google account → suffixed login, no merge by e-mail", async () => {
|
||||
google.account = { sub: "g-1002", email: "anna.petrova@other.org", email_verified: true, name: "Another Anna" };
|
||||
const a = await login();
|
||||
const r = await core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state });
|
||||
assert.equal(r.user.login, "anna.petrova-2");
|
||||
google.account = { sub: "g-1001", email: "anna.petrova@example.com", email_verified: true, name: "Anna Petrova" };
|
||||
});
|
||||
|
||||
test("replayed callback is refused", async () => {
|
||||
const a = await login();
|
||||
await core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state });
|
||||
await assert.rejects(core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state }), /устарел/);
|
||||
});
|
||||
|
||||
test("forged state and a state from another browser are refused, without calling Google", async () => {
|
||||
const calls = google.seen.token.length;
|
||||
const a = await login();
|
||||
await assert.rejects(core.completeGoogleFlow(db, { state: "forged", code: a.code, cookieState: "forged" }), /устарел/);
|
||||
await assert.rejects(core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: "" }), /заново/);
|
||||
await assert.rejects(core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: "other-browser" }), /заново/);
|
||||
assert.equal(google.seen.token.length, calls, "no token exchange");
|
||||
// The failed attempts did not spend the flow: the real browser still completes.
|
||||
const ok = await core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state });
|
||||
assert.equal(ok.user.googleSub, "g-1001");
|
||||
});
|
||||
|
||||
test("a stolen code without the PKCE verifier is useless", async () => {
|
||||
const a = await login();
|
||||
const res = await fetch(`${process.env.GOOGLE_OAUTH_BASE}/token`, {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({ grant_type: "authorization_code", code: a.code, redirect_uri: REDIRECT, client_id: google.clientId, client_secret: google.clientSecret, code_verifier: "guess" }),
|
||||
});
|
||||
assert.equal(res.status, 400);
|
||||
});
|
||||
|
||||
test("unverified e-mail is refused and creates nothing", async () => {
|
||||
google.account = { sub: "g-3003", email: "fake@example.com", email_verified: false };
|
||||
const a = await login();
|
||||
await assert.rejects(core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state }), /не подтверждена/);
|
||||
assert.equal(await core.getUserByLogin(db, "fake"), null);
|
||||
google.account = { sub: "g-1001", email: "anna.petrova@example.com", email_verified: true, name: "Anna Petrova" };
|
||||
});
|
||||
|
||||
test("a disabled user is not allowed", async () => {
|
||||
const a = await login();
|
||||
const r = await core.completeGoogleFlow(db, { state: a.state, code: a.code, cookieState: a.f.state });
|
||||
await core.setUserDisabled(db, r.user.id, true);
|
||||
const b = await login();
|
||||
const r2 = await core.completeGoogleFlow(db, { state: b.state, code: b.code, cookieState: b.f.state });
|
||||
assert.equal(await core.isUserAllowed(db, r2.user), false);
|
||||
await core.setUserDisabled(db, r.user.id, false);
|
||||
});
|
||||
|
||||
test("link Google to an eGov account, taken account refused, unlink guard", async () => {
|
||||
const egov = await core.registerEgovUser(db, { iin: "900101300126", name: "ТЕСТОВА АСЕЛЬ" });
|
||||
await assert.rejects(core.startGoogleFlow(db, "link", REDIRECT, null), /после входа/);
|
||||
google.account = { sub: "g-2002", email: "asel@example.com", email_verified: true };
|
||||
const l = await login("link", egov.id);
|
||||
const r = await core.completeGoogleFlow(db, { state: l.state, code: l.code, cookieState: l.f.state });
|
||||
assert.equal(r.purpose, "link");
|
||||
assert.equal(r.user.id, egov.id);
|
||||
assert.equal(r.user.googleSub, "g-2002");
|
||||
const again = await login();
|
||||
const r2 = await core.completeGoogleFlow(db, { state: again.state, code: again.code, cookieState: again.f.state });
|
||||
assert.equal(r2.user.id, egov.id, "Google now leads into the eGov account");
|
||||
|
||||
// g-1001 belongs to anna.petrova: the eGov account cannot take it.
|
||||
google.account = { sub: "g-1001", email: "anna.petrova@example.com", email_verified: true };
|
||||
const t = await login("link", egov.id);
|
||||
await assert.rejects(core.completeGoogleFlow(db, { state: t.state, code: t.code, cookieState: t.f.state }), /уже привязан/);
|
||||
|
||||
const unlinked = await core.unlinkGoogle(db, egov.id);
|
||||
assert.equal(unlinked.googleSub, null);
|
||||
// Google-only account cannot drop its only way in.
|
||||
const [anna] = await db.select().from((await import("@peppa/db")).users).where((await import("drizzle-orm")).eq((await import("@peppa/db")).users.googleSub, "g-1001"));
|
||||
await assert.rejects(core.unlinkGoogle(db, anna!.id), /единственный/);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user