diff --git a/.peppa/memory.md b/.peppa/memory.md
index 681abbd8..f533ea65 100644
--- a/.peppa/memory.md
+++ b/.peppa/memory.md
@@ -30,11 +30,8 @@
- Продукт на другой docker переносить только с данными (PEP-231): `scripts/server-move/products-move.sh` — тома со сверкой сумм, Postgres дампом, без отчёта о выкладке; `peppa deploy redeploy` поднимает продукт с пустыми томами.
- Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`.
- Пути сессий с Mac (PEP-246): `runnerCwd` пересоздаёт копию сам; чистка — `peppa session paths --fix`.
-- Сервер (PEP-230): памятка — docs/SERVER.md. В контейнере агента нет глобального git: автор коммита — `gitRelayEnv` (GIT_AUTHOR_*); на старом образе — `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
-- Песочница раннера: нет tmux, openspec, Node 26 (есть 22). tmux — `.deb` с deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH; openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; e2e на 22 — MIN_MAJOR в scripts/lib/require-node.mjs (не коммитить).
- Сервер (PEP-230): docs/SERVER.md. Нет глобального git в контейнере: автор — `gitRelayEnv`; иначе `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22). tmux — .deb с deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + обёртка с LD_LIBRARY_PATH; openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; тесты на 22 — MIN_MAJOR в scripts/lib/require-node.mjs (не коммитить).
-- Сервер (PEP-230): памятка — docs/SERVER.md. В контейнере агента нет глобального git: автор коммита — `gitRelayEnv` (GIT_AUTHOR_*).
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22: тесты с бинарями peppa и glossary-check.test падают — это среда). openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; tmux — `.deb` с deb.debian.org + `dpkg-deb -x`.
- Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`).
@@ -59,6 +56,7 @@
- act_runner (PEP-233): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь.
## Решения
+- Access Hub (PEP-254): журнал — только `appendJournal` (core/connection-journal.ts, цепочка хэшей; правка строки задним числом = нарушение), ключ подключения — `sealConnectionSecret`/`openConnectionSecret`, не `encrypt`/`decrypt`.
- История (PEP-221): журнал/статусы — `history.db` (core/history.ts), логи — `archive/<вид>/<день>.jsonl.gz`; из основной базы события удаляет только `runRetention` после переноса.
- Docker (PEP-222): раннеры по умолчанию `container` (тесты — `PEPPA_DEFAULT_ISOLATION=none`).
- Медленные запросы (PEP-213): `core/request-timing.ts` (`http.Server` в instrumentation.ts, probe в db) → warning Bugsink; порог `PEPPA_SLOW_REQUEST_MS`.
diff --git a/apps/web/app/(app)/connections/page.tsx b/apps/web/app/(app)/connections/page.tsx
index 1b5fddf5..d2cb7ad1 100644
--- a/apps/web/app/(app)/connections/page.tsx
+++ b/apps/web/app/(app)/connections/page.tsx
@@ -7,6 +7,7 @@ import {
CONNECTION_CHECK_TEXT,
CONNECTION_REASON_TEXT,
connectionJournal,
+ JOURNAL_VERIFY_SCRIPT,
grantableAgents,
listConnections,
listUserProjects,
@@ -43,6 +44,9 @@ const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
const BACK = "/connections";
function Decision({ row, t }: { row: ConnectionLogView; t: Translator }) {
+ // PEP-254: the call is written before the service answers; no result after a while — a crash in the middle.
+ if (row.state === "running") return {t("выполняется")};
+ if (row.state === "unfinished") return {t("начато, итога нет")};
if (row.decision === "allowed") return {t("разрешено")};
if (row.decision === "denied") return {t("запрещено")};
return {t("не выполнено")};
@@ -320,6 +324,34 @@ function Catalog({ q, kind, t }: { q: string; kind: string | null; t: Translator
);
}
+/** PEP-254: download the journal with hashes and how to check it yourself. */
+function JournalExport({ t, engineer }: { t: Translator; engineer: boolean }) {
+ return (
+
+
+ {t("Журнал нельзя незаметно изменить: каждая запись связана с предыдущей, и раз в сутки FORGE сохраняет отметку журнала отдельно. Если запись изменят, вы и администратор получите сообщение.")}
+
+
+
+ {t("Как проверить журнал самому")}
+
+
+ {t("Скачайте журнал для проверки и сохраните программу ниже рядом с ним. Запустите её так, как написано в её первой строке. Ответ «ok» значит, что журнал не меняли; иначе программа назовёт первую изменённую запись.")}
+
+
{JOURNAL_VERIFY_SCRIPT}
+
+
+
+ );
+}
+
/** PEP-234/249 Access Hub: «Подключения» — the user's own external services and who may use them. */
export default async function ConnectionsPage({ searchParams }: { searchParams: Promise }) {
const q = await searchParams;
@@ -390,6 +422,7 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
)}
+
);
diff --git a/apps/web/app/api/connections/journal/route.ts b/apps/web/app/api/connections/journal/route.ts
new file mode 100644
index 00000000..28dfc312
--- /dev/null
+++ b/apps/web/app/api/connections/journal/route.ts
@@ -0,0 +1,25 @@
+// PEP-254: the owner downloads their whole Access Hub journal with hashes (JSONL or CSV) to
+// check it on their own. Only the signed-in user's own rows.
+import { exportConnectionJournal } from "@peppa/core";
+import { currentUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+import { getT } from "@/lib/i18n";
+
+export const dynamic = "force-dynamic";
+
+export async function GET(req: Request) {
+ const t = await getT();
+ const me = await currentUser();
+ if (!me) return Response.json({ error: t("Нужен вход") }, { status: 401 });
+ const format = new URL(req.url).searchParams.get("format") === "csv" ? "csv" : "jsonl";
+ const body = await exportConnectionJournal(db, me.id, format);
+ const day = new Date().toISOString().slice(0, 10);
+ return new Response(body, {
+ headers: {
+ "content-type": format === "csv" ? "text/csv; charset=utf-8" : "application/x-ndjson; charset=utf-8",
+ "content-disposition": `attachment; filename="connections-journal-${day}.${format}"`,
+ "cache-control": "no-store",
+ "x-content-type-options": "nosniff",
+ },
+ });
+}
diff --git a/openspec/changes/pep-254-access-hub-journal-integrity/design.md b/openspec/changes/pep-254-access-hub-journal-integrity/design.md
new file mode 100644
index 00000000..af6cd5fd
--- /dev/null
+++ b/openspec/changes/pep-254-access-hub-journal-integrity/design.md
@@ -0,0 +1,29 @@
+## Context
+
+`connection_log` (PEP-234/249) — одна строка на решение шлюза, пишется после запроса. `connections.secret_enc` — `encrypt()` ключом, производным от `PEPPA_SECRET`.
+
+## Decisions
+
+### Запись до действия — две строки, а не правка одной
+Цепочка хэшей не терпит правку строки после того, как за ней появились следующие. Поэтому разрешённый вызов — строка `kind = call` (решение `allowed`, до запроса), итог — строка `kind = result` с `parent_id` вызова (код, `duration_ms`, решение `allowed`/`failed`, причина). Отказ (`denied`) — одна строка `call`, итога не ждёт. Проверка ключа владельцем — `call` + `result` как у шлюза. На экране и в `connectionJournal` итог подклеивается к вызову; разрешённый вызов без итога старше таймаута шлюза — «начато, итога нет». Лимит 60/мин считает только `call`.
+
+### Цепочка по владельцу, хэш без внешних ключей
+Журнал читает владелец — цепочка тоже по `owner_id`. Хэш = `sha256(prev_hash + "\n" + JSON.stringify([id, owner_id, kind, parent_id, connection_name, project_key, agent_name, method, path, decision, reason, status_code, duration_ms, created_at_ms]))`, первая строка владельца — `prev_hash = ""`. Внешние ключи (`connection_id`, `project_id`, `session_id`, `agent_id`) в хэш не входят: при удалении подключения/проекта/сессии они становятся `null` (`onDelete: set null`), и честная цепочка сломалась бы. Вместо них — снимки `connection_name`, `project_key`, `agent_name`. Вставка — синхронная транзакция (`BEGIN IMMEDIATE`): чтение головы и вставка не разойдутся при параллельных вызовах.
+
+Хэш без ключа (не HMAC) — чтобы владелец проверил выгрузку сам. Подделку «пересчитать всю цепочку» ловят контрольные точки вне таблицы: событие платформы и сообщение в канал «services».
+
+### Контрольные точки
+`connectionJournalTick` (вачдог, раз в час проверяет, раз в сутки пишет): для каждого владельца `verifyConnectionJournal` и сверка с прошлой точкой (`settings` `connection.journal.checkpoint:` `{id, hash, at}`: строка `id` всё ещё имеет хэш `hash`). Новая голова → событие `connection_journal_checkpoint` в платформенном проекте и одна строка в общем сообщении канала «services» за день. Нарушение → `alertAdmins` + сообщение владельцу (мастер-чат и `deliverToUser`), одно на нарушение (`connection.journal.broken:` = id первой плохой строки). Строки до первой сохранившейся — якорь: начало цепочки берётся из `prev_hash` первой строки (на будущее, если журнал будут чистить по сроку).
+
+### Envelope
+`connections.dek_enc` = `encrypt(base64(dek))` (ключ платформы), `secret_enc` = `v2.` + AES-256-GCM ключом данных (`sealWithKey`/`openWithKey` в crypto.ts, AAD `connection-secret`). Без `dek_enc` строка — старого формата (`decrypt`). `upgradeConnectionKeys` переводит старые: расшифровка и шифрование в памяти процесса, без вывода. В `encryptedColumns` вместо `connections.secret_enc` — `connections.dek_enc` и `connections.secret_enc` только у строк без `dek_enc` (вдруг перевод ещё не прошёл). `reencryptAll` перед обходом зовёт `upgradeConnectionKeys`. Расшифровка одного подключения даёт только его ключ данных.
+
+### Ответы сервисов
+Шлюз отдаёт ответ агенту и ничего из него не сохраняет. Частичной выдачи (`fetch_body`) нет. Хранения нет — нечего шифровать и удалять; в спеке это требование «тело ответа не хранится и не попадает в уведомления».
+
+### Выгрузка
+`exportConnectionJournal(db, userId, "jsonl" | "csv")` — все строки владельца по `id` с `prev_hash` и `hash`; `GET /api/connections/journal?format=…` (только вход, только свои). Инструкция на экране под «Подробнее»: формула и короткий скрипт Node.
+
+## Risks
+- Рост журнала вдвое (две строки на вызов) — приемлемо: строки короткие, лимит 60/мин на сессию.
+- Старые строки без хэша: миграция строит цепочку для них в `upgradeConnectionJournal` (тот же вызов, что и для ключей).
diff --git a/openspec/changes/pep-254-access-hub-journal-integrity/proposal.md b/openspec/changes/pep-254-access-hub-journal-integrity/proposal.md
new file mode 100644
index 00000000..02ffd96b
--- /dev/null
+++ b/openspec/changes/pep-254-access-hub-journal-integrity/proposal.md
@@ -0,0 +1,22 @@
+## Why
+
+Журнал Access Hub (PEP-234) — обычная таблица: при доступе к базе запись можно тихо изменить или удалить, а запись появляется только после вызова сервиса — сбой посередине не оставляет следа. Все ключи подключений зашифрованы одним ключом платформы (`PEPPA_SECRET`): утечка его вместе с базой открывает все ключи сразу, а ротация перешифровывает сами секреты.
+
+## What Changes
+
+- **Запись до действия**: строка журнала «вызов» пишется до запроса к сервису, итог (код ответа, длительность) — отдельной строкой «итог» после. Вызов без итога виден владельцу как «начато, итога нет».
+- **Цепочка хэшей** по владельцу: каждая строка хранит хэш предыдущей и свой хэш (SHA-256 от канонической записи). `verifyConnectionJournal` проверяет цепочку.
+- **Контрольные точки** раз в сутки (`connectionJournalTick` в вачдоге): голова цепочки каждого владельца — в журнал событий платформы и в канал «services»; заодно проверка цепочек. Нарушение — одно сообщение суперадмину и владельцу.
+- **Выгрузка** журнала владельцем — JSONL и CSV с хэшами (`GET /api/connections/journal`), на экране «Подключения» — кнопки и инструкция, как проверить самому.
+- **Отдельный ключ на каждый ключ (envelope)**: у подключения свой случайный ключ данных (`connections.dek_enc` — зашифрован ключом платформы), секрет шифруется ключом данных. Ротация `PEPPA_SECRET` (`reencryptAll`) перешифровывает только ключи данных. Старые подключения переводятся `upgradeConnectionKeys` (в `peppa db migrate` и в тике вачдога) — расшифровка только в памяти процесса.
+- **Ответы сервисов** шлюз не хранит (ни целиком, ни по частям) — требование о шифровании и сроке 30 дней фиксируется в спеке как запрет хранения.
+
+## Capabilities
+
+### Modified Capabilities
+- `access-hub`: журнал с записью до действия и цепочкой хэшей, контрольные точки, выгрузка, ключ данных на каждое подключение.
+
+## Impact
+
+- База: миграция 0030 — `connections.dek_enc`; `connection_log.kind`, `parent_id`, `project_key`, `duration_ms`, `prev_hash`, `hash`.
+- Код: `core/connections.ts`, новый `core/connection-journal.ts`, `core/crypto.ts` (шифрование ключом данных), `core/secrets-audit.ts` (`encryptedColumns`), вачдог, CLI `peppa db migrate`, веб «Подключения» и маршрут выгрузки, переводы.
diff --git a/openspec/changes/pep-254-access-hub-journal-integrity/specs/access-hub/spec.md b/openspec/changes/pep-254-access-hub-journal-integrity/specs/access-hub/spec.md
new file mode 100644
index 00000000..7889213e
--- /dev/null
+++ b/openspec/changes/pep-254-access-hub-journal-integrity/specs/access-hub/spec.md
@@ -0,0 +1,69 @@
+## ADDED Requirements
+
+### Requirement: Журнал пишется до действия
+Шлюз SHALL записывать вызов в журнал до запроса к внешнему сервису, а итог (код ответа, длительность) — отдельной записью после. Вызов без итога SHALL быть виден владельцу как «начато, итога нет».
+
+#### Scenario: Итог дописывается после вызова
+- **GIVEN** агенту проекта «SHOP» разрешено «GET /items» подключения «CRM» пользователя «anna»
+- **WHEN** агент просит «GET /items/5» и сервис отвечает 200
+- **THEN** в журнале «anna» есть запись вызова «GET /items/5»
+- **AND** к ней итог с кодом 200
+
+#### Scenario: Сбой посередине виден
+- **GIVEN** вызов «GET /items/5» через «CRM» записан, а процесс упал до ответа сервиса
+- **WHEN** «anna» открывает журнал через минуту
+- **THEN** у вызова видно «начато, итога нет»
+
+### Requirement: Журнал защищён от подделки
+Каждая запись журнала SHALL хранить хэш предыдущей записи того же владельца и свой хэш. Проверка цепочки SHALL обнаруживать изменённую или удалённую запись. Раз в сутки голова цепочки SHALL сохраняться вне таблицы журнала (журнал событий платформы и канал «services»); о нарушении SHALL узнавать суперадмин и владелец.
+
+#### Scenario: Изменённая запись обнаруживается
+- **GIVEN** в журнале «anna» три записи
+- **WHEN** во второй записи путь «/items/5» заменён на «/items/6» прямо в базе
+- **THEN** проверка журнала «anna» сообщает о нарушении на второй записи
+
+#### Scenario: Нарушение доходит до людей
+- **GIVEN** запись журнала «anna» изменена в базе
+- **WHEN** проходит ежедневная проверка
+- **THEN** суперадмин получает одно сообщение о нарушении журнала
+- **AND** «anna» получает одно сообщение
+- **AND** следующая проверка того же нарушения повторно не пишет
+
+#### Scenario: Пересчитанная цепочка не совпадает с контрольной точкой
+- **GIVEN** вчерашняя контрольная точка журнала «anna» сохранена
+- **WHEN** запись до неё изменена и хэши всех следующих пересчитаны
+- **THEN** проверка сообщает о нарушении
+
+### Requirement: Выгрузка журнала
+Владелец SHALL выгружать свой журнал в JSONL и CSV вместе с хэшами и SHALL иметь инструкцию, как проверить цепочку самому. Чужой журнал выгрузить SHALL NOT.
+
+#### Scenario: Выгрузка проверяется
+- **GIVEN** в журнале «anna» пять записей
+- **WHEN** она выгружает журнал в JSONL
+- **THEN** в файле пять строк с полями «prev_hash» и «hash»
+- **AND** пересчёт хэшей по инструкции совпадает с файлом
+
+#### Scenario: Чужой журнал не выгружается
+- **GIVEN** у «anna» есть записи в журнале
+- **WHEN** «boris» запрашивает выгрузку
+- **THEN** он получает только свои записи
+
+### Requirement: Отдельный ключ шифрования у каждого подключения
+У каждого подключения SHALL быть свой случайный ключ данных, которым шифруется ключ доступа; ключ данных SHALL шифроваться ключом платформы. Смена ключа платформы SHALL перешифровывать только ключи данных. Ответы сервисов шлюз SHALL NOT хранить и SHALL NOT отправлять в уведомления.
+
+#### Scenario: Ключ данных одного подключения не открывает другое
+- **GIVEN** у «anna» подключения «CRM» и «Почта»
+- **WHEN** ключ данных «CRM» применяют к зашифрованному ключу «Почты»
+- **THEN** расшифровка не удаётся
+
+#### Scenario: Ротация ключа платформы
+- **GIVEN** подключение «CRM» сохранено при старом ключе платформы
+- **WHEN** ключ платформы меняется и запускается перешифровка
+- **THEN** перешифрован только ключ данных «CRM», а зашифрованный ключ доступа не изменился
+- **AND** агент по-прежнему вызывает «CRM»
+
+#### Scenario: Старое подключение переводится на свой ключ
+- **GIVEN** подключение «CRM» создано до этого изменения
+- **WHEN** выполняется перевод ключей
+- **THEN** у «CRM» появляется свой ключ данных
+- **AND** вызов через «CRM» работает с прежним ключом доступа
diff --git a/openspec/changes/pep-254-access-hub-journal-integrity/tasks.md b/openspec/changes/pep-254-access-hub-journal-integrity/tasks.md
new file mode 100644
index 00000000..a80a48a3
--- /dev/null
+++ b/openspec/changes/pep-254-access-hub-journal-integrity/tasks.md
@@ -0,0 +1,16 @@
+## 1. База и шифрование
+- [x] 1.1 Схема и миграция 0030: `connections.dek_enc`; `connection_log.kind`, `parent_id`, `project_key`, `duration_ms`, `prev_hash`, `hash`
+- [x] 1.2 crypto.ts: `newDataKey`, `sealWithKey`/`openWithKey`; connections.ts: `sealConnectionSecret`/`openConnectionSecret`, `upgradeConnectionKeys`
+- [x] 1.3 secrets-audit: `encryptedColumns` — `dek_enc` (+ старые `secret_enc`), `reencryptAll` сначала переводит старые
+
+## 2. Журнал
+- [x] 2.1 `core/connection-journal.ts`: хэш, `appendJournal` (синхронная транзакция), `verifyJournalRows`, `verifyConnectionJournal`, `exportConnectionJournal`, построение цепочки для старых строк
+- [x] 2.2 Шлюз и проверка ключа: вызов до запроса, итог после; лимит считает только вызовы; `connectionJournal` подклеивает итог, «начато, итога нет»
+- [x] 2.3 `connectionJournalTick`: проверка, контрольная точка (событие + канал), сообщения о нарушении; вачдог; `peppa db migrate` зовёт перевод ключей и цепочки
+
+## 3. Веб
+- [x] 3.1 `GET /api/connections/journal?format=jsonl|csv`, кнопки выгрузки и инструкция; «начато, итога нет» в журнале; переводы ru/kk/en
+
+## 4. Тесты и завершение
+- [x] 4.1 Тест `access-hub-journal.test.ts`: подделка, пересчёт после точки, выгрузка, сообщения, envelope, ротация, перевод старых
+- [x] 4.2 Прогон access-hub тестов, lint, typecheck; память; archive; PR
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 78e3c73c..10a450fa 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -213,8 +213,17 @@ const env = loadEnv();
if (positionals[0] === "db") {
try {
if (positionals[1] === "migrate") {
- migrateDb(createDb(env.PEPPA_DB));
+ const mdb = createDb(env.PEPPA_DB);
+ migrateDb(mdb);
console.log(`migrated ${env.PEPPA_DB}`);
+ // PEP-254: old Access Hub keys get their own data key, old journals a hash chain (in-process only).
+ const core = await import("@peppa/core");
+ const journal = await core.upgradeConnectionJournal(mdb).catch((e: Error) => (console.error(`connection journal: ${e.message}`), 0));
+ if (journal) console.log(`connection journal: ${journal} rows chained`);
+ if (env.PEPPA_SECRET) {
+ const keys = await core.upgradeConnectionKeys(mdb).catch((e: Error) => (console.error(`connection keys: ${e.message}`), null));
+ if (keys?.upgraded || keys?.unreadable) console.log(`connection keys: ${keys.upgraded} moved to own data keys, ${keys.unreadable} unreadable`);
+ }
} else if (positionals[1] === "backup") {
const db = createDb(env.PEPPA_DB);
// PEP-48: CLI commands are an admin's actions on this machine.
diff --git a/packages/core/src/connection-journal.ts b/packages/core/src/connection-journal.ts
new file mode 100644
index 00000000..647a1744
--- /dev/null
+++ b/packages/core/src/connection-journal.ts
@@ -0,0 +1,357 @@
+// PEP-254: the Access Hub journal can't be changed quietly.
+// Every row of an owner carries the hash of the owner's previous row and its own:
+// hash = sha256(prev_hash + "\n" + JSON.stringify([id, owner_id, kind, parent_id, connection,
+// project, agent, method, path, decision, reason, status_code, duration_ms, created_at]))
+// (created_at in ms; the first row of an owner has prev_hash ""). Foreign keys are not hashed —
+// they turn null when a connection, project or session is deleted; their name snapshots are.
+// The hash has no key, so an owner can check an export alone; rewriting the whole chain is caught
+// by daily checkpoints kept outside the table (platform journal + the «services» channel).
+import { asIs, m as tr } from "@peppa/shared/i18n";
+import { connectionLog, projects, users, type Db } from "@peppa/db";
+import { and, asc, desc, eq, isNotNull, isNull, sql } from "drizzle-orm";
+import { createHash } from "node:crypto";
+import { logEvent } from "./audit.ts";
+import { addMasterMessage } from "./chats.ts";
+import { alertAdmins } from "./monitor.ts";
+import { deliverToUser } from "./notifications.ts";
+import { platformProjectKey, postToChannel } from "./platform-channel.ts";
+import { deleteSetting, getSetting, setSetting } from "./settings.ts";
+
+export type ConnectionJournalKind = "call" | "result";
+export type ConnectionJournalDecision = "allowed" | "denied" | "failed";
+
+/** What a gateway decision writes; ids and the hash are added by `appendJournal`. */
+export interface ConnectionJournalEntry {
+ ownerId: number;
+ kind: ConnectionJournalKind;
+ parentId?: number | null;
+ connectionId: number | null;
+ connectionName: string | null;
+ projectId?: number | null;
+ projectKey?: string | null;
+ sessionId?: number | null;
+ agentId?: number | null;
+ agentName?: string | null;
+ method: string;
+ path: string;
+ decision: ConnectionJournalDecision;
+ reason: string | null;
+ statusCode: number | null;
+ durationMs?: number | null;
+ createdAt: Date;
+}
+
+/** One row as exported and as hashed (snake_case — the same names as in the file). */
+export interface ConnectionJournalRecord {
+ id: number;
+ owner_id: number;
+ kind: ConnectionJournalKind;
+ parent_id: number | null;
+ connection: string | null;
+ project: string | null;
+ agent: string | null;
+ method: string;
+ path: string;
+ decision: ConnectionJournalDecision;
+ reason: string | null;
+ status_code: number | null;
+ duration_ms: number | null;
+ created_at: number;
+ prev_hash: string | null;
+ hash: string | null;
+}
+
+export function journalCanonical(r: Omit): string {
+ return JSON.stringify([r.id, r.owner_id, r.kind, r.parent_id, r.connection, r.project, r.agent, r.method, r.path, r.decision, r.reason, r.status_code, r.duration_ms, r.created_at]);
+}
+
+export const journalHash = (prevHash: string, r: Omit): string =>
+ createHash("sha256").update(`${prevHash}\n${journalCanonical(r)}`).digest("hex");
+
+type LogRow = typeof connectionLog.$inferSelect;
+
+export const toRecord = (r: LogRow): ConnectionJournalRecord => ({
+ id: r.id,
+ owner_id: r.ownerId!,
+ kind: r.kind,
+ parent_id: r.parentId ?? null,
+ connection: r.connectionName ?? null,
+ project: r.projectKey ?? null,
+ agent: r.agentName ?? null,
+ method: r.method,
+ path: r.path,
+ decision: r.decision,
+ reason: r.reason ?? null,
+ status_code: r.statusCode ?? null,
+ duration_ms: r.durationMs ?? null,
+ created_at: r.createdAt.getTime(),
+ prev_hash: r.prevHash ?? null,
+ hash: r.hash ?? null,
+});
+
+/**
+ * Appends one row to the owner's chain. One synchronous transaction (BEGIN IMMEDIATE): reading
+ * the head and inserting can't interleave with another call of the same owner.
+ */
+export function appendJournal(db: Db, e: ConnectionJournalEntry): number {
+ return db.transaction((tx) => {
+ const head = tx
+ .select({ hash: connectionLog.hash })
+ .from(connectionLog)
+ .where(and(eq(connectionLog.ownerId, e.ownerId), isNotNull(connectionLog.hash)))
+ .orderBy(desc(connectionLog.id))
+ .limit(1)
+ .get();
+ const projectKey = e.projectKey ?? (e.projectId ? (tx.select({ key: projects.key }).from(projects).where(eq(projects.id, e.projectId)).get()?.key ?? null) : null);
+ const prevHash = head?.hash ?? "";
+ const row = tx
+ .insert(connectionLog)
+ .values({
+ ownerId: e.ownerId,
+ kind: e.kind,
+ parentId: e.parentId ?? null,
+ connectionId: e.connectionId,
+ connectionName: e.connectionName,
+ projectId: e.projectId ?? null,
+ projectKey,
+ sessionId: e.sessionId ?? null,
+ agentId: e.agentId ?? null,
+ agentName: e.agentName ?? null,
+ method: e.method,
+ path: e.path,
+ decision: e.decision,
+ reason: e.reason,
+ statusCode: e.statusCode,
+ durationMs: e.durationMs ?? null,
+ createdAt: e.createdAt,
+ prevHash,
+ })
+ .returning()
+ .get();
+ const hash = journalHash(prevHash, toRecord(row));
+ tx.update(connectionLog).set({ hash }).where(eq(connectionLog.id, row.id)).run();
+ return row.id;
+ });
+}
+
+export type ConnectionJournalBreak = "hash" | "link" | "missing_hash" | "checkpoint";
+
+export interface ConnectionJournalVerdict {
+ ok: boolean;
+ /** Rows checked (hashed ones). */
+ checked: number;
+ /** Rows written before the journal was protected (no hash, before the first hashed row). */
+ unprotected: number;
+ head: { id: number; hash: string } | null;
+ first: { id: number; hash: string } | null;
+ brokenAt?: number;
+ reason?: ConnectionJournalBreak;
+}
+
+/**
+ * Checks a chain (rows of ONE owner, any order). Leading rows without a hash are older than
+ * PEP-254 and are not checked; the first hashed row anchors the chain (its prev_hash is taken).
+ * Works on exported records too — the same code an owner could run.
+ */
+export function verifyJournalRows(input: ConnectionJournalRecord[]): ConnectionJournalVerdict {
+ const rows = [...input].sort((a, b) => a.id - b.id);
+ let i = 0;
+ while (i < rows.length && rows[i]!.hash == null) i++;
+ const out: ConnectionJournalVerdict = { ok: true, checked: 0, unprotected: i, head: null, first: null };
+ let prev: string | null = null;
+ for (; i < rows.length; i++) {
+ const r = rows[i]!;
+ const fail = (reason: ConnectionJournalBreak) => ({ ...out, ok: false, brokenAt: r.id, reason });
+ if (r.hash == null || r.prev_hash == null) return fail("missing_hash");
+ if (prev !== null && r.prev_hash !== prev) return fail("link");
+ if (journalHash(r.prev_hash, r) !== r.hash) return fail("hash");
+ if (!out.first) out.first = { id: r.id, hash: r.hash };
+ out.head = { id: r.id, hash: r.hash };
+ prev = r.hash;
+ out.checked++;
+ }
+ return out;
+}
+
+export interface ConnectionJournalCheckpoint {
+ id: number;
+ hash: string;
+ firstId: number;
+ firstHash: string;
+ at: number;
+}
+
+const checkpointKey = (ownerId: number) => `connection.journal.checkpoint:${ownerId}`;
+const brokenKey = (ownerId: number) => `connection.journal.broken:${ownerId}`;
+
+export const getJournalCheckpoint = (db: Db, ownerId: number) => getSetting(db, checkpointKey(ownerId));
+
+async function ownerRows(db: Db, ownerId: number): Promise {
+ return (await db.select().from(connectionLog).where(eq(connectionLog.ownerId, ownerId)).orderBy(asc(connectionLog.id))).map(toRecord);
+}
+
+/**
+ * The owner's chain plus the last checkpoint: the row it names must still be there with the same
+ * hash, and so must the first row — a chain rewritten from scratch doesn't pass.
+ */
+export async function verifyConnectionJournal(db: Db, ownerId: number): Promise {
+ const rows = await ownerRows(db, ownerId);
+ const v = verifyJournalRows(rows);
+ if (!v.ok) return v;
+ const cp = await getJournalCheckpoint(db, ownerId);
+ if (cp) {
+ const byId = new Map(rows.map((r) => [r.id, r]));
+ if (byId.get(cp.firstId)?.hash !== cp.firstHash) return { ...v, ok: false, brokenAt: cp.firstId, reason: "checkpoint" };
+ if (byId.get(cp.id)?.hash !== cp.hash) return { ...v, ok: false, brokenAt: cp.id, reason: "checkpoint" };
+ }
+ return v;
+}
+
+/**
+ * Gives a hash chain to owners whose journal has none yet (rows from before PEP-254). Owners that
+ * already have a chain keep their older rows as «before protection».
+ */
+export async function upgradeConnectionJournal(db: Db): Promise {
+ const owners = await db
+ .select({ ownerId: connectionLog.ownerId })
+ .from(connectionLog)
+ .where(isNotNull(connectionLog.ownerId))
+ .groupBy(connectionLog.ownerId)
+ .having(sql`count(${connectionLog.hash}) = 0`);
+ let n = 0;
+ for (const { ownerId } of owners) {
+ n += db.transaction((tx) => {
+ if (tx.select({ id: connectionLog.id }).from(connectionLog).where(and(eq(connectionLog.ownerId, ownerId!), isNotNull(connectionLog.hash))).limit(1).get()) return 0;
+ const rows = tx.select().from(connectionLog).where(and(eq(connectionLog.ownerId, ownerId!), isNull(connectionLog.hash))).orderBy(asc(connectionLog.id)).all();
+ let prev = "";
+ for (const r of rows) {
+ const hash = journalHash(prev, toRecord(r));
+ tx.update(connectionLog).set({ prevHash: prev, hash }).where(eq(connectionLog.id, r.id)).run();
+ prev = hash;
+ }
+ return rows.length;
+ });
+ }
+ return n;
+}
+
+// ---------- export ----------
+
+export const JOURNAL_EXPORT_FIELDS = ["id", "owner_id", "kind", "parent_id", "connection", "project", "agent", "method", "path", "decision", "reason", "status_code", "duration_ms", "created_at", "prev_hash", "hash"] as const;
+
+const csvCell = (v: unknown) => {
+ if (v == null) return "";
+ const s = String(v);
+ // A leading = + - @ would be a formula in a spreadsheet: quote it with an apostrophe.
+ const safe = /^[=+\-@\t\r]/.test(s) ? `'${s}` : s;
+ return /[",\n\r]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe;
+};
+
+/** The owner's whole journal with hashes, oldest first. Only the owner's own rows. */
+export async function exportConnectionJournal(db: Db, ownerId: number, format: "jsonl" | "csv"): Promise {
+ const rows = await ownerRows(db, ownerId);
+ if (format === "jsonl") return rows.map((r) => JSON.stringify(Object.fromEntries(JOURNAL_EXPORT_FIELDS.map((f) => [f, r[f]])))).join("\n") + (rows.length ? "\n" : "");
+ return [JOURNAL_EXPORT_FIELDS.join(","), ...rows.map((r) => JOURNAL_EXPORT_FIELDS.map((f) => csvCell(r[f])).join(","))].join("\n") + "\n";
+}
+
+/** Reads an exported JSONL back (for checking it). */
+export const parseJournalJsonl = (text: string): ConnectionJournalRecord[] =>
+ text
+ .split("\n")
+ .filter((l) => l.trim())
+ .map((l) => JSON.parse(l) as ConnectionJournalRecord);
+
+/** A self-contained Node script that checks an exported JSONL (shown on the «Подключения» page). */
+export const JOURNAL_VERIFY_SCRIPT = `// node verify.mjs journal.jsonl
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+const rows = readFileSync(process.argv[2], "utf8").split("\\n").filter(Boolean).map((l) => JSON.parse(l));
+let prev = null, bad = 0;
+for (const r of rows) {
+ if (r.hash == null) continue; // written before the protection
+ const body = JSON.stringify([r.id, r.owner_id, r.kind, r.parent_id, r.connection, r.project, r.agent, r.method, r.path, r.decision, r.reason, r.status_code, r.duration_ms, r.created_at]);
+ const h = createHash("sha256").update(r.prev_hash + "\\n" + body).digest("hex");
+ if ((prev !== null && r.prev_hash !== prev) || h !== r.hash) { console.log("BROKEN at id", r.id); bad++; break; }
+ prev = r.hash;
+}
+console.log(bad ? "journal changed" : "ok, head " + prev);
+`;
+
+// ---------- daily checkpoint and check ----------
+
+const CHECKPOINT_EVERY_MS = 24 * 3600_000;
+const TICK_EVERY_MS = 3600_000;
+let lastTick = 0;
+
+export interface ConnectionJournalTickResult {
+ checked: number;
+ checkpoints: number;
+ broken: number[];
+}
+
+/**
+ * Watchdog, once an hour: moves old keys and journals onto PEP-254, checks every owner's chain,
+ * once a day per owner writes a checkpoint (platform journal event + one «services» channel post
+ * for the day). A broken chain — one message to the superadmins and to the owner per break.
+ */
+export async function connectionJournalTick(db: Db, o: { now?: Date; force?: boolean; log?: (m: string) => void } = {}): Promise {
+ const now = o.now ?? new Date();
+ const out: ConnectionJournalTickResult = { checked: 0, checkpoints: 0, broken: [] };
+ if (process.env.PEPPA_CONNECTION_JOURNAL === "off") return out;
+ if (!o.force && now.getTime() - lastTick < TICK_EVERY_MS) return out;
+ lastTick = now.getTime();
+ const log = o.log ?? (() => {});
+ const { upgradeConnectionKeys } = await import("./connections.ts");
+ await upgradeConnectionKeys(db).catch(() => null);
+ await upgradeConnectionJournal(db);
+
+ const owners = (await db.select({ ownerId: connectionLog.ownerId }).from(connectionLog).where(isNotNull(connectionLog.hash)).groupBy(connectionLog.ownerId)).map((r) => r.ownerId!);
+ const [platform] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, platformProjectKey()));
+ const heads: string[] = [];
+ for (const ownerId of owners) {
+ out.checked++;
+ const v = await verifyConnectionJournal(db, ownerId);
+ if (!v.ok) {
+ out.broken.push(ownerId);
+ await reportBreak(db, ownerId, v, log);
+ continue;
+ }
+ await deleteSetting(db, brokenKey(ownerId));
+ const cp = await getJournalCheckpoint(db, ownerId);
+ if (!v.head || !v.first) continue;
+ if (cp && (cp.id === v.head.id || now.getTime() - cp.at < CHECKPOINT_EVERY_MS)) continue;
+ const next: ConnectionJournalCheckpoint = { id: v.head.id, hash: v.head.hash, firstId: v.first.id, firstHash: v.first.hash, at: now.getTime() };
+ await setSetting(db, checkpointKey(ownerId), next);
+ if (platform) await logEvent(db, { projectId: platform.id, type: "connection_journal_checkpoint", payload: { ownerId, headId: next.id, headHash: next.hash, firstId: next.firstId, firstHash: next.firstHash } });
+ heads.push(`u${ownerId} #${next.id} ${next.hash.slice(0, 16)}`);
+ out.checkpoints++;
+ }
+ if (heads.length) {
+ // glossary-ignore: the «services» channel is read by the platform's engineers.
+ const html = `${tr("Журнал подключений: контрольные точки")}\n${heads.join("\n")}`;
+ await postToChannel(db, "services", `mon:ch:connection-journal:${now.toISOString().slice(0, 13)}`, html).catch(() => false);
+ }
+ return out;
+}
+
+async function reportBreak(db: Db, ownerId: number, v: ConnectionJournalVerdict, log: (m: string) => void): Promise {
+ const seen = await getSetting<{ id: number }>(db, brokenKey(ownerId));
+ if (seen?.id === v.brokenAt) return; // already told about this break
+ await setSetting(db, brokenKey(ownerId), { id: v.brokenAt, reason: v.reason, at: Date.now() });
+ const [u] = await db.select().from(users).where(eq(users.id, ownerId));
+ const [platform] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, platformProjectKey()));
+ if (platform) await logEvent(db, { projectId: platform.id, type: "connection_journal_broken", payload: { ownerId, id: v.brokenAt, reason: v.reason } });
+ const admin = tr("Журнал подключений пользователя {login} изменён в обход FORGE (запись {id}). Проверьте доступ к базе.", { login: asIs(u?.login ?? `#${ownerId}`), id: v.brokenAt ?? 0 });
+ await alertAdmins(db, `connection-journal:${ownerId}:${v.brokenAt}`, admin, log).catch(() => 0);
+ if (!u || u.disabledAt) return;
+ const text = tr("Журнал ваших подключений изменён в обход FORGE. Администратор уже знает и разбирается; ключи доступа лучше заменить в разделе «Подключения».");
+ const key = `connection-journal:${ownerId}:${v.brokenAt}`;
+ await addMasterMessage(db, ownerId, { kind: "event", important: true, text, dedupeKey: `master:${key}`, url: "/connections" }).catch(() => null);
+ await deliverToUser(db, u, {
+ event: "failures",
+ dedupeKey: `${key}:${u.telegramChatId}`,
+ pushKey: `${key}:u${u.id}`,
+ telegram: { params: { text } },
+ push: { title: tr("FORGE"), body: text, url: "/connections", tag: "connection-journal" },
+ }).catch(() => null);
+}
diff --git a/packages/core/src/connections.ts b/packages/core/src/connections.ts
index ff509b0d..d44566ad 100644
--- a/packages/core/src/connections.ts
+++ b/packages/core/src/connections.ts
@@ -7,7 +7,7 @@
// pep-234-access-hub (design.md — threat model).
import { asIs, m as tr } from "@peppa/shared/i18n";
import { agents, connectionGrants, connectionLog, connections, projects, sessions, users, type Db } from "@peppa/db";
-import { and, asc, count, desc, eq, gt, inArray } from "drizzle-orm";
+import { and, asc, count, desc, eq, gt, inArray, isNotNull, isNull, sql } from "drizzle-orm";
import { lookup as dnsLookup, type LookupAddress } from "node:dns";
import { request as httpRequest, type IncomingMessage } from "node:http";
import { request as httpsRequest } from "node:https";
@@ -15,7 +15,8 @@ import { isIP } from "node:net";
import { logEvent } from "./audit.ts";
import { catalogService, classifyRequest, type CatalogAuth, type CatalogCheck } from "./connection-catalog.ts";
import { addMasterMessage } from "./chats.ts";
-import { decrypt, encrypt } from "./crypto.ts";
+import { appendJournal, type ConnectionJournalDecision } from "./connection-journal.ts";
+import { decrypt, encrypt, newDataKey, openWithKey, sealWithKey } from "./crypto.ts";
import { deliverToUser } from "./notifications.ts";
import { PeppaError } from "./errors.ts";
import { maskSecrets } from "./secrets.ts";
@@ -130,6 +131,10 @@ export interface ConnectionLogView {
decision: "allowed" | "denied" | "failed";
reason: string | null;
statusCode: number | null;
+ /** PEP-254: how long the service took (from the result row). */
+ durationMs: number | null;
+ /** done — a decision or a result is written; running — the call is in flight; unfinished — started, no result (a crash in the middle). */
+ state: "done" | "running" | "unfinished";
createdAt: Date;
}
@@ -249,6 +254,49 @@ function secretError(secret: string): string | null {
const HEADER_RE = /^[A-Za-z][A-Za-z0-9-]{0,63}$/;
const FORBIDDEN_HEADERS = new Set(["host", "content-length", "content-type", "transfer-encoding", "connection", "cookie", "accept-encoding"]);
+// ---------- PEP-254: one data key per connection (envelope) ----------
+
+const SECRET_V2 = "v2.";
+const SECRET_AAD = "connection-secret";
+
+/**
+ * Encrypts a connection key with a fresh data key of its own; the data key goes under
+ * PEPPA_SECRET. Decrypting one connection's data key opens nothing else.
+ */
+export function sealConnectionSecret(secret: string): { secretEnc: string; dekEnc: string } {
+ const dek = newDataKey();
+ return { secretEnc: SECRET_V2 + sealWithKey(dek, secret, SECRET_AAD), dekEnc: encrypt(dek.toString("base64url")) };
+}
+
+/** The key of a connection (gateway and check only — never returned anywhere else). */
+export function openConnectionSecret(c: { secretEnc: string | null; dekEnc: string | null }): string | null {
+ if (!c.secretEnc) return null;
+ if (!c.dekEnc || !c.secretEnc.startsWith(SECRET_V2)) return decrypt(c.secretEnc); // an old row
+ return openWithKey(Buffer.from(decrypt(c.dekEnc), "base64url"), c.secretEnc.slice(SECRET_V2.length), SECRET_AAD);
+}
+
+/**
+ * Moves connections stored before PEP-254 (secret under PEPPA_SECRET) to their own data key.
+ * The key is decrypted and re-encrypted inside this process only. Unreadable rows are skipped.
+ */
+export async function upgradeConnectionKeys(db: Db): Promise<{ upgraded: number; unreadable: number }> {
+ const rows = await db.select({ id: connections.id, secretEnc: connections.secretEnc }).from(connections).where(and(isNotNull(connections.secretEnc), isNull(connections.dekEnc)));
+ let upgraded = 0;
+ let unreadable = 0;
+ for (const r of rows) {
+ let plain: string;
+ try {
+ plain = decrypt(r.secretEnc!);
+ } catch {
+ unreadable++;
+ continue;
+ }
+ await db.update(connections).set(sealConnectionSecret(plain)).where(and(eq(connections.id, r.id), isNull(connections.dekEnc)));
+ upgraded++;
+ }
+ return { upgraded, unreadable };
+}
+
export interface ConnectionInput {
/** Default: the catalog card's name. */
name?: string;
@@ -303,7 +351,7 @@ export async function createConnection(db: Db, userId: number, i: ConnectionInpu
const [dup] = await db.select({ id: connections.id }).from(connections).where(and(eq(connections.ownerId, userId), eq(connections.name, name)));
if (dup) throw new PeppaError(tr("Подключение «{name}» уже есть", { name }));
const slug = await freeSlug(db, userId, card?.id ?? slugify(name));
- const [row] = await db.insert(connections).values({ ownerId: userId, name, baseUrl, authKind, authHeader, catalogId: card?.id ?? null, slug, secretEnc: encrypt(i.secret) }).returning({ id: connections.id });
+ const [row] = await db.insert(connections).values({ ownerId: userId, name, baseUrl, authKind, authHeader, catalogId: card?.id ?? null, slug, ...sealConnectionSecret(i.secret) }).returning({ id: connections.id });
return (await listConnections(db, userId)).find((c) => c.id === row!.id)!;
}
@@ -313,7 +361,7 @@ export async function replaceConnectionSecret(db: Db, userId: number, connection
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.
- await db.update(connections).set({ secretEnc: encrypt(secret), status: "active", revokedAt: null, checkStatus: null, checkedAt: null, checkAlertedAt: null }).where(eq(connections.id, connectionId));
+ await db.update(connections).set({ ...sealConnectionSecret(secret), status: "active", revokedAt: null, checkStatus: null, checkedAt: null, checkAlertedAt: null }).where(eq(connections.id, connectionId));
}
/**
@@ -323,7 +371,7 @@ export async function replaceConnectionSecret(db: Db, userId: number, connection
*/
export async function revokeConnection(db: Db, userId: number, connectionId: number): Promise {
const c = await ownConnection(db, userId, connectionId);
- await db.update(connections).set({ status: "revoked", secretEnc: null, revokedAt: new Date() }).where(eq(connections.id, c.id));
+ await db.update(connections).set({ status: "revoked", secretEnc: null, dekEnc: null, revokedAt: new Date() }).where(eq(connections.id, c.id));
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 } });
}
@@ -431,13 +479,13 @@ export async function listConnections(db: Db, userId: number): Promise {
- return db
+export async function connectionJournal(db: Db, userId: number, o: { connectionId?: number; limit?: number; now?: Date } = {}): Promise {
+ const calls = await db
.select({
id: connectionLog.id,
connectionId: connectionLog.connectionId,
connectionName: connectionLog.connectionName,
- projectKey: projects.key,
+ projectKey: sql`coalesce(${connectionLog.projectKey}, ${projects.key})`,
agentName: connectionLog.agentName,
sessionId: connectionLog.sessionId,
method: connectionLog.method,
@@ -445,13 +493,26 @@ export async function connectionJournal(db: Db, userId: number, o: { connectionI
decision: connectionLog.decision,
reason: connectionLog.reason,
statusCode: connectionLog.statusCode,
+ durationMs: connectionLog.durationMs,
createdAt: connectionLog.createdAt,
})
.from(connectionLog)
.leftJoin(projects, eq(projects.id, connectionLog.projectId))
- .where(and(eq(connectionLog.ownerId, userId), o.connectionId != null ? eq(connectionLog.connectionId, o.connectionId) : undefined))
+ .where(and(eq(connectionLog.ownerId, userId), eq(connectionLog.kind, "call"), o.connectionId != null ? eq(connectionLog.connectionId, o.connectionId) : undefined))
.orderBy(desc(connectionLog.id))
.limit(Math.min(o.limit ?? 100, 500));
+ // PEP-254: an allowed call is written before the request; its result is a row of its own.
+ const ids = calls.filter((c) => c.decision === "allowed" && c.statusCode == null).map((c) => c.id);
+ const results = ids.length ? await db.select().from(connectionLog).where(and(eq(connectionLog.ownerId, userId), eq(connectionLog.kind, "result"), inArray(connectionLog.parentId, ids))) : [];
+ const byParent = new Map(results.map((r) => [r.parentId!, r]));
+ const now = (o.now ?? new Date()).getTime();
+ return calls.map((c) => {
+ const r = byParent.get(c.id);
+ if (r) return { ...c, decision: r.decision, reason: r.reason, statusCode: r.statusCode, durationMs: r.durationMs, state: "done" as const };
+ const open = c.decision === "allowed" && c.statusCode == null && ids.includes(c.id);
+ if (!open) return { ...c, state: "done" as const };
+ return { ...c, state: now - c.createdAt.getTime() > CONNECTION_TIMEOUT_MS * 2 ? ("unfinished" as const) : ("running" as const) };
+ });
}
/** Agents to choose from in a grant (the platform's team). */
@@ -654,10 +715,13 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
const s = await sessionCtx(db, call.sessionId);
let conn: typeof connections.$inferSelect | null = null;
- const record = async (decision: "allowed" | "denied" | "failed", reason: ConnectionReason | null, statusCode: number | null) => {
- if (!conn) return; // nothing to attribute: an unknown connection is not someone's journal
- await db.insert(connectionLog).values({
+ // PEP-254: every row goes into the owner's hash chain; an allowed call is written BEFORE the request.
+ const record = async (decision: ConnectionJournalDecision, reason: ConnectionReason | null, statusCode: number | null, extra: { kind?: "call" | "result"; parentId?: number; durationMs?: number } = {}): Promise => {
+ if (!conn) return null; // nothing to attribute: an unknown connection is not someone's journal
+ return appendJournal(db, {
ownerId: conn.ownerId,
+ kind: extra.kind ?? "call",
+ parentId: extra.parentId ?? null,
connectionId: conn.id,
connectionName: conn.name,
projectId: s?.projectId ?? null,
@@ -669,7 +733,8 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
decision,
reason,
statusCode,
- createdAt: now,
+ durationMs: extra.durationMs ?? null,
+ createdAt: extra.kind === "result" ? new Date(now.getTime() + (extra.durationMs ?? 0)) : now,
});
};
const deny = async (reason: ConnectionReason): Promise => {
@@ -707,12 +772,12 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
if (body && (body.length > CONNECTION_BODY_MAX_BYTES || method === "GET")) return deny("bad_request");
const contentType = call.contentType?.trim() || (body ? "application/json" : null);
if (contentType && !CONTENT_TYPE_RE.test(contentType)) return deny("bad_request");
- const [{ n }] = (await db.select({ n: count() }).from(connectionLog).where(and(eq(connectionLog.sessionId, s.id), gt(connectionLog.createdAt, new Date(now.getTime() - 60_000))))) as [{ n: number }];
+ 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 = decrypt(conn.secretEnc);
+ secret = openConnectionSecret(conn)!;
} catch {
await record("failed", "upstream_error", null);
return { ok: false, reason: "upstream_error" };
@@ -722,19 +787,25 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
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))!;
+ const started = Date.now();
+ 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 });
if (res.status >= 300 && res.status < 400 && res.location) {
- await record("failed", "redirect", res.status);
+ await result("failed", "redirect", res.status);
return { ok: false, reason: "redirect", status: res.status };
}
- await record("allowed", res.truncated ? "too_large" : null, res.status);
+ 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] : []);
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";
- await record(reason === "blocked_address" ? "denied" : "failed", reason, null);
+ await result(reason === "blocked_address" ? "denied" : "failed", reason, null);
return { ok: false, reason };
}
}
@@ -773,9 +844,12 @@ async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: { fetc
const raw = check?.path ?? "/";
const clean = cleanPath(raw) ?? { path: "/", query: "" };
let res: { status: number; body: string } | null = null;
- let secret = "";
+ // PEP-254: the check is journaled like a gateway call — the call first, its result after.
+ 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();
try {
- secret = decrypt(conn.secretEnc!);
+ const secret = openConnectionSecret(conn)!;
const built = buildRequest(conn, secret, clean, null, null);
if (built) {
// Own service: the check is the base address itself (no trailing «/» added).
@@ -787,17 +861,8 @@ async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: { fetc
res = null;
}
const verdict = judgeCheck(check, res);
- await db.insert(connectionLog).values({
- ownerId: conn.ownerId,
- connectionId: conn.id,
- connectionName: conn.name,
- method,
- path: clean.path.slice(0, 300),
- decision: verdict.status === "ok" ? "allowed" : "failed",
- reason: "owner_check",
- statusCode: res?.status ?? null,
- createdAt: now,
- });
+ 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));
diff --git a/packages/core/src/crypto.ts b/packages/core/src/crypto.ts
index 982cbf30..a82fd035 100644
--- a/packages/core/src/crypto.ts
+++ b/packages/core/src/crypto.ts
@@ -50,6 +50,27 @@ export function decrypt(enc: string): string {
}
}
+/** PEP-254: a fresh random 256-bit data key (envelope encryption). */
+export const newDataKey = (): Buffer => randomBytes(32);
+
+/** AES-256-GCM with a given data key and associated data; base64url(iv | tag | ciphertext). */
+export function sealWithKey(dataKey: Buffer, plain: string, aad: string): string {
+ const iv = randomBytes(12);
+ const c = createCipheriv("aes-256-gcm", dataKey, iv);
+ c.setAAD(Buffer.from(aad, "utf8"));
+ const data = Buffer.concat([c.update(plain, "utf8"), c.final()]);
+ return Buffer.concat([iv, c.getAuthTag(), data]).toString("base64url");
+}
+
+/** Opens `sealWithKey`; throws on a wrong key or tampered data. */
+export function openWithKey(dataKey: Buffer, enc: string, aad: string): string {
+ const buf = Buffer.from(enc, "base64url");
+ const d = createDecipheriv("aes-256-gcm", dataKey, buf.subarray(0, 12));
+ d.setAAD(Buffer.from(aad, "utf8"));
+ d.setAuthTag(buf.subarray(12, 28));
+ return Buffer.concat([d.update(buf.subarray(28)), d.final()]).toString("utf8");
+}
+
/** Which key an encrypted value opens with (PEP-19: what still waits for `reencrypt`). */
export function encryptedWith(enc: string): "current" | "previous" | "unknown" {
const buf = Buffer.from(enc, "base64url");
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 0718cf50..13b43606 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -108,6 +108,7 @@ export * from "./feature-status.ts";
export * from "./accept-screen.ts";
export * from "./accept-digest.ts";
export * from "./connections.ts";
+export * from "./connection-journal.ts";
export * from "./connection-catalog.ts";
export * from "./edge-dns.ts";
export * from "./retention.ts";
diff --git a/packages/core/src/secrets-audit.ts b/packages/core/src/secrets-audit.ts
index 687d024b..9bb6bebd 100644
--- a/packages/core/src/secrets-audit.ts
+++ b/packages/core/src/secrets-audit.ts
@@ -8,6 +8,7 @@ import { connections, oauthClients, oauthTokens, projects, projectSecrets, sessi
import { and, eq, gt, isNotNull, isNull, notInArray, sql } from "drizzle-orm";
import { logEvent } from "./audit.ts";
import { encrypt, decrypt, encryptedWith, rotatingSecret } from "./crypto.ts";
+import { upgradeConnectionKeys } from "./connections.ts";
import { PeppaError } from "./errors.ts";
import { GiteaClient } from "./gitea.ts";
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
@@ -190,8 +191,10 @@ function encryptedColumns(db: Db) {
{ table: "users", column: "telegram_bot_token_enc", rows: () => db.select({ id: users.id, enc: users.telegramBotTokenEnc }).from(users).where(isNotNull(users.telegramBotTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ telegramBotTokenEnc: enc }).where(eq(users.id, id)) },
{ table: "subscriptions", column: "secret_enc", rows: () => db.select({ id: subscriptions.id, enc: subscriptions.secretEnc }).from(subscriptions).where(isNotNull(subscriptions.secretEnc)), set: (id: number, enc: string) => db.update(subscriptions).set({ secretEnc: enc }).where(eq(subscriptions.id, id)) },
{ table: "project_secrets", column: "value_enc", rows: () => db.select({ id: projectSecrets.id, enc: projectSecrets.valueEnc }).from(projectSecrets), set: (id: number, enc: string) => db.update(projectSecrets).set({ valueEnc: enc }).where(eq(projectSecrets.id, id)) },
- // PEP-234: Access Hub keys (revoked connections have none).
- { table: "connections", column: "secret_enc", rows: () => db.select({ id: connections.id, enc: connections.secretEnc }).from(connections).where(isNotNull(connections.secretEnc)), set: (id: number, enc: string) => db.update(connections).set({ secretEnc: enc }).where(eq(connections.id, id)) },
+ // PEP-254: Access Hub keys sit under their own data key; PEPPA_SECRET guards only the data
+ // keys. Old rows not yet moved by `upgradeConnectionKeys` still hold the key itself.
+ { table: "connections", column: "dek_enc", rows: () => db.select({ id: connections.id, enc: connections.dekEnc }).from(connections).where(isNotNull(connections.dekEnc)), set: (id: number, enc: string) => db.update(connections).set({ dekEnc: enc }).where(eq(connections.id, id)) },
+ { table: "connections", column: "secret_enc", rows: () => db.select({ id: connections.id, enc: connections.secretEnc }).from(connections).where(and(isNotNull(connections.secretEnc), isNull(connections.dekEnc))), set: (id: number, enc: string) => db.update(connections).set({ secretEnc: enc }).where(and(eq(connections.id, id), isNull(connections.dekEnc))) },
];
}
@@ -315,6 +318,8 @@ export interface ReencryptResult {
export async function reencryptAll(db: Db, by: string | null = null): Promise {
if (!envSet("PEPPA_SECRET", process.env)) throw new PeppaError(tr("PEPPA_SECRET не задан"));
const out: ReencryptResult = { reencrypted: 0, alreadyCurrent: 0, unreadable: [] };
+ // PEP-254: old Access Hub rows first get a data key of their own (then only it is re-encrypted).
+ await upgradeConnectionKeys(db);
for (const c of encryptedColumns(db)) {
for (const r of await c.rows()) {
const k = encryptedWith(r.enc!);
diff --git a/packages/db/migrations/0030_access_hub_journal.sql b/packages/db/migrations/0030_access_hub_journal.sql
new file mode 100644
index 00000000..148e68d1
--- /dev/null
+++ b/packages/db/migrations/0030_access_hub_journal.sql
@@ -0,0 +1,8 @@
+ALTER TABLE `connection_log` ADD `kind` text DEFAULT 'call' NOT NULL;--> statement-breakpoint
+ALTER TABLE `connection_log` ADD `parent_id` integer;--> statement-breakpoint
+ALTER TABLE `connection_log` ADD `project_key` text;--> statement-breakpoint
+ALTER TABLE `connection_log` ADD `duration_ms` integer;--> statement-breakpoint
+ALTER TABLE `connection_log` ADD `prev_hash` text;--> statement-breakpoint
+ALTER TABLE `connection_log` ADD `hash` text;--> statement-breakpoint
+ALTER TABLE `connections` ADD `dek_enc` text;--> statement-breakpoint
+UPDATE `connection_log` SET `project_key` = (SELECT `key` FROM `projects` WHERE `projects`.`id` = `connection_log`.`project_id`) WHERE `project_id` IS NOT NULL;
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0030_snapshot.json b/packages/db/migrations/meta/0030_snapshot.json
new file mode 100644
index 00000000..391e7c83
--- /dev/null
+++ b/packages/db/migrations/meta/0030_snapshot.json
@@ -0,0 +1,5267 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "1ad8db33-759f-4508-9ebd-50d0f75742c5",
+ "prevId": "b9725df3-9c8c-4040-ac82-7c39e6ad630b",
+ "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
+ },
+ "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 66ec5d56..b7d35a85 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -211,6 +211,13 @@
"when": 1795445709219,
"tag": "0029_access_hub_catalog",
"breakpoints": true
+ },
+ {
+ "idx": 30,
+ "version": "6",
+ "when": 1795512094088,
+ "tag": "0030_access_hub_journal",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index eec9c611..3483bc51 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -684,7 +684,11 @@ export const connections = sqliteTable(
checkStatus: text("check_status").$type<"ok" | "bad_key" | "down">(),
checkedAt: integer("checked_at", { mode: "timestamp_ms" }),
checkAlertedAt: integer("check_alerted_at", { mode: "timestamp_ms" }),
+ // PEP-254 envelope: `secret_enc` = "v2." + AES-GCM with this connection's own data key;
+ // `dek_enc` = that data key under PEPPA_SECRET (rotation re-encrypts only it). No dek_enc —
+ // 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"),
revokedAt: integer("revoked_at", { mode: "timestamp_ms" }),
lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }),
@@ -730,6 +734,14 @@ export const connectionLog = sqliteTable(
decision: text("decision").$type<"allowed" | "denied" | "failed">().notNull(),
reason: text("reason"),
statusCode: integer("status_code"),
+ // PEP-254: `call` is written before the request, its `result` (parent_id) after it.
+ kind: text("kind").$type<"call" | "result">().notNull().default("call"),
+ parentId: integer("parent_id"),
+ projectKey: text("project_key"),
+ durationMs: integer("duration_ms"),
+ // Hash chain per owner (core/connection-journal.ts): sha256(prev_hash + "\n" + canonical row).
+ prevHash: text("prev_hash"),
+ hash: text("hash"),
createdAt: createdAt(),
},
(t) => [index("connection_log_owner").on(t.ownerId, t.id), index("connection_log_session_created").on(t.sessionId, t.createdAt)],
diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts
index 8e91b0c1..744c565b 100644
--- a/packages/runner/src/watchdog.ts
+++ b/packages/runner/src/watchdog.ts
@@ -39,7 +39,7 @@ import { limitDelay, limitOver } from "./limit-delay.ts";
import { checksQueueTick, platformDelayTick } from "./platform-delays.ts";
import { readyDigestTick } from "./ready-digest.ts";
import { stuckTaskTick } from "./stuck-tasks.ts";
-import { connectionCheckTick } from "@peppa/core";
+import { connectionCheckTick, connectionJournalTick } from "@peppa/core";
import { domainGuardTick } from "./domain-guard.ts";
import { edgeDnsTick } from "./edge-dns.ts";
import { actRunnerTick } from "./act-runner.ts";
@@ -422,6 +422,8 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS
await stuckTaskTick(db, { log }).catch(failed(db, log, "stuck tasks failed"));
// PEP-249: each connection's key is checked once a day; a key that stopped working — one message to its owner.
await connectionCheckTick(db).catch(failed(db, log, "connection check failed"));
+ // PEP-254: hourly — the connections journal chain is checked, a daily checkpoint goes outside the table.
+ await connectionJournalTick(db, { log }).catch(failed(db, log, "connection journal failed"));
// PEP-209: one «Готово к приёмке» summary instead of many «готово» messages in Telegram.
await acceptDigestTick(db, { log }).catch(failed(db, log, "accept digest failed"));
await pruneAcceptFailures(db).catch(() => {});
diff --git a/packages/shared/src/i18n/en/access-hub.ts b/packages/shared/src/i18n/en/access-hub.ts
index 506ceca9..ed68b521 100644
--- a/packages/shared/src/i18n/en/access-hub.ts
+++ b/packages/shared/src/i18n/en/access-hub.ts
@@ -153,4 +153,14 @@ export const accessHub: Record = {
"Имя параметра для ключа: латинские буквы, цифры, дефис и подчёркивание, например key": "Key parameter name: Latin letters, digits, hyphens and underscores, for example key",
"Разрешите чтение, запись или хотя бы одну операцию": "Allow reading, writing or at least one operation",
"Ключ доступа подключения «{name}» перестал работать: агенты не смогут им пользоваться. Замените ключ в разделе «Подключения».": "The access key of connection «{name}» stopped working: agents can't use it. Replace the key in «Connections».",
+ "выполняется": "in progress",
+ "начато, итога нет": "started, no result",
+ "Журнал нельзя незаметно изменить: каждая запись связана с предыдущей, и раз в сутки FORGE сохраняет отметку журнала отдельно. Если запись изменят, вы и администратор получите сообщение.": "The journal can't be changed unnoticed: each entry is linked to the previous one, and once a day FORGE keeps a mark of the journal separately. If an entry is changed, you and the administrator get a message.",
+ "Скачать журнал (таблица)": "Download the journal (table)",
+ "Скачать журнал для проверки": "Download the journal for checking",
+ "Как проверить журнал самому": "How to check the journal yourself",
+ "Скачайте журнал для проверки и сохраните программу ниже рядом с ним. Запустите её так, как написано в её первой строке. Ответ «ok» значит, что журнал не меняли; иначе программа назовёт первую изменённую запись.": "Download the journal for checking and save the program below next to it. Run it as its first line says. The answer «ok» means the journal wasn't changed; otherwise the program names the first changed entry.",
+ "Журнал подключений: контрольные точки": "Connections journal: checkpoints",
+ "Журнал подключений пользователя {login} изменён в обход FORGE (запись {id}). Проверьте доступ к базе.": "The connections journal of user {login} was changed bypassing FORGE (entry {id}). Check access to the database.",
+ "Журнал ваших подключений изменён в обход FORGE. Администратор уже знает и разбирается; ключи доступа лучше заменить в разделе «Подключения».": "The journal of your connections was changed bypassing FORGE. The administrator already knows and is looking into it; better replace the access keys in «Connections».",
};
diff --git a/packages/shared/src/i18n/kk/access-hub.ts b/packages/shared/src/i18n/kk/access-hub.ts
index 48789800..147b3c06 100644
--- a/packages/shared/src/i18n/kk/access-hub.ts
+++ b/packages/shared/src/i18n/kk/access-hub.ts
@@ -153,4 +153,14 @@ export const accessHub: Record = {
"Имя параметра для ключа: латинские буквы, цифры, дефис и подчёркивание, например key": "Кілт параметрінің атауы: латын әріптері, сандар, дефис және астын сызу, мысалы key",
"Разрешите чтение, запись или хотя бы одну операцию": "Оқуға, жазуға немесе кемінде бір операцияға рұқсат беріңіз",
"Ключ доступа подключения «{name}» перестал работать: агенты не смогут им пользоваться. Замените ключ в разделе «Подключения».": "«{name}» қосылымының қолжетімділік кілті жұмыс істемей қалды: агенттер оны пайдалана алмайды. Кілтті «Қосылымдар» бөлімінде ауыстырыңыз.",
+ "выполняется": "орындалуда",
+ "начато, итога нет": "басталды, нәтижесі жоқ",
+ "Журнал нельзя незаметно изменить: каждая запись связана с предыдущей, и раз в сутки FORGE сохраняет отметку журнала отдельно. Если запись изменят, вы и администратор получите сообщение.": "Журналды байқатпай өзгерту мүмкін емес: әр жазба алдыңғысымен байланысты, ал FORGE тәулігіне бір рет журналдың белгісін бөлек сақтайды. Жазба өзгертілсе, сіз де, әкімші де хабарлама аласыз.",
+ "Скачать журнал (таблица)": "Журналды жүктеу (кесте)",
+ "Скачать журнал для проверки": "Тексеруге арналған журналды жүктеу",
+ "Как проверить журнал самому": "Журналды өзіңіз қалай тексеруге болады",
+ "Скачайте журнал для проверки и сохраните программу ниже рядом с ним. Запустите её так, как написано в её первой строке. Ответ «ok» значит, что журнал не меняли; иначе программа назовёт первую изменённую запись.": "Тексеруге арналған журналды жүктеп, төмендегі бағдарламаны оның жанына сақтаңыз. Оны бірінші жолында жазылғандай іске қосыңыз. «ok» жауабы журнал өзгертілмегенін білдіреді; әйтпесе бағдарлама алғашқы өзгертілген жазбаны атайды.",
+ "Журнал подключений: контрольные точки": "Қосылымдар журналы: бақылау нүктелері",
+ "Журнал подключений пользователя {login} изменён в обход FORGE (запись {id}). Проверьте доступ к базе.": "{login} пайдаланушысының қосылымдар журналы FORGE-ды айналып өтіп өзгертілді (жазба {id}). Дерекқорға қолжетімділікті тексеріңіз.",
+ "Журнал ваших подключений изменён в обход FORGE. Администратор уже знает и разбирается; ключи доступа лучше заменить в разделе «Подключения».": "Қосылымдарыңыздың журналы FORGE-ды айналып өтіп өзгертілді. Әкімші біледі және анықтап жатыр; қолжетімділік кілттерін «Қосылымдар» бөлімінде ауыстырған жөн.",
};
diff --git a/packages/testkit/test/access-hub-journal.test.ts b/packages/testkit/test/access-hub-journal.test.ts
new file mode 100644
index 00000000..ac0795b4
--- /dev/null
+++ b/packages/testkit/test/access-hub-journal.test.ts
@@ -0,0 +1,276 @@
+// PEP-254 Access Hub: the journal is written before the action and can't be changed quietly
+// (hash chain + checkpoints outside the table), the owner exports and checks it; every connection
+// key sits under its own data key. Scenario names follow
+// openspec/changes/pep-254-access-hub-journal-integrity/specs/access-hub/spec.md.
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { after, before, describe, test } from "node:test";
+import { and, eq } from "drizzle-orm";
+import { stripAsIs } from "@peppa/shared/i18n";
+import type { ConnectionFetch } from "@peppa/core";
+import { core, db, project, teardown } from "./helpers.ts";
+
+process.env.PEPPA_SECRET = "mock-journal-secret-current";
+delete process.env.PEPPA_SECRET_PREVIOUS;
+const { connections, connectionLog, agents, sessions, events, telegramOutbox } = await import("@peppa/db");
+
+const KEY = "sk_live_mock_journal_111111";
+const KEY_MAIL = "sk_live_mock_mail_222222";
+
+let anna: Awaited>;
+let boris: Awaited>;
+
+before(async () => {
+ anna = await core.upsertUserFromGitea(db, { id: 2541, login: "mock-j-anna" }, { access_token: "a" });
+ boris = await core.upsertUserFromGitea(db, { id: 2542, login: "mock-j-boris" }, { access_token: "b" });
+ process.env.PEPPA_PLATFORM_KEY = (await project({ turns: [] })).key;
+ await db.update((await import("@peppa/db")).users).set({ telegramChatId: 254001 }).where(eq((await import("@peppa/db")).users.id, anna.id));
+});
+after(teardown);
+
+process.env.PEPPA_CONNECTIONS_UNISOLATED = "on";
+
+/** A mock external service in-process: status per path, optional hang. */
+function mockFetch(o: { status?: number; fail?: boolean } = {}): ConnectionFetch {
+ return async ({ url }) => {
+ if (o.fail) throw new Error("mock crash in the middle");
+ return { status: o.status ?? 200, contentType: "application/json", body: Buffer.from(JSON.stringify({ path: url.pathname })), truncated: false };
+ };
+}
+
+async function setup(ownerId: number, name: string, secret = KEY) {
+ 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 c = await core.createConnection(db, ownerId, { name, baseUrl: "https://crm.example.com/api", secret });
+ await core.grantConnection(db, ownerId, c.id, { projectId: proj.id, operations: "GET /items" });
+ const s = await core.createSession(db, { projectId: proj.id, taskId: task.id });
+ const [a] = await db.insert(agents).values({ name: `Мок-журнал ${s.id}` }).returning();
+ await db.update(sessions).set({ agentId: a!.id }).where(eq(sessions.id, s.id));
+ return { proj, c, sessionId: s.id };
+}
+
+const ownerRows = (ownerId: number) => db.select().from(connectionLog).where(eq(connectionLog.ownerId, ownerId)).orderBy(connectionLog.id);
+
+describe("Журнал пишется до действия", () => {
+ test("Итог дописывается после вызова", async () => {
+ const { c, sessionId, proj } = await setup(anna.id, "CRM");
+ let seenRows = -1;
+ const r = await core.callConnection(db, { sessionId, connection: "CRM", method: "GET", path: "/items/5" }, {
+ fetch: async (req) => {
+ // At the moment of the request the call is already in the journal.
+ seenRows = (await db.select().from(connectionLog).where(and(eq(connectionLog.connectionId, c.id), eq(connectionLog.kind, "call")))).length;
+ return mockFetch()(req);
+ },
+ });
+ assert.equal(r.ok, true);
+ assert.equal(seenRows, 1, "the call is written before the service is called");
+ const rows = (await ownerRows(anna.id)).filter((x) => x.connectionId === c.id);
+ assert.deepEqual(rows.map((x) => x.kind), ["call", "result"]);
+ assert.equal(rows[1]!.parentId, rows[0]!.id);
+ assert.equal(rows[1]!.statusCode, 200);
+ assert.equal(rows[0]!.projectKey, proj.key);
+ const view = (await core.connectionJournal(db, anna.id, { connectionId: c.id }))[0]!;
+ assert.equal(view.path, "/items/5");
+ assert.equal(view.statusCode, 200);
+ assert.equal(view.state, "done");
+ assert.equal((await core.connectionJournal(db, anna.id, { connectionId: c.id })).length, 1, "the result joins its call on screen");
+ });
+
+ test("Сбой посередине виден", async () => {
+ const { c, sessionId } = await setup(anna.id, "CRM-crash");
+ const t0 = new Date();
+ // The process «dies» between the call row and the result: simulate by dropping the result.
+ await core.callConnection(db, { sessionId, connection: "CRM-crash", method: "GET", path: "/items/5" }, { fetch: mockFetch(), now: t0 });
+ const [res] = await db.select().from(connectionLog).where(and(eq(connectionLog.connectionId, c.id), eq(connectionLog.kind, "result")));
+ // A real crash leaves no result row; it is the last row of the chain, so removing it keeps the chain whole.
+ await db.delete(connectionLog).where(eq(connectionLog.id, res!.id));
+ const soon = (await core.connectionJournal(db, anna.id, { connectionId: c.id, now: new Date(t0.getTime() + 1000) }))[0]!;
+ assert.equal(soon.state, "running");
+ const later = (await core.connectionJournal(db, anna.id, { connectionId: c.id, now: new Date(t0.getTime() + 60_000) }))[0]!;
+ assert.equal(later.state, "unfinished");
+ assert.equal((await core.verifyConnectionJournal(db, anna.id)).ok, true);
+ });
+
+ test("Отказ — одна запись, лимит считает только вызовы", async () => {
+ const { c, sessionId } = await setup(anna.id, "CRM-deny");
+ const r = await core.callConnection(db, { sessionId, connection: "CRM-deny", method: "DELETE", path: "/items/5" }, { fetch: mockFetch() });
+ assert.equal(r.ok, false);
+ const rows = await db.select().from(connectionLog).where(eq(connectionLog.connectionId, c.id));
+ assert.equal(rows.length, 1);
+ assert.equal(rows[0]!.decision, "denied");
+ });
+});
+
+describe("Журнал защищён от подделки", () => {
+ test("Изменённая запись обнаруживается", async () => {
+ const { sessionId } = await setup(boris.id, "CRM-b");
+ for (const p of ["/items/1", "/items/5", "/items/9"]) await core.callConnection(db, { sessionId, connection: "CRM-b", method: "GET", path: p }, { fetch: mockFetch() });
+ const before = await core.verifyConnectionJournal(db, boris.id);
+ assert.equal(before.ok, true);
+ assert.equal(before.checked, 6);
+ const rows = await ownerRows(boris.id);
+ const second = rows.find((r) => r.path === "/items/5" && r.kind === "call")!;
+ await db.update(connectionLog).set({ path: "/items/6" }).where(eq(connectionLog.id, second.id));
+ const v = await core.verifyConnectionJournal(db, boris.id);
+ assert.equal(v.ok, false);
+ assert.equal(v.brokenAt, second.id);
+ assert.equal(v.reason, "hash");
+ await db.update(connectionLog).set({ path: "/items/5" }).where(eq(connectionLog.id, second.id));
+ // A deleted row in the middle breaks the link.
+ const third = rows.find((r) => r.path === "/items/9" && r.kind === "call")!;
+ const saved = rows.find((r) => r.id === third.id)!;
+ await db.delete(connectionLog).where(eq(connectionLog.id, third.id));
+ const d = await core.verifyConnectionJournal(db, boris.id);
+ assert.equal(d.ok, false);
+ assert.equal(d.reason, "link");
+ await db.insert(connectionLog).values(saved);
+ assert.equal((await core.verifyConnectionJournal(db, boris.id)).ok, true);
+ });
+
+ test("Пересчитанная цепочка не совпадает с контрольной точкой", async () => {
+ const t0 = new Date("2026-11-24T10:00:00Z");
+ const r = await core.connectionJournalTick(db, { now: t0, force: true });
+ assert.ok(r.checkpoints >= 2, "a checkpoint per owner");
+ const cp = await core.getJournalCheckpoint(db, boris.id);
+ assert.ok(cp);
+ const [ev] = await db.select().from(events).where(eq(events.type, "connection_journal_checkpoint"));
+ assert.ok(ev, "the checkpoint is in the platform journal");
+
+ // Rewrite a row before the checkpoint and recompute every hash after it.
+ const rows = (await ownerRows(boris.id)).map(core.toRecord);
+ rows[0]!.path = "/forged";
+ let prev = rows[0]!.prev_hash!;
+ for (const r2 of rows) {
+ r2.prev_hash = prev;
+ r2.hash = core.journalHash(prev, r2);
+ prev = r2.hash;
+ await db.update(connectionLog).set({ path: r2.path, prevHash: r2.prev_hash, hash: r2.hash }).where(eq(connectionLog.id, r2.id));
+ }
+ assert.equal(core.verifyJournalRows(rows).ok, true, "the chain alone looks fine");
+ const v = await core.verifyConnectionJournal(db, boris.id);
+ assert.equal(v.ok, false);
+ assert.equal(v.reason, "checkpoint");
+ });
+
+ test("Нарушение доходит до людей", async () => {
+ const asel = await core.upsertUserFromGitea(db, { id: 2543, login: "mock-j-asel" }, { access_token: "c" });
+ const users = (await import("@peppa/db")).users;
+ await db.update(users).set({ telegramChatId: 254003 }).where(eq(users.id, asel.id));
+ await core.setPlatformAdmins(db, ["mock-j-asel"]);
+ await db.update(users).set({ telegramChatId: 254002 }).where(eq(users.id, boris.id));
+ const t1 = new Date("2026-11-24T12:00:00Z");
+ const r = await core.connectionJournalTick(db, { now: t1, force: true });
+ assert.deepEqual(r.broken, [boris.id]);
+ const outbox = async (chat: number) => (await db.select().from(telegramOutbox)).filter((m) => (m.params as { chat_id?: number }).chat_id === chat);
+ assert.equal((await outbox(254003)).length, 1, "the superadmin gets one message");
+ assert.equal((await outbox(254002)).length, 1, "the owner gets one message");
+ assert.match(stripAsIs(String((await outbox(254002))[0]!.params.text)), /изменён в обход FORGE/);
+ await core.connectionJournalTick(db, { now: new Date(t1.getTime() + 3600_000), force: true });
+ assert.equal((await outbox(254003)).length, 1, "the same break is not reported again");
+ assert.equal((await outbox(254002)).length, 1);
+ });
+});
+
+describe("Выгрузка журнала", () => {
+ test("Выгрузка проверяется", async () => {
+ const jsonl = await core.exportConnectionJournal(db, anna.id, "jsonl");
+ const rows = core.parseJournalJsonl(jsonl);
+ const own = await ownerRows(anna.id);
+ assert.equal(rows.length, own.length);
+ assert.ok(rows.every((r) => typeof r.hash === "string" && typeof r.prev_hash === "string"));
+ assert.equal(core.verifyJournalRows(rows).ok, true);
+ // The script from the page checks the file on its own.
+ const dir = mkdtempSync(join(tmpdir(), "mock-journal-"));
+ writeFileSync(join(dir, "journal.jsonl"), jsonl);
+ writeFileSync(join(dir, "verify.mjs"), core.JOURNAL_VERIFY_SCRIPT);
+ assert.match(execFileSync(process.execPath, [join(dir, "verify.mjs"), join(dir, "journal.jsonl")], { encoding: "utf8" }), /^ok, head [0-9a-f]{64}/m);
+ const forged = jsonl.replace('"/items/5"', '"/items/6"');
+ writeFileSync(join(dir, "journal.jsonl"), forged);
+ assert.match(execFileSync(process.execPath, [join(dir, "verify.mjs"), join(dir, "journal.jsonl")], { encoding: "utf8" }), /journal changed/);
+ const csv = await core.exportConnectionJournal(db, anna.id, "csv");
+ assert.equal(csv.trim().split("\n").length, own.length + 1);
+ assert.match(csv.split("\n")[0]!, /prev_hash,hash$/);
+ });
+
+ test("Чужой журнал не выгружается", async () => {
+ const mine = core.parseJournalJsonl(await core.exportConnectionJournal(db, anna.id, "jsonl"));
+ assert.ok(mine.every((r) => r.owner_id === anna.id));
+ assert.ok(!mine.some((r) => r.connection === "CRM-b"));
+ });
+});
+
+describe("Отдельный ключ шифрования у каждого подключения", () => {
+ test("Ключ данных одного подключения не открывает другое", async () => {
+ const a = await core.createConnection(db, anna.id, { name: "CRM-env", baseUrl: "https://crm.example.com/api", secret: KEY });
+ const b = await core.createConnection(db, anna.id, { name: "Почта", baseUrl: "https://mail.example.com/api", secret: KEY_MAIL });
+ const [ra] = await db.select().from(connections).where(eq(connections.id, a.id));
+ const [rb] = await db.select().from(connections).where(eq(connections.id, b.id));
+ assert.ok(ra!.dekEnc && rb!.dekEnc && ra!.dekEnc !== rb!.dekEnc);
+ assert.ok(ra!.secretEnc!.startsWith("v2."));
+ assert.equal(core.openConnectionSecret(ra!), KEY);
+ assert.equal(core.openConnectionSecret(rb!), KEY_MAIL);
+ assert.throws(() => core.openConnectionSecret({ secretEnc: rb!.secretEnc, dekEnc: ra!.dekEnc }), "CRM's data key does not open Почта");
+ assert.throws(() => core.decrypt(rb!.secretEnc!.slice(3)), "the platform key alone does not open a key either");
+ });
+
+ test("Старое подключение переводится на свой ключ", async () => {
+ const c = await core.createConnection(db, anna.id, { name: "CRM-old", baseUrl: "https://crm.example.com/api", secret: KEY });
+ // As stored before PEP-254: the key itself under PEPPA_SECRET, no data key.
+ await db.update(connections).set({ secretEnc: core.encrypt(KEY), dekEnc: null }).where(eq(connections.id, c.id));
+ const [old] = await db.select().from(connections).where(eq(connections.id, c.id));
+ assert.equal(core.openConnectionSecret(old!), KEY, "old rows still work before the move");
+ const r = await core.upgradeConnectionKeys(db);
+ assert.ok(r.upgraded >= 1);
+ const [moved] = await db.select().from(connections).where(eq(connections.id, c.id));
+ assert.ok(moved!.dekEnc && moved!.secretEnc!.startsWith("v2."));
+ assert.equal(core.openConnectionSecret(moved!), KEY);
+ assert.equal((await core.upgradeConnectionKeys(db)).upgraded, 0, "idempotent");
+ });
+
+ test("Ротация ключа платформы", async () => {
+ const { c, sessionId } = await setup(anna.id, "CRM-rot");
+ const [beforeRow] = await db.select().from(connections).where(eq(connections.id, c.id));
+ process.env.PEPPA_SECRET_PREVIOUS = process.env.PEPPA_SECRET;
+ process.env.PEPPA_SECRET = "mock-journal-secret-next";
+ try {
+ const r = await core.reencryptAll(db, "mock-j-asel");
+ assert.ok(r.reencrypted >= 1);
+ assert.equal(r.unreadable.length, 0);
+ const [afterRow] = await db.select().from(connections).where(eq(connections.id, c.id));
+ assert.notEqual(afterRow!.dekEnc, beforeRow!.dekEnc, "the data key is re-encrypted");
+ assert.equal(afterRow!.secretEnc, beforeRow!.secretEnc, "the encrypted key itself is untouched");
+ delete process.env.PEPPA_SECRET_PREVIOUS;
+ assert.equal(core.encryptedWith(afterRow!.dekEnc!), "current");
+ let auth = "";
+ const res = await core.callConnection(db, { sessionId, connection: "CRM-rot", method: "GET", path: "/items" }, {
+ fetch: async (req) => {
+ auth = req.headers.Authorization ?? req.headers.authorization ?? "";
+ return mockFetch()(req);
+ },
+ });
+ assert.equal(res.ok, true);
+ assert.equal(auth, `Bearer ${KEY}`);
+ } finally {
+ delete process.env.PEPPA_SECRET_PREVIOUS;
+ }
+ });
+});
+
+describe("Старый журнал получает цепочку", () => {
+ test("Записи до изменения связываются при переводе", async () => {
+ const carl = await core.upsertUserFromGitea(db, { id: 2544, login: "mock-j-carl" }, { access_token: "d" });
+ const c = await core.createConnection(db, carl.id, { name: "Old", baseUrl: "https://crm.example.com/api", secret: KEY });
+ for (const p of ["/a", "/b"]) await db.insert(connectionLog).values({ ownerId: carl.id, connectionId: c.id, connectionName: "Old", method: "GET", path: p, decision: "allowed", statusCode: 200, createdAt: new Date() });
+ assert.equal((await core.verifyConnectionJournal(db, carl.id)).unprotected, 2);
+ assert.equal(await core.upgradeConnectionJournal(db), 2);
+ const v = await core.verifyConnectionJournal(db, carl.id);
+ assert.equal(v.ok, true);
+ assert.equal(v.checked, 2);
+ assert.equal(await core.upgradeConnectionJournal(db), 0, "idempotent");
+ });
+});
diff --git a/packages/testkit/test/access-hub.test.ts b/packages/testkit/test/access-hub.test.ts
index 63403b88..09a2fa0a 100644
--- a/packages/testkit/test/access-hub.test.ts
+++ b/packages/testkit/test/access-hub.test.ts
@@ -95,10 +95,10 @@ describe("Подключение внешнего сервиса", () => {
assert.ok(!JSON.stringify(list).includes(KEY), "the list never carries the key");
const [row] = await db.select().from(connections).where(eq(connections.id, c.id));
assert.ok(row!.secretEnc && !row!.secretEnc.includes(KEY), "stored encrypted");
- assert.equal(core.decrypt(row!.secretEnc), KEY);
- // PEP-19: the key column takes part in PEPPA_SECRET rotation.
+ assert.equal(core.openConnectionSecret(row!), KEY);
+ // PEP-19/254: the connection's own data key takes part in PEPPA_SECRET rotation.
const audit = await core.secretsAudit(db);
- assert.ok(audit.encryption.columns.some((col) => col.table === "connections" && col.column === "secret_enc" && col.total >= 1));
+ assert.ok(audit.encryption.columns.some((col) => col.table === "connections" && col.column === "dek_enc" && col.total >= 1));
});
test("Небезопасный адрес отклоняется", async () => {