diff --git a/.env.example b/.env.example index 18bb27b2..4c9ecfaf 100644 --- a/.env.example +++ b/.env.example @@ -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 /auth/google/callback +# GOOGLE_CLIENT_ID= +# GOOGLE_CLIENT_SECRET= diff --git a/.peppa/memory.md b/.peppa/memory.md index 4c94ef16..0d84414d 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -12,3 +12,4 @@ - Репозитории платформы — в организации Gitea `peppa` (PEP-4): `peppa/peppa`, `peppa/template`; старые адреса `peppa-bot/…` живут редиректом — не создавать `peppa-bot/peppa|template` заново. Проект переносит `peppa project transfer `. - Чаты (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) — не от правок. diff --git a/AGENTS.md b/AGENTS.md index 6600b08f..14003a0d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::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` (документ ``, поток в `settings` `egov.flow:`, 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 <ИИН|->`. Мок `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:` (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 `/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 [--admin] [--name]`, `peppa user passwd|disable|enable ` (пароль из 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:`, кто использует, шаги ротации), шифрование по колонкам, 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`: Claude `claude setup-token` (ссылка → код → токен в `secret_enc`) или готовый токен; Codex `codex login --device-auth` (ссылка + код, страница опрашивает) или `--with-api-key`, вход живёт в своём `CODEX_HOME` = `$PEPPA_HOME/subscriptions/s/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 --prompt`, правила и MCP из `OPENCODE_CONFIG` (opencode.json в каталоге запуска), хуков нет — статус по процессу. Миграция 0003 перенесла токены `users.claude_token_enc` (PEP-13, колонки больше не читаются) в подписки «Claude — » и пулы проектов владельца. Моки: `mock-claude setup-token|-p`, `mock-codex login|exec`, `mock-opencode` diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 29671a88..65e9ed3b 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -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 () => { diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index fd64b22f..28a9e66c 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -75,7 +75,7 @@ export default async function Help() {
  • Telegram — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда /newbot), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Не хотите создавать — там же можно выбрать общего бота Пеппы.
  • Продакт и аналитик — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено.
  • Команда — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.
  • -
  • Вход — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, aigerim.ivanova). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot.
  • +
  • Вход — через eGov QR (с телефона — кнопка «Открыть в eGov Mobile») или через Google (кнопка есть, когда суперадмин задал GOOGLE_CLIENT_ID/SECRET); в «Настройках» их можно связать в одну учётку. Первый вход сам создаёт учётку по ИИН или Google-почте: логин из имени в сертификате (например, aigerim.ivanova). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве peppa-bot.
  • Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и живой терминал: экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.
  • Новый терминал — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выбери проект, имя, агента и напиши промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляешь ты в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать.
  • Раннеры и стори — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка task/…, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь.
  • diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index f57ba0ce..70d86853 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -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

    Логин {user.login} - {user.name ? <> · {user.name} : null}. Вход в Пеппу — только через eGov QR + {user.name ? <> · {user.name} : null}. Вход в Пеппу — через eGov QR или Google {user.egovIin ? ( <> , ИИН {maskIin(user.egovIin)}. ) : ( - <>. ИИН ещё не привязан — привяжите его ниже, иначе после выхода вы не сможете войти. + <>. ИИН ещё не привязан{user.googleSub ? "." : " — привяжите его ниже или Google, иначе после выхода вы не сможете войти."} )}

    {local && ( @@ -113,6 +114,32 @@ export default async function Settings({ searchParams }: { searchParams: Promise )} {user.egovIin && egov === "linked" && eGov привязан — теперь можно входить по QR} + {(googleEnabled() || user.googleSub) && ( +
    + {google === "linked" && Google привязан — теперь можно входить через него} + {user.googleSub ? ( + + + + + } + > + {user.googleEmail}. Войти через Google можно в ту же учётку. + + ) : ( + +

    Привяжите Google-аккаунт — и в эту учётку можно будет входить и через него.

    +
    + +
    +
    + )} +
    + )} +
    {bot === "connected" && Бот @{user.telegramBotUsername} подключён — остался последний шаг: откройте его и нажмите Start.} {user.telegramChatId ? ( diff --git a/apps/web/app/(app)/users/page.tsx b/apps/web/app/(app)/users/page.tsx index 93041a8a..73f40400 100644 --- a/apps/web/app/(app)/users/page.tsx +++ b/apps/web/app/(app)/users/page.tsx @@ -39,7 +39,9 @@ export default async function Users({ searchParams }: { searchParams: Promise<{ {!local && Gitea} {admins.has(u.login.toLowerCase()) && суперадмин} {u.disabledAt && отключён} - {u.egovIin ? eGov {maskIin(u.egovIin)} : без eGov — не войдёт} + {u.egovIin && eGov {maskIin(u.egovIin)}} + {u.googleSub && Google {u.googleEmail}} + {!u.egovIin && !u.googleSub && !u.passwordHash && без eGov и Google — не войдёт} {u.lastLoginAt ? `вход ${ago(u.lastLoginAt)}` : "ещё не входил"}
    diff --git a/apps/web/app/auth/google/callback/route.ts b/apps/web/app/auth/google/callback/route.ts new file mode 100644 index 00000000..7c090202 --- /dev/null +++ b/apps/web/app/auth/google/callback/route.ts @@ -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"); + } +} diff --git a/apps/web/app/auth/google/start/route.ts b/apps/web/app/auth/google/start/route.ts new file mode 100644 index 00000000..934db849 --- /dev/null +++ b/apps/web/app/auth/google/start/route.ts @@ -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"); + } +} diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx index 9020612e..a904a1c7 100644 --- a/apps/web/app/login/page.tsx +++ b/apps/web/app/login/page.tsx @@ -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<{ diff --git a/apps/web/components/GoogleSignIn.tsx b/apps/web/components/GoogleSignIn.tsx new file mode 100644 index 00000000..0418446c --- /dev/null +++ b/apps/web/components/GoogleSignIn.tsx @@ -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 ( +
    + + {next && } + +
    + ); +} diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.ts index 0dfe4e3b..b28265da 100644 --- a/apps/web/lib/auth.ts +++ b/apps/web/lib/auth.ts @@ -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://"); /** diff --git a/openspec/changes/archive/2026-11-15-pep-90-google-login/design.md b/openspec/changes/archive/2026-11-15-pep-90-google-login/design.md new file mode 100644 index 00000000..af7055df --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-90-google-login/design.md @@ -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:`, 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`. diff --git a/openspec/changes/archive/2026-11-15-pep-90-google-login/proposal.md b/openspec/changes/archive/2026-11-15-pep-90-google-login/proposal.md new file mode 100644 index 00000000..954d699e --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-90-google-login/proposal.md @@ -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 нет. diff --git a/openspec/changes/archive/2026-11-15-pep-90-google-login/specs/web-auth/spec.md b/openspec/changes/archive/2026-11-15-pep-90-google-login/specs/web-auth/spec.md new file mode 100644 index 00000000..e84f640e --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-90-google-login/specs/web-auth/spec.md @@ -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** привязка отклонена с сообщением, что аккаунт уже привязан diff --git a/openspec/changes/archive/2026-11-15-pep-90-google-login/tasks.md b/openspec/changes/archive/2026-11-15-pep-90-google-login/tasks.md new file mode 100644 index 00000000..2c4fc289 --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-90-google-login/tasks.md @@ -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) diff --git a/openspec/specs/web-auth/spec.md b/openspec/specs/web-auth/spec.md index a81a41df..da673c6e 100644 --- a/openspec/specs/web-auth/spec.md +++ b/openspec/specs/web-auth/spec.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** привязка отклонена с сообщением, что аккаунт уже привязан diff --git a/packages/core/src/google.ts b/packages/core/src/google.ts new file mode 100644 index 00000000..962aa1af --- /dev/null +++ b/packages/core/src/google.ts @@ -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 { + 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(url: string, body: URLSearchParams): Promise { + 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 { + const { state, code, cookieState } = input; + if (!state || !code || state !== cookieState) throw new PeppaError("Вход не удался — начните заново"); + const flow = await getSetting(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-". */ +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 { + 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 { + 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 { + 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))!; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e8663891..9e25b48d 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -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"; diff --git a/packages/db/migrations/0017_lowly_ghost_rider.sql b/packages/db/migrations/0017_lowly_ghost_rider.sql new file mode 100644 index 00000000..f5219444 --- /dev/null +++ b/packages/db/migrations/0017_lowly_ghost_rider.sql @@ -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`); \ No newline at end of file diff --git a/packages/db/migrations/meta/0017_snapshot.json b/packages/db/migrations/meta/0017_snapshot.json new file mode 100644 index 00000000..7e0fee99 --- /dev/null +++ b/packages/db/migrations/meta/0017_snapshot.json @@ -0,0 +1,4148 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "be145d37-3842-4e43-b7b7-8435001d71eb", + "prevId": "adc91e4e-2273-4fb3-aaa1-fd9d3dc11061", + "tables": { + "agents": { + "name": "agents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "character": { + "name": "character", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "agents_name_unique": { + "name": "agents_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chat_messages": { + "name": "chat_messages", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "chat_id": { + "name": "chat_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "thread_key": { + "name": "thread_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "thread_title": { + "name": "thread_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "important": { + "name": "important", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "author_kind": { + "name": "author_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'system'" + }, + "author_user_id": { + "name": "author_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "author_login": { + "name": "author_login", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "via": { + "name": "via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_chat_id": { + "name": "tg_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_message_id": { + "name": "tg_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "chat_messages_dedupe_key_unique": { + "name": "chat_messages_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + }, + "chat_messages_chat": { + "name": "chat_messages_chat", + "columns": [ + "chat_id", + "id" + ], + "isUnique": false + }, + "chat_messages_created_at": { + "name": "chat_messages_created_at", + "columns": [ + "created_at" + ], + "isUnique": false + }, + "chat_messages_tg": { + "name": "chat_messages_tg", + "columns": [ + "tg_chat_id", + "tg_message_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "chat_messages_chat_id_chats_id_fk": { + "name": "chat_messages_chat_id_chats_id_fk", + "tableFrom": "chat_messages", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_messages_author_user_id_users_id_fk": { + "name": "chat_messages_author_user_id_users_id_fk", + "tableFrom": "chat_messages", + "tableTo": "users", + "columnsFrom": [ + "author_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "chat_messages_question_id_questions_id_fk": { + "name": "chat_messages_question_id_questions_id_fk", + "tableFrom": "chat_messages", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "chat_messages_task_id_tasks_id_fk": { + "name": "chat_messages_task_id_tasks_id_fk", + "tableFrom": "chat_messages", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chats": { + "name": "chats", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_chat_id": { + "name": "tg_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_title": { + "name": "tg_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_linked_at": { + "name": "tg_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_linked_by": { + "name": "tg_linked_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "chats_user_id_unique": { + "name": "chats_user_id_unique", + "columns": [ + "user_id" + ], + "isUnique": true + }, + "chats_project_id_unique": { + "name": "chats_project_id_unique", + "columns": [ + "project_id" + ], + "isUnique": true + }, + "chats_tg_chat_id_unique": { + "name": "chats_tg_chat_id_unique", + "columns": [ + "tg_chat_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "chats_user_id_users_id_fk": { + "name": "chats_user_id_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chats_project_id_projects_id_fk": { + "name": "chats_project_id_projects_id_fk", + "tableFrom": "chats", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chats_tg_linked_by_users_id_fk": { + "name": "chats_tg_linked_by_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "tg_linked_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "check_runs": { + "name": "check_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + "project_id", + "sha", + "check" + ], + "isUnique": true + } + }, + "foreignKeys": { + "check_runs_project_id_projects_id_fk": { + "name": "check_runs_project_id_projects_id_fk", + "tableFrom": "check_runs", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "check_runs_task_id_tasks_id_fk": { + "name": "check_runs_task_id_tasks_id_fk", + "tableFrom": "check_runs", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "code_reviews": { + "name": "code_reviews", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "verdict": { + "name": "verdict", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "findings": { + "name": "findings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "code_reviews_project_id_projects_id_fk": { + "name": "code_reviews_project_id_projects_id_fk", + "tableFrom": "code_reviews", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "code_reviews_task_id_tasks_id_fk": { + "name": "code_reviews_task_id_tasks_id_fk", + "tableFrom": "code_reviews", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "error_sources": { + "name": "error_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "columns": [ + "bugsink_project_id" + ], + "isUnique": true + }, + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + "project_id", + "kind" + ], + "isUnique": true + } + }, + "foreignKeys": { + "error_sources_project_id_projects_id_fk": { + "name": "error_sources_project_id_projects_id_fk", + "tableFrom": "error_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_kind": { + "name": "actor_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_channel": { + "name": "actor_channel", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_client_id": { + "name": "actor_client_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "events_created_at": { + "name": "events_created_at", + "columns": [ + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "events_actor_user_id_users_id_fk": { + "name": "events_actor_user_id_users_id_fk", + "tableFrom": "events", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_secrets": { + "name": "project_secrets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value_enc": { + "name": "value_enc", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_by": { + "name": "updated_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_secrets_project_name": { + "name": "project_secrets_project_name", + "columns": [ + "project_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_secrets_project_id_projects_id_fk": { + "name": "project_secrets_project_id_projects_id_fk", + "tableFrom": "project_secrets", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_secrets_created_by_users_id_fk": { + "name": "project_secrets_created_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "project_secrets_updated_by_users_id_fk": { + "name": "project_secrets_updated_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "subscription_pool_id": { + "name": "subscription_pool_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + }, + "projects_key_unique": { + "name": "projects_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_subscription_pool_id_subscription_pools_id_fk": { + "name": "projects_subscription_pool_id_subscription_pools_id_fk", + "tableFrom": "projects", + "tableTo": "subscription_pools", + "columnsFrom": [ + "subscription_pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_outbox": { + "name": "push_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "urgency": { + "name": "urgency", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_outbox_dedupe_key_unique": { + "name": "push_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_outbox_subscription_id_push_subscriptions_id_fk": { + "name": "push_outbox_subscription_id_push_subscriptions_id_fk", + "tableFrom": "push_outbox", + "tableTo": "push_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_ok_at": { + "name": "last_ok_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "columns": [ + "endpoint" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_user_id_users_id_fk": { + "name": "push_subscriptions_user_id_users_id_fk", + "tableFrom": "push_subscriptions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "questions": { + "name": "questions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "reminders": { + "name": "reminders", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "releases": { + "name": "releases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tasks": { + "name": "tasks", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "releases_project_id_projects_id_fk": { + "name": "releases_project_id_projects_id_fk", + "tableFrom": "releases", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "review_settings": { + "name": "review_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "max_iterations": { + "name": "max_iterations", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 2 + }, + "rules": { + "name": "rules", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "review_settings_project_id_projects_id_fk": { + "name": "review_settings_project_id_projects_id_fk", + "tableFrom": "review_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_commands": { + "name": "runner_commands", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_kind": { + "name": "error_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_commands_status_idx": { + "name": "runner_commands_status_idx", + "columns": [ + "status", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_hosts": { + "name": "runner_hosts", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_target": { + "name": "ssh_target", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_port": { + "name": "ssh_port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 22 + }, + "workdir": { + "name": "workdir", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'peppa'" + }, + "peppa_url": { + "name": "peppa_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unknown'" + }, + "info": { + "name": "info", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "runner_hosts_name_unique": { + "name": "runner_hosts_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_tasks": { + "name": "runner_tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "front": { + "name": "front", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_tasks_session_idx": { + "name": "runner_tasks_session_idx", + "columns": [ + "session_id", + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "runner_tasks_session_id_sessions_id_fk": { + "name": "runner_tasks_session_id_sessions_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "runner_tasks_task_id_tasks_id_fk": { + "name": "runner_tasks_task_id_tasks_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rotate_reason": { + "name": "rotate_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_id": { + "name": "host_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "container": { + "name": "container", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "usage": { + "name": "usage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "watch_state": { + "name": "watch_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_subscription_id_subscriptions_id_fk": { + "name": "sessions_subscription_id_subscriptions_id_fk", + "tableFrom": "sessions", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_host_id_runner_hosts_id_fk": { + "name": "sessions_host_id_runner_hosts_id_fk", + "tableFrom": "sessions", + "tableTo": "runner_hosts", + "columnsFrom": [ + "host_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_agent_id_agents_id_fk": { + "name": "sessions_agent_id_agents_id_fk", + "tableFrom": "sessions", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pool_members": { + "name": "subscription_pool_members", + "columns": { + "pool_id": { + "name": "pool_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "subscription_pool_members_pool_id_subscription_pools_id_fk": { + "name": "subscription_pool_members_pool_id_subscription_pools_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscription_pools", + "columnsFrom": [ + "pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscription_pool_members_subscription_id_subscriptions_id_fk": { + "name": "subscription_pool_members_subscription_id_subscriptions_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscription_pool_members_pool_id_subscription_id_pk": { + "columns": [ + "pool_id", + "subscription_id" + ], + "name": "subscription_pool_members_pool_id_subscription_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pools": { + "name": "subscription_pools", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "subscription_pools_name_unique": { + "name": "subscription_pools_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "subscription_pools_created_by_users_id_fk": { + "name": "subscription_pools_created_by_users_id_fk", + "tableFrom": "subscription_pools", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key_provider": { + "name": "key_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "limited_until": { + "name": "limited_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "subscriptions_created_by_users_id_fk": { + "name": "subscriptions_created_by_users_id_fk", + "tableFrom": "subscriptions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "task_deps": { + "name": "task_deps", + "columns": { + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blocked_by_id": { + "name": "blocked_by_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "task_deps_blocked_by": { + "name": "task_deps_blocked_by", + "columns": [ + "blocked_by_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "task_deps_task_id_tasks_id_fk": { + "name": "task_deps_task_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_deps_blocked_by_id_tasks_id_fk": { + "name": "task_deps_blocked_by_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "blocked_by_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "task_deps_task_id_blocked_by_id_pk": { + "columns": [ + "task_id", + "blocked_by_id" + ], + "name": "task_deps_task_id_blocked_by_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_issue": { + "name": "gitea_issue", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "archived_at": { + "name": "archived_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + "project_id", + "number" + ], + "isUnique": true + }, + "tasks_project_issue": { + "name": "tasks_project_issue", + "columns": [ + "project_id", + "gitea_issue" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_outbox": { + "name": "telegram_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "chat_message_id": { + "name": "chat_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "telegram_outbox_chat_message_id_chat_messages_id_fk": { + "name": "telegram_outbox_chat_message_id_chat_messages_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "chat_messages", + "columnsFrom": [ + "chat_message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_updates": { + "name": "telegram_updates", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_bot_token_enc": { + "name": "telegram_bot_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_bot_username": { + "name": "telegram_bot_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_iin": { + "name": "egov_iin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_linked_at": { + "name": "egov_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_sub": { + "name": "google_sub", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_email": { + "name": "google_email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_linked_at": { + "name": "google_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_set_at": { + "name": "password_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_login_at": { + "name": "last_login_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "columns": [ + "gitea_id" + ], + "isUnique": true + }, + "users_login_unique": { + "name": "users_login_unique", + "columns": [ + "login" + ], + "isUnique": true + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "columns": [ + "telegram_chat_id" + ], + "isUnique": true + }, + "users_egov_iin_unique": { + "name": "users_egov_iin_unique", + "columns": [ + "egov_iin" + ], + "isUnique": true + }, + "users_google_sub_unique": { + "name": "users_google_sub_unique", + "columns": [ + "google_sub" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index d91b73ba..3f6e63e3 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -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 } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 6521db13..467f6084 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -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" }), diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts index 0091752e..23f29b4b 100644 --- a/packages/shared/src/env.ts +++ b/packages/shared/src/env.ts @@ -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"), }); diff --git a/packages/testkit/bin/mock-google b/packages/testkit/bin/mock-google new file mode 100755 index 00000000..cc2608e9 --- /dev/null +++ b/packages/testkit/bin/mock-google @@ -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" "$@" diff --git a/packages/testkit/src/mock-google.ts b/packages/testkit/src/mock-google.ts new file mode 100644 index 00000000..1949aa7b --- /dev/null +++ b/packages/testkit/src/mock-google.ts @@ -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=. +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(); + readonly tokens = new Map(); + /** 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 { + this.server = createServer((req, res) => void this.handle(req.method ?? "GET", req.url ?? "/", req, res)); + await new Promise((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 { + await new Promise((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}`); +} diff --git a/packages/testkit/test/google.test.ts b/packages/testkit/test/google.test.ts new file mode 100644 index 00000000..023bdc8c --- /dev/null +++ b/packages/testkit/test/google.test.ts @@ -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), /единственный/); + }); +});