From cb4a01d1bbdd75560c24e302faa88ebac76e12e6 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 24 Nov 2026 12:09:31 +0000 Subject: [PATCH] =?UTF-8?q?PEP-252:=20=D0=B2=D1=85=D0=BE=D0=B4=20=D0=B2=20?= =?UTF-8?q?=D1=81=D0=B5=D1=80=D0=B2=D0=B8=D1=81=D1=8B=20=D1=87=D0=B5=D1=80?= =?UTF-8?q?=D0=B5=D0=B7=20OAuth=20=E2=80=94=20=D1=8F=D0=B4=D1=80=D0=BE,=20?= =?UTF-8?q?=D0=BE=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20?= =?UTF-8?q?=D1=82=D0=BE=D0=BA=D0=B5=D0=BD=D0=BE=D0=B2,=20=D0=BE=D1=82?= =?UTF-8?q?=D0=B7=D1=8B=D0=B2,=20=D0=BC=D0=BE=D0=BA=20=D0=B8=20=D1=82?= =?UTF-8?q?=D0=B5=D1=81=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../pep-252-access-hub-oauth/design.md | 54 + .../pep-252-access-hub-oauth/proposal.md | 35 + .../specs/access-hub/spec.md | 65 + .../changes/pep-252-access-hub-oauth/tasks.md | 23 + packages/core/src/connection-catalog.ts | 33 +- packages/core/src/connection-oauth-flow.ts | 122 + packages/core/src/connection-oauth.ts | 203 + packages/core/src/connections.ts | 175 +- packages/core/src/index.ts | 2 + packages/core/src/secrets-audit.ts | 26 + .../db/migrations/0031_access_hub_oauth.sql | 3 + .../db/migrations/meta/0031_snapshot.json | 5288 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 11 +- packages/shared/src/env.ts | 7 + packages/testkit/bin/mock-oauth-service | 3 + packages/testkit/src/mock-oauth-service.ts | 202 + .../testkit/test/access-hub-oauth.test.ts | 282 + 18 files changed, 6510 insertions(+), 31 deletions(-) create mode 100644 openspec/changes/pep-252-access-hub-oauth/design.md create mode 100644 openspec/changes/pep-252-access-hub-oauth/proposal.md create mode 100644 openspec/changes/pep-252-access-hub-oauth/specs/access-hub/spec.md create mode 100644 openspec/changes/pep-252-access-hub-oauth/tasks.md create mode 100644 packages/core/src/connection-oauth-flow.ts create mode 100644 packages/core/src/connection-oauth.ts create mode 100644 packages/db/migrations/0031_access_hub_oauth.sql create mode 100644 packages/db/migrations/meta/0031_snapshot.json create mode 100755 packages/testkit/bin/mock-oauth-service create mode 100644 packages/testkit/src/mock-oauth-service.ts create mode 100644 packages/testkit/test/access-hub-oauth.test.ts diff --git a/openspec/changes/pep-252-access-hub-oauth/design.md b/openspec/changes/pep-252-access-hub-oauth/design.md new file mode 100644 index 00000000..c769c103 --- /dev/null +++ b/openspec/changes/pep-252-access-hub-oauth/design.md @@ -0,0 +1,54 @@ +# Design — PEP-252 + +## Решения +1. **Где хранить токены.** В том же конверте, что и ключ (PEP-254): `secret_enc` = JSON + `{access, refresh, type}` под собственным ключом данных подключения, `dek_enc` под + `PEPPA_SECRET`. Новой зашифрованной колонки нет — ротация `PEPPA_SECRET` и ревизия + `encryptedColumns` работают без изменений. Права (`oauth_scopes`, JSON) и срок + (`token_expires_at`) не секретны и лежат открыто: их показываем владельцу и по ним решаем, + пора ли обновлять, не расшифровывая токены. +2. **Способ подключения.** `auth_kind = "oauth"`, `catalog_id` — карточка (sheets/drive/ + calendar/github), `oauth_provider` — google|github. Шлюз передаёт `Authorization: Bearer + `; адрес, правило чтения и проверочный вызов берутся из карточки, как у ключей. +3. **Права.** Минимальные на уровень: Google Sheets `spreadsheets.readonly` / `spreadsheets`, + Drive `drive.readonly` / `drive`, Calendar `calendar.readonly` / `+calendar.events`. У GitHub + OAuth-приложений нет права «только чтение» для закрытых репозиториев: для обоих уровней + просим `repo read:org` (+ `workflow` не просим), а «только чтение» обеспечивает шлюз своим + правилом (PEP-249). Это написано владельцу рядом с кнопкой. Уровень «чтение» не даёт + выставить «Запись: сразу» бессмысленно — сервис сам откажет (403), шлюз это не скрывает. +4. **Поток.** Как вход Google (PEP-90): `state` 24 байта и `verifier` 32 байта, в `settings` + `conn.oauth.flow:` (10 мин, удаляется первым делом в callback), cookie + `peppa_conn_oauth` (httpOnly, SameSite=Lax, путь `/connections/oauth`). Callback требует: + state == cookie, поток жив, текущий пользователь == начавший поток (чужой — отказ, поток + сгорает). Google: `access_type=offline`, `prompt=consent` (иначе refresh_token не придёт + повторно), `include_granted_scopes=false`. Код и state в адресе живут только до + 303-редиректа на `/connections?…` без них. Сообщения об ошибке провайдера — фиксированные + фразы, текст ответа сервиса не показываем. +5. **Обновление.** `connectionCredential(db, conn, {now, force})`: срок истекает ≤ 60 с (или + `force` после 401) и есть refresh → `POST token grant_type=refresh_token`. Ответ 400/401 + (`invalid_grant`, отозвали) → перечитываем строку: если токены уже поменял другой процесс + (GitHub меняет refresh при каждом обновлении — гонка двух процессов) — берём новые; иначе + `status = relogin`, токены стёрты, одно сообщение владельцу (`check_alerted_at`). Сетевой + сбой/5xx — запрос отказан `upstream_error`, подключение не трогаем. В процессе обновления + одного подключения идут по одному (карта промисов). +6. **Новый статус `relogin`** («нужно войти заново»): шлюз отказывает причиной `needs_login`, + агент видит в `list_connections` `checkStatus = bad_key`; разрешения не удаляются. + «Войти заново» = тот же поток с `connectionId`: токены заменяются, статус `active`. +7. **Отзыв в сервисе.** `revokeConnection` перед стиранием токенов зовёт отзыв провайдера + (5 с, ошибки глотаются, итог — `remote: revoked|failed|unsupported`). Google — `POST + /revoke token=`; GitHub — `DELETE /applications/{client_id}/grant` с basic + client_id:secret и `{access_token}` (снимает всё разрешение приложения у пользователя). +8. **Клиенты FORGE.** `oauthProviderEnabled(provider)` = заданы id и секрет. Google берёт + `PEPPA_OAUTH_GOOGLE_*`, иначе общий клиент входа PEP-90 (тот же проект Google Cloud, нужен + ещё адрес возврата `<адрес>/connections/oauth/callback` и включённые API). Базы для мока — + `PEPPA_OAUTH_GOOGLE_BASE`, `PEPPA_OAUTH_GITHUB_BASE` (пути как у настоящих: Google + `/auth|/token|/revoke`, GitHub `/login/oauth/authorize|/login/oauth/access_token|/applications/{id}/grant`). + Запросы к эндпоинтам провайдера — обычный `fetch` к постоянным адресам (не адрес агента). +9. **Секреты не утекают.** Токены не в журнале (журнал пишет метод/путь), не в `ConnectionView` + (`hasKey` только), не в адресах, маскируются в ответе шлюза (`maskSecrets`) вместе с ключом. + +## Риски +- Google требует проверки приложения для `spreadsheets`/`drive` у внешних пользователей — + забота администратора (настройка клиента), в коде не решается. +- GitHub App с истекающими токенами и OAuth App без срока — оба поддержаны: без `expires_in` + токен считается бессрочным. diff --git a/openspec/changes/pep-252-access-hub-oauth/proposal.md b/openspec/changes/pep-252-access-hub-oauth/proposal.md new file mode 100644 index 00000000..d327f213 --- /dev/null +++ b/openspec/changes/pep-252-access-hub-oauth/proposal.md @@ -0,0 +1,35 @@ +# PEP-252: Access Hub — вход в сервисы через OAuth (Google, GitHub), шлюз сам обновляет токены + +## Why +Access Hub (PEP-234/249) умеет только вставленные ключи. Google и GitHub удобнее и безопаснее +подключать входом: владелец жмёт «Войти через Google», видит, какие права просит FORGE, и всё. +Ключ Google по API key открывает только публичные таблицы — для своих таблиц нужен вход. + +## What Changes +- Карточки каталога Google Sheets, Google Drive, Google Calendar и GitHub получают второй + способ подключения — «вход через сервис» (`oauth` в карточке: провайдер, права для «чтения» + и отдельно для «записи», пояснение). Владелец выбирает «только чтение» или «чтение и запись» + и видит список прав до входа. +- Поток: `/connections/oauth/start` (POST) → страница входа сервиса (code + PKCE S256, state) + → `/connections/oauth/callback` → токены (доступа и обновления) в зашифрованном конверте + подключения (PEP-254, `secret_enc`), права и срок токена — в открытых колонках. Поток + одноразовый, 10 минут, привязан к браузеру (httpOnly cookie) и к пользователю, начавшему его. +- Шлюз (`callConnection`) и проверка подключения сами обновляют токен доступа перед вызовом + (и один раз после ответа 401). Обновление отклонено сервисом → подключение «нужно войти + заново», токены стёрты, владельцу одно сообщение; «Войти заново» возвращает подключение + с прежними разрешениями. +- OAuth-клиенты FORGE — настройки платформы в `.env`: `PEPPA_OAUTH_GOOGLE_CLIENT_ID/_SECRET` + (иначе общий `GOOGLE_CLIENT_ID/_SECRET` входа PEP-90), `PEPPA_OAUTH_GITHUB_CLIENT_ID/_SECRET`; + без них кнопка скрыта. Секреты в ревизии `/secrets`. Адрес возврата — текущий адрес FORGE. + Провайдеры описаны таблицей — Slack, Notion, Microsoft добавляются записью. +- «Отозвать доступ» и «Удалить» отзывают токен и в самом сервисе (Google `revoke`, + GitHub `DELETE /applications/{client_id}/grant`), сбой отзыва не мешает отзыву в FORGE. +- Мок `mock-oauth-service` по контракту Google и GitHub: authorize, token (code и refresh), + revoke, ресурсы для проверки токена. + +## Impact +- Схема: `connections.oauth_provider`, `oauth_scopes`, `token_expires_at`; статус + `relogin`; `auth_kind` = `oauth`. Миграция 0031. Подключения по ключу не меняются. +- Код: `core/connection-oauth.ts` (новый), `core/connections.ts`, `core/connection-catalog.ts`, + `core/secrets-audit.ts`, `shared/env.ts`; веб `/connections` и маршруты start/callback; + testkit `mock-oauth-service`; i18n ru/kk/en. diff --git a/openspec/changes/pep-252-access-hub-oauth/specs/access-hub/spec.md b/openspec/changes/pep-252-access-hub-oauth/specs/access-hub/spec.md new file mode 100644 index 00000000..209cb32c --- /dev/null +++ b/openspec/changes/pep-252-access-hub-oauth/specs/access-hub/spec.md @@ -0,0 +1,65 @@ +## ADDED Requirements + +### Requirement: Подключение входом через сервис +Карточки Google Sheets, Google Drive, Google Calendar и GitHub SHALL предлагать подключение +входом через сервис (OAuth 2.0 code + PKCE S256), когда у FORGE настроен клиент этого +сервиса; без настроенного клиента способ SHALL быть скрыт. Владелец SHALL видеть права, +которые просит FORGE, отдельно для «только чтение» и «чтение и запись». Токены SHALL +храниться только в зашифрованном конверте подключения и не попадать в журнал, ответы, +адреса и экраны. + +#### Scenario: Владелец подключает Google Sheets входом +- **GIVEN** у FORGE настроен клиент Google +- **AND** владелец «anna» открыла карточку Google Sheets +- **WHEN** она выбирает «только чтение» и входит в Google +- **THEN** в «Ваших подключениях» появляется «Google Sheets» с правом `spreadsheets.readonly` +- **AND** токенов нет ни в журнале, ни на странице + +#### Scenario: Клиент не настроен +- **GIVEN** у FORGE не задан клиент GitHub +- **WHEN** владелец открывает карточку GitHub +- **THEN** кнопки «Войти через GitHub» нет, остаётся подключение ключом + +#### Scenario: Поток подменили +- **GIVEN** «anna» начала вход через Google +- **WHEN** ответ сервиса приходит с другим state, повторно или в браузер «boris» +- **THEN** подключение не создаётся +- **AND** поток больше не принимается + +### Requirement: Шлюз сам обновляет токен +Шлюз SHALL перед вызовом обновлять токен доступа, срок которого истекает (и один раз после +ответа 401), и сохранять новые токены. Если сервис отклонил обновление, подключение SHALL +получить статус «нужно войти заново», токены SHALL быть стёрты, владелец SHALL получить одно +сообщение, а вызовы агентов SHALL отклоняться с причиной «нужно войти заново». + +#### Scenario: Токен истёк — агент читает таблицу +- **GIVEN** подключение Google Sheets с разрешением чтения проекту PEP +- **AND** срок токена доступа истёк +- **WHEN** агент проекта читает таблицу через шлюз +- **THEN** шлюз обновляет токен и отдаёт агенту ответ 200 + +#### Scenario: Доступ отозвали в самом сервисе +- **GIVEN** владелец отозвал доступ FORGE в настройках Google +- **WHEN** агент обращается к подключению с истёкшим токеном +- **THEN** агент получает отказ «нужно войти заново» +- **AND** владелец получает одно сообщение, повторный вызов второго не создаёт + +#### Scenario: Войти заново +- **GIVEN** подключение в статусе «нужно войти заново» с разрешением проекту PEP +- **WHEN** владелец нажимает «Войти заново» и входит в сервис +- **THEN** подключение снова активно с прежними разрешениями + +### Requirement: Отзыв доступа отзывает токен в сервисе +«Отозвать доступ» и «Удалить» для подключения входом SHALL отзывать токен и в самом сервисе, +если сервис это поддерживает; сбой сервиса SHALL NOT мешать отзыву в FORGE. + +#### Scenario: Отзыв GitHub +- **GIVEN** подключение GitHub входом +- **WHEN** владелец нажимает «Отозвать доступ» +- **THEN** GitHub получает запрос на отзыв разрешения FORGE +- **AND** агенты получают отказ «подключение отозвано» + +#### Scenario: Сервис не отвечает при отзыве +- **GIVEN** сервис отзыва недоступен +- **WHEN** владелец отзывает подключение +- **THEN** подключение в FORGE отозвано и токены стёрты diff --git a/openspec/changes/pep-252-access-hub-oauth/tasks.md b/openspec/changes/pep-252-access-hub-oauth/tasks.md new file mode 100644 index 00000000..bf1cd46b --- /dev/null +++ b/openspec/changes/pep-252-access-hub-oauth/tasks.md @@ -0,0 +1,23 @@ +## 1. Данные и провайдеры +- [ ] 1.1 Колонки `oauth_provider`, `oauth_scopes`, `token_expires_at`, статус `relogin`, миграция 0031 +- [ ] 1.2 `core/connection-oauth.ts`: провайдеры google/github, настройки клиентов, права карточек +- [ ] 1.3 env: `PEPPA_OAUTH_*`; ревизия `/secrets` + +## 2. Поток входа +- [ ] 2.1 `startConnectionOAuth` / `completeConnectionOAuth` (state, PKCE, браузер, пользователь, одноразовость) +- [ ] 2.2 Создание и «войти заново» подключения с токенами в конверте + +## 3. Шлюз +- [ ] 3.1 `connectionCredential`: обновление токена, гонка, `relogin` + одно сообщение +- [ ] 3.2 `callConnection` и проверка: Bearer, повтор после 401, причина `needs_login` +- [ ] 3.3 Отзыв в сервисе при «Отозвать доступ» / «Удалить» + +## 4. Веб +- [ ] 4.1 Маршруты `/connections/oauth/start` и `/connections/oauth/callback` +- [ ] 4.2 `/connections`: кнопка входа с выбором уровня и списком прав, «Войти заново», статус +- [ ] 4.3 Тексты ru/kk/en, словарь + +## 5. Проверки +- [ ] 5.1 Мок `mock-oauth-service` (Google/GitHub: authorize, token, refresh, revoke, ресурсы) +- [ ] 5.2 Тест `access-hub-oauth.test.ts`: вход, обновление, отозванный токен, чужой пользователь, отзыв +- [ ] 5.3 lint, typecheck, тесты, память проекта, archive, PR diff --git a/packages/core/src/connection-catalog.ts b/packages/core/src/connection-catalog.ts index 3f7f4e29..e072642d 100644 --- a/packages/core/src/connection-catalog.ts +++ b/packages/core/src/connection-catalog.ts @@ -3,13 +3,13 @@ // its `catalog_id`; read rules, fixed headers and the check call are taken from this file on every // call, so a fix here applies to existing connections at once. // -// Sources: each service's public API documentation (docsUrl). Google is by API key only (public -// data); service accounts and OAuth are a separate story. Kazakhstan: Kaspi Магазин has an open +// Sources: each service's public API documentation (docsUrl). A Google API key opens only public +// data; signing in (OAuth, PEP-252) — the card's `oauth`, core/connection-oauth.ts. Kazakhstan: Kaspi Магазин has an open // seller API with `X-Auth-Token`; 2GIS — key in the query. Others (Kaspi Pay, Halyk, eGov) have no // open API with a plain key — not in the catalog, use «Свой сервис» if a partner gives one. import { m as tr } from "@peppa/shared/i18n"; -export type CatalogAuth = "bearer" | "header" | "basic" | "query" | "path"; +export type CatalogAuth = "bearer" | "header" | "basic" | "query" | "path" | "oauth"; export type CatalogKind = "payments" | "code" | "mail" | "messaging" | "ai" | "cloud" | "errors" | "data" | "docs" | "maps" | "commerce"; export const CATALOG_KINDS: CatalogKind[] = ["payments", "code", "mail", "messaging", "ai", "cloud", "errors", "data", "docs", "maps", "commerce"]; @@ -40,6 +40,19 @@ export interface CatalogCheck { bodyIncludes?: string; } +/** PEP-252: sign-in through the service (OAuth 2.0 code + PKCE) — core/connection-oauth.ts. */ +export type OAuthProviderId = "google" | "github"; + +export interface CatalogOAuth { + provider: OAuthProviderId; + /** Scopes for «только чтение» — the minimum the service has. */ + read: string[]; + /** Scopes for «чтение и запись». */ + write: string[]; + /** Said to the owner next to the button (translated), e.g. when the service has no read-only scope. */ + note?: string; +} + export interface CatalogService { /** Also the default short name of the connection for agents. */ id: string; @@ -65,8 +78,12 @@ export interface CatalogService { idempotency?: boolean; /** Extra search words (ru/en). */ tags?: string[]; + /** PEP-252: the card can also be connected by signing in (when FORGE has a client of the provider). */ + oauth?: CatalogOAuth; } +const GOOGLE_SCOPE = "https://www.googleapis.com/auth/"; + const GET_ALL = ["GET /"]; export const CONNECTION_CATALOG: CatalogService[] = [ @@ -83,6 +100,13 @@ export const CONNECTION_CATALOG: CatalogService[] = [ read: GET_ALL, check: { method: "GET", path: "/user" }, tags: ["git", "код", "code"], + oauth: { + provider: "github", + // GitHub OAuth apps have no read-only scope for private repositories: «только чтение» is kept by the gateway's read rule. + read: ["repo", "read:org"], + write: ["repo", "read:org"], + note: tr("У GitHub нет отдельного права «только чтение» для закрытых репозиториев: GitHub покажет полный доступ к коду, а читать или менять — решает разрешение в FORGE."), + }, }, { id: "gitea", @@ -127,6 +151,7 @@ export const CONNECTION_CATALOG: CatalogService[] = [ // A valid key gets 404 for a sheet that doesn't exist; a bad key — 400 «API key not valid». check: { method: "GET", path: "/v4/spreadsheets/forge-key-check", ok: [200, 404], badKey: [400, 401, 403] }, tags: ["google", "таблицы", "sheets"], + oauth: { provider: "google", read: [`${GOOGLE_SCOPE}spreadsheets.readonly`], write: [`${GOOGLE_SCOPE}spreadsheets`] }, }, { id: "google-drive", @@ -142,6 +167,7 @@ export const CONNECTION_CATALOG: CatalogService[] = [ read: GET_ALL, check: { method: "GET", path: "/files/forge-key-check", ok: [200, 404], badKey: [400, 401, 403] }, tags: ["google", "файлы", "drive"], + oauth: { provider: "google", read: [`${GOOGLE_SCOPE}drive.readonly`], write: [`${GOOGLE_SCOPE}drive`] }, }, { id: "google-calendar", @@ -157,6 +183,7 @@ export const CONNECTION_CATALOG: CatalogService[] = [ read: GET_ALL, check: { method: "GET", path: "/calendars/forge-key-check/events", ok: [200, 404], badKey: [400, 401, 403] }, tags: ["google", "календарь", "calendar"], + oauth: { provider: "google", read: [`${GOOGLE_SCOPE}calendar.readonly`], write: [`${GOOGLE_SCOPE}calendar.readonly`, `${GOOGLE_SCOPE}calendar.events`] }, }, { id: "telegram", diff --git a/packages/core/src/connection-oauth-flow.ts b/packages/core/src/connection-oauth-flow.ts new file mode 100644 index 00000000..e65c925a --- /dev/null +++ b/packages/core/src/connection-oauth-flow.ts @@ -0,0 +1,122 @@ +// PEP-252: the sign-in flow of a connection — like Google login (PEP-90): state and PKCE verifier +// in `settings` (one-shot, 10 min), the state also in an httpOnly cookie of the starting browser, +// and the callback must come to the same signed-in owner. Only then the code is exchanged; the +// tokens go straight into the connection's sealed envelope (PEP-254). +import { m as tr } from "@peppa/shared/i18n"; +import { connectionGrants, connections, type Db } from "@peppa/db"; +import { and, eq } from "drizzle-orm"; +import { createHash, randomBytes } from "node:crypto"; +import { logEvent } from "./audit.ts"; +import { catalogService } from "./connection-catalog.ts"; +import { cardScopes, exchangeCode, OAUTH_ERROR_TEXT, oauthClient, packTokens, scopesLevel, type OAuthLevel } from "./connection-oauth.ts"; +import { CONNECTION_NAME_MAX, freeSlug, ownConnection, sealConnectionSecret } from "./connections.ts"; +import { hashToken } from "./crypto.ts"; +import { PeppaError } from "./errors.ts"; +import { deleteSetting, getSetting, setSetting } from "./settings.ts"; + +export const CONNECTION_OAUTH_TTL_MS = 10 * 60_000; +/** The browser cookie of the flow (path /connections/oauth). */ +export const CONNECTION_OAUTH_COOKIE = "peppa_conn_oauth"; + +interface Flow { + userId: number; + catalogId: string; + level: OAuthLevel; + /** «Войти заново»: the connection whose tokens are replaced. */ + connectionId: number | null; + verifier: string; + redirectUri: string; + scopes: string[]; + expiresAt: number; +} + +const flowKey = (state: string) => `conn.oauth.flow:${hashToken(state)}`; + +export interface ConnectionOAuthStart { + url: string; + /** Goes into the httpOnly cookie; the callback must bring it back. */ + state: string; +} + +/** Starts signing in for a catalog card (new connection) or for an own connection (`connectionId`, sign in again). */ +export async function startConnectionOAuth(db: Db, userId: number, i: { catalogId?: string | null; connectionId?: number | null; level?: string | null; redirectUri: string }, env: NodeJS.ProcessEnv = process.env): Promise { + let catalogId = i.catalogId ?? null; + let level: OAuthLevel = i.level === "write" ? "write" : "read"; + if (i.connectionId != null) { + const c = await ownConnection(db, userId, i.connectionId); + if (c.authKind !== "oauth") throw new PeppaError(tr("Это подключение работает по ключу доступа")); + catalogId = c.catalogId; + if (i.level !== "read" && i.level !== "write") level = scopesLevel(catalogService(c.catalogId), c.oauthScopes); + } + const card = catalogService(catalogId); + if (!card?.oauth) throw new PeppaError(tr("У этого сервиса нет входа через сервис — подключите его ключом")); + const client = oauthClient(card.oauth.provider, env); + if (!client) throw new PeppaError(OAUTH_ERROR_TEXT.notConfigured); + const scopes = cardScopes(card, level); + const state = randomBytes(24).toString("base64url"); + const verifier = randomBytes(32).toString("base64url"); + await setSetting(db, flowKey(state), { userId, catalogId: card.id, level, connectionId: i.connectionId ?? null, verifier, redirectUri: i.redirectUri, scopes, expiresAt: Date.now() + CONNECTION_OAUTH_TTL_MS } satisfies Flow); + const q = new URLSearchParams({ + client_id: client.clientId, + redirect_uri: i.redirectUri, + response_type: "code", + scope: scopes.join(" "), + state, + code_challenge: createHash("sha256").update(verifier).digest("base64url"), + code_challenge_method: "S256", + ...client.provider.authorizeParams, + }); + return { url: `${client.provider.authorize(client.base)}?${q}`, state }; +} + +/** + * The service sent the browser back. One-shot: the flow is removed before anything else. Refused + * (and nothing created) when the state differs from the browser's cookie, the flow is gone or + * stale, or another person is signed in now. + */ +export async function completeConnectionOAuth(db: Db, userId: number, i: { state: string; code: string; cookieState: string }, o: { now?: Date } = {}): Promise<{ connectionId: number; created: boolean }> { + if (!i.state || !i.code || i.state !== i.cookieState) throw new PeppaError(OAUTH_ERROR_TEXT.stale); + const flow = await getSetting(db, flowKey(i.state)); + await deleteSetting(db, flowKey(i.state)); + if (!flow || Date.now() >= flow.expiresAt) throw new PeppaError(OAUTH_ERROR_TEXT.stale); + if (flow.userId !== userId) throw new PeppaError(OAUTH_ERROR_TEXT.stale); + const card = catalogService(flow.catalogId); + const client = card?.oauth ? oauthClient(card.oauth.provider) : null; + if (!card?.oauth || !client) throw new PeppaError(OAUTH_ERROR_TEXT.notConfigured); + const r = await exchangeCode(client, { code: i.code, redirectUri: flow.redirectUri, verifier: flow.verifier }, o.now); + if (!r.ok) throw new PeppaError(OAUTH_ERROR_TEXT.failed); + // Google lets a person untick scopes: without any of the asked ones the connection is useless. + const granted = r.answer.scopes ?? flow.scopes; + if (!flow.scopes.some((s) => granted.includes(s))) throw new PeppaError(OAUTH_ERROR_TEXT.noScopes); + const patch = { + ...sealConnectionSecret(packTokens(r.answer.tokens)), + oauthProvider: card.oauth.provider, + oauthScopes: granted, + tokenExpiresAt: r.answer.expiresAt, + status: "active" as const, + revokedAt: null, + checkStatus: null, + checkedAt: null, + checkAlertedAt: null, + }; + + if (flow.connectionId != null) { + // Sign in again: the same connection with its grants. Gone or not the owner's — refused. + const c = await ownConnection(db, userId, flow.connectionId); + if (c.authKind !== "oauth" || c.catalogId !== card.id) throw new PeppaError(OAUTH_ERROR_TEXT.stale); + await db.update(connections).set(patch).where(and(eq(connections.id, c.id), eq(connections.ownerId, userId))); + const grants = await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, c.id)); + for (const projectId of new Set(grants.map((g) => g.projectId))) await logEvent(db, { projectId, type: "connection_signed_in", payload: { connectionId: c.id } }); + return { connectionId: c.id, created: false }; + } + + const taken = new Set((await db.select({ name: connections.name }).from(connections).where(eq(connections.ownerId, userId))).map((r) => r.name)); + let name = card.name; + for (let n = 2; taken.has(name); n++) name = `${card.name} ${n}`.slice(0, CONNECTION_NAME_MAX); + const slug = await freeSlug(db, userId, card.id); + const [row] = await db + .insert(connections) + .values({ ownerId: userId, name, baseUrl: card.baseUrl, authKind: "oauth", authHeader: null, catalogId: card.id, slug, ...patch }) + .returning({ id: connections.id }); + return { connectionId: row!.id, created: true }; +} diff --git a/packages/core/src/connection-oauth.ts b/packages/core/src/connection-oauth.ts new file mode 100644 index 00000000..35decb43 --- /dev/null +++ b/packages/core/src/connection-oauth.ts @@ -0,0 +1,203 @@ +// PEP-252 Access Hub: connecting a service by signing in (OAuth 2.0 authorization code + PKCE S256). +// This file knows the providers — their endpoints, FORGE's client settings and the token calls +// (code exchange, refresh, revoke) — and nothing about the database. The flow (state in settings, +// the browser cookie, the owner) is in connection-oauth-flow.ts; the gateway's refresh is in +// connections.ts (`connectionCredential`). Tokens never leave these functions except into the +// connection's sealed envelope (PEP-254) and the outgoing Authorization header. +import { m as tr } from "@peppa/shared/i18n"; +import { catalogService, type CatalogService, type OAuthProviderId } from "./connection-catalog.ts"; + +export type { OAuthProviderId } from "./connection-catalog.ts"; + +export const OAUTH_TIMEOUT_MS = 15_000; +export const OAUTH_REVOKE_TIMEOUT_MS = 5_000; +/** A token that expires within this window is refreshed before the call. */ +export const OAUTH_REFRESH_EARLY_MS = 60_000; + +export interface OAuthProvider { + id: OAuthProviderId; + /** Brand name for «Войти через …». */ + name: string; + /** Env names of FORGE's client; `fallback` — another client of the same provider (Google login, PEP-90). */ + env: { id: string; secret: string; base: string; fallbackId?: string; fallbackSecret?: string }; + authorize: (base: string | null) => string; + token: (base: string | null) => string; + /** Extra authorize parameters (Google: offline access, so a refresh token comes). */ + authorizeParams: Record; +} + +export const OAUTH_PROVIDERS: Record = { + google: { + id: "google", + name: "Google", + env: { id: "PEPPA_OAUTH_GOOGLE_CLIENT_ID", secret: "PEPPA_OAUTH_GOOGLE_CLIENT_SECRET", base: "PEPPA_OAUTH_GOOGLE_BASE", fallbackId: "GOOGLE_CLIENT_ID", fallbackSecret: "GOOGLE_CLIENT_SECRET" }, + authorize: (b) => (b ? `${b}/auth` : "https://accounts.google.com/o/oauth2/v2/auth"), + token: (b) => (b ? `${b}/token` : "https://oauth2.googleapis.com/token"), + // prompt=consent: Google sends a refresh token only on a consent screen. + authorizeParams: { access_type: "offline", prompt: "consent", include_granted_scopes: "false" }, + }, + github: { + id: "github", + name: "GitHub", + env: { id: "PEPPA_OAUTH_GITHUB_CLIENT_ID", secret: "PEPPA_OAUTH_GITHUB_CLIENT_SECRET", base: "PEPPA_OAUTH_GITHUB_BASE" }, + authorize: (b) => `${b ?? "https://github.com"}/login/oauth/authorize`, + token: (b) => `${b ?? "https://github.com"}/login/oauth/access_token`, + authorizeParams: { allow_signup: "false" }, + }, +}; + +export interface ServiceOAuthClient { + provider: OAuthProvider; + clientId: string; + clientSecret: string; + /** Test/mock base of the provider's endpoints, null — the real ones. */ + base: string | null; +} + +/** FORGE's client of a provider, or null — the sign-in way is hidden. */ +export function oauthClient(id: OAuthProviderId | string | null | undefined, env: NodeJS.ProcessEnv = process.env): ServiceOAuthClient | null { + const provider = id ? OAUTH_PROVIDERS[id as OAuthProviderId] : undefined; + if (!provider) return null; + const own = env[provider.env.id] && env[provider.env.secret]; + const clientId = own ? env[provider.env.id] : provider.env.fallbackId ? env[provider.env.fallbackId] : undefined; + const clientSecret = own ? env[provider.env.secret] : provider.env.fallbackSecret ? env[provider.env.fallbackSecret] : undefined; + if (!clientId || !clientSecret) return null; + const base = env[provider.env.base]?.replace(/\/+$/, "") || null; + return { provider, clientId, clientSecret, base }; +} + +export const oauthEnabled = (id: OAuthProviderId | string | null | undefined, env: NodeJS.ProcessEnv = process.env) => !!oauthClient(id, env); + +export type OAuthLevel = "read" | "write"; + +/** Scopes FORGE asks for one level of a card. */ +export function cardScopes(card: CatalogService, level: OAuthLevel): string[] { + return card.oauth ? (level === "write" ? card.oauth.write : card.oauth.read) : []; +} + +/** What a card offers for signing in, for the page: null — no sign-in for it (or no client). */ +export function oauthOffer(catalogId: string | null | undefined, env: NodeJS.ProcessEnv = process.env): { provider: OAuthProviderId; providerName: string; read: string[]; write: string[]; note: string | null } | null { + const card = catalogService(catalogId); + if (!card?.oauth || !oauthEnabled(card.oauth.provider, env)) return null; + return { provider: card.oauth.provider, providerName: OAUTH_PROVIDERS[card.oauth.provider].name, read: card.oauth.read, write: card.oauth.write, note: card.oauth.note ?? null }; +} + +/** «https://www.googleapis.com/auth/spreadsheets.readonly» → «spreadsheets.readonly». */ +export const scopeLabel = (scope: string) => scope.replace(/^https:\/\/www\.googleapis\.com\/auth\//, ""); + +/** Level of saved scopes: all write scopes of the card granted → write. */ +export function scopesLevel(card: CatalogService | null, scopes: string[] | null | undefined): OAuthLevel { + if (!card?.oauth || !scopes?.length) return "read"; + const read = new Set(card.oauth.read); + const extra = card.oauth.write.filter((s) => !read.has(s)); + if (!extra.length) return "read"; + return extra.every((s) => scopes.includes(s)) ? "write" : "read"; +} + +// ---------- tokens ---------- + +/** What the sealed envelope of a sign-in connection holds (JSON). */ +export interface ServiceTokens { + access: string; + refresh: string | null; +} + +export const packTokens = (t: ServiceTokens) => JSON.stringify({ v: 1, access: t.access, refresh: t.refresh }); + +export function unpackTokens(raw: string): ServiceTokens | null { + try { + const j = JSON.parse(raw) as { v?: number; access?: unknown; refresh?: unknown }; + if (j.v !== 1 || typeof j.access !== "string" || !j.access) return null; + return { access: j.access, refresh: typeof j.refresh === "string" && j.refresh ? j.refresh : null }; + } catch { + return null; + } +} + +export interface TokenAnswer { + tokens: ServiceTokens; + /** null — the token does not expire (GitHub OAuth app). */ + expiresAt: Date | null; + /** What the service says it granted; null — it didn't say. */ + scopes: string[] | null; +} + +/** rejected — the service refused (revoked, wrong code); failed — no answer / 5xx (try later). */ +export type TokenFailure = { ok: false; rejected: boolean }; + +const TOKEN_SHAPE = /^[\x21-\x7e]{1,4096}$/; + +async function tokenCall(c: ServiceOAuthClient, body: Record, now: Date): Promise<{ ok: true; answer: TokenAnswer } | TokenFailure> { + let res: Response; + try { + res = await fetch(c.provider.token(c.base), { + method: "POST", + // GitHub answers form-encoded without Accept. + headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json", "user-agent": "PeppaFactory-AccessHub/1" }, + body: new URLSearchParams({ ...body, client_id: c.clientId, client_secret: c.clientSecret }), + redirect: "error", + signal: AbortSignal.timeout(OAUTH_TIMEOUT_MS), + }); + } catch { + return { ok: false, rejected: false }; + } + if (res.status >= 500) return { ok: false, rejected: false }; + const j = (await res.json().catch(() => null)) as { access_token?: unknown; refresh_token?: unknown; expires_in?: unknown; scope?: unknown; error?: unknown } | null; + // GitHub reports errors with 200 and `error`; Google with 400/401. + if (!j || j.error || !res.ok || typeof j.access_token !== "string" || !TOKEN_SHAPE.test(j.access_token)) return { ok: false, rejected: res.status < 500 && !!j }; + const refresh = typeof j.refresh_token === "string" && TOKEN_SHAPE.test(j.refresh_token) ? j.refresh_token : null; + const sec = Number(j.expires_in); + const scopes = typeof j.scope === "string" ? j.scope.split(/[\s,]+/).filter(Boolean) : null; + return { ok: true, answer: { tokens: { access: j.access_token, refresh }, expiresAt: Number.isFinite(sec) && sec > 0 ? new Date(now.getTime() + sec * 1000) : null, scopes } }; +} + +export function exchangeCode(c: ServiceOAuthClient, i: { code: string; redirectUri: string; verifier: string }, now = new Date()) { + return tokenCall(c, { grant_type: "authorization_code", code: i.code, redirect_uri: i.redirectUri, code_verifier: i.verifier }, now); +} + +export function refreshTokens(c: ServiceOAuthClient, refresh: string, now = new Date()) { + return tokenCall(c, { grant_type: "refresh_token", refresh_token: refresh }, now); +} + +/** + * Revokes FORGE's access in the service itself. Google: POST /revoke (the refresh token revokes + * the whole grant); GitHub: DELETE /applications/{client_id}/grant (basic client auth). Never + * throws: the revoke in FORGE happens whatever the service answers. + */ +export async function revokeAtService(providerId: string | null | undefined, tokens: ServiceTokens, env: NodeJS.ProcessEnv = process.env): Promise<"revoked" | "failed" | "unsupported"> { + const c = oauthClient(providerId, env); + if (!c) return "unsupported"; + try { + let res: Response; + if (c.provider.id === "google") { + res = await fetch(c.base ? `${c.base}/revoke` : "https://oauth2.googleapis.com/revoke", { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ token: tokens.refresh ?? tokens.access }), + redirect: "error", + signal: AbortSignal.timeout(OAUTH_REVOKE_TIMEOUT_MS), + }); + } else { + res = await fetch(`${c.base ?? "https://api.github.com"}/applications/${encodeURIComponent(c.clientId)}/grant`, { + method: "DELETE", + headers: { authorization: `Basic ${Buffer.from(`${c.clientId}:${c.clientSecret}`).toString("base64")}`, accept: "application/vnd.github+json", "content-type": "application/json", "user-agent": "PeppaFactory-AccessHub/1" }, + body: JSON.stringify({ access_token: tokens.access }), + redirect: "error", + signal: AbortSignal.timeout(OAUTH_REVOKE_TIMEOUT_MS), + }); + } + await res.arrayBuffer().catch(() => null); + // Already revoked/unknown token: nothing left to revoke. + return res.ok || res.status === 400 || res.status === 404 ? "revoked" : "failed"; + } catch { + return "failed"; + } +} + +export const OAUTH_ERROR_TEXT = { + notConfigured: tr("Вход через этот сервис в FORGE пока не настроен — подключите его ключом"), + denied: tr("Вход отменён: подключение не создано"), + stale: tr("Вход устарел или уже использован — начните заново"), + failed: tr("Сервис не подтвердил вход — попробуйте ещё раз"), + noScopes: tr("Вы не дали FORGE нужный доступ — начните заново и отметьте все пункты"), +}; diff --git a/packages/core/src/connections.ts b/packages/core/src/connections.ts index d44566ad..96ec6a9c 100644 --- a/packages/core/src/connections.ts +++ b/packages/core/src/connections.ts @@ -16,6 +16,7 @@ import { logEvent } from "./audit.ts"; import { catalogService, classifyRequest, type CatalogAuth, type CatalogCheck } from "./connection-catalog.ts"; import { addMasterMessage } from "./chats.ts"; import { appendJournal, type ConnectionJournalDecision } from "./connection-journal.ts"; +import { OAUTH_REFRESH_EARLY_MS, oauthClient, packTokens, refreshTokens, revokeAtService, unpackTokens } from "./connection-oauth.ts"; import { decrypt, encrypt, newDataKey, openWithKey, sealWithKey } from "./crypto.ts"; import { deliverToUser } from "./notifications.ts"; import { PeppaError } from "./errors.ts"; @@ -40,6 +41,7 @@ export type ConnectionReason = | "unknown_connection" | "ambiguous_connection" | "revoked" + | "needs_login" | "no_grant" | "operation_denied" | "read_denied" @@ -61,6 +63,7 @@ export const CONNECTION_REASON_TEXT: Record = { unknown_connection: tr("нет такого подключения"), ambiguous_connection: tr("несколько подключений с таким названием"), revoked: tr("подключение отозвано"), + needs_login: tr("нужно заново войти в сервис"), no_grant: tr("нет разрешения для проекта или агента"), operation_denied: tr("операция не разрешена"), read_denied: tr("чтение не разрешено"), @@ -89,8 +92,13 @@ export interface ConnectionView { slug: string; checkStatus: ConnectionCheckStatus | null; checkedAt: Date | null; - status: "active" | "revoked"; + /** relogin (PEP-252): the service refused to refresh the sign-in — «Войти заново». */ + status: "active" | "revoked" | "relogin"; hasKey: boolean; + /** PEP-252: signed in through the service (google|github), null — a key. */ + oauthProvider: string | null; + /** PEP-252: scopes the service granted (shown to the owner). */ + oauthScopes: string[]; revokedAt: Date | null; lastUsedAt: Date | null; createdAt: Date; @@ -231,7 +239,7 @@ export function normalizeOperations(raw: string[] | string, o: { allowEmpty?: bo // ---------- owner's management ---------- -async function ownConnection(db: Db, userId: number, connectionId: number) { +export async function ownConnection(db: Db, userId: number, connectionId: number) { const [c] = await db.select().from(connections).where(eq(connections.id, connectionId)); // No superadmin bypass: a connection is its owner's alone. if (!c || c.ownerId !== userId) throw new PeppaError(tr("Подключение не найдено")); @@ -319,7 +327,7 @@ export function slugify(name: string): string { return latin.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, ""); } -async function freeSlug(db: Db, userId: number, base: string, exceptId?: number): Promise { +export async function freeSlug(db: Db, userId: number, base: string, exceptId?: number): Promise { const root = base || "service"; const taken = new Set((await db.select({ id: connections.id, slug: connections.slug }).from(connections).where(eq(connections.ownerId, userId))).filter((r) => r.id !== exceptId).map((r) => r.slug)); if (!taken.has(root)) return root; @@ -358,6 +366,7 @@ export async function createConnection(db: Db, userId: number, i: ConnectionInpu /** Replaces the key; also brings a revoked connection back with its grants. */ export async function replaceConnectionSecret(db: Db, userId: number, connectionId: number, secret: string): Promise { const c = await ownConnection(db, userId, connectionId); + if (c.authKind === "oauth") throw new PeppaError(tr("Это подключение работает через вход в сервис: нажмите «Войти заново»")); const err = secretError(secret) ?? keyShapeError(c.authKind, secret); if (err) throw new PeppaError(err); // A new key: the old check result and the «key stopped working» message no longer apply. @@ -369,11 +378,24 @@ export async function replaceConnectionSecret(db: Db, userId: number, connection * and even a copy of the database no longer holds it. Grants stay visible to the owner and * start working again only after a new key (`replaceConnectionSecret`). */ -export async function revokeConnection(db: Db, userId: number, connectionId: number): Promise { +export async function revokeConnection(db: Db, userId: number, connectionId: number): Promise<{ remote: "revoked" | "failed" | "unsupported" | null }> { const c = await ownConnection(db, userId, connectionId); - await db.update(connections).set({ status: "revoked", secretEnc: null, dekEnc: null, revokedAt: new Date() }).where(eq(connections.id, c.id)); + // Wiped first: the gateway refuses at once, whatever the service answers below. + await db.update(connections).set({ status: "revoked", secretEnc: null, dekEnc: null, tokenExpiresAt: null, revokedAt: new Date() }).where(eq(connections.id, c.id)); + // PEP-252: a sign-in connection is revoked in the service too (best effort, ≤ 5 s). + let remote: "revoked" | "failed" | "unsupported" | null = null; + if (c.authKind === "oauth" && c.secretEnc) { + let tokens = null; + try { + tokens = unpackTokens(openConnectionSecret(c) ?? ""); + } catch { + tokens = null; + } + remote = tokens ? await revokeAtService(c.oauthProvider, tokens) : "failed"; + } const grants = await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, c.id)); - for (const projectId of new Set(grants.map((g) => g.projectId))) await logEvent(db, { projectId, type: "connection_revoked", payload: { connectionId: c.id } }); + for (const projectId of new Set(grants.map((g) => g.projectId))) await logEvent(db, { projectId, type: "connection_revoked", payload: { connectionId: c.id, ...(remote ? { remote } : {}) } }); + return { remote }; } export async function deleteConnection(db: Db, userId: number, connectionId: number): Promise { @@ -471,6 +493,8 @@ export async function listConnections(db: Db, userId: number): Promise(); for (const r of rows) { if (r.agentId != null && r.agentId !== s.agentId) continue; const card = catalogService(r.c.catalogId); - const c = by.get(r.c.id) ?? { id: r.c.id, name: r.c.name, slug: connectionSlug(r.c), service: card?.name ?? null, baseUrl: r.c.baseUrl, docsUrl: card?.docsUrl ?? null, readMode: "off", writeMode: "off", operations: [], checkStatus: r.c.checkStatus }; + const c = by.get(r.c.id) ?? { id: r.c.id, name: r.c.name, slug: connectionSlug(r.c), service: card?.name ?? null, baseUrl: r.c.baseUrl, docsUrl: card?.docsUrl ?? null, readMode: "off", writeMode: "off", operations: [], checkStatus: r.c.status === "relogin" ? "bad_key" : r.c.checkStatus }; c.operations = [...new Set([...c.operations, ...r.operations])]; c.readMode = widest(c.readMode, r.readMode); c.writeMode = widest(c.writeMode, r.writeMode); @@ -629,10 +653,78 @@ function buildRequest(conn: typeof connections.$inferSelect, secret: string, cle if (body) headers["content-length"] = String(body.length); if (conn.authKind === "header" && conn.authHeader) headers[conn.authHeader.toLowerCase()] = secret; else if (conn.authKind === "basic") headers.authorization = `Basic ${Buffer.from(secret).toString("base64")}`; - else if (conn.authKind === "bearer") headers.authorization = `Bearer ${secret}`; + else if (conn.authKind === "bearer" || conn.authKind === "oauth") headers.authorization = `Bearer ${secret}`; return { url, headers }; } +// ---------- PEP-252: the credential of a call (a key, or a sign-in token refreshed in time) ---------- + +type ConnRow = typeof connections.$inferSelect; +export type ConnectionCredential = { ok: true; secret: string; refreshable: boolean; refreshed: boolean } | { ok: false; reason: "needs_login" | "upstream_error" }; + +/** One refresh per connection at a time in this process (GitHub rotates the refresh token on use). */ +const refreshing = new Map>(); + +/** + * What goes into the request: the key as is; for a sign-in connection the access token, refreshed + * first when it expires within a minute (or `force` — the service answered 401). The service + * refused the refresh → the connection needs signing in again: tokens wiped, the owner gets one + * message. A refresh that got no answer leaves everything as is (`upstream_error`). + */ +export async function connectionCredential(db: Db, conn: ConnRow, o: { now?: Date; force?: boolean; notify?: (db: Db, c: { id: number; ownerId: number; name: string }) => Promise } = {}): Promise { + let plain: string | null; + try { + plain = openConnectionSecret(conn); + } catch { + return { ok: false, reason: "upstream_error" }; + } + if (conn.authKind !== "oauth") return plain ? { ok: true, secret: plain, refreshable: false, refreshed: false } : { ok: false, reason: "upstream_error" }; + const tokens = plain ? unpackTokens(plain) : null; + if (!tokens) return { ok: false, reason: "needs_login" }; + const now = o.now ?? new Date(); + const due = !!conn.tokenExpiresAt && conn.tokenExpiresAt.getTime() - now.getTime() <= OAUTH_REFRESH_EARLY_MS; + if (!o.force && !due) return { ok: true, secret: tokens.access, refreshable: !!tokens.refresh, refreshed: false }; + if (!tokens.refresh) { + // Nothing to refresh with: an expired token is the end of this sign-in; a 401 on a lasting token too. + await markRelogin(db, conn, o.notify); + return { ok: false, reason: "needs_login" }; + } + const running = refreshing.get(conn.id); + if (running) return running; + const job = (async (): Promise => { + const client = oauthClient(conn.oauthProvider); + if (!client) return { ok: false, reason: "upstream_error" }; // FORGE's client was removed: not the owner's fault + const r = await refreshTokens(client, tokens.refresh!, now); + if (r.ok) { + const next = { access: r.answer.tokens.access, refresh: r.answer.tokens.refresh ?? tokens.refresh }; + await db.update(connections).set({ ...sealConnectionSecret(packTokens(next)), tokenExpiresAt: r.answer.expiresAt, ...(r.answer.scopes ? { oauthScopes: r.answer.scopes } : {}) }).where(and(eq(connections.id, conn.id), eq(connections.status, "active"))); + return { ok: true, secret: next.access, refreshable: true, refreshed: true }; + } + if (!r.rejected) return { ok: false, reason: "upstream_error" }; + // Another process may have refreshed in between (and spent the old refresh token): take its tokens. + const [fresh] = await db.select().from(connections).where(eq(connections.id, conn.id)); + if (fresh?.status === "active" && fresh.secretEnc && fresh.secretEnc !== conn.secretEnc) return connectionCredential(db, fresh, { now, notify: o.notify }); + await markRelogin(db, conn, o.notify); + return { ok: false, reason: "needs_login" }; + })().finally(() => refreshing.delete(conn.id)); + refreshing.set(conn.id, job); + return job; +} + +/** The sign-in is over: tokens wiped, grants kept, ONE message to the owner until they sign in again. */ +async function markRelogin(db: Db, conn: ConnRow, notify?: (db: Db, c: { id: number; ownerId: number; name: string }) => Promise): Promise { + const [row] = await db + .update(connections) + .set({ status: "relogin", secretEnc: null, dekEnc: null, tokenExpiresAt: null, checkStatus: "bad_key", checkedAt: new Date() }) + .where(and(eq(connections.id, conn.id), eq(connections.status, "active"))) + .returning({ alerted: connections.checkAlertedAt }); + if (!row || row.alerted) return; + await db.update(connections).set({ checkAlertedAt: new Date() }).where(eq(connections.id, conn.id)); + await (notify ?? tellReloginNeeded)(db, { id: conn.id, ownerId: conn.ownerId, name: conn.name }); + const grants = await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, conn.id)); + for (const projectId of new Set(grants.map((g) => g.projectId))) await logEvent(db, { projectId, type: "connection_relogin", payload: { connectionId: conn.id } }); +} + export interface ConnectionCall { sessionId: number | null | undefined; /** Connection id or its name (when only one granted connection has it). */ @@ -760,6 +852,7 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?: conn = matches[0]!.c; if (!agentIsolated(s, o.env)) return deny("not_isolated"); + if (conn.status === "relogin") return deny("needs_login"); if (conn.status !== "active" || !conn.secretEnc) return deny("revoked"); const mine = matches.filter((g) => g.agentId == null || g.agentId === s.agentId); if (!mine.length) return deny("no_grant"); @@ -775,17 +868,16 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?: const [{ n }] = (await db.select({ n: count() }).from(connectionLog).where(and(eq(connectionLog.sessionId, s.id), eq(connectionLog.kind, "call"), gt(connectionLog.createdAt, new Date(now.getTime() - 60_000))))) as [{ n: number }]; if (n >= CONNECTION_RATE_PER_MIN) return deny("rate_limited"); - let secret: string; - try { - secret = openConnectionSecret(conn)!; - } catch { - await record("failed", "upstream_error", null); - return { ok: false, reason: "upstream_error" }; + // PEP-252: a sign-in token is refreshed here when it is about to expire. + let cred = await connectionCredential(db, conn, { now }); + if (!cred.ok) { + if (cred.reason === "needs_login") return deny("needs_login"); + await record("failed", cred.reason, null); + return { ok: false, reason: cred.reason }; } // Target = base (+ key in the path) + path; the host and the base path must survive URL parsing unchanged. - const built = buildRequest(conn, secret, clean, contentType, body); + let built = buildRequest(conn, cred.secret, clean, contentType, body); if (!built) return deny("bad_path"); - const { url, headers } = built; // Written before the service is called: a crash in the middle leaves «started, no result». const callId = (await record("allowed", null, null))!; @@ -793,7 +885,18 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?: const result = (decision: ConnectionJournalDecision, reason: ConnectionReason | null, statusCode: number | null) => record(decision, reason, statusCode, { kind: "result", parentId: callId, durationMs: Date.now() - started }); try { - const res = await (o.fetch ?? defaultConnectionFetch)({ url, method, headers, body }); + let res = await (o.fetch ?? defaultConnectionFetch)({ url: built.url, method, headers: built.headers, body }); + // A sign-in token the service no longer takes: refresh once and repeat (the same journal call). + if (res.status === 401 && cred.refreshable && !cred.refreshed) { + const again = await connectionCredential(db, conn, { now, force: true }); + if (!again.ok) { + await result(again.reason === "needs_login" ? "denied" : "failed", again.reason, again.reason === "needs_login" ? 401 : null); + return { ok: false, reason: again.reason }; + } + cred = again; + built = buildRequest(conn, cred.secret, clean, contentType, body)!; + res = await (o.fetch ?? defaultConnectionFetch)({ url: built.url, method, headers: built.headers, body }); + } if (res.status >= 300 && res.status < 400 && res.location) { await result("failed", "redirect", res.status); return { ok: false, reason: "redirect", status: res.status }; @@ -801,7 +904,7 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?: await result("allowed", res.truncated ? "too_large" : null, res.status); await db.update(connections).set({ lastUsedAt: now }).where(eq(connections.id, conn.id)); // The answer goes to the agent only: nothing of it is stored or sent anywhere (PEP-254). - const text = maskSecrets(res.body.toString("utf8"), secret.length >= 4 ? [secret] : []); + const text = maskSecrets(res.body.toString("utf8"), cred.secret.length >= 4 ? [cred.secret] : []); return { ok: true, status: res.status, contentType: res.contentType, body: text, truncated: res.truncated }; } catch (e) { const reason = e instanceof Refused ? e.reason : "upstream_error"; @@ -837,7 +940,7 @@ export function judgeCheck(check: CatalogCheck | null, res: { status: number; bo return { status: "down" }; } -async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: { fetch?: ConnectionFetch; now?: Date }): Promise { +async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: { fetch?: ConnectionFetch; now?: Date; notify?: (db: Db, c: { id: number; ownerId: number; name: string }) => Promise }): Promise { const now = o.now ?? new Date(); const check = catalogService(conn.catalogId)?.check ?? null; const method = check?.method ?? "GET"; @@ -848,9 +951,11 @@ async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: { fetc const entry = { ownerId: conn.ownerId, connectionId: conn.id, connectionName: conn.name, method, path: clean.path.slice(0, 300), createdAt: now }; const callId = appendJournal(db, { ...entry, kind: "call", decision: "allowed", reason: "owner_check", statusCode: null }); const started = Date.now(); + let relogin = false; try { - const secret = openConnectionSecret(conn)!; - const built = buildRequest(conn, secret, clean, null, null); + const cred = await connectionCredential(db, conn, { now, notify: o.notify }); + if (!cred.ok) relogin = cred.reason === "needs_login"; + const built = cred.ok ? buildRequest(conn, cred.secret, clean, null, null) : null; if (built) { // Own service: the check is the base address itself (no trailing «/» added). if (!check) built.url.pathname = built.url.pathname.replace(/\/$/, "") || "/"; @@ -860,18 +965,19 @@ async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: { fetc } catch { res = null; } - const verdict = judgeCheck(check, res); + const verdict = relogin ? { status: "bad_key" as const } : judgeCheck(check, res); const durationMs = Date.now() - started; appendJournal(db, { ...entry, kind: "result", parentId: callId, decision: verdict.status === "ok" ? "allowed" : "failed", reason: "owner_check", statusCode: res?.status ?? null, durationMs, createdAt: new Date(now.getTime() + durationMs) }); const patch: Partial = { checkStatus: verdict.status, checkedAt: now }; if (verdict.status === "ok") patch.checkAlertedAt = null; await db.update(connections).set(patch).where(eq(connections.id, conn.id)); - return { ...verdict, httpStatus: res?.status, checkedAt: now }; + return { ...verdict, httpStatus: res?.status, checkedAt: now, ...(relogin ? { relogin } : {}) }; } /** «Проверить»: the catalog's check call through the same address guards, owner only. */ export async function checkConnection(db: Db, userId: number, connectionId: number, o: { fetch?: ConnectionFetch; now?: Date } = {}): Promise { const c = await ownConnection(db, userId, connectionId); + if (c.status === "relogin") throw new PeppaError(tr("Сервис больше не пускает FORGE: нажмите «Войти заново»")); if (c.status !== "active" || !c.secretEnc) throw new PeppaError(tr("Подключение отозвано: сначала задайте новый ключ доступа")); return runCheck(db, c, o); } @@ -888,8 +994,9 @@ export async function connectionCheckTick(db: Db, o: { fetch?: ConnectionFetch; .filter((c) => c.secretEnc && (!c.checkedAt || now.getTime() - c.checkedAt.getTime() >= CONNECTION_CHECK_EVERY_MS)) .slice(0, CHECK_BATCH); for (const c of due) { - const r = await runCheck(db, c, { fetch: o.fetch, now }); - if (r.status === "bad_key" && c.checkStatus === "ok" && !c.checkAlertedAt) { + const r = await runCheck(db, c, { fetch: o.fetch, now, notify: o.notify }); + // A sign-in that ended has already told its owner (markRelogin). + if (!r.relogin && r.status === "bad_key" && c.checkStatus === "ok" && !c.checkAlertedAt) { await db.update(connections).set({ checkAlertedAt: now }).where(eq(connections.id, c.id)); await (o.notify ?? tellKeyStopped)(db, { id: c.id, ownerId: c.ownerId, name: c.name }); } @@ -897,6 +1004,22 @@ export async function connectionCheckTick(db: Db, o: { fetch?: ConnectionFetch; return due.length; } +/** PEP-252: one message to the owner — the service no longer lets FORGE in, sign in again. */ +export async function tellReloginNeeded(db: Db, c: { id: number; ownerId: number; name: string }): Promise { + const text = tr("Сервис больше не пускает FORGE в подключение «{name}» — возможно, доступ отозвали в самом сервисе. Агенты не смогут им пользоваться, пока вы не нажмёте «Войти заново» в разделе «Подключения».", { name: asIs(c.name) }); + const key = `connection-relogin:${c.id}`; + await addMasterMessage(db, c.ownerId, { kind: "event", important: true, text, dedupeKey: `master:${key}:${Date.now()}`, url: `/connections#c${c.id}` }).catch(() => null); + const [u] = await db.select().from(users).where(eq(users.id, c.ownerId)); + if (!u) return; + await deliverToUser(db, u, { + event: "failures", + dedupeKey: `${key}:${Date.now()}:${u.telegramChatId}`, + pushKey: `${key}:${Date.now()}:u${u.id}`, + telegram: { params: { text } }, + push: { title: tr("FORGE"), body: text, url: "/connections", tag: key }, + }).catch(() => null); +} + /** One message to the owner: the key of a connection stopped working. */ export async function tellKeyStopped(db: Db, c: { id: number; ownerId: number; name: string }): Promise { const text = tr("Ключ доступа подключения «{name}» перестал работать: агенты не смогут им пользоваться. Замените ключ в разделе «Подключения».", { name: asIs(c.name) }); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 13b43606..7612bd31 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -110,6 +110,8 @@ export * from "./accept-digest.ts"; export * from "./connections.ts"; export * from "./connection-journal.ts"; export * from "./connection-catalog.ts"; +export * from "./connection-oauth.ts"; +export * from "./connection-oauth-flow.ts"; export * from "./edge-dns.ts"; export * from "./retention.ts"; export * from "./history.ts"; diff --git a/packages/core/src/secrets-audit.ts b/packages/core/src/secrets-audit.ts index 9bb6bebd..d7a4e86b 100644 --- a/packages/core/src/secrets-audit.ts +++ b/packages/core/src/secrets-audit.ts @@ -97,6 +97,32 @@ export const PLATFORM_SECRETS: PlatformSecretDef[] = [ tr("Отметить: `peppa secrets rotated GITEA_OAUTH_CLIENT_SECRET`."), ], }, + { + name: "PEPPA_OAUTH_GOOGLE_CLIENT_SECRET", + label: tr("Секрет OAuth-клиента Google для подключений"), + usedBy: tr("вход в Google Sheets, Drive и Calendar в разделе «Подключения» и обновление их токенов (без него — общий клиент входа через Google)"), + how: "external", + optional: true, + steps: [ + tr("Google Cloud → APIs & Services → Credentials → OAuth-клиент FORGE → «Add secret», адрес возврата `<адрес FORGE>/connections/oauth/callback`, включены Sheets, Drive и Calendar API."), + tr("Идентификатор — в `PEPPA_OAUTH_GOOGLE_CLIENT_ID`, новый секрет — в `PEPPA_OAUTH_GOOGLE_CLIENT_SECRET`, {restart}", { restart: RESTART }), + tr("Старый секрет удалить в Google Cloud; выданные пользователям токены продолжают работать."), + tr("Отметить: `peppa secrets rotated PEPPA_OAUTH_GOOGLE_CLIENT_SECRET`."), + ], + }, + { + name: "PEPPA_OAUTH_GITHUB_CLIENT_SECRET", + label: tr("Секрет OAuth-приложения GitHub для подключений"), + usedBy: tr("вход в GitHub в разделе «Подключения», обновление и отзыв токенов"), + how: "external", + optional: true, + steps: [ + tr("GitHub → Settings → Developer settings → OAuth Apps → приложение FORGE (адрес возврата `<адрес FORGE>/connections/oauth/callback`) → «Generate a new client secret»."), + tr("Идентификатор — в `PEPPA_OAUTH_GITHUB_CLIENT_ID`, новый секрет — в `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`, {restart}", { restart: RESTART }), + tr("Старый секрет удалить в GitHub; выданные пользователям токены продолжают работать."), + tr("Отметить: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`."), + ], + }, { name: "BUGSINK_TOKEN", label: tr("API-токен Bugsink"), diff --git a/packages/db/migrations/0031_access_hub_oauth.sql b/packages/db/migrations/0031_access_hub_oauth.sql new file mode 100644 index 00000000..03f71cf5 --- /dev/null +++ b/packages/db/migrations/0031_access_hub_oauth.sql @@ -0,0 +1,3 @@ +ALTER TABLE `connections` ADD `oauth_provider` text;--> statement-breakpoint +ALTER TABLE `connections` ADD `oauth_scopes` text;--> statement-breakpoint +ALTER TABLE `connections` ADD `token_expires_at` integer; \ No newline at end of file diff --git a/packages/db/migrations/meta/0031_snapshot.json b/packages/db/migrations/meta/0031_snapshot.json new file mode 100644 index 00000000..5f56033c --- /dev/null +++ b/packages/db/migrations/meta/0031_snapshot.json @@ -0,0 +1,5288 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "6c47fd7d-e673-4463-a233-f919756f2836", + "prevId": "1ad8db33-759f-4508-9ebd-50d0f75742c5", + "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": {} + }, + "attachments": { + "name": "attachments", + "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 + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "chat_message_id": { + "name": "chat_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file": { + "name": "file", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mime": { + "name": "mime", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "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": { + "attachments_task": { + "name": "attachments_task", + "columns": [ + "task_id" + ], + "isUnique": false + }, + "attachments_message": { + "name": "attachments_message", + "columns": [ + "chat_message_id" + ], + "isUnique": false + }, + "attachments_event": { + "name": "attachments_event", + "columns": [ + "event_id" + ], + "isUnique": false + }, + "attachments_project": { + "name": "attachments_project", + "columns": [ + "project_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "attachments_project_id_projects_id_fk": { + "name": "attachments_project_id_projects_id_fk", + "tableFrom": "attachments", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "attachments_user_id_users_id_fk": { + "name": "attachments_user_id_users_id_fk", + "tableFrom": "attachments", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "attachments_task_id_tasks_id_fk": { + "name": "attachments_task_id_tasks_id_fk", + "tableFrom": "attachments", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "attachments_chat_message_id_chat_messages_id_fk": { + "name": "attachments_chat_message_id_chat_messages_id_fk", + "tableFrom": "attachments", + "tableTo": "chat_messages", + "columnsFrom": [ + "chat_message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "attachments_event_id_events_id_fk": { + "name": "attachments_event_id_events_id_fk", + "tableFrom": "attachments", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "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_thread": { + "name": "chat_messages_thread", + "columns": [ + "chat_id", + "thread_key", + "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 + }, + "tg_bot_user_id": { + "name": "tg_bot_user_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": { + "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" + }, + "chats_tg_bot_user_id_users_id_fk": { + "name": "chats_tg_bot_user_id_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "tg_bot_user_id" + ], + "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 + }, + "check_runs_task_sha": { + "name": "check_runs_task_sha", + "columns": [ + "task_id", + "sha" + ], + "isUnique": false + }, + "check_runs_updated": { + "name": "check_runs_updated", + "columns": [ + "updated_at" + ], + "isUnique": false + } + }, + "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": {} + }, + "connection_grants": { + "name": "connection_grants", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "connection_id": { + "name": "connection_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "operations": { + "name": "operations", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "read_mode": { + "name": "read_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'off'" + }, + "write_mode": { + "name": "write_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'off'" + }, + "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": { + "connection_grants_project": { + "name": "connection_grants_project", + "columns": [ + "project_id" + ], + "isUnique": false + }, + "connection_grants_connection": { + "name": "connection_grants_connection", + "columns": [ + "connection_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "connection_grants_connection_id_connections_id_fk": { + "name": "connection_grants_connection_id_connections_id_fk", + "tableFrom": "connection_grants", + "tableTo": "connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "connection_grants_project_id_projects_id_fk": { + "name": "connection_grants_project_id_projects_id_fk", + "tableFrom": "connection_grants", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "connection_grants_agent_id_agents_id_fk": { + "name": "connection_grants_agent_id_agents_id_fk", + "tableFrom": "connection_grants", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "connection_grants_created_by_users_id_fk": { + "name": "connection_grants_created_by_users_id_fk", + "tableFrom": "connection_grants", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "connection_log": { + "name": "connection_log", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "connection_id": { + "name": "connection_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "connection_name": { + "name": "connection_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_name": { + "name": "agent_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status_code": { + "name": "status_code", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'call'" + }, + "parent_id": { + "name": "parent_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_key": { + "name": "project_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "prev_hash": { + "name": "prev_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hash": { + "name": "hash", + "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": { + "connection_log_owner": { + "name": "connection_log_owner", + "columns": [ + "owner_id", + "id" + ], + "isUnique": false + }, + "connection_log_session_created": { + "name": "connection_log_session_created", + "columns": [ + "session_id", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "connection_log_owner_id_users_id_fk": { + "name": "connection_log_owner_id_users_id_fk", + "tableFrom": "connection_log", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "connection_log_connection_id_connections_id_fk": { + "name": "connection_log_connection_id_connections_id_fk", + "tableFrom": "connection_log", + "tableTo": "connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "connection_log_project_id_projects_id_fk": { + "name": "connection_log_project_id_projects_id_fk", + "tableFrom": "connection_log", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "connection_log_session_id_sessions_id_fk": { + "name": "connection_log_session_id_sessions_id_fk", + "tableFrom": "connection_log", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "connection_log_agent_id_agents_id_fk": { + "name": "connection_log_agent_id_agents_id_fk", + "tableFrom": "connection_log", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "connections": { + "name": "connections", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "base_url": { + "name": "base_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'bearer'" + }, + "auth_header": { + "name": "auth_header", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "catalog_id": { + "name": "catalog_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check_status": { + "name": "check_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check_alerted_at": { + "name": "check_alerted_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dek_enc": { + "name": "dek_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'active'" + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "oauth_provider": { + "name": "oauth_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "oauth_scopes": { + "name": "oauth_scopes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_used_at": { + "name": "last_used_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": { + "connections_owner_name": { + "name": "connections_owner_name", + "columns": [ + "owner_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "connections_owner_id_users_id_fk": { + "name": "connections_owner_id_users_id_fk", + "tableFrom": "connections", + "tableTo": "users", + "columnsFrom": [ + "owner_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 + }, + "events_session_type": { + "name": "events_session_type", + "columns": [ + "session_id", + "type" + ], + "isUnique": false + }, + "events_type_created": { + "name": "events_type_created", + "columns": [ + "type", + "created_at" + ], + "isUnique": false + }, + "events_project_created": { + "name": "events_project_created", + "columns": [ + "project_id", + "created_at" + ], + "isUnique": false + }, + "events_task_type": { + "name": "events_task_type", + "columns": [ + "task_id", + "type" + ], + "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": {} + }, + "feedback": { + "name": "feedback", + "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 + }, + "via": { + "name": "via", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "context": { + "name": "context", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'received'" + }, + "analysis": { + "name": "analysis", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "analysis_error": { + "name": "analysis_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "analysis_started_at": { + "name": "analysis_started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "option_index": { + "name": "option_index", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reject_reason": { + "name": "reject_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_at": { + "name": "decided_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": { + "feedback_user": { + "name": "feedback_user", + "columns": [ + "user_id", + "created_at" + ], + "isUnique": false + }, + "feedback_status": { + "name": "feedback_status", + "columns": [ + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "feedback_user_id_users_id_fk": { + "name": "feedback_user_id_users_id_fk", + "tableFrom": "feedback", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "feedback_task_id_tasks_id_fk": { + "name": "feedback_task_id_tasks_id_fk", + "tableFrom": "feedback", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "feedback_decided_by_users_id_fk": { + "name": "feedback_decided_by_users_id_fk", + "tableFrom": "feedback", + "tableTo": "users", + "columnsFrom": [ + "decided_by" + ], + "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 + }, + "deleted_at": { + "name": "deleted_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deleted_by": { + "name": "deleted_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))" + } + }, + "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" + }, + "projects_deleted_by_users_id_fk": { + "name": "projects_deleted_by_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "deleted_by" + ], + "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 + }, + "push_outbox_status_created": { + "name": "push_outbox_status_created", + "columns": [ + "status", + "created_at" + ], + "isUnique": false + } + }, + "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 + }, + "msg_type": { + "name": "msg_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "default_option": { + "name": "default_option", + "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": { + "questions_project_answered": { + "name": "questions_project_answered", + "columns": [ + "project_id", + "answered_at" + ], + "isUnique": false + }, + "questions_task": { + "name": "questions_task", + "columns": [ + "task_id" + ], + "isUnique": false + } + }, + "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 + }, + "sessions_task_status": { + "name": "sessions_task_status", + "columns": [ + "task_id", + "status" + ], + "isUnique": false + }, + "sessions_status": { + "name": "sessions_status", + "columns": [ + "status" + ], + "isUnique": false + } + }, + "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 + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'human'" + }, + "proposed": { + "name": "proposed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "severity": { + "name": "severity", + "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))" + }, + "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 + }, + "tasks_project_status_pos": { + "name": "tasks_project_status_pos", + "columns": [ + "project_id", + "status", + "position" + ], + "isUnique": false + } + }, + "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 + }, + "telegram_outbox_status_created": { + "name": "telegram_outbox_status_created", + "columns": [ + "status", + "created_at" + ], + "isUnique": false + } + }, + "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": { + "telegram_updates_created": { + "name": "telegram_updates_created", + "columns": [ + "created_at" + ], + "isUnique": false + } + }, + "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 b7d35a85..4dd8bfff 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -218,6 +218,13 @@ "when": 1795512094088, "tag": "0030_access_hub_journal", "breakpoints": true + }, + { + "idx": 31, + "version": "6", + "when": 1795521789822, + "tag": "0031_access_hub_oauth", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 3483bc51..288cc8d3 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -675,7 +675,8 @@ export const connections = sqliteTable( baseUrl: text("base_url").notNull(), // bearer: Authorization: Bearer ; header: : ; basic: «login:password»; // query: ?=; path: base URL + key (Telegram). PEP-249. - authKind: text("auth_kind").$type<"bearer" | "header" | "basic" | "query" | "path">().notNull().default("bearer"), + // oauth (PEP-252): Authorization: Bearer , refreshed by the gateway. + authKind: text("auth_kind").$type<"bearer" | "header" | "basic" | "query" | "path" | "oauth">().notNull().default("bearer"), authHeader: text("auth_header"), // PEP-249: the catalog card (core/connection-catalog.ts) or null = own service. catalogId: text("catalog_id"), @@ -689,8 +690,14 @@ export const connections = sqliteTable( // an old row, secret_enc is under PEPPA_SECRET until `upgradeConnectionKeys`. secretEnc: text("secret_enc"), dekEnc: text("dek_enc"), - status: text("status").$type<"active" | "revoked">().notNull().default("active"), + // relogin (PEP-252): the service refused to refresh the OAuth token — tokens wiped, grants kept. + status: text("status").$type<"active" | "revoked" | "relogin">().notNull().default("active"), revokedAt: integer("revoked_at", { mode: "timestamp_ms" }), + // PEP-252: sign-in connections — provider (google|github), granted scopes (not secret) and + // when the access token expires (null — no expiry); tokens are in secret_enc. + oauthProvider: text("oauth_provider"), + oauthScopes: text("oauth_scopes", { mode: "json" }).$type(), + tokenExpiresAt: integer("token_expires_at", { mode: "timestamp_ms" }), lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }), createdAt: createdAt(), updatedAt: updatedAt(), diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts index a719aaed..3a403712 100644 --- a/packages/shared/src/env.ts +++ b/packages/shared/src/env.ts @@ -33,6 +33,13 @@ const schema = z.object({ GOOGLE_CLIENT_SECRET: z.string().optional(), // Test override of accounts.google.com / oauth2.googleapis.com (mock-google). GOOGLE_OAUTH_BASE: z.string().url().optional(), + // Access Hub sign-in (PEP-252): FORGE's OAuth clients for connections; Google falls back to the login client. + PEPPA_OAUTH_GOOGLE_CLIENT_ID: z.string().optional(), + PEPPA_OAUTH_GOOGLE_CLIENT_SECRET: z.string().optional(), + PEPPA_OAUTH_GOOGLE_BASE: z.string().url().optional(), + PEPPA_OAUTH_GITHUB_CLIENT_ID: z.string().optional(), + PEPPA_OAUTH_GITHUB_CLIENT_SECRET: z.string().optional(), + PEPPA_OAUTH_GITHUB_BASE: z.string().url().optional(), EGOV_ORGANISATION_BIN: z.string().regex(/^\d{12}$/).default("241140100000"), }); diff --git a/packages/testkit/bin/mock-oauth-service b/packages/testkit/bin/mock-oauth-service new file mode 100755 index 00000000..2994fde1 --- /dev/null +++ b/packages/testkit/bin/mock-oauth-service @@ -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-oauth-service.ts" "$@" diff --git a/packages/testkit/src/mock-oauth-service.ts b/packages/testkit/src/mock-oauth-service.ts new file mode 100644 index 00000000..f7f73579 --- /dev/null +++ b/packages/testkit/src/mock-oauth-service.ts @@ -0,0 +1,202 @@ +// Mock OAuth service (PEP-252) for Access Hub sign-in tests and checks without real Google/GitHub +// clients. Follows each provider's contract: +// google — GET /auth (consents at once → redirect with code+state), POST /token (authorization_code +// with PKCE S256, refresh_token: same refresh token, new access), POST /revoke (token=…), +// resources GET /v4/spreadsheets/, GET /calendar/v3/calendars//events (Bearer + matching scope); +// github — GET /login/oauth/authorize, POST /login/oauth/access_token (errors as 200 + `error`, +// refresh rotates the refresh token), DELETE /applications//grant (basic client +// auth, JSON {access_token}), resources GET /user, GET /repos//. +// `revokeAll()` is the person revoking FORGE in the service's settings; `expireAccess()` ages tokens. +// Standalone: `mock-oauth-service google|github [port]`. +import { createHash, randomUUID } from "node:crypto"; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import type { AddressInfo } from "node:net"; + +export type MockOAuthKind = "google" | "github"; + +interface Access { + scopes: string[]; + expiresAt: number | null; + refresh: string | null; +} + +export class MockOAuthService { + readonly kind: MockOAuthKind; + clientId: string; + clientSecret: string; + /** Lifetime of an access token, seconds; null — never expires (GitHub OAuth app). */ + expiresIn: number | null; + /** GitHub (expiring user tokens) gives a new refresh token on each refresh and kills the old one. */ + rotateRefresh: boolean; + /** Scopes the person ticks on the consent screen; null — all asked. */ + consentScopes: string[] | null = null; + /** The person presses «Cancel». */ + deny = false; + /** 503 on token and revoke calls. */ + down = false; + readonly codes = new Map(); + readonly access = new Map(); + readonly refresh = new Map(); + /** For assertions: what reached the service. */ + readonly seen: { authorize: URLSearchParams[]; token: URLSearchParams[]; revoked: string[]; api: Array<{ path: string; auth: string }> } = { authorize: [], token: [], revoked: [], api: [] }; + private server: Server | null = null; + + constructor(kind: MockOAuthKind) { + this.kind = kind; + this.clientId = `mock-${kind}-client`; + this.clientSecret = `mock-${kind}-secret`; + this.expiresIn = kind === "google" ? 3599 : 28800; + this.rotateRefresh = kind === "github"; + } + + async start(port = 0): Promise { + this.server = createServer((req, res) => void this.handle(req, res).catch(() => this.send(res, 500, { error: "server_error" }))); + 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())); + } + + /** The person revoked FORGE in the service: every token dies. */ + revokeAll(): void { + this.access.clear(); + this.refresh.clear(); + } + + /** Every access token is expired now (refresh tokens stay alive). */ + expireAccess(): void { + for (const a of this.access.values()) a.expiresAt = Date.now() - 1000; + } + + private send(res: ServerResponse, code: number, body: unknown) { + res.writeHead(code, { "content-type": "application/json" }); + res.end(code === 204 ? undefined : JSON.stringify(body)); + } + + private paths() { + return this.kind === "google" ? { authorize: "/auth", token: "/token" } : { authorize: "/login/oauth/authorize", token: "/login/oauth/access_token" }; + } + + private issue(scopes: string[], refresh: string | null) { + const token = `${this.kind === "github" ? "gho_" : "ya29."}${randomUUID().replace(/-/g, "")}`; + this.access.set(token, { scopes, expiresAt: this.expiresIn == null ? null : Date.now() + this.expiresIn * 1000, refresh }); + return token; + } + + private tokenAnswer(access: string, refresh: string | null, scopes: string[]) { + const a: Record = { access_token: access, token_type: "bearer", scope: scopes.join(this.kind === "github" ? "," : " ") }; + if (this.expiresIn != null) a.expires_in = this.expiresIn; + if (refresh) a.refresh_token = refresh; + return a; + } + + private tokenError(res: ServerResponse, error: string) { + // GitHub answers errors with 200; Google with 400 (401 for a bad client). + this.send(res, this.kind === "github" ? 200 : error === "invalid_client" ? 401 : 400, { error }); + } + + private async body(req: IncomingMessage): Promise { + let raw = ""; + for await (const chunk of req) raw += chunk; + return raw; + } + + private async handle(req: IncomingMessage, res: ServerResponse) { + const u = new URL(req.url ?? "/", "http://mock"); + const method = req.method ?? "GET"; + const p = this.paths(); + if (method === "GET" && u.pathname === p.authorize) { + const q = u.searchParams; + this.seen.authorize.push(q); + if (q.get("client_id") !== this.clientId || q.get("response_type") !== "code" || q.get("code_challenge_method") !== "S256" || !q.get("code_challenge") || !q.get("redirect_uri") || !q.get("state")) return this.send(res, 400, { error: "invalid_request" }); + const back = new URL(q.get("redirect_uri")!); + back.searchParams.set("state", q.get("state")!); + if (this.deny) back.searchParams.set("error", "access_denied"); + else { + const asked = (q.get("scope") ?? "").split(/\s+/).filter(Boolean); + const code = randomUUID(); + this.codes.set(code, { redirectUri: q.get("redirect_uri")!, challenge: q.get("code_challenge")!, scopes: this.consentScopes ?? asked }); + back.searchParams.set("code", code); + } + res.writeHead(302, { location: back.toString() }); + return res.end(); + } + if (method === "POST" && u.pathname === p.token) { + if (this.down) return this.send(res, 503, { error: "unavailable" }); + const f = new URLSearchParams(await this.body(req)); + this.seen.token.push(f); + if (f.get("client_id") !== this.clientId || f.get("client_secret") !== this.clientSecret) return this.tokenError(res, "invalid_client"); + if (f.get("grant_type") === "authorization_code") { + const grant = this.codes.get(f.get("code") ?? ""); + this.codes.delete(f.get("code") ?? ""); // one use + if (!grant || f.get("redirect_uri") !== grant.redirectUri) return this.tokenError(res, this.kind === "github" ? "bad_verification_code" : "invalid_grant"); + if (createHash("sha256").update(f.get("code_verifier") ?? "").digest("base64url") !== grant.challenge) return this.tokenError(res, "invalid_grant"); + const refresh = this.expiresIn == null ? null : `rt_${randomUUID().replace(/-/g, "")}`; + if (refresh) this.refresh.set(refresh, { scopes: grant.scopes }); + return this.send(res, 200, this.tokenAnswer(this.issue(grant.scopes, refresh), refresh, grant.scopes)); + } + if (f.get("grant_type") === "refresh_token") { + const old = f.get("refresh_token") ?? ""; + const r = this.refresh.get(old); + if (!r) return this.tokenError(res, this.kind === "github" ? "bad_refresh_token" : "invalid_grant"); + let refresh = old; + if (this.rotateRefresh) { + this.refresh.delete(old); + refresh = `rt_${randomUUID().replace(/-/g, "")}`; + this.refresh.set(refresh, r); + } + // Google doesn't resend its refresh token. + return this.send(res, 200, this.tokenAnswer(this.issue(r.scopes, refresh), this.rotateRefresh ? refresh : null, r.scopes)); + } + return this.tokenError(res, "unsupported_grant_type"); + } + if (this.kind === "google" && method === "POST" && u.pathname === "/revoke") { + if (this.down) return this.send(res, 503, { error: "unavailable" }); + const token = new URLSearchParams(await this.body(req)).get("token") ?? ""; + this.seen.revoked.push(token); + const known = this.refresh.has(token) || this.access.has(token); + // Revoking a refresh token revokes the whole grant. + for (const [k, a] of this.access) if (k === token || a.refresh === token) this.access.delete(k); + this.refresh.delete(token); + return known ? this.send(res, 200, {}) : this.send(res, 400, { error: "invalid_token" }); + } + if (this.kind === "github" && method === "DELETE" && u.pathname === `/applications/${this.clientId}/grant`) { + if (this.down) return this.send(res, 503, { message: "unavailable" }); + if (req.headers.authorization !== `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString("base64")}`) return this.send(res, 401, { message: "Requires authentication" }); + const token = (JSON.parse((await this.body(req)) || "{}") as { access_token?: string }).access_token ?? ""; + this.seen.revoked.push(token); + if (!this.access.has(token)) return this.send(res, 404, { message: "Not Found" }); + this.revokeAll(); + return this.send(res, 204, null); + } + // Resources: only a live access token with a suitable scope. + const auth = String(req.headers.authorization ?? ""); + this.seen.api.push({ path: u.pathname, auth }); + const a = this.access.get(auth.replace(/^Bearer /i, "")); + if (!a || (a.expiresAt != null && a.expiresAt <= Date.now())) return this.send(res, 401, this.kind === "github" ? { message: "Bad credentials" } : { error: { code: 401, status: "UNAUTHENTICATED" } }); + if (this.kind === "google" && method === "GET" && u.pathname.startsWith("/v4/spreadsheets/")) { + if (!a.scopes.some((s) => /\/spreadsheets(\.readonly)?$/.test(s))) return this.send(res, 403, { error: { code: 403, status: "PERMISSION_DENIED" } }); + const id = u.pathname.split("/")[3]!; + if (id === "forge-key-check") return this.send(res, 404, { error: { code: 404, status: "NOT_FOUND" } }); + return this.send(res, 200, { spreadsheetId: id, properties: { title: "Продажи" }, values: [["Месяц", "Сумма"], ["Ноябрь", "120"]] }); + } + if (this.kind === "google" && method === "GET" && /^\/calendar\/v3\/calendars\/[^/]+\/events$/.test(u.pathname)) { + if (!a.scopes.some((s) => /\/calendar(\.readonly|\.events)?$/.test(s))) return this.send(res, 403, { error: { code: 403, status: "PERMISSION_DENIED" } }); + if (u.pathname.includes("forge-key-check")) return this.send(res, 404, { error: { code: 404, status: "NOT_FOUND" } }); + return this.send(res, 200, { kind: "calendar#events", items: [{ summary: "Встреча с поставщиком" }] }); + } + if (this.kind === "github" && method === "GET" && u.pathname === "/user") return this.send(res, 200, { login: "mock-anna", id: 1001 }); + if (this.kind === "github" && method === "GET" && /^\/repos\/[^/]+\/[^/]+$/.test(u.pathname)) return this.send(res, 200, { full_name: u.pathname.slice(7), private: true }); + this.send(res, 404, { error: "not_found" }); + } +} + +if (import.meta.main) { + const kind = (process.argv[2] === "github" ? "github" : "google") as MockOAuthKind; + const s = new MockOAuthService(kind); + const url = await s.start(Number(process.argv[3] ?? process.env.MOCK_PORT ?? 3105)); + const K = kind.toUpperCase(); + console.log(`mock-oauth-service ${kind} (TEST ONLY): PEPPA_OAUTH_${K}_BASE=${url} PEPPA_OAUTH_${K}_CLIENT_ID=${s.clientId} PEPPA_OAUTH_${K}_CLIENT_SECRET=${s.clientSecret}`); +} diff --git a/packages/testkit/test/access-hub-oauth.test.ts b/packages/testkit/test/access-hub-oauth.test.ts new file mode 100644 index 00000000..38d5baf6 --- /dev/null +++ b/packages/testkit/test/access-hub-oauth.test.ts @@ -0,0 +1,282 @@ +// PEP-252 Access Hub: connecting Google Sheets and GitHub by signing in (OAuth code + PKCE), +// the gateway refreshing tokens itself, «нужно войти заново», revoke in the service, another +// person's callback. Scenario names follow openspec/changes/pep-252-access-hub-oauth/specs. +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; +import { eq, like } from "drizzle-orm"; +import { core, db, project, teardown } from "./helpers.ts"; +import { MockOAuthService } from "../src/mock-oauth-service.ts"; +import { stripAsIs } from "@peppa/shared/i18n"; + +process.env.PEPPA_SECRET ??= "mock-access-hub-secret"; +process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = "1"; +const { connections, connectionLog, agents, sessions, chatMessages } = await import("@peppa/db"); + +const google = new MockOAuthService("google"); +const github = new MockOAuthService("github"); +let googleBase: string; +let githubBase: string; +const REDIRECT = "https://forge.example.com/connections/oauth/callback"; + +let anna: Awaited>; +let boris: Awaited>; + +before(async () => { + googleBase = await google.start(); + githubBase = await github.start(); + Object.assign(process.env, { + PEPPA_OAUTH_GOOGLE_CLIENT_ID: google.clientId, + PEPPA_OAUTH_GOOGLE_CLIENT_SECRET: google.clientSecret, + PEPPA_OAUTH_GOOGLE_BASE: googleBase, + PEPPA_OAUTH_GITHUB_CLIENT_ID: github.clientId, + PEPPA_OAUTH_GITHUB_CLIENT_SECRET: github.clientSecret, + PEPPA_OAUTH_GITHUB_BASE: githubBase, + }); + anna = await core.upsertUserFromGitea(db, { id: 2521, login: "mock-anna-oauth" }, { access_token: "a" }); + boris = await core.upsertUserFromGitea(db, { id: 2522, login: "mock-boris-oauth" }, { access_token: "b" }); +}); +after(async () => { + await google.stop(); + await github.stop(); + await teardown(); +}); + +/** The gateway's request goes to the mock instead of sheets.googleapis.com / api.github.com. */ +const toMock = (mockBase: string): core.ConnectionFetch => (o) => { + const real = new URL(o.url); + const url = new URL(mockBase + real.pathname + real.search); + return core.defaultConnectionFetch({ ...o, url }); +}; + +/** The browser: start → the service's page → back with code and state. */ +async function signIn(userId: number, i: { catalogId?: string; connectionId?: number; level?: string }) { + const start = await core.startConnectionOAuth(db, userId, { ...i, redirectUri: REDIRECT }); + const res = await fetch(start.url, { redirect: "manual" }); + assert.equal(res.status, 302); + const back = new URL(res.headers.get("location")!); + assert.equal(back.origin + back.pathname, REDIRECT); + return { start, code: back.searchParams.get("code") ?? "", state: back.searchParams.get("state") ?? "", error: back.searchParams.get("error") }; +} + +async function connect(userId: number, catalogId: string, level = "read") { + const s = await signIn(userId, { catalogId, level }); + return core.completeConnectionOAuth(db, userId, { state: s.state, code: s.code, cookieState: s.start.state }); +} + +async function agentFor(ownerId: number) { + const p = await project({ turns: [] }); + const proj = await core.getProject(db, p.key); + await core.setProjectOwner(db, proj.id, ownerId); + const task = (await core.listTasks(db, { projectId: proj.id }))[0]!; + const s = await core.createSession(db, { projectId: proj.id, taskId: task.id }); + const [a] = await db.insert(agents).values({ name: `Мок-агент OAuth ${s.id}` }).returning(); + await db.update(sessions).set({ agentId: a!.id, container: `peppa-s${s.id}` }).where(eq(sessions.id, s.id)); + return { proj, sessionId: s.id }; +} + +const row = async (id: number) => (await db.select().from(connections).where(eq(connections.id, id)))[0]!; +const reloginMessages = async (name: string) => (await db.select().from(chatMessages).where(like(chatMessages.text, "%Войти заново%"))).filter((m) => stripAsIs(m.text).includes(`«${name}»`)).length; + +describe("Подключение входом через сервис", () => { + test("Владелец подключает Google Sheets входом", async () => { + const offer = core.oauthOffer("google-sheets"); + assert.ok(offer, "the sign-in way is offered when FORGE has a Google client"); + assert.deepEqual(offer!.read.map(core.scopeLabel), ["spreadsheets.readonly"]); + const s = await signIn(anna.id, { catalogId: "google-sheets", level: "read" }); + const asked = google.seen.authorize.at(-1)!; + assert.equal(asked.get("scope"), "https://www.googleapis.com/auth/spreadsheets.readonly"); + assert.equal(asked.get("code_challenge_method"), "S256"); + assert.equal(asked.get("access_type"), "offline"); + const r = await core.completeConnectionOAuth(db, anna.id, { state: s.state, code: s.code, cookieState: s.start.state }); + assert.equal(r.created, true); + const c = (await core.listConnections(db, anna.id)).find((x) => x.id === r.connectionId)!; + assert.equal(c.name, "Google Sheets"); + assert.equal(c.authKind, "oauth"); + assert.equal(c.oauthProvider, "google"); + assert.deepEqual(c.oauthScopes.map(core.scopeLabel), ["spreadsheets.readonly"]); + // Tokens: only in the sealed envelope. + const tokens = [...google.access.keys(), ...google.refresh.keys()]; + const stored = await row(r.connectionId); + for (const t of tokens) { + assert.ok(!JSON.stringify(c).includes(t), "not in the owner's view"); + assert.ok(!JSON.stringify(stored).includes(t), "not in the clear in the database"); + } + assert.ok(stored.dekEnc && stored.secretEnc?.startsWith("v2.")); + // The PKCE verifier reached the token endpoint, the client secret too. + const tok = google.seen.token.at(-1)!; + assert.ok(tok.get("code_verifier")); + }); + + test("Клиент не настроен — способ скрыт", async () => { + const env = { ...process.env, PEPPA_OAUTH_GITHUB_CLIENT_ID: "", PEPPA_OAUTH_GITHUB_CLIENT_SECRET: "" }; + assert.equal(core.oauthOffer("github", env), null); + assert.ok(core.oauthOffer("github")); + assert.equal(core.oauthOffer("stripe"), null, "a card without sign-in"); + await assert.rejects(core.startConnectionOAuth(db, anna.id, { catalogId: "github", redirectUri: REDIRECT }, env), /не настроен/); + }); + + test("Поток подменили: другой state, повтор, чужой пользователь", async () => { + const s = await signIn(anna.id, { catalogId: "github" }); + const before = (await core.listConnections(db, anna.id)).length; + await assert.rejects(core.completeConnectionOAuth(db, anna.id, { state: s.state, code: s.code, cookieState: "other-browser" }), core.PeppaError); + // The flow is spent even by a refused try. + const s2 = await signIn(anna.id, { catalogId: "github" }); + await assert.rejects(core.completeConnectionOAuth(db, boris.id, { state: s2.state, code: s2.code, cookieState: s2.start.state }), core.PeppaError, "another person signed in"); + await assert.rejects(core.completeConnectionOAuth(db, anna.id, { state: s2.state, code: s2.code, cookieState: s2.start.state }), core.PeppaError, "one-shot"); + assert.equal((await core.listConnections(db, anna.id)).length, before); + assert.equal((await core.listConnections(db, boris.id)).length, 0); + // «Войти заново» into someone else's connection is refused at the start. + const mine = (await core.listConnections(db, anna.id))[0]!; + await assert.rejects(core.startConnectionOAuth(db, boris.id, { connectionId: mine.id, redirectUri: REDIRECT }), /не найдено/); + }); + + test("Отказ на странице сервиса и непрошенные права", async () => { + google.deny = true; + const s = await signIn(anna.id, { catalogId: "google-drive" }); + google.deny = false; + assert.equal(s.error, "access_denied"); + assert.equal(s.code, ""); + google.consentScopes = ["openid"]; + try { + await assert.rejects(connect(anna.id, "google-drive"), /нужный доступ/); + } finally { + google.consentScopes = null; + } + }); +}); + +describe("Шлюз сам обновляет токен", () => { + test("Токен истёк — агент читает таблицу", async () => { + const { connectionId } = await connect(anna.id, "google-sheets"); + const { proj, sessionId } = await agentFor(anna.id); + await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" }); + const fetch = toMock(googleBase); + const slug = (await row(connectionId)).slug!; + const first = await core.callConnection(db, { sessionId, connection: slug, method: "GET", path: "/v4/spreadsheets/abc" }, { fetch }); + assert.equal(first.ok && first.status, 200); + assert.match(first.ok ? first.body : "", /Продажи/); + const refreshesBefore = google.seen.token.filter((f) => f.get("grant_type") === "refresh_token").length; + // Expired by its stored date: refreshed before the call. + const now = new Date(Date.now() + 2 * 3600_000); + google.expireAccess(); + const second = await core.callConnection(db, { sessionId, connection: slug, method: "GET", path: "/v4/spreadsheets/abc" }, { fetch, now }); + assert.equal(second.ok && second.status, 200); + assert.equal(google.seen.token.filter((f) => f.get("grant_type") === "refresh_token").length, refreshesBefore + 1); + // Expired early at the service (date says fine): 401 → one refresh → repeated. + google.expireAccess(); + const third = await core.callConnection(db, { sessionId, connection: slug, method: "GET", path: "/v4/spreadsheets/abc" }, { fetch, now }); + assert.equal(third.ok && third.status, 200); + // Writing is not granted: refused before any token is used. + const write = await core.callConnection(db, { sessionId, connection: slug, method: "PUT", path: "/v4/spreadsheets/abc/values/A1", body: "{}" }, { fetch, now }); + assert.equal(!write.ok && write.reason, "write_denied"); + // Nothing of the tokens in the journal. + const log = JSON.stringify(await db.select().from(connectionLog).where(eq(connectionLog.connectionId, connectionId))); + for (const t of [...google.access.keys(), ...google.refresh.keys()]) assert.ok(!log.includes(t)); + // Daily check works with the token too. + const chk = await core.checkConnection(db, anna.id, connectionId, { fetch, now }); + assert.equal(chk.status, "ok"); + }); + + test("GitHub: агент читает репозиторий, обновление меняет и ключ обновления", async () => { + const { connectionId } = await connect(anna.id, "github"); + const { proj, sessionId } = await agentFor(anna.id); + await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" }); + const fetch = toMock(githubBase); + const now = new Date(Date.now() + 9 * 3600_000); + const oldRefresh = [...github.refresh.keys()]; + const r = await core.callConnection(db, { sessionId, connection: "github", method: "GET", path: "/repos/mock-anna/shop" }, { fetch, now }); + assert.equal(r.ok && r.status, 200); + assert.ok(oldRefresh.every((t) => !github.refresh.has(t)), "the old refresh token is spent"); + const again = await core.callConnection(db, { sessionId, connection: "github", method: "GET", path: "/user" }, { fetch, now }); + assert.equal(again.ok && again.status, 200, "the new refresh token was saved"); + }); + + test("Доступ отозвали в самом сервисе — нужно войти заново, одно сообщение", async () => { + const { connectionId } = await connect(anna.id, "google-calendar"); + const { proj, sessionId } = await agentFor(anna.id); + await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" }); + const name = (await row(connectionId)).name; + google.revokeAll(); + const fetch = toMock(googleBase); + const now = new Date(Date.now() + 2 * 3600_000); + const r = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/calendars/primary/events" }, { fetch, now }); + assert.equal(!r.ok && r.reason, "needs_login"); + const c = await row(connectionId); + assert.equal(c.status, "relogin"); + assert.equal(c.secretEnc, null, "dead tokens are wiped"); + assert.equal(await reloginMessages(name), 1); + const r2 = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/calendars/primary/events" }, { fetch, now }); + assert.equal(!r2.ok && r2.reason, "needs_login"); + await core.connectionCheckTick(db, { fetch, now: new Date(now.getTime() + 2 * 86400_000) }); + assert.equal(await reloginMessages(name), 1, "no second message"); + // The agent sees it as not working. + const seen = (await core.agentConnections(db, sessionId)).find((x) => x.id === connectionId)!; + assert.equal(seen.checkStatus, "bad_key"); + + // Войти заново: same connection, grants kept. + const s = await signIn(anna.id, { connectionId }); + const back = await core.completeConnectionOAuth(db, anna.id, { state: s.state, code: s.code, cookieState: s.start.state }); + assert.deepEqual(back, { connectionId, created: false }); + assert.equal((await row(connectionId)).status, "active"); + assert.equal((await core.listConnections(db, anna.id)).find((x) => x.id === connectionId)!.grants.length, 1); + const ok = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/calendars/primary/events" }, { fetch }); + assert.equal(ok.ok && ok.status, 200); + assert.match(ok.ok ? ok.body : "", /поставщиком/); + }); + + test("Сервис обновления не отвечает — подключение не ломается", async () => { + const { connectionId } = await connect(anna.id, "google-sheets"); + const { proj, sessionId } = await agentFor(anna.id); + await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" }); + google.down = true; + try { + const r = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/v4/spreadsheets/x" }, { fetch: toMock(googleBase), now: new Date(Date.now() + 2 * 3600_000) }); + assert.equal(!r.ok && r.reason, "upstream_error"); + } finally { + google.down = false; + } + assert.equal((await row(connectionId)).status, "active"); + }); + + test("Ключ у подключения входом заменить нельзя", async () => { + const { connectionId } = await connect(anna.id, "google-drive"); + await assert.rejects(core.replaceConnectionSecret(db, anna.id, connectionId, "AIza-mock-key-123"), /Войти заново/); + }); +}); + +describe("Отзыв доступа отзывает токен в сервисе", () => { + test("Отзыв GitHub", async () => { + const { connectionId } = await connect(anna.id, "github"); + const access = [...github.access.keys()].at(-1)!; + const { proj, sessionId } = await agentFor(anna.id); + await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" }); + const r = await core.revokeConnection(db, anna.id, connectionId); + assert.equal(r.remote, "revoked"); + assert.ok(github.seen.revoked.includes(access)); + assert.equal(github.access.size, 0); + const call = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/user" }, { fetch: toMock(githubBase) }); + assert.equal(!call.ok && call.reason, "revoked"); + }); + + test("Удаление отзывает Google", async () => { + const { connectionId } = await connect(anna.id, "google-sheets"); + const refresh = [...google.refresh.keys()].at(-1)!; + await core.deleteConnection(db, anna.id, connectionId); + assert.ok(google.seen.revoked.includes(refresh)); + assert.ok(!google.refresh.has(refresh)); + }); + + test("Сервис не отвечает при отзыве", async () => { + const { connectionId } = await connect(anna.id, "google-sheets"); + google.down = true; + try { + const r = await core.revokeConnection(db, anna.id, connectionId); + assert.equal(r.remote, "failed"); + } finally { + google.down = false; + } + const c = await row(connectionId); + assert.equal(c.status, "revoked"); + assert.equal(c.secretEnc, null); + }); +});