PEP-252: вход в сервисы через OAuth — ядро, обновление токенов, отзыв, мок и тесты

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-24 12:09:31 +00:00
parent d3e7163b66
commit cb4a01d1bb
18 changed files with 6510 additions and 31 deletions

View File

@ -0,0 +1,54 @@
# Design — PEP-252
## Решения
1. **Где хранить токены.** В том же конверте, что и ключ (PEP-254): `secret_enc` = JSON
`{access, refresh, type}` под собственным ключом данных подключения, `dek_enc` под
`PEPPA_SECRET`. Новой зашифрованной колонки нет — ротация `PEPPA_SECRET` и ревизия
`encryptedColumns` работают без изменений. Права (`oauth_scopes`, JSON) и срок
(`token_expires_at`) не секретны и лежат открыто: их показываем владельцу и по ним решаем,
пора ли обновлять, не расшифровывая токены.
2. **Способ подключения.** `auth_kind = "oauth"`, `catalog_id` — карточка (sheets/drive/
calendar/github), `oauth_provider` — google|github. Шлюз передаёт `Authorization: Bearer
<access>`; адрес, правило чтения и проверочный вызов берутся из карточки, как у ключей.
3. **Права.** Минимальные на уровень: Google Sheets `spreadsheets.readonly` / `spreadsheets`,
Drive `drive.readonly` / `drive`, Calendar `calendar.readonly` / `+calendar.events`. У GitHub
OAuth-приложений нет права «только чтение» для закрытых репозиториев: для обоих уровней
просим `repo read:org` (+ `workflow` не просим), а «только чтение» обеспечивает шлюз своим
правилом (PEP-249). Это написано владельцу рядом с кнопкой. Уровень «чтение» не даёт
выставить «Запись: сразу» бессмысленно — сервис сам откажет (403), шлюз это не скрывает.
4. **Поток.** Как вход Google (PEP-90): `state` 24 байта и `verifier` 32 байта, в `settings`
`conn.oauth.flow:<sha256(state)>` (10 мин, удаляется первым делом в callback), cookie
`peppa_conn_oauth` (httpOnly, SameSite=Lax, путь `/connections/oauth`). Callback требует:
state == cookie, поток жив, текущий пользователь == начавший поток (чужой — отказ, поток
сгорает). Google: `access_type=offline`, `prompt=consent` (иначе refresh_token не придёт
повторно), `include_granted_scopes=false`. Код и state в адресе живут только до
303-редиректа на `/connections?…` без них. Сообщения об ошибке провайдера — фиксированные
фразы, текст ответа сервиса не показываем.
5. **Обновление.** `connectionCredential(db, conn, {now, force})`: срок истекает ≤ 60 с (или
`force` после 401) и есть refresh → `POST token grant_type=refresh_token`. Ответ 400/401
(`invalid_grant`, отозвали) → перечитываем строку: если токены уже поменял другой процесс
(GitHub меняет refresh при каждом обновлении — гонка двух процессов) — берём новые; иначе
`status = relogin`, токены стёрты, одно сообщение владельцу (`check_alerted_at`). Сетевой
сбой/5xx — запрос отказан `upstream_error`, подключение не трогаем. В процессе обновления
одного подключения идут по одному (карта промисов).
6. **Новый статус `relogin`** («нужно войти заново»): шлюз отказывает причиной `needs_login`,
агент видит в `list_connections` `checkStatus = bad_key`; разрешения не удаляются.
«Войти заново» = тот же поток с `connectionId`: токены заменяются, статус `active`.
7. **Отзыв в сервисе.** `revokeConnection` перед стиранием токенов зовёт отзыв провайдера
(5 с, ошибки глотаются, итог — `remote: revoked|failed|unsupported`). Google — `POST
/revoke token=<refresh|access>`; GitHub — `DELETE /applications/{client_id}/grant` с basic
client_id:secret и `{access_token}` (снимает всё разрешение приложения у пользователя).
8. **Клиенты FORGE.** `oauthProviderEnabled(provider)` = заданы id и секрет. Google берёт
`PEPPA_OAUTH_GOOGLE_*`, иначе общий клиент входа PEP-90 (тот же проект Google Cloud, нужен
ещё адрес возврата `<адрес>/connections/oauth/callback` и включённые API). Базы для мока —
`PEPPA_OAUTH_GOOGLE_BASE`, `PEPPA_OAUTH_GITHUB_BASE` (пути как у настоящих: Google
`/auth|/token|/revoke`, GitHub `/login/oauth/authorize|/login/oauth/access_token|/applications/{id}/grant`).
Запросы к эндпоинтам провайдера — обычный `fetch` к постоянным адресам (не адрес агента).
9. **Секреты не утекают.** Токены не в журнале (журнал пишет метод/путь), не в `ConnectionView`
(`hasKey` только), не в адресах, маскируются в ответе шлюза (`maskSecrets`) вместе с ключом.
## Риски
- Google требует проверки приложения для `spreadsheets`/`drive` у внешних пользователей —
забота администратора (настройка клиента), в коде не решается.
- GitHub App с истекающими токенами и OAuth App без срока — оба поддержаны: без `expires_in`
токен считается бессрочным.

View File

@ -0,0 +1,35 @@
# PEP-252: Access Hub — вход в сервисы через OAuth (Google, GitHub), шлюз сам обновляет токены
## Why
Access Hub (PEP-234/249) умеет только вставленные ключи. Google и GitHub удобнее и безопаснее
подключать входом: владелец жмёт «Войти через Google», видит, какие права просит FORGE, и всё.
Ключ Google по API key открывает только публичные таблицы — для своих таблиц нужен вход.
## What Changes
- Карточки каталога Google Sheets, Google Drive, Google Calendar и GitHub получают второй
способ подключения — «вход через сервис» (`oauth` в карточке: провайдер, права для «чтения»
и отдельно для «записи», пояснение). Владелец выбирает «только чтение» или «чтение и запись»
и видит список прав до входа.
- Поток: `/connections/oauth/start` (POST) → страница входа сервиса (code + PKCE S256, state)
→ `/connections/oauth/callback` → токены (доступа и обновления) в зашифрованном конверте
подключения (PEP-254, `secret_enc`), права и срок токена — в открытых колонках. Поток
одноразовый, 10 минут, привязан к браузеру (httpOnly cookie) и к пользователю, начавшему его.
- Шлюз (`callConnection`) и проверка подключения сами обновляют токен доступа перед вызовом
(и один раз после ответа 401). Обновление отклонено сервисом → подключение «нужно войти
заново», токены стёрты, владельцу одно сообщение; «Войти заново» возвращает подключение
с прежними разрешениями.
- OAuth-клиенты FORGE — настройки платформы в `.env`: `PEPPA_OAUTH_GOOGLE_CLIENT_ID/_SECRET`
(иначе общий `GOOGLE_CLIENT_ID/_SECRET` входа PEP-90), `PEPPA_OAUTH_GITHUB_CLIENT_ID/_SECRET`;
без них кнопка скрыта. Секреты в ревизии `/secrets`. Адрес возврата — текущий адрес FORGE.
Провайдеры описаны таблицей — Slack, Notion, Microsoft добавляются записью.
- «Отозвать доступ» и «Удалить» отзывают токен и в самом сервисе (Google `revoke`,
GitHub `DELETE /applications/{client_id}/grant`), сбой отзыва не мешает отзыву в FORGE.
- Мок `mock-oauth-service` по контракту Google и GitHub: authorize, token (code и refresh),
revoke, ресурсы для проверки токена.
## Impact
- Схема: `connections.oauth_provider`, `oauth_scopes`, `token_expires_at`; статус
`relogin`; `auth_kind` = `oauth`. Миграция 0031. Подключения по ключу не меняются.
- Код: `core/connection-oauth.ts` (новый), `core/connections.ts`, `core/connection-catalog.ts`,
`core/secrets-audit.ts`, `shared/env.ts`; веб `/connections` и маршруты start/callback;
testkit `mock-oauth-service`; i18n ru/kk/en.

View File

@ -0,0 +1,65 @@
## ADDED Requirements
### Requirement: Подключение входом через сервис
Карточки Google Sheets, Google Drive, Google Calendar и GitHub SHALL предлагать подключение
входом через сервис (OAuth 2.0 code + PKCE S256), когда у FORGE настроен клиент этого
сервиса; без настроенного клиента способ SHALL быть скрыт. Владелец SHALL видеть права,
которые просит FORGE, отдельно для «только чтение» и «чтение и запись». Токены SHALL
храниться только в зашифрованном конверте подключения и не попадать в журнал, ответы,
адреса и экраны.
#### Scenario: Владелец подключает Google Sheets входом
- **GIVEN** у FORGE настроен клиент Google
- **AND** владелец «anna» открыла карточку Google Sheets
- **WHEN** она выбирает «только чтение» и входит в Google
- **THEN** в «Ваших подключениях» появляется «Google Sheets» с правом `spreadsheets.readonly`
- **AND** токенов нет ни в журнале, ни на странице
#### Scenario: Клиент не настроен
- **GIVEN** у FORGE не задан клиент GitHub
- **WHEN** владелец открывает карточку GitHub
- **THEN** кнопки «Войти через GitHub» нет, остаётся подключение ключом
#### Scenario: Поток подменили
- **GIVEN** «anna» начала вход через Google
- **WHEN** ответ сервиса приходит с другим state, повторно или в браузер «boris»
- **THEN** подключение не создаётся
- **AND** поток больше не принимается
### Requirement: Шлюз сам обновляет токен
Шлюз SHALL перед вызовом обновлять токен доступа, срок которого истекает (и один раз после
ответа 401), и сохранять новые токены. Если сервис отклонил обновление, подключение SHALL
получить статус «нужно войти заново», токены SHALL быть стёрты, владелец SHALL получить одно
сообщение, а вызовы агентов SHALL отклоняться с причиной «нужно войти заново».
#### Scenario: Токен истёк — агент читает таблицу
- **GIVEN** подключение Google Sheets с разрешением чтения проекту PEP
- **AND** срок токена доступа истёк
- **WHEN** агент проекта читает таблицу через шлюз
- **THEN** шлюз обновляет токен и отдаёт агенту ответ 200
#### Scenario: Доступ отозвали в самом сервисе
- **GIVEN** владелец отозвал доступ FORGE в настройках Google
- **WHEN** агент обращается к подключению с истёкшим токеном
- **THEN** агент получает отказ «нужно войти заново»
- **AND** владелец получает одно сообщение, повторный вызов второго не создаёт
#### Scenario: Войти заново
- **GIVEN** подключение в статусе «нужно войти заново» с разрешением проекту PEP
- **WHEN** владелец нажимает «Войти заново» и входит в сервис
- **THEN** подключение снова активно с прежними разрешениями
### Requirement: Отзыв доступа отзывает токен в сервисе
«Отозвать доступ» и «Удалить» для подключения входом SHALL отзывать токен и в самом сервисе,
если сервис это поддерживает; сбой сервиса SHALL NOT мешать отзыву в FORGE.
#### Scenario: Отзыв GitHub
- **GIVEN** подключение GitHub входом
- **WHEN** владелец нажимает «Отозвать доступ»
- **THEN** GitHub получает запрос на отзыв разрешения FORGE
- **AND** агенты получают отказ «подключение отозвано»
#### Scenario: Сервис не отвечает при отзыве
- **GIVEN** сервис отзыва недоступен
- **WHEN** владелец отзывает подключение
- **THEN** подключение в FORGE отозвано и токены стёрты

View File

@ -0,0 +1,23 @@
## 1. Данные и провайдеры
- [ ] 1.1 Колонки `oauth_provider`, `oauth_scopes`, `token_expires_at`, статус `relogin`, миграция 0031
- [ ] 1.2 `core/connection-oauth.ts`: провайдеры google/github, настройки клиентов, права карточек
- [ ] 1.3 env: `PEPPA_OAUTH_*`; ревизия `/secrets`
## 2. Поток входа
- [ ] 2.1 `startConnectionOAuth` / `completeConnectionOAuth` (state, PKCE, браузер, пользователь, одноразовость)
- [ ] 2.2 Создание и «войти заново» подключения с токенами в конверте
## 3. Шлюз
- [ ] 3.1 `connectionCredential`: обновление токена, гонка, `relogin` + одно сообщение
- [ ] 3.2 `callConnection` и проверка: Bearer, повтор после 401, причина `needs_login`
- [ ] 3.3 Отзыв в сервисе при «Отозвать доступ» / «Удалить»
## 4. Веб
- [ ] 4.1 Маршруты `/connections/oauth/start` и `/connections/oauth/callback`
- [ ] 4.2 `/connections`: кнопка входа с выбором уровня и списком прав, «Войти заново», статус
- [ ] 4.3 Тексты ru/kk/en, словарь
## 5. Проверки
- [ ] 5.1 Мок `mock-oauth-service` (Google/GitHub: authorize, token, refresh, revoke, ресурсы)
- [ ] 5.2 Тест `access-hub-oauth.test.ts`: вход, обновление, отозванный токен, чужой пользователь, отзыв
- [ ] 5.3 lint, typecheck, тесты, память проекта, archive, PR

View File

@ -3,13 +3,13 @@
// its `catalog_id`; read rules, fixed headers and the check call are taken from this file on every
// call, so a fix here applies to existing connections at once.
//
// Sources: each service's public API documentation (docsUrl). Google is by API key only (public
// data); service accounts and OAuth are a separate story. Kazakhstan: Kaspi Магазин has an open
// Sources: each service's public API documentation (docsUrl). A Google API key opens only public
// data; signing in (OAuth, PEP-252) — the card's `oauth`, core/connection-oauth.ts. Kazakhstan: Kaspi Магазин has an open
// seller API with `X-Auth-Token`; 2GIS — key in the query. Others (Kaspi Pay, Halyk, eGov) have no
// open API with a plain key — not in the catalog, use «Свой сервис» if a partner gives one.
import { m as tr } from "@peppa/shared/i18n";
export type CatalogAuth = "bearer" | "header" | "basic" | "query" | "path";
export type CatalogAuth = "bearer" | "header" | "basic" | "query" | "path" | "oauth";
export type CatalogKind = "payments" | "code" | "mail" | "messaging" | "ai" | "cloud" | "errors" | "data" | "docs" | "maps" | "commerce";
export const CATALOG_KINDS: CatalogKind[] = ["payments", "code", "mail", "messaging", "ai", "cloud", "errors", "data", "docs", "maps", "commerce"];
@ -40,6 +40,19 @@ export interface CatalogCheck {
bodyIncludes?: string;
}
/** PEP-252: sign-in through the service (OAuth 2.0 code + PKCE) — core/connection-oauth.ts. */
export type OAuthProviderId = "google" | "github";
export interface CatalogOAuth {
provider: OAuthProviderId;
/** Scopes for «только чтение» — the minimum the service has. */
read: string[];
/** Scopes for «чтение и запись». */
write: string[];
/** Said to the owner next to the button (translated), e.g. when the service has no read-only scope. */
note?: string;
}
export interface CatalogService {
/** Also the default short name of the connection for agents. */
id: string;
@ -65,8 +78,12 @@ export interface CatalogService {
idempotency?: boolean;
/** Extra search words (ru/en). */
tags?: string[];
/** PEP-252: the card can also be connected by signing in (when FORGE has a client of the provider). */
oauth?: CatalogOAuth;
}
const GOOGLE_SCOPE = "https://www.googleapis.com/auth/";
const GET_ALL = ["GET /"];
export const CONNECTION_CATALOG: CatalogService[] = [
@ -83,6 +100,13 @@ export const CONNECTION_CATALOG: CatalogService[] = [
read: GET_ALL,
check: { method: "GET", path: "/user" },
tags: ["git", "код", "code"],
oauth: {
provider: "github",
// GitHub OAuth apps have no read-only scope for private repositories: «только чтение» is kept by the gateway's read rule.
read: ["repo", "read:org"],
write: ["repo", "read:org"],
note: tr("У GitHub нет отдельного права «только чтение» для закрытых репозиториев: GitHub покажет полный доступ к коду, а читать или менять — решает разрешение в FORGE."),
},
},
{
id: "gitea",
@ -127,6 +151,7 @@ export const CONNECTION_CATALOG: CatalogService[] = [
// A valid key gets 404 for a sheet that doesn't exist; a bad key — 400 «API key not valid».
check: { method: "GET", path: "/v4/spreadsheets/forge-key-check", ok: [200, 404], badKey: [400, 401, 403] },
tags: ["google", "таблицы", "sheets"],
oauth: { provider: "google", read: [`${GOOGLE_SCOPE}spreadsheets.readonly`], write: [`${GOOGLE_SCOPE}spreadsheets`] },
},
{
id: "google-drive",
@ -142,6 +167,7 @@ export const CONNECTION_CATALOG: CatalogService[] = [
read: GET_ALL,
check: { method: "GET", path: "/files/forge-key-check", ok: [200, 404], badKey: [400, 401, 403] },
tags: ["google", "файлы", "drive"],
oauth: { provider: "google", read: [`${GOOGLE_SCOPE}drive.readonly`], write: [`${GOOGLE_SCOPE}drive`] },
},
{
id: "google-calendar",
@ -157,6 +183,7 @@ export const CONNECTION_CATALOG: CatalogService[] = [
read: GET_ALL,
check: { method: "GET", path: "/calendars/forge-key-check/events", ok: [200, 404], badKey: [400, 401, 403] },
tags: ["google", "календарь", "calendar"],
oauth: { provider: "google", read: [`${GOOGLE_SCOPE}calendar.readonly`], write: [`${GOOGLE_SCOPE}calendar.readonly`, `${GOOGLE_SCOPE}calendar.events`] },
},
{
id: "telegram",

View File

@ -0,0 +1,122 @@
// PEP-252: the sign-in flow of a connection — like Google login (PEP-90): state and PKCE verifier
// in `settings` (one-shot, 10 min), the state also in an httpOnly cookie of the starting browser,
// and the callback must come to the same signed-in owner. Only then the code is exchanged; the
// tokens go straight into the connection's sealed envelope (PEP-254).
import { m as tr } from "@peppa/shared/i18n";
import { connectionGrants, connections, type Db } from "@peppa/db";
import { and, eq } from "drizzle-orm";
import { createHash, randomBytes } from "node:crypto";
import { logEvent } from "./audit.ts";
import { catalogService } from "./connection-catalog.ts";
import { cardScopes, exchangeCode, OAUTH_ERROR_TEXT, oauthClient, packTokens, scopesLevel, type OAuthLevel } from "./connection-oauth.ts";
import { CONNECTION_NAME_MAX, freeSlug, ownConnection, sealConnectionSecret } from "./connections.ts";
import { hashToken } from "./crypto.ts";
import { PeppaError } from "./errors.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
export const CONNECTION_OAUTH_TTL_MS = 10 * 60_000;
/** The browser cookie of the flow (path /connections/oauth). */
export const CONNECTION_OAUTH_COOKIE = "peppa_conn_oauth";
interface Flow {
userId: number;
catalogId: string;
level: OAuthLevel;
/** «Войти заново»: the connection whose tokens are replaced. */
connectionId: number | null;
verifier: string;
redirectUri: string;
scopes: string[];
expiresAt: number;
}
const flowKey = (state: string) => `conn.oauth.flow:${hashToken(state)}`;
export interface ConnectionOAuthStart {
url: string;
/** Goes into the httpOnly cookie; the callback must bring it back. */
state: string;
}
/** Starts signing in for a catalog card (new connection) or for an own connection (`connectionId`, sign in again). */
export async function startConnectionOAuth(db: Db, userId: number, i: { catalogId?: string | null; connectionId?: number | null; level?: string | null; redirectUri: string }, env: NodeJS.ProcessEnv = process.env): Promise<ConnectionOAuthStart> {
let catalogId = i.catalogId ?? null;
let level: OAuthLevel = i.level === "write" ? "write" : "read";
if (i.connectionId != null) {
const c = await ownConnection(db, userId, i.connectionId);
if (c.authKind !== "oauth") throw new PeppaError(tr("Это подключение работает по ключу доступа"));
catalogId = c.catalogId;
if (i.level !== "read" && i.level !== "write") level = scopesLevel(catalogService(c.catalogId), c.oauthScopes);
}
const card = catalogService(catalogId);
if (!card?.oauth) throw new PeppaError(tr("У этого сервиса нет входа через сервис — подключите его ключом"));
const client = oauthClient(card.oauth.provider, env);
if (!client) throw new PeppaError(OAUTH_ERROR_TEXT.notConfigured);
const scopes = cardScopes(card, level);
const state = randomBytes(24).toString("base64url");
const verifier = randomBytes(32).toString("base64url");
await setSetting(db, flowKey(state), { userId, catalogId: card.id, level, connectionId: i.connectionId ?? null, verifier, redirectUri: i.redirectUri, scopes, expiresAt: Date.now() + CONNECTION_OAUTH_TTL_MS } satisfies Flow);
const q = new URLSearchParams({
client_id: client.clientId,
redirect_uri: i.redirectUri,
response_type: "code",
scope: scopes.join(" "),
state,
code_challenge: createHash("sha256").update(verifier).digest("base64url"),
code_challenge_method: "S256",
...client.provider.authorizeParams,
});
return { url: `${client.provider.authorize(client.base)}?${q}`, state };
}
/**
* The service sent the browser back. One-shot: the flow is removed before anything else. Refused
* (and nothing created) when the state differs from the browser's cookie, the flow is gone or
* stale, or another person is signed in now.
*/
export async function completeConnectionOAuth(db: Db, userId: number, i: { state: string; code: string; cookieState: string }, o: { now?: Date } = {}): Promise<{ connectionId: number; created: boolean }> {
if (!i.state || !i.code || i.state !== i.cookieState) throw new PeppaError(OAUTH_ERROR_TEXT.stale);
const flow = await getSetting<Flow>(db, flowKey(i.state));
await deleteSetting(db, flowKey(i.state));
if (!flow || Date.now() >= flow.expiresAt) throw new PeppaError(OAUTH_ERROR_TEXT.stale);
if (flow.userId !== userId) throw new PeppaError(OAUTH_ERROR_TEXT.stale);
const card = catalogService(flow.catalogId);
const client = card?.oauth ? oauthClient(card.oauth.provider) : null;
if (!card?.oauth || !client) throw new PeppaError(OAUTH_ERROR_TEXT.notConfigured);
const r = await exchangeCode(client, { code: i.code, redirectUri: flow.redirectUri, verifier: flow.verifier }, o.now);
if (!r.ok) throw new PeppaError(OAUTH_ERROR_TEXT.failed);
// Google lets a person untick scopes: without any of the asked ones the connection is useless.
const granted = r.answer.scopes ?? flow.scopes;
if (!flow.scopes.some((s) => granted.includes(s))) throw new PeppaError(OAUTH_ERROR_TEXT.noScopes);
const patch = {
...sealConnectionSecret(packTokens(r.answer.tokens)),
oauthProvider: card.oauth.provider,
oauthScopes: granted,
tokenExpiresAt: r.answer.expiresAt,
status: "active" as const,
revokedAt: null,
checkStatus: null,
checkedAt: null,
checkAlertedAt: null,
};
if (flow.connectionId != null) {
// Sign in again: the same connection with its grants. Gone or not the owner's — refused.
const c = await ownConnection(db, userId, flow.connectionId);
if (c.authKind !== "oauth" || c.catalogId !== card.id) throw new PeppaError(OAUTH_ERROR_TEXT.stale);
await db.update(connections).set(patch).where(and(eq(connections.id, c.id), eq(connections.ownerId, userId)));
const grants = await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, c.id));
for (const projectId of new Set(grants.map((g) => g.projectId))) await logEvent(db, { projectId, type: "connection_signed_in", payload: { connectionId: c.id } });
return { connectionId: c.id, created: false };
}
const taken = new Set((await db.select({ name: connections.name }).from(connections).where(eq(connections.ownerId, userId))).map((r) => r.name));
let name = card.name;
for (let n = 2; taken.has(name); n++) name = `${card.name} ${n}`.slice(0, CONNECTION_NAME_MAX);
const slug = await freeSlug(db, userId, card.id);
const [row] = await db
.insert(connections)
.values({ ownerId: userId, name, baseUrl: card.baseUrl, authKind: "oauth", authHeader: null, catalogId: card.id, slug, ...patch })
.returning({ id: connections.id });
return { connectionId: row!.id, created: true };
}

View File

@ -0,0 +1,203 @@
// PEP-252 Access Hub: connecting a service by signing in (OAuth 2.0 authorization code + PKCE S256).
// This file knows the providers — their endpoints, FORGE's client settings and the token calls
// (code exchange, refresh, revoke) — and nothing about the database. The flow (state in settings,
// the browser cookie, the owner) is in connection-oauth-flow.ts; the gateway's refresh is in
// connections.ts (`connectionCredential`). Tokens never leave these functions except into the
// connection's sealed envelope (PEP-254) and the outgoing Authorization header.
import { m as tr } from "@peppa/shared/i18n";
import { catalogService, type CatalogService, type OAuthProviderId } from "./connection-catalog.ts";
export type { OAuthProviderId } from "./connection-catalog.ts";
export const OAUTH_TIMEOUT_MS = 15_000;
export const OAUTH_REVOKE_TIMEOUT_MS = 5_000;
/** A token that expires within this window is refreshed before the call. */
export const OAUTH_REFRESH_EARLY_MS = 60_000;
export interface OAuthProvider {
id: OAuthProviderId;
/** Brand name for «Войти через …». */
name: string;
/** Env names of FORGE's client; `fallback` — another client of the same provider (Google login, PEP-90). */
env: { id: string; secret: string; base: string; fallbackId?: string; fallbackSecret?: string };
authorize: (base: string | null) => string;
token: (base: string | null) => string;
/** Extra authorize parameters (Google: offline access, so a refresh token comes). */
authorizeParams: Record<string, string>;
}
export const OAUTH_PROVIDERS: Record<OAuthProviderId, OAuthProvider> = {
google: {
id: "google",
name: "Google",
env: { id: "PEPPA_OAUTH_GOOGLE_CLIENT_ID", secret: "PEPPA_OAUTH_GOOGLE_CLIENT_SECRET", base: "PEPPA_OAUTH_GOOGLE_BASE", fallbackId: "GOOGLE_CLIENT_ID", fallbackSecret: "GOOGLE_CLIENT_SECRET" },
authorize: (b) => (b ? `${b}/auth` : "https://accounts.google.com/o/oauth2/v2/auth"),
token: (b) => (b ? `${b}/token` : "https://oauth2.googleapis.com/token"),
// prompt=consent: Google sends a refresh token only on a consent screen.
authorizeParams: { access_type: "offline", prompt: "consent", include_granted_scopes: "false" },
},
github: {
id: "github",
name: "GitHub",
env: { id: "PEPPA_OAUTH_GITHUB_CLIENT_ID", secret: "PEPPA_OAUTH_GITHUB_CLIENT_SECRET", base: "PEPPA_OAUTH_GITHUB_BASE" },
authorize: (b) => `${b ?? "https://github.com"}/login/oauth/authorize`,
token: (b) => `${b ?? "https://github.com"}/login/oauth/access_token`,
authorizeParams: { allow_signup: "false" },
},
};
export interface ServiceOAuthClient {
provider: OAuthProvider;
clientId: string;
clientSecret: string;
/** Test/mock base of the provider's endpoints, null — the real ones. */
base: string | null;
}
/** FORGE's client of a provider, or null — the sign-in way is hidden. */
export function oauthClient(id: OAuthProviderId | string | null | undefined, env: NodeJS.ProcessEnv = process.env): ServiceOAuthClient | null {
const provider = id ? OAUTH_PROVIDERS[id as OAuthProviderId] : undefined;
if (!provider) return null;
const own = env[provider.env.id] && env[provider.env.secret];
const clientId = own ? env[provider.env.id] : provider.env.fallbackId ? env[provider.env.fallbackId] : undefined;
const clientSecret = own ? env[provider.env.secret] : provider.env.fallbackSecret ? env[provider.env.fallbackSecret] : undefined;
if (!clientId || !clientSecret) return null;
const base = env[provider.env.base]?.replace(/\/+$/, "") || null;
return { provider, clientId, clientSecret, base };
}
export const oauthEnabled = (id: OAuthProviderId | string | null | undefined, env: NodeJS.ProcessEnv = process.env) => !!oauthClient(id, env);
export type OAuthLevel = "read" | "write";
/** Scopes FORGE asks for one level of a card. */
export function cardScopes(card: CatalogService, level: OAuthLevel): string[] {
return card.oauth ? (level === "write" ? card.oauth.write : card.oauth.read) : [];
}
/** What a card offers for signing in, for the page: null — no sign-in for it (or no client). */
export function oauthOffer(catalogId: string | null | undefined, env: NodeJS.ProcessEnv = process.env): { provider: OAuthProviderId; providerName: string; read: string[]; write: string[]; note: string | null } | null {
const card = catalogService(catalogId);
if (!card?.oauth || !oauthEnabled(card.oauth.provider, env)) return null;
return { provider: card.oauth.provider, providerName: OAUTH_PROVIDERS[card.oauth.provider].name, read: card.oauth.read, write: card.oauth.write, note: card.oauth.note ?? null };
}
/** «https://www.googleapis.com/auth/spreadsheets.readonly» → «spreadsheets.readonly». */
export const scopeLabel = (scope: string) => scope.replace(/^https:\/\/www\.googleapis\.com\/auth\//, "");
/** Level of saved scopes: all write scopes of the card granted → write. */
export function scopesLevel(card: CatalogService | null, scopes: string[] | null | undefined): OAuthLevel {
if (!card?.oauth || !scopes?.length) return "read";
const read = new Set(card.oauth.read);
const extra = card.oauth.write.filter((s) => !read.has(s));
if (!extra.length) return "read";
return extra.every((s) => scopes.includes(s)) ? "write" : "read";
}
// ---------- tokens ----------
/** What the sealed envelope of a sign-in connection holds (JSON). */
export interface ServiceTokens {
access: string;
refresh: string | null;
}
export const packTokens = (t: ServiceTokens) => JSON.stringify({ v: 1, access: t.access, refresh: t.refresh });
export function unpackTokens(raw: string): ServiceTokens | null {
try {
const j = JSON.parse(raw) as { v?: number; access?: unknown; refresh?: unknown };
if (j.v !== 1 || typeof j.access !== "string" || !j.access) return null;
return { access: j.access, refresh: typeof j.refresh === "string" && j.refresh ? j.refresh : null };
} catch {
return null;
}
}
export interface TokenAnswer {
tokens: ServiceTokens;
/** null — the token does not expire (GitHub OAuth app). */
expiresAt: Date | null;
/** What the service says it granted; null — it didn't say. */
scopes: string[] | null;
}
/** rejected — the service refused (revoked, wrong code); failed — no answer / 5xx (try later). */
export type TokenFailure = { ok: false; rejected: boolean };
const TOKEN_SHAPE = /^[\x21-\x7e]{1,4096}$/;
async function tokenCall(c: ServiceOAuthClient, body: Record<string, string>, now: Date): Promise<{ ok: true; answer: TokenAnswer } | TokenFailure> {
let res: Response;
try {
res = await fetch(c.provider.token(c.base), {
method: "POST",
// GitHub answers form-encoded without Accept.
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json", "user-agent": "PeppaFactory-AccessHub/1" },
body: new URLSearchParams({ ...body, client_id: c.clientId, client_secret: c.clientSecret }),
redirect: "error",
signal: AbortSignal.timeout(OAUTH_TIMEOUT_MS),
});
} catch {
return { ok: false, rejected: false };
}
if (res.status >= 500) return { ok: false, rejected: false };
const j = (await res.json().catch(() => null)) as { access_token?: unknown; refresh_token?: unknown; expires_in?: unknown; scope?: unknown; error?: unknown } | null;
// GitHub reports errors with 200 and `error`; Google with 400/401.
if (!j || j.error || !res.ok || typeof j.access_token !== "string" || !TOKEN_SHAPE.test(j.access_token)) return { ok: false, rejected: res.status < 500 && !!j };
const refresh = typeof j.refresh_token === "string" && TOKEN_SHAPE.test(j.refresh_token) ? j.refresh_token : null;
const sec = Number(j.expires_in);
const scopes = typeof j.scope === "string" ? j.scope.split(/[\s,]+/).filter(Boolean) : null;
return { ok: true, answer: { tokens: { access: j.access_token, refresh }, expiresAt: Number.isFinite(sec) && sec > 0 ? new Date(now.getTime() + sec * 1000) : null, scopes } };
}
export function exchangeCode(c: ServiceOAuthClient, i: { code: string; redirectUri: string; verifier: string }, now = new Date()) {
return tokenCall(c, { grant_type: "authorization_code", code: i.code, redirect_uri: i.redirectUri, code_verifier: i.verifier }, now);
}
export function refreshTokens(c: ServiceOAuthClient, refresh: string, now = new Date()) {
return tokenCall(c, { grant_type: "refresh_token", refresh_token: refresh }, now);
}
/**
* Revokes FORGE's access in the service itself. Google: POST /revoke (the refresh token revokes
* the whole grant); GitHub: DELETE /applications/{client_id}/grant (basic client auth). Never
* throws: the revoke in FORGE happens whatever the service answers.
*/
export async function revokeAtService(providerId: string | null | undefined, tokens: ServiceTokens, env: NodeJS.ProcessEnv = process.env): Promise<"revoked" | "failed" | "unsupported"> {
const c = oauthClient(providerId, env);
if (!c) return "unsupported";
try {
let res: Response;
if (c.provider.id === "google") {
res = await fetch(c.base ? `${c.base}/revoke` : "https://oauth2.googleapis.com/revoke", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ token: tokens.refresh ?? tokens.access }),
redirect: "error",
signal: AbortSignal.timeout(OAUTH_REVOKE_TIMEOUT_MS),
});
} else {
res = await fetch(`${c.base ?? "https://api.github.com"}/applications/${encodeURIComponent(c.clientId)}/grant`, {
method: "DELETE",
headers: { authorization: `Basic ${Buffer.from(`${c.clientId}:${c.clientSecret}`).toString("base64")}`, accept: "application/vnd.github+json", "content-type": "application/json", "user-agent": "PeppaFactory-AccessHub/1" },
body: JSON.stringify({ access_token: tokens.access }),
redirect: "error",
signal: AbortSignal.timeout(OAUTH_REVOKE_TIMEOUT_MS),
});
}
await res.arrayBuffer().catch(() => null);
// Already revoked/unknown token: nothing left to revoke.
return res.ok || res.status === 400 || res.status === 404 ? "revoked" : "failed";
} catch {
return "failed";
}
}
export const OAUTH_ERROR_TEXT = {
notConfigured: tr("Вход через этот сервис в FORGE пока не настроен — подключите его ключом"),
denied: tr("Вход отменён: подключение не создано"),
stale: tr("Вход устарел или уже использован — начните заново"),
failed: tr("Сервис не подтвердил вход — попробуйте ещё раз"),
noScopes: tr("Вы не дали FORGE нужный доступ — начните заново и отметьте все пункты"),
};

View File

@ -16,6 +16,7 @@ import { logEvent } from "./audit.ts";
import { catalogService, classifyRequest, type CatalogAuth, type CatalogCheck } from "./connection-catalog.ts";
import { addMasterMessage } from "./chats.ts";
import { appendJournal, type ConnectionJournalDecision } from "./connection-journal.ts";
import { OAUTH_REFRESH_EARLY_MS, oauthClient, packTokens, refreshTokens, revokeAtService, unpackTokens } from "./connection-oauth.ts";
import { decrypt, encrypt, newDataKey, openWithKey, sealWithKey } from "./crypto.ts";
import { deliverToUser } from "./notifications.ts";
import { PeppaError } from "./errors.ts";
@ -40,6 +41,7 @@ export type ConnectionReason =
| "unknown_connection"
| "ambiguous_connection"
| "revoked"
| "needs_login"
| "no_grant"
| "operation_denied"
| "read_denied"
@ -61,6 +63,7 @@ export const CONNECTION_REASON_TEXT: Record<ConnectionReason, string> = {
unknown_connection: tr("нет такого подключения"),
ambiguous_connection: tr("несколько подключений с таким названием"),
revoked: tr("подключение отозвано"),
needs_login: tr("нужно заново войти в сервис"),
no_grant: tr("нет разрешения для проекта или агента"),
operation_denied: tr("операция не разрешена"),
read_denied: tr("чтение не разрешено"),
@ -89,8 +92,13 @@ export interface ConnectionView {
slug: string;
checkStatus: ConnectionCheckStatus | null;
checkedAt: Date | null;
status: "active" | "revoked";
/** relogin (PEP-252): the service refused to refresh the sign-in — «Войти заново». */
status: "active" | "revoked" | "relogin";
hasKey: boolean;
/** PEP-252: signed in through the service (google|github), null — a key. */
oauthProvider: string | null;
/** PEP-252: scopes the service granted (shown to the owner). */
oauthScopes: string[];
revokedAt: Date | null;
lastUsedAt: Date | null;
createdAt: Date;
@ -231,7 +239,7 @@ export function normalizeOperations(raw: string[] | string, o: { allowEmpty?: bo
// ---------- owner's management ----------
async function ownConnection(db: Db, userId: number, connectionId: number) {
export async function ownConnection(db: Db, userId: number, connectionId: number) {
const [c] = await db.select().from(connections).where(eq(connections.id, connectionId));
// No superadmin bypass: a connection is its owner's alone.
if (!c || c.ownerId !== userId) throw new PeppaError(tr("Подключение не найдено"));
@ -319,7 +327,7 @@ export function slugify(name: string): string {
return latin.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, "");
}
async function freeSlug(db: Db, userId: number, base: string, exceptId?: number): Promise<string> {
export async function freeSlug(db: Db, userId: number, base: string, exceptId?: number): Promise<string> {
const root = base || "service";
const taken = new Set((await db.select({ id: connections.id, slug: connections.slug }).from(connections).where(eq(connections.ownerId, userId))).filter((r) => r.id !== exceptId).map((r) => r.slug));
if (!taken.has(root)) return root;
@ -358,6 +366,7 @@ export async function createConnection(db: Db, userId: number, i: ConnectionInpu
/** Replaces the key; also brings a revoked connection back with its grants. */
export async function replaceConnectionSecret(db: Db, userId: number, connectionId: number, secret: string): Promise<void> {
const c = await ownConnection(db, userId, connectionId);
if (c.authKind === "oauth") throw new PeppaError(tr("Это подключение работает через вход в сервис: нажмите «Войти заново»"));
const err = secretError(secret) ?? keyShapeError(c.authKind, secret);
if (err) throw new PeppaError(err);
// A new key: the old check result and the «key stopped working» message no longer apply.
@ -369,11 +378,24 @@ export async function replaceConnectionSecret(db: Db, userId: number, connection
* and even a copy of the database no longer holds it. Grants stay visible to the owner and
* start working again only after a new key (`replaceConnectionSecret`).
*/
export async function revokeConnection(db: Db, userId: number, connectionId: number): Promise<void> {
export async function revokeConnection(db: Db, userId: number, connectionId: number): Promise<{ remote: "revoked" | "failed" | "unsupported" | null }> {
const c = await ownConnection(db, userId, connectionId);
await db.update(connections).set({ status: "revoked", secretEnc: null, dekEnc: null, revokedAt: new Date() }).where(eq(connections.id, c.id));
// Wiped first: the gateway refuses at once, whatever the service answers below.
await db.update(connections).set({ status: "revoked", secretEnc: null, dekEnc: null, tokenExpiresAt: null, revokedAt: new Date() }).where(eq(connections.id, c.id));
// PEP-252: a sign-in connection is revoked in the service too (best effort, ≤ 5 s).
let remote: "revoked" | "failed" | "unsupported" | null = null;
if (c.authKind === "oauth" && c.secretEnc) {
let tokens = null;
try {
tokens = unpackTokens(openConnectionSecret(c) ?? "");
} catch {
tokens = null;
}
remote = tokens ? await revokeAtService(c.oauthProvider, tokens) : "failed";
}
const grants = await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, c.id));
for (const projectId of new Set(grants.map((g) => g.projectId))) await logEvent(db, { projectId, type: "connection_revoked", payload: { connectionId: c.id } });
for (const projectId of new Set(grants.map((g) => g.projectId))) await logEvent(db, { projectId, type: "connection_revoked", payload: { connectionId: c.id, ...(remote ? { remote } : {}) } });
return { remote };
}
export async function deleteConnection(db: Db, userId: number, connectionId: number): Promise<void> {
@ -471,6 +493,8 @@ export async function listConnections(db: Db, userId: number): Promise<Connectio
checkedAt: r.checkedAt,
status: r.status,
hasKey: !!r.secretEnc,
oauthProvider: r.oauthProvider ?? null,
oauthScopes: r.oauthScopes ?? [],
revokedAt: r.revokedAt,
lastUsedAt: r.lastUsedAt,
createdAt: r.createdAt,
@ -576,13 +600,13 @@ export async function agentConnections(db: Db, sessionId: number): Promise<Agent
.select({ c: connections, agentId: connectionGrants.agentId, operations: connectionGrants.operations, readMode: connectionGrants.readMode, writeMode: connectionGrants.writeMode })
.from(connectionGrants)
.innerJoin(connections, eq(connections.id, connectionGrants.connectionId))
.where(and(eq(connectionGrants.projectId, s.projectId), eq(connections.status, "active")))
.where(and(eq(connectionGrants.projectId, s.projectId), inArray(connections.status, ["active", "relogin"])))
.orderBy(asc(connections.name));
const by = new Map<number, AgentConnection>();
for (const r of rows) {
if (r.agentId != null && r.agentId !== s.agentId) continue;
const card = catalogService(r.c.catalogId);
const c = by.get(r.c.id) ?? { id: r.c.id, name: r.c.name, slug: connectionSlug(r.c), service: card?.name ?? null, baseUrl: r.c.baseUrl, docsUrl: card?.docsUrl ?? null, readMode: "off", writeMode: "off", operations: [], checkStatus: r.c.checkStatus };
const c = by.get(r.c.id) ?? { id: r.c.id, name: r.c.name, slug: connectionSlug(r.c), service: card?.name ?? null, baseUrl: r.c.baseUrl, docsUrl: card?.docsUrl ?? null, readMode: "off", writeMode: "off", operations: [], checkStatus: r.c.status === "relogin" ? "bad_key" : r.c.checkStatus };
c.operations = [...new Set([...c.operations, ...r.operations])];
c.readMode = widest(c.readMode, r.readMode);
c.writeMode = widest(c.writeMode, r.writeMode);
@ -629,10 +653,78 @@ function buildRequest(conn: typeof connections.$inferSelect, secret: string, cle
if (body) headers["content-length"] = String(body.length);
if (conn.authKind === "header" && conn.authHeader) headers[conn.authHeader.toLowerCase()] = secret;
else if (conn.authKind === "basic") headers.authorization = `Basic ${Buffer.from(secret).toString("base64")}`;
else if (conn.authKind === "bearer") headers.authorization = `Bearer ${secret}`;
else if (conn.authKind === "bearer" || conn.authKind === "oauth") headers.authorization = `Bearer ${secret}`;
return { url, headers };
}
// ---------- PEP-252: the credential of a call (a key, or a sign-in token refreshed in time) ----------
type ConnRow = typeof connections.$inferSelect;
export type ConnectionCredential = { ok: true; secret: string; refreshable: boolean; refreshed: boolean } | { ok: false; reason: "needs_login" | "upstream_error" };
/** One refresh per connection at a time in this process (GitHub rotates the refresh token on use). */
const refreshing = new Map<number, Promise<ConnectionCredential>>();
/**
* What goes into the request: the key as is; for a sign-in connection the access token, refreshed
* first when it expires within a minute (or `force` — the service answered 401). The service
* refused the refresh → the connection needs signing in again: tokens wiped, the owner gets one
* message. A refresh that got no answer leaves everything as is (`upstream_error`).
*/
export async function connectionCredential(db: Db, conn: ConnRow, o: { now?: Date; force?: boolean; notify?: (db: Db, c: { id: number; ownerId: number; name: string }) => Promise<void> } = {}): Promise<ConnectionCredential> {
let plain: string | null;
try {
plain = openConnectionSecret(conn);
} catch {
return { ok: false, reason: "upstream_error" };
}
if (conn.authKind !== "oauth") return plain ? { ok: true, secret: plain, refreshable: false, refreshed: false } : { ok: false, reason: "upstream_error" };
const tokens = plain ? unpackTokens(plain) : null;
if (!tokens) return { ok: false, reason: "needs_login" };
const now = o.now ?? new Date();
const due = !!conn.tokenExpiresAt && conn.tokenExpiresAt.getTime() - now.getTime() <= OAUTH_REFRESH_EARLY_MS;
if (!o.force && !due) return { ok: true, secret: tokens.access, refreshable: !!tokens.refresh, refreshed: false };
if (!tokens.refresh) {
// Nothing to refresh with: an expired token is the end of this sign-in; a 401 on a lasting token too.
await markRelogin(db, conn, o.notify);
return { ok: false, reason: "needs_login" };
}
const running = refreshing.get(conn.id);
if (running) return running;
const job = (async (): Promise<ConnectionCredential> => {
const client = oauthClient(conn.oauthProvider);
if (!client) return { ok: false, reason: "upstream_error" }; // FORGE's client was removed: not the owner's fault
const r = await refreshTokens(client, tokens.refresh!, now);
if (r.ok) {
const next = { access: r.answer.tokens.access, refresh: r.answer.tokens.refresh ?? tokens.refresh };
await db.update(connections).set({ ...sealConnectionSecret(packTokens(next)), tokenExpiresAt: r.answer.expiresAt, ...(r.answer.scopes ? { oauthScopes: r.answer.scopes } : {}) }).where(and(eq(connections.id, conn.id), eq(connections.status, "active")));
return { ok: true, secret: next.access, refreshable: true, refreshed: true };
}
if (!r.rejected) return { ok: false, reason: "upstream_error" };
// Another process may have refreshed in between (and spent the old refresh token): take its tokens.
const [fresh] = await db.select().from(connections).where(eq(connections.id, conn.id));
if (fresh?.status === "active" && fresh.secretEnc && fresh.secretEnc !== conn.secretEnc) return connectionCredential(db, fresh, { now, notify: o.notify });
await markRelogin(db, conn, o.notify);
return { ok: false, reason: "needs_login" };
})().finally(() => refreshing.delete(conn.id));
refreshing.set(conn.id, job);
return job;
}
/** The sign-in is over: tokens wiped, grants kept, ONE message to the owner until they sign in again. */
async function markRelogin(db: Db, conn: ConnRow, notify?: (db: Db, c: { id: number; ownerId: number; name: string }) => Promise<void>): Promise<void> {
const [row] = await db
.update(connections)
.set({ status: "relogin", secretEnc: null, dekEnc: null, tokenExpiresAt: null, checkStatus: "bad_key", checkedAt: new Date() })
.where(and(eq(connections.id, conn.id), eq(connections.status, "active")))
.returning({ alerted: connections.checkAlertedAt });
if (!row || row.alerted) return;
await db.update(connections).set({ checkAlertedAt: new Date() }).where(eq(connections.id, conn.id));
await (notify ?? tellReloginNeeded)(db, { id: conn.id, ownerId: conn.ownerId, name: conn.name });
const grants = await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, conn.id));
for (const projectId of new Set(grants.map((g) => g.projectId))) await logEvent(db, { projectId, type: "connection_relogin", payload: { connectionId: conn.id } });
}
export interface ConnectionCall {
sessionId: number | null | undefined;
/** Connection id or its name (when only one granted connection has it). */
@ -760,6 +852,7 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
conn = matches[0]!.c;
if (!agentIsolated(s, o.env)) return deny("not_isolated");
if (conn.status === "relogin") return deny("needs_login");
if (conn.status !== "active" || !conn.secretEnc) return deny("revoked");
const mine = matches.filter((g) => g.agentId == null || g.agentId === s.agentId);
if (!mine.length) return deny("no_grant");
@ -775,17 +868,16 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
const [{ n }] = (await db.select({ n: count() }).from(connectionLog).where(and(eq(connectionLog.sessionId, s.id), eq(connectionLog.kind, "call"), gt(connectionLog.createdAt, new Date(now.getTime() - 60_000))))) as [{ n: number }];
if (n >= CONNECTION_RATE_PER_MIN) return deny("rate_limited");
let secret: string;
try {
secret = openConnectionSecret(conn)!;
} catch {
await record("failed", "upstream_error", null);
return { ok: false, reason: "upstream_error" };
// PEP-252: a sign-in token is refreshed here when it is about to expire.
let cred = await connectionCredential(db, conn, { now });
if (!cred.ok) {
if (cred.reason === "needs_login") return deny("needs_login");
await record("failed", cred.reason, null);
return { ok: false, reason: cred.reason };
}
// Target = base (+ key in the path) + path; the host and the base path must survive URL parsing unchanged.
const built = buildRequest(conn, secret, clean, contentType, body);
let built = buildRequest(conn, cred.secret, clean, contentType, body);
if (!built) return deny("bad_path");
const { url, headers } = built;
// Written before the service is called: a crash in the middle leaves «started, no result».
const callId = (await record("allowed", null, null))!;
@ -793,7 +885,18 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
const result = (decision: ConnectionJournalDecision, reason: ConnectionReason | null, statusCode: number | null) =>
record(decision, reason, statusCode, { kind: "result", parentId: callId, durationMs: Date.now() - started });
try {
const res = await (o.fetch ?? defaultConnectionFetch)({ url, method, headers, body });
let res = await (o.fetch ?? defaultConnectionFetch)({ url: built.url, method, headers: built.headers, body });
// A sign-in token the service no longer takes: refresh once and repeat (the same journal call).
if (res.status === 401 && cred.refreshable && !cred.refreshed) {
const again = await connectionCredential(db, conn, { now, force: true });
if (!again.ok) {
await result(again.reason === "needs_login" ? "denied" : "failed", again.reason, again.reason === "needs_login" ? 401 : null);
return { ok: false, reason: again.reason };
}
cred = again;
built = buildRequest(conn, cred.secret, clean, contentType, body)!;
res = await (o.fetch ?? defaultConnectionFetch)({ url: built.url, method, headers: built.headers, body });
}
if (res.status >= 300 && res.status < 400 && res.location) {
await result("failed", "redirect", res.status);
return { ok: false, reason: "redirect", status: res.status };
@ -801,7 +904,7 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
await result("allowed", res.truncated ? "too_large" : null, res.status);
await db.update(connections).set({ lastUsedAt: now }).where(eq(connections.id, conn.id));
// The answer goes to the agent only: nothing of it is stored or sent anywhere (PEP-254).
const text = maskSecrets(res.body.toString("utf8"), secret.length >= 4 ? [secret] : []);
const text = maskSecrets(res.body.toString("utf8"), cred.secret.length >= 4 ? [cred.secret] : []);
return { ok: true, status: res.status, contentType: res.contentType, body: text, truncated: res.truncated };
} catch (e) {
const reason = e instanceof Refused ? e.reason : "upstream_error";
@ -837,7 +940,7 @@ export function judgeCheck(check: CatalogCheck | null, res: { status: number; bo
return { status: "down" };
}
async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: { fetch?: ConnectionFetch; now?: Date }): Promise<ConnectionCheckResult> {
async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: { fetch?: ConnectionFetch; now?: Date; notify?: (db: Db, c: { id: number; ownerId: number; name: string }) => Promise<void> }): Promise<ConnectionCheckResult & { relogin?: boolean }> {
const now = o.now ?? new Date();
const check = catalogService(conn.catalogId)?.check ?? null;
const method = check?.method ?? "GET";
@ -848,9 +951,11 @@ async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: { fetc
const entry = { ownerId: conn.ownerId, connectionId: conn.id, connectionName: conn.name, method, path: clean.path.slice(0, 300), createdAt: now };
const callId = appendJournal(db, { ...entry, kind: "call", decision: "allowed", reason: "owner_check", statusCode: null });
const started = Date.now();
let relogin = false;
try {
const secret = openConnectionSecret(conn)!;
const built = buildRequest(conn, secret, clean, null, null);
const cred = await connectionCredential(db, conn, { now, notify: o.notify });
if (!cred.ok) relogin = cred.reason === "needs_login";
const built = cred.ok ? buildRequest(conn, cred.secret, clean, null, null) : null;
if (built) {
// Own service: the check is the base address itself (no trailing «/» added).
if (!check) built.url.pathname = built.url.pathname.replace(/\/$/, "") || "/";
@ -860,18 +965,19 @@ async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: { fetc
} catch {
res = null;
}
const verdict = judgeCheck(check, res);
const verdict = relogin ? { status: "bad_key" as const } : judgeCheck(check, res);
const durationMs = Date.now() - started;
appendJournal(db, { ...entry, kind: "result", parentId: callId, decision: verdict.status === "ok" ? "allowed" : "failed", reason: "owner_check", statusCode: res?.status ?? null, durationMs, createdAt: new Date(now.getTime() + durationMs) });
const patch: Partial<typeof connections.$inferInsert> = { checkStatus: verdict.status, checkedAt: now };
if (verdict.status === "ok") patch.checkAlertedAt = null;
await db.update(connections).set(patch).where(eq(connections.id, conn.id));
return { ...verdict, httpStatus: res?.status, checkedAt: now };
return { ...verdict, httpStatus: res?.status, checkedAt: now, ...(relogin ? { relogin } : {}) };
}
/** «Проверить»: the catalog's check call through the same address guards, owner only. */
export async function checkConnection(db: Db, userId: number, connectionId: number, o: { fetch?: ConnectionFetch; now?: Date } = {}): Promise<ConnectionCheckResult> {
const c = await ownConnection(db, userId, connectionId);
if (c.status === "relogin") throw new PeppaError(tr("Сервис больше не пускает FORGE: нажмите «Войти заново»"));
if (c.status !== "active" || !c.secretEnc) throw new PeppaError(tr("Подключение отозвано: сначала задайте новый ключ доступа"));
return runCheck(db, c, o);
}
@ -888,8 +994,9 @@ export async function connectionCheckTick(db: Db, o: { fetch?: ConnectionFetch;
.filter((c) => c.secretEnc && (!c.checkedAt || now.getTime() - c.checkedAt.getTime() >= CONNECTION_CHECK_EVERY_MS))
.slice(0, CHECK_BATCH);
for (const c of due) {
const r = await runCheck(db, c, { fetch: o.fetch, now });
if (r.status === "bad_key" && c.checkStatus === "ok" && !c.checkAlertedAt) {
const r = await runCheck(db, c, { fetch: o.fetch, now, notify: o.notify });
// A sign-in that ended has already told its owner (markRelogin).
if (!r.relogin && r.status === "bad_key" && c.checkStatus === "ok" && !c.checkAlertedAt) {
await db.update(connections).set({ checkAlertedAt: now }).where(eq(connections.id, c.id));
await (o.notify ?? tellKeyStopped)(db, { id: c.id, ownerId: c.ownerId, name: c.name });
}
@ -897,6 +1004,22 @@ export async function connectionCheckTick(db: Db, o: { fetch?: ConnectionFetch;
return due.length;
}
/** PEP-252: one message to the owner — the service no longer lets FORGE in, sign in again. */
export async function tellReloginNeeded(db: Db, c: { id: number; ownerId: number; name: string }): Promise<void> {
const text = tr("Сервис больше не пускает FORGE в подключение «{name}» — возможно, доступ отозвали в самом сервисе. Агенты не смогут им пользоваться, пока вы не нажмёте «Войти заново» в разделе «Подключения».", { name: asIs(c.name) });
const key = `connection-relogin:${c.id}`;
await addMasterMessage(db, c.ownerId, { kind: "event", important: true, text, dedupeKey: `master:${key}:${Date.now()}`, url: `/connections#c${c.id}` }).catch(() => null);
const [u] = await db.select().from(users).where(eq(users.id, c.ownerId));
if (!u) return;
await deliverToUser(db, u, {
event: "failures",
dedupeKey: `${key}:${Date.now()}:${u.telegramChatId}`,
pushKey: `${key}:${Date.now()}:u${u.id}`,
telegram: { params: { text } },
push: { title: tr("FORGE"), body: text, url: "/connections", tag: key },
}).catch(() => null);
}
/** One message to the owner: the key of a connection stopped working. */
export async function tellKeyStopped(db: Db, c: { id: number; ownerId: number; name: string }): Promise<void> {
const text = tr("Ключ доступа подключения «{name}» перестал работать: агенты не смогут им пользоваться. Замените ключ в разделе «Подключения».", { name: asIs(c.name) });

View File

@ -110,6 +110,8 @@ export * from "./accept-digest.ts";
export * from "./connections.ts";
export * from "./connection-journal.ts";
export * from "./connection-catalog.ts";
export * from "./connection-oauth.ts";
export * from "./connection-oauth-flow.ts";
export * from "./edge-dns.ts";
export * from "./retention.ts";
export * from "./history.ts";

View File

@ -97,6 +97,32 @@ export const PLATFORM_SECRETS: PlatformSecretDef[] = [
tr("Отметить: `peppa secrets rotated GITEA_OAUTH_CLIENT_SECRET`."),
],
},
{
name: "PEPPA_OAUTH_GOOGLE_CLIENT_SECRET",
label: tr("Секрет OAuth-клиента Google для подключений"),
usedBy: tr("вход в Google Sheets, Drive и Calendar в разделе «Подключения» и обновление их токенов (без него — общий клиент входа через Google)"),
how: "external",
optional: true,
steps: [
tr("Google Cloud → APIs & Services → Credentials → OAuth-клиент FORGE → «Add secret», адрес возврата `<адрес FORGE>/connections/oauth/callback`, включены Sheets, Drive и Calendar API."),
tr("Идентификатор — в `PEPPA_OAUTH_GOOGLE_CLIENT_ID`, новый секрет — в `PEPPA_OAUTH_GOOGLE_CLIENT_SECRET`, {restart}", { restart: RESTART }),
tr("Старый секрет удалить в Google Cloud; выданные пользователям токены продолжают работать."),
tr("Отметить: `peppa secrets rotated PEPPA_OAUTH_GOOGLE_CLIENT_SECRET`."),
],
},
{
name: "PEPPA_OAUTH_GITHUB_CLIENT_SECRET",
label: tr("Секрет OAuth-приложения GitHub для подключений"),
usedBy: tr("вход в GitHub в разделе «Подключения», обновление и отзыв токенов"),
how: "external",
optional: true,
steps: [
tr("GitHub → Settings → Developer settings → OAuth Apps → приложение FORGE (адрес возврата `<адрес FORGE>/connections/oauth/callback`) → «Generate a new client secret»."),
tr("Идентификатор — в `PEPPA_OAUTH_GITHUB_CLIENT_ID`, новый секрет — в `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`, {restart}", { restart: RESTART }),
tr("Старый секрет удалить в GitHub; выданные пользователям токены продолжают работать."),
tr("Отметить: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`."),
],
},
{
name: "BUGSINK_TOKEN",
label: tr("API-токен Bugsink"),

View File

@ -0,0 +1,3 @@
ALTER TABLE `connections` ADD `oauth_provider` text;--> statement-breakpoint
ALTER TABLE `connections` ADD `oauth_scopes` text;--> statement-breakpoint
ALTER TABLE `connections` ADD `token_expires_at` integer;

File diff suppressed because it is too large Load Diff

View File

@ -218,6 +218,13 @@
"when": 1795512094088,
"tag": "0030_access_hub_journal",
"breakpoints": true
},
{
"idx": 31,
"version": "6",
"when": 1795521789822,
"tag": "0031_access_hub_oauth",
"breakpoints": true
}
]
}

View File

@ -675,7 +675,8 @@ export const connections = sqliteTable(
baseUrl: text("base_url").notNull(),
// bearer: Authorization: Bearer <key>; header: <authHeader>: <key>; basic: «login:password»;
// query: ?<authHeader>=<key>; path: base URL + key (Telegram). PEP-249.
authKind: text("auth_kind").$type<"bearer" | "header" | "basic" | "query" | "path">().notNull().default("bearer"),
// oauth (PEP-252): Authorization: Bearer <access token>, refreshed by the gateway.
authKind: text("auth_kind").$type<"bearer" | "header" | "basic" | "query" | "path" | "oauth">().notNull().default("bearer"),
authHeader: text("auth_header"),
// PEP-249: the catalog card (core/connection-catalog.ts) or null = own service.
catalogId: text("catalog_id"),
@ -689,8 +690,14 @@ export const connections = sqliteTable(
// an old row, secret_enc is under PEPPA_SECRET until `upgradeConnectionKeys`.
secretEnc: text("secret_enc"),
dekEnc: text("dek_enc"),
status: text("status").$type<"active" | "revoked">().notNull().default("active"),
// relogin (PEP-252): the service refused to refresh the OAuth token — tokens wiped, grants kept.
status: text("status").$type<"active" | "revoked" | "relogin">().notNull().default("active"),
revokedAt: integer("revoked_at", { mode: "timestamp_ms" }),
// PEP-252: sign-in connections — provider (google|github), granted scopes (not secret) and
// when the access token expires (null — no expiry); tokens are in secret_enc.
oauthProvider: text("oauth_provider"),
oauthScopes: text("oauth_scopes", { mode: "json" }).$type<string[]>(),
tokenExpiresAt: integer("token_expires_at", { mode: "timestamp_ms" }),
lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }),
createdAt: createdAt(),
updatedAt: updatedAt(),

View File

@ -33,6 +33,13 @@ const schema = z.object({
GOOGLE_CLIENT_SECRET: z.string().optional(),
// Test override of accounts.google.com / oauth2.googleapis.com (mock-google).
GOOGLE_OAUTH_BASE: z.string().url().optional(),
// Access Hub sign-in (PEP-252): FORGE's OAuth clients for connections; Google falls back to the login client.
PEPPA_OAUTH_GOOGLE_CLIENT_ID: z.string().optional(),
PEPPA_OAUTH_GOOGLE_CLIENT_SECRET: z.string().optional(),
PEPPA_OAUTH_GOOGLE_BASE: z.string().url().optional(),
PEPPA_OAUTH_GITHUB_CLIENT_ID: z.string().optional(),
PEPPA_OAUTH_GITHUB_CLIENT_SECRET: z.string().optional(),
PEPPA_OAUTH_GITHUB_BASE: z.string().url().optional(),
EGOV_ORGANISATION_BIN: z.string().regex(/^\d{12}$/).default("241140100000"),
});

View File

@ -0,0 +1,3 @@
#!/usr/bin/env bash
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-oauth-service.ts" "$@"

View File

@ -0,0 +1,202 @@
// Mock OAuth service (PEP-252) for Access Hub sign-in tests and checks without real Google/GitHub
// clients. Follows each provider's contract:
// google — GET /auth (consents at once → redirect with code+state), POST /token (authorization_code
// with PKCE S256, refresh_token: same refresh token, new access), POST /revoke (token=…),
// resources GET /v4/spreadsheets/<id>, GET /calendar/v3/calendars/<id>/events (Bearer + matching scope);
// github — GET /login/oauth/authorize, POST /login/oauth/access_token (errors as 200 + `error`,
// refresh rotates the refresh token), DELETE /applications/<client_id>/grant (basic client
// auth, JSON {access_token}), resources GET /user, GET /repos/<o>/<r>.
// `revokeAll()` is the person revoking FORGE in the service's settings; `expireAccess()` ages tokens.
// Standalone: `mock-oauth-service google|github [port]`.
import { createHash, randomUUID } from "node:crypto";
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import type { AddressInfo } from "node:net";
export type MockOAuthKind = "google" | "github";
interface Access {
scopes: string[];
expiresAt: number | null;
refresh: string | null;
}
export class MockOAuthService {
readonly kind: MockOAuthKind;
clientId: string;
clientSecret: string;
/** Lifetime of an access token, seconds; null — never expires (GitHub OAuth app). */
expiresIn: number | null;
/** GitHub (expiring user tokens) gives a new refresh token on each refresh and kills the old one. */
rotateRefresh: boolean;
/** Scopes the person ticks on the consent screen; null — all asked. */
consentScopes: string[] | null = null;
/** The person presses «Cancel». */
deny = false;
/** 503 on token and revoke calls. */
down = false;
readonly codes = new Map<string, { redirectUri: string; challenge: string; scopes: string[] }>();
readonly access = new Map<string, Access>();
readonly refresh = new Map<string, { scopes: string[] }>();
/** For assertions: what reached the service. */
readonly seen: { authorize: URLSearchParams[]; token: URLSearchParams[]; revoked: string[]; api: Array<{ path: string; auth: string }> } = { authorize: [], token: [], revoked: [], api: [] };
private server: Server | null = null;
constructor(kind: MockOAuthKind) {
this.kind = kind;
this.clientId = `mock-${kind}-client`;
this.clientSecret = `mock-${kind}-secret`;
this.expiresIn = kind === "google" ? 3599 : 28800;
this.rotateRefresh = kind === "github";
}
async start(port = 0): Promise<string> {
this.server = createServer((req, res) => void this.handle(req, res).catch(() => this.send(res, 500, { error: "server_error" })));
await new Promise<void>((r) => this.server!.listen(port, "127.0.0.1", r));
return `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
}
async stop(): Promise<void> {
await new Promise<void>((r) => (this.server ? this.server.close(() => r()) : r()));
}
/** The person revoked FORGE in the service: every token dies. */
revokeAll(): void {
this.access.clear();
this.refresh.clear();
}
/** Every access token is expired now (refresh tokens stay alive). */
expireAccess(): void {
for (const a of this.access.values()) a.expiresAt = Date.now() - 1000;
}
private send(res: ServerResponse, code: number, body: unknown) {
res.writeHead(code, { "content-type": "application/json" });
res.end(code === 204 ? undefined : JSON.stringify(body));
}
private paths() {
return this.kind === "google" ? { authorize: "/auth", token: "/token" } : { authorize: "/login/oauth/authorize", token: "/login/oauth/access_token" };
}
private issue(scopes: string[], refresh: string | null) {
const token = `${this.kind === "github" ? "gho_" : "ya29."}${randomUUID().replace(/-/g, "")}`;
this.access.set(token, { scopes, expiresAt: this.expiresIn == null ? null : Date.now() + this.expiresIn * 1000, refresh });
return token;
}
private tokenAnswer(access: string, refresh: string | null, scopes: string[]) {
const a: Record<string, unknown> = { access_token: access, token_type: "bearer", scope: scopes.join(this.kind === "github" ? "," : " ") };
if (this.expiresIn != null) a.expires_in = this.expiresIn;
if (refresh) a.refresh_token = refresh;
return a;
}
private tokenError(res: ServerResponse, error: string) {
// GitHub answers errors with 200; Google with 400 (401 for a bad client).
this.send(res, this.kind === "github" ? 200 : error === "invalid_client" ? 401 : 400, { error });
}
private async body(req: IncomingMessage): Promise<string> {
let raw = "";
for await (const chunk of req) raw += chunk;
return raw;
}
private async handle(req: IncomingMessage, res: ServerResponse) {
const u = new URL(req.url ?? "/", "http://mock");
const method = req.method ?? "GET";
const p = this.paths();
if (method === "GET" && u.pathname === p.authorize) {
const q = u.searchParams;
this.seen.authorize.push(q);
if (q.get("client_id") !== this.clientId || q.get("response_type") !== "code" || q.get("code_challenge_method") !== "S256" || !q.get("code_challenge") || !q.get("redirect_uri") || !q.get("state")) return this.send(res, 400, { error: "invalid_request" });
const back = new URL(q.get("redirect_uri")!);
back.searchParams.set("state", q.get("state")!);
if (this.deny) back.searchParams.set("error", "access_denied");
else {
const asked = (q.get("scope") ?? "").split(/\s+/).filter(Boolean);
const code = randomUUID();
this.codes.set(code, { redirectUri: q.get("redirect_uri")!, challenge: q.get("code_challenge")!, scopes: this.consentScopes ?? asked });
back.searchParams.set("code", code);
}
res.writeHead(302, { location: back.toString() });
return res.end();
}
if (method === "POST" && u.pathname === p.token) {
if (this.down) return this.send(res, 503, { error: "unavailable" });
const f = new URLSearchParams(await this.body(req));
this.seen.token.push(f);
if (f.get("client_id") !== this.clientId || f.get("client_secret") !== this.clientSecret) return this.tokenError(res, "invalid_client");
if (f.get("grant_type") === "authorization_code") {
const grant = this.codes.get(f.get("code") ?? "");
this.codes.delete(f.get("code") ?? ""); // one use
if (!grant || f.get("redirect_uri") !== grant.redirectUri) return this.tokenError(res, this.kind === "github" ? "bad_verification_code" : "invalid_grant");
if (createHash("sha256").update(f.get("code_verifier") ?? "").digest("base64url") !== grant.challenge) return this.tokenError(res, "invalid_grant");
const refresh = this.expiresIn == null ? null : `rt_${randomUUID().replace(/-/g, "")}`;
if (refresh) this.refresh.set(refresh, { scopes: grant.scopes });
return this.send(res, 200, this.tokenAnswer(this.issue(grant.scopes, refresh), refresh, grant.scopes));
}
if (f.get("grant_type") === "refresh_token") {
const old = f.get("refresh_token") ?? "";
const r = this.refresh.get(old);
if (!r) return this.tokenError(res, this.kind === "github" ? "bad_refresh_token" : "invalid_grant");
let refresh = old;
if (this.rotateRefresh) {
this.refresh.delete(old);
refresh = `rt_${randomUUID().replace(/-/g, "")}`;
this.refresh.set(refresh, r);
}
// Google doesn't resend its refresh token.
return this.send(res, 200, this.tokenAnswer(this.issue(r.scopes, refresh), this.rotateRefresh ? refresh : null, r.scopes));
}
return this.tokenError(res, "unsupported_grant_type");
}
if (this.kind === "google" && method === "POST" && u.pathname === "/revoke") {
if (this.down) return this.send(res, 503, { error: "unavailable" });
const token = new URLSearchParams(await this.body(req)).get("token") ?? "";
this.seen.revoked.push(token);
const known = this.refresh.has(token) || this.access.has(token);
// Revoking a refresh token revokes the whole grant.
for (const [k, a] of this.access) if (k === token || a.refresh === token) this.access.delete(k);
this.refresh.delete(token);
return known ? this.send(res, 200, {}) : this.send(res, 400, { error: "invalid_token" });
}
if (this.kind === "github" && method === "DELETE" && u.pathname === `/applications/${this.clientId}/grant`) {
if (this.down) return this.send(res, 503, { message: "unavailable" });
if (req.headers.authorization !== `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString("base64")}`) return this.send(res, 401, { message: "Requires authentication" });
const token = (JSON.parse((await this.body(req)) || "{}") as { access_token?: string }).access_token ?? "";
this.seen.revoked.push(token);
if (!this.access.has(token)) return this.send(res, 404, { message: "Not Found" });
this.revokeAll();
return this.send(res, 204, null);
}
// Resources: only a live access token with a suitable scope.
const auth = String(req.headers.authorization ?? "");
this.seen.api.push({ path: u.pathname, auth });
const a = this.access.get(auth.replace(/^Bearer /i, ""));
if (!a || (a.expiresAt != null && a.expiresAt <= Date.now())) return this.send(res, 401, this.kind === "github" ? { message: "Bad credentials" } : { error: { code: 401, status: "UNAUTHENTICATED" } });
if (this.kind === "google" && method === "GET" && u.pathname.startsWith("/v4/spreadsheets/")) {
if (!a.scopes.some((s) => /\/spreadsheets(\.readonly)?$/.test(s))) return this.send(res, 403, { error: { code: 403, status: "PERMISSION_DENIED" } });
const id = u.pathname.split("/")[3]!;
if (id === "forge-key-check") return this.send(res, 404, { error: { code: 404, status: "NOT_FOUND" } });
return this.send(res, 200, { spreadsheetId: id, properties: { title: "Продажи" }, values: [["Месяц", "Сумма"], ["Ноябрь", "120"]] });
}
if (this.kind === "google" && method === "GET" && /^\/calendar\/v3\/calendars\/[^/]+\/events$/.test(u.pathname)) {
if (!a.scopes.some((s) => /\/calendar(\.readonly|\.events)?$/.test(s))) return this.send(res, 403, { error: { code: 403, status: "PERMISSION_DENIED" } });
if (u.pathname.includes("forge-key-check")) return this.send(res, 404, { error: { code: 404, status: "NOT_FOUND" } });
return this.send(res, 200, { kind: "calendar#events", items: [{ summary: "Встреча с поставщиком" }] });
}
if (this.kind === "github" && method === "GET" && u.pathname === "/user") return this.send(res, 200, { login: "mock-anna", id: 1001 });
if (this.kind === "github" && method === "GET" && /^\/repos\/[^/]+\/[^/]+$/.test(u.pathname)) return this.send(res, 200, { full_name: u.pathname.slice(7), private: true });
this.send(res, 404, { error: "not_found" });
}
}
if (import.meta.main) {
const kind = (process.argv[2] === "github" ? "github" : "google") as MockOAuthKind;
const s = new MockOAuthService(kind);
const url = await s.start(Number(process.argv[3] ?? process.env.MOCK_PORT ?? 3105));
const K = kind.toUpperCase();
console.log(`mock-oauth-service ${kind} (TEST ONLY): PEPPA_OAUTH_${K}_BASE=${url} PEPPA_OAUTH_${K}_CLIENT_ID=${s.clientId} PEPPA_OAUTH_${K}_CLIENT_SECRET=${s.clientSecret}`);
}

View File

@ -0,0 +1,282 @@
// PEP-252 Access Hub: connecting Google Sheets and GitHub by signing in (OAuth code + PKCE),
// the gateway refreshing tokens itself, «нужно войти заново», revoke in the service, another
// person's callback. Scenario names follow openspec/changes/pep-252-access-hub-oauth/specs.
import assert from "node:assert/strict";
import { after, before, describe, test } from "node:test";
import { eq, like } from "drizzle-orm";
import { core, db, project, teardown } from "./helpers.ts";
import { MockOAuthService } from "../src/mock-oauth-service.ts";
import { stripAsIs } from "@peppa/shared/i18n";
process.env.PEPPA_SECRET ??= "mock-access-hub-secret";
process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = "1";
const { connections, connectionLog, agents, sessions, chatMessages } = await import("@peppa/db");
const google = new MockOAuthService("google");
const github = new MockOAuthService("github");
let googleBase: string;
let githubBase: string;
const REDIRECT = "https://forge.example.com/connections/oauth/callback";
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let boris: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
before(async () => {
googleBase = await google.start();
githubBase = await github.start();
Object.assign(process.env, {
PEPPA_OAUTH_GOOGLE_CLIENT_ID: google.clientId,
PEPPA_OAUTH_GOOGLE_CLIENT_SECRET: google.clientSecret,
PEPPA_OAUTH_GOOGLE_BASE: googleBase,
PEPPA_OAUTH_GITHUB_CLIENT_ID: github.clientId,
PEPPA_OAUTH_GITHUB_CLIENT_SECRET: github.clientSecret,
PEPPA_OAUTH_GITHUB_BASE: githubBase,
});
anna = await core.upsertUserFromGitea(db, { id: 2521, login: "mock-anna-oauth" }, { access_token: "a" });
boris = await core.upsertUserFromGitea(db, { id: 2522, login: "mock-boris-oauth" }, { access_token: "b" });
});
after(async () => {
await google.stop();
await github.stop();
await teardown();
});
/** The gateway's request goes to the mock instead of sheets.googleapis.com / api.github.com. */
const toMock = (mockBase: string): core.ConnectionFetch => (o) => {
const real = new URL(o.url);
const url = new URL(mockBase + real.pathname + real.search);
return core.defaultConnectionFetch({ ...o, url });
};
/** The browser: start → the service's page → back with code and state. */
async function signIn(userId: number, i: { catalogId?: string; connectionId?: number; level?: string }) {
const start = await core.startConnectionOAuth(db, userId, { ...i, redirectUri: REDIRECT });
const res = await fetch(start.url, { redirect: "manual" });
assert.equal(res.status, 302);
const back = new URL(res.headers.get("location")!);
assert.equal(back.origin + back.pathname, REDIRECT);
return { start, code: back.searchParams.get("code") ?? "", state: back.searchParams.get("state") ?? "", error: back.searchParams.get("error") };
}
async function connect(userId: number, catalogId: string, level = "read") {
const s = await signIn(userId, { catalogId, level });
return core.completeConnectionOAuth(db, userId, { state: s.state, code: s.code, cookieState: s.start.state });
}
async function agentFor(ownerId: number) {
const p = await project({ turns: [] });
const proj = await core.getProject(db, p.key);
await core.setProjectOwner(db, proj.id, ownerId);
const task = (await core.listTasks(db, { projectId: proj.id }))[0]!;
const s = await core.createSession(db, { projectId: proj.id, taskId: task.id });
const [a] = await db.insert(agents).values({ name: `Мок-агент OAuth ${s.id}` }).returning();
await db.update(sessions).set({ agentId: a!.id, container: `peppa-s${s.id}` }).where(eq(sessions.id, s.id));
return { proj, sessionId: s.id };
}
const row = async (id: number) => (await db.select().from(connections).where(eq(connections.id, id)))[0]!;
const reloginMessages = async (name: string) => (await db.select().from(chatMessages).where(like(chatMessages.text, "%Войти заново%"))).filter((m) => stripAsIs(m.text).includes(`«${name}»`)).length;
describe("Подключение входом через сервис", () => {
test("Владелец подключает Google Sheets входом", async () => {
const offer = core.oauthOffer("google-sheets");
assert.ok(offer, "the sign-in way is offered when FORGE has a Google client");
assert.deepEqual(offer!.read.map(core.scopeLabel), ["spreadsheets.readonly"]);
const s = await signIn(anna.id, { catalogId: "google-sheets", level: "read" });
const asked = google.seen.authorize.at(-1)!;
assert.equal(asked.get("scope"), "https://www.googleapis.com/auth/spreadsheets.readonly");
assert.equal(asked.get("code_challenge_method"), "S256");
assert.equal(asked.get("access_type"), "offline");
const r = await core.completeConnectionOAuth(db, anna.id, { state: s.state, code: s.code, cookieState: s.start.state });
assert.equal(r.created, true);
const c = (await core.listConnections(db, anna.id)).find((x) => x.id === r.connectionId)!;
assert.equal(c.name, "Google Sheets");
assert.equal(c.authKind, "oauth");
assert.equal(c.oauthProvider, "google");
assert.deepEqual(c.oauthScopes.map(core.scopeLabel), ["spreadsheets.readonly"]);
// Tokens: only in the sealed envelope.
const tokens = [...google.access.keys(), ...google.refresh.keys()];
const stored = await row(r.connectionId);
for (const t of tokens) {
assert.ok(!JSON.stringify(c).includes(t), "not in the owner's view");
assert.ok(!JSON.stringify(stored).includes(t), "not in the clear in the database");
}
assert.ok(stored.dekEnc && stored.secretEnc?.startsWith("v2."));
// The PKCE verifier reached the token endpoint, the client secret too.
const tok = google.seen.token.at(-1)!;
assert.ok(tok.get("code_verifier"));
});
test("Клиент не настроен — способ скрыт", async () => {
const env = { ...process.env, PEPPA_OAUTH_GITHUB_CLIENT_ID: "", PEPPA_OAUTH_GITHUB_CLIENT_SECRET: "" };
assert.equal(core.oauthOffer("github", env), null);
assert.ok(core.oauthOffer("github"));
assert.equal(core.oauthOffer("stripe"), null, "a card without sign-in");
await assert.rejects(core.startConnectionOAuth(db, anna.id, { catalogId: "github", redirectUri: REDIRECT }, env), /не настроен/);
});
test("Поток подменили: другой state, повтор, чужой пользователь", async () => {
const s = await signIn(anna.id, { catalogId: "github" });
const before = (await core.listConnections(db, anna.id)).length;
await assert.rejects(core.completeConnectionOAuth(db, anna.id, { state: s.state, code: s.code, cookieState: "other-browser" }), core.PeppaError);
// The flow is spent even by a refused try.
const s2 = await signIn(anna.id, { catalogId: "github" });
await assert.rejects(core.completeConnectionOAuth(db, boris.id, { state: s2.state, code: s2.code, cookieState: s2.start.state }), core.PeppaError, "another person signed in");
await assert.rejects(core.completeConnectionOAuth(db, anna.id, { state: s2.state, code: s2.code, cookieState: s2.start.state }), core.PeppaError, "one-shot");
assert.equal((await core.listConnections(db, anna.id)).length, before);
assert.equal((await core.listConnections(db, boris.id)).length, 0);
// «Войти заново» into someone else's connection is refused at the start.
const mine = (await core.listConnections(db, anna.id))[0]!;
await assert.rejects(core.startConnectionOAuth(db, boris.id, { connectionId: mine.id, redirectUri: REDIRECT }), /не найдено/);
});
test("Отказ на странице сервиса и непрошенные права", async () => {
google.deny = true;
const s = await signIn(anna.id, { catalogId: "google-drive" });
google.deny = false;
assert.equal(s.error, "access_denied");
assert.equal(s.code, "");
google.consentScopes = ["openid"];
try {
await assert.rejects(connect(anna.id, "google-drive"), /нужный доступ/);
} finally {
google.consentScopes = null;
}
});
});
describe("Шлюз сам обновляет токен", () => {
test("Токен истёк — агент читает таблицу", async () => {
const { connectionId } = await connect(anna.id, "google-sheets");
const { proj, sessionId } = await agentFor(anna.id);
await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" });
const fetch = toMock(googleBase);
const slug = (await row(connectionId)).slug!;
const first = await core.callConnection(db, { sessionId, connection: slug, method: "GET", path: "/v4/spreadsheets/abc" }, { fetch });
assert.equal(first.ok && first.status, 200);
assert.match(first.ok ? first.body : "", /Продажи/);
const refreshesBefore = google.seen.token.filter((f) => f.get("grant_type") === "refresh_token").length;
// Expired by its stored date: refreshed before the call.
const now = new Date(Date.now() + 2 * 3600_000);
google.expireAccess();
const second = await core.callConnection(db, { sessionId, connection: slug, method: "GET", path: "/v4/spreadsheets/abc" }, { fetch, now });
assert.equal(second.ok && second.status, 200);
assert.equal(google.seen.token.filter((f) => f.get("grant_type") === "refresh_token").length, refreshesBefore + 1);
// Expired early at the service (date says fine): 401 → one refresh → repeated.
google.expireAccess();
const third = await core.callConnection(db, { sessionId, connection: slug, method: "GET", path: "/v4/spreadsheets/abc" }, { fetch, now });
assert.equal(third.ok && third.status, 200);
// Writing is not granted: refused before any token is used.
const write = await core.callConnection(db, { sessionId, connection: slug, method: "PUT", path: "/v4/spreadsheets/abc/values/A1", body: "{}" }, { fetch, now });
assert.equal(!write.ok && write.reason, "write_denied");
// Nothing of the tokens in the journal.
const log = JSON.stringify(await db.select().from(connectionLog).where(eq(connectionLog.connectionId, connectionId)));
for (const t of [...google.access.keys(), ...google.refresh.keys()]) assert.ok(!log.includes(t));
// Daily check works with the token too.
const chk = await core.checkConnection(db, anna.id, connectionId, { fetch, now });
assert.equal(chk.status, "ok");
});
test("GitHub: агент читает репозиторий, обновление меняет и ключ обновления", async () => {
const { connectionId } = await connect(anna.id, "github");
const { proj, sessionId } = await agentFor(anna.id);
await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" });
const fetch = toMock(githubBase);
const now = new Date(Date.now() + 9 * 3600_000);
const oldRefresh = [...github.refresh.keys()];
const r = await core.callConnection(db, { sessionId, connection: "github", method: "GET", path: "/repos/mock-anna/shop" }, { fetch, now });
assert.equal(r.ok && r.status, 200);
assert.ok(oldRefresh.every((t) => !github.refresh.has(t)), "the old refresh token is spent");
const again = await core.callConnection(db, { sessionId, connection: "github", method: "GET", path: "/user" }, { fetch, now });
assert.equal(again.ok && again.status, 200, "the new refresh token was saved");
});
test("Доступ отозвали в самом сервисе — нужно войти заново, одно сообщение", async () => {
const { connectionId } = await connect(anna.id, "google-calendar");
const { proj, sessionId } = await agentFor(anna.id);
await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" });
const name = (await row(connectionId)).name;
google.revokeAll();
const fetch = toMock(googleBase);
const now = new Date(Date.now() + 2 * 3600_000);
const r = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/calendars/primary/events" }, { fetch, now });
assert.equal(!r.ok && r.reason, "needs_login");
const c = await row(connectionId);
assert.equal(c.status, "relogin");
assert.equal(c.secretEnc, null, "dead tokens are wiped");
assert.equal(await reloginMessages(name), 1);
const r2 = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/calendars/primary/events" }, { fetch, now });
assert.equal(!r2.ok && r2.reason, "needs_login");
await core.connectionCheckTick(db, { fetch, now: new Date(now.getTime() + 2 * 86400_000) });
assert.equal(await reloginMessages(name), 1, "no second message");
// The agent sees it as not working.
const seen = (await core.agentConnections(db, sessionId)).find((x) => x.id === connectionId)!;
assert.equal(seen.checkStatus, "bad_key");
// Войти заново: same connection, grants kept.
const s = await signIn(anna.id, { connectionId });
const back = await core.completeConnectionOAuth(db, anna.id, { state: s.state, code: s.code, cookieState: s.start.state });
assert.deepEqual(back, { connectionId, created: false });
assert.equal((await row(connectionId)).status, "active");
assert.equal((await core.listConnections(db, anna.id)).find((x) => x.id === connectionId)!.grants.length, 1);
const ok = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/calendars/primary/events" }, { fetch });
assert.equal(ok.ok && ok.status, 200);
assert.match(ok.ok ? ok.body : "", /поставщиком/);
});
test("Сервис обновления не отвечает — подключение не ломается", async () => {
const { connectionId } = await connect(anna.id, "google-sheets");
const { proj, sessionId } = await agentFor(anna.id);
await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" });
google.down = true;
try {
const r = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/v4/spreadsheets/x" }, { fetch: toMock(googleBase), now: new Date(Date.now() + 2 * 3600_000) });
assert.equal(!r.ok && r.reason, "upstream_error");
} finally {
google.down = false;
}
assert.equal((await row(connectionId)).status, "active");
});
test("Ключ у подключения входом заменить нельзя", async () => {
const { connectionId } = await connect(anna.id, "google-drive");
await assert.rejects(core.replaceConnectionSecret(db, anna.id, connectionId, "AIza-mock-key-123"), /Войти заново/);
});
});
describe("Отзыв доступа отзывает токен в сервисе", () => {
test("Отзыв GitHub", async () => {
const { connectionId } = await connect(anna.id, "github");
const access = [...github.access.keys()].at(-1)!;
const { proj, sessionId } = await agentFor(anna.id);
await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" });
const r = await core.revokeConnection(db, anna.id, connectionId);
assert.equal(r.remote, "revoked");
assert.ok(github.seen.revoked.includes(access));
assert.equal(github.access.size, 0);
const call = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/user" }, { fetch: toMock(githubBase) });
assert.equal(!call.ok && call.reason, "revoked");
});
test("Удаление отзывает Google", async () => {
const { connectionId } = await connect(anna.id, "google-sheets");
const refresh = [...google.refresh.keys()].at(-1)!;
await core.deleteConnection(db, anna.id, connectionId);
assert.ok(google.seen.revoked.includes(refresh));
assert.ok(!google.refresh.has(refresh));
});
test("Сервис не отвечает при отзыве", async () => {
const { connectionId } = await connect(anna.id, "google-sheets");
google.down = true;
try {
const r = await core.revokeConnection(db, anna.id, connectionId);
assert.equal(r.remote, "failed");
} finally {
google.down = false;
}
const c = await row(connectionId);
assert.equal(c.status, "revoked");
assert.equal(c.secretEnc, null);
});
});