peppa/packages/core/src/connection-catalog.ts
peppa-bot c83454889c
All checks were successful
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 34с
peppa/test test: success за 1416с
peppa-ci / ci (pull_request) Successful in 26m6s
PEP-252: вход в сервисы через OAuth (Google, GitHub) — поверх свежей main
Ядро (обновление токенов, «Войти заново», отзыв в сервисе), экран «Подключения»,
тексты ru/kk/en, мок и тесты. Пересобрано на main после PEP-251/258:
миграция теперь 0033_access_hub_oauth, маскировка ответа — connectionKeyForms
от текущего токена, проверка подключений принимает notify вместе с drivers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:00:23 +00:00

443 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-249 Access Hub catalog: ready services for «Подключения». Data lives here, in the code —
// nothing is downloaded (no icons, no descriptions, no new network addresses). A connection keeps
// 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). 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" | "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"];
export const CATALOG_KIND_TEXT: Record<CatalogKind, string> = {
payments: tr("Платежи"),
code: tr("Код"),
mail: tr("Почта"),
messaging: tr("Сообщения"),
ai: tr("ИИ"),
cloud: tr("Облако"),
errors: tr("Ошибки"),
data: tr("Данные и таблицы"),
docs: tr("Документы"),
maps: tr("Карты"),
commerce: tr("Торговля"),
};
export interface CatalogCheck {
method: "GET" | "POST";
/** Relative to the service address; may carry a query. */
path: string;
/** Statuses that mean «ключ работает» (default: any 2xx). */
ok?: number[];
/** Statuses that mean «ключ не подходит» (default: 401, 403). */
badKey?: number[];
/** A 2xx answer must contain this text, otherwise the key is bad (Slack answers 200 `"ok":false`). */
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;
/** Brand name, not translated. */
name: string;
kind: CatalogKind;
baseUrl: string;
/** Every user has their own address (self-hosted, per-project): baseUrl is only a sample. */
baseEditable?: boolean;
auth: CatalogAuth;
/** Header name (auth=header) or query parameter (auth=query). */
authParam?: string;
/** Fixed headers the service needs; the agent can't change them. */
headers?: Record<string, string>;
docsUrl: string;
keyUrl: string;
/** Where to get the key — for a person, in plain words (translated). */
keyHint: string;
/** Read-only operations: «METHOD /path», `*` = one segment, prefix match on segment boundary. */
read: string[];
check: CatalogCheck;
/** The service accepts `Idempotency-Key` (used by owner confirmations, PEP-235). */
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[] = [
{
id: "github",
name: "GitHub",
kind: "code",
baseUrl: "https://api.github.com",
auth: "bearer",
headers: { accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28" },
docsUrl: "https://docs.github.com/en/rest",
keyUrl: "https://github.com/settings/personal-access-tokens/new",
keyHint: tr("Settings → Developer settings → Fine-grained tokens: создайте ключ с доступом только к нужным проектам."),
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",
name: "Gitea",
kind: "code",
baseUrl: "https://gitea.example.com/api/v1",
baseEditable: true,
auth: "bearer",
docsUrl: "https://docs.gitea.com/api/1.22/",
keyUrl: "https://docs.gitea.com/development/api-usage#generating-and-listing-api-tokens",
keyHint: tr("В своём сервере: Настройки → Приложения → «Создать новый ключ». Адрес — ваш сервер и /api/v1 в конце."),
read: GET_ALL,
check: { method: "GET", path: "/user" },
tags: ["git", "код", "code"],
},
{
id: "stripe",
name: "Stripe",
kind: "payments",
baseUrl: "https://api.stripe.com",
auth: "bearer",
docsUrl: "https://docs.stripe.com/api",
keyUrl: "https://dashboard.stripe.com/apikeys",
keyHint: tr("Developers → API keys. Для начала возьмите тестовый ключ (sk_test_…) или ключ с ограниченными правами."),
read: GET_ALL,
check: { method: "GET", path: "/v1/balance" },
idempotency: true,
tags: ["оплата", "платежи", "payments", "billing"],
},
{
id: "google-sheets",
name: "Google Sheets",
kind: "data",
baseUrl: "https://sheets.googleapis.com",
auth: "query",
authParam: "key",
docsUrl: "https://developers.google.com/workspace/sheets/api/reference/rest",
keyUrl: "https://console.cloud.google.com/apis/credentials",
// glossary-ignore: дословные названия пунктов меню и адрес внешнего сервиса — по ним пользователь находит ключ
keyHint: tr("Google Cloud → APIs & Services → Credentials → «Create credentials» → API key, включите Sheets API. По такому ключу открываются только таблицы с доступом по ссылке."),
read: GET_ALL,
// 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",
name: "Google Drive",
kind: "docs",
baseUrl: "https://www.googleapis.com/drive/v3",
auth: "query",
authParam: "key",
docsUrl: "https://developers.google.com/workspace/drive/api/reference/rest/v3",
keyUrl: "https://console.cloud.google.com/apis/credentials",
// glossary-ignore: дословные названия пунктов меню и адрес внешнего сервиса — по ним пользователь находит ключ
keyHint: tr("Google Cloud → APIs & Services → Credentials → API key, включите Drive API. По такому ключу видны только файлы с доступом по ссылке."),
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",
name: "Google Calendar",
kind: "data",
baseUrl: "https://www.googleapis.com/calendar/v3",
auth: "query",
authParam: "key",
docsUrl: "https://developers.google.com/workspace/calendar/api/v3/reference",
keyUrl: "https://console.cloud.google.com/apis/credentials",
// glossary-ignore: дословные названия пунктов меню и адрес внешнего сервиса — по ним пользователь находит ключ
keyHint: tr("Google Cloud → APIs & Services → Credentials → API key, включите Calendar API. По такому ключу видны только общедоступные календари."),
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",
name: "Telegram Bot API",
kind: "messaging",
baseUrl: "https://api.telegram.org",
auth: "path",
docsUrl: "https://core.telegram.org/bots/api",
keyUrl: "https://t.me/BotFather",
keyHint: tr("Отправьте @BotFather сообщение /newbot (или /token для своего бота) и вставьте ключ, который он пришлёт."),
// Telegram takes changes through GET too — reading is listed by method.
read: ["GET /getMe", "GET /getChat", "GET /getChatMember", "GET /getChatMemberCount", "GET /getChatAdministrators", "GET /getWebhookInfo", "GET /getFile", "GET /getMyCommands", "GET /getUserProfilePhotos"],
check: { method: "GET", path: "/getMe" },
tags: ["телеграм", "бот", "telegram", "bot"],
},
{
id: "resend",
name: "Resend",
kind: "mail",
baseUrl: "https://api.resend.com",
auth: "bearer",
docsUrl: "https://resend.com/docs/api-reference/introduction",
keyUrl: "https://resend.com/api-keys",
keyHint: tr("API Keys → «Create API Key». Для проверки и чтения нужен ключ с полным доступом."),
read: GET_ALL,
check: { method: "GET", path: "/domains" },
idempotency: true,
tags: ["почта", "письма", "email", "mail"],
},
{
id: "sendgrid",
name: "SendGrid",
kind: "mail",
baseUrl: "https://api.sendgrid.com",
auth: "bearer",
docsUrl: "https://www.twilio.com/docs/sendgrid/api-reference",
keyUrl: "https://app.sendgrid.com/settings/api_keys",
keyHint: tr("Settings → API Keys → «Create API Key», права — только нужные."),
read: GET_ALL,
check: { method: "GET", path: "/v3/scopes" },
tags: ["почта", "письма", "email", "mail"],
},
{
id: "openai",
name: "OpenAI",
kind: "ai",
baseUrl: "https://api.openai.com",
auth: "bearer",
docsUrl: "https://platform.openai.com/docs/api-reference",
keyUrl: "https://platform.openai.com/api-keys",
keyHint: tr("API keys → «Create new secret key». Запросы к ИИ тратят деньги на вашем счёте — это «запись»."),
read: GET_ALL,
check: { method: "GET", path: "/v1/models" },
tags: ["ии", "ai", "gpt", "chatgpt"],
},
{
id: "anthropic",
name: "Anthropic",
kind: "ai",
baseUrl: "https://api.anthropic.com",
auth: "header",
authParam: "x-api-key",
headers: { "anthropic-version": "2023-06-01" },
docsUrl: "https://docs.anthropic.com/en/api/overview",
keyUrl: "https://console.anthropic.com/settings/keys",
keyHint: tr("Console → Settings → API keys → «Create Key». Запросы к ИИ тратят деньги на вашем счёте — это «запись»."),
read: GET_ALL,
check: { method: "GET", path: "/v1/models" },
tags: ["ии", "ai", "claude"],
},
{
id: "cloudflare",
name: "Cloudflare",
kind: "cloud",
baseUrl: "https://api.cloudflare.com/client/v4",
auth: "bearer",
docsUrl: "https://developers.cloudflare.com/api/",
keyUrl: "https://dash.cloudflare.com/profile/api-tokens",
keyHint: tr("My Profile → API Tokens → «Create Token», выберите шаблон с нужными правами."),
read: GET_ALL,
check: { method: "GET", path: "/user/tokens/verify" },
tags: ["dns", "домены", "облако", "cloud"],
},
{
id: "sentry",
name: "Sentry",
kind: "errors",
baseUrl: "https://sentry.io/api/0",
baseEditable: true,
auth: "bearer",
docsUrl: "https://docs.sentry.io/api/",
keyUrl: "https://sentry.io/settings/account/api/auth-tokens/",
// glossary-ignore: дословные названия пунктов меню и адрес внешнего сервиса — по ним пользователь находит ключ
keyHint: tr("User settings → Auth Tokens → «Create New Token». Адрес — https://sentry.io/api/0 или ваш сервер."),
read: GET_ALL,
check: { method: "GET", path: "/organizations/" },
tags: ["ошибки", "errors"],
},
{
id: "bugsink",
name: "Bugsink",
kind: "errors",
baseUrl: "https://bugsink.example.com/api/canonical/0",
baseEditable: true,
auth: "bearer",
docsUrl: "https://www.bugsink.com/docs/api/",
keyUrl: "https://www.bugsink.com/docs/api/",
keyHint: tr("В своём сервере создайте ключ доступа администратора. Адрес — ваш сервер и /api/canonical/0 в конце."),
read: GET_ALL,
check: { method: "GET", path: "/projects/" },
tags: ["ошибки", "errors"],
},
{
id: "supabase",
name: "Supabase",
kind: "data",
baseUrl: "https://project-ref.supabase.co",
baseEditable: true,
auth: "header",
authParam: "apikey",
docsUrl: "https://supabase.com/docs/guides/api",
keyUrl: "https://supabase.com/dashboard/project/_/settings/api-keys",
keyHint: tr("Project Settings → API Keys. Адрес — Project URL вида https://<проект>.supabase.co."),
read: GET_ALL,
check: { method: "GET", path: "/rest/v1/" },
tags: ["база", "база данных", "database", "postgres"],
},
{
id: "notion",
name: "Notion",
kind: "docs",
baseUrl: "https://api.notion.com",
auth: "bearer",
headers: { "notion-version": "2022-06-28" },
docsUrl: "https://developers.notion.com/reference/intro",
keyUrl: "https://www.notion.so/profile/integrations",
keyHint: tr("Integrations → «New integration», скопируйте секрет и дайте интеграции доступ к нужным страницам (Share → Connections)."),
// Search and database queries are POST but only read.
read: ["GET /", "POST /v1/search", "POST /v1/databases/*/query", "POST /v1/data_sources/*/query"],
check: { method: "GET", path: "/v1/users/me" },
tags: ["заметки", "документы", "docs", "wiki"],
},
{
id: "airtable",
name: "Airtable",
kind: "data",
baseUrl: "https://api.airtable.com",
auth: "bearer",
docsUrl: "https://airtable.com/developers/web/api/introduction",
keyUrl: "https://airtable.com/create/tokens",
keyHint: tr("Developer hub → Personal access tokens → «Create token», выберите базы и права."),
read: GET_ALL,
check: { method: "GET", path: "/v0/meta/whoami" },
tags: ["таблицы", "база", "tables"],
},
{
id: "slack",
name: "Slack",
kind: "messaging",
baseUrl: "https://slack.com/api",
auth: "bearer",
docsUrl: "https://api.slack.com/methods",
keyUrl: "https://api.slack.com/apps",
// glossary-ignore: дословные названия пунктов меню и адрес внешнего сервиса — по ним пользователь находит ключ
keyHint: tr("Your Apps → ваше приложение → OAuth & Permissions → Bot User OAuth Token (xoxb-…)."),
// Slack takes changes through GET too — reading is listed by method.
read: ["GET /auth.test", "GET /conversations.list", "GET /conversations.info", "GET /conversations.history", "GET /conversations.replies", "GET /conversations.members", "GET /users.list", "GET /users.info", "GET /team.info", "GET /search.messages"],
check: { method: "GET", path: "/auth.test", bodyIncludes: '"ok":true' },
tags: ["чат", "сообщения", "chat"],
},
{
id: "twilio",
name: "Twilio",
kind: "messaging",
baseUrl: "https://api.twilio.com/2010-04-01",
auth: "basic",
docsUrl: "https://www.twilio.com/docs/usage/api",
keyUrl: "https://console.twilio.com/",
keyHint: tr("Console → Account Info: вставьте «Account SID:Auth Token» через двоеточие."),
read: GET_ALL,
check: { method: "GET", path: "/Accounts.json" },
idempotency: true,
tags: ["смс", "sms", "звонки", "whatsapp"],
},
{
id: "kaspi",
name: "Kaspi Магазин",
kind: "commerce",
baseUrl: "https://kaspi.kz/shop/api/v2",
auth: "header",
authParam: "X-Auth-Token",
headers: { accept: "application/vnd.api+json" },
docsUrl: "https://guide.kaspi.kz/partner/ru/shop/api/goods",
keyUrl: "https://kaspi.kz/mc/",
// glossary-ignore: дословные названия пунктов меню и адрес внешнего сервиса — по ним пользователь находит ключ
keyHint: tr("Кабинет продавца Kaspi → Настройки → Токен API: сгенерируйте и вставьте его."),
read: GET_ALL,
// Orders without a date filter answer 400 — still a sign the key was accepted.
check: { method: "GET", path: "/orders?page%5Bnumber%5D=0&page%5Bsize%5D=1", ok: [200, 400] },
tags: ["каспи", "kaspi", "заказы", "магазин", "казахстан"],
},
{
id: "2gis",
name: "2GIS",
kind: "maps",
baseUrl: "https://catalog.api.2gis.com",
auth: "query",
authParam: "key",
docsUrl: "https://docs.2gis.com/ru/api/search/places/overview",
keyUrl: "https://platform.2gis.ru/",
keyHint: tr("Кабинет 2GIS Platform Manager → ключи доступа: создайте ключ для Places API."),
read: GET_ALL,
// 2GIS answers HTTP 200 with meta.code in the body.
check: { method: "GET", path: "/3.0/items?q=cafe&page_size=1", bodyIncludes: '"code":200' },
tags: ["карты", "адреса", "2гис", "maps", "казахстан"],
},
];
const BY_ID = new Map(CONNECTION_CATALOG.map((s) => [s.id, s]));
export function catalogService(id: string | null | undefined): CatalogService | null {
return id ? (BY_ID.get(id) ?? null) : null;
}
/** Read rule of an own service (no catalog card): GET only. */
export const CUSTOM_READ_RULES = GET_ALL;
/** Rule «METHOD /a/* /b» matches on segment boundaries; `*` is exactly one segment. */
export function ruleMatches(rule: string, method: string, path: string): boolean {
const m = rule.trim().match(/^([A-Z]+)\s+(\/\S*)$/);
if (!m || m[1] !== method.toUpperCase()) return false;
const want = m[2]!.replace(/\/+$/, "");
if (!want) return true; // «GET /» — every path
const ruleSeg = want.split("/").slice(1);
const pathSeg = path.replace(/\/+$/, "").split("/").slice(1);
if (pathSeg.length < ruleSeg.length) return false;
return ruleSeg.every((r, i) => r === "*" ? !!pathSeg[i] : r === pathSeg[i]);
}
/** read = covered by the catalog's read rule (own service: GET); everything else is write. */
export function classifyRequest(catalogId: string | null | undefined, method: string, path: string): "read" | "write" {
const rules = catalogService(catalogId)?.read ?? CUSTOM_READ_RULES;
return rules.some((r) => ruleMatches(r, method, path)) ? "read" : "write";
}
/** Catalog search: name, id, tags and the kind's name; `kind` filters. Empty query — everything. */
export function searchCatalog(q: string, o: { kind?: string | null; kindText?: (k: CatalogKind) => string } = {}): CatalogService[] {
const words = q.toLowerCase().split(/\s+/).filter(Boolean);
return CONNECTION_CATALOG.filter((s) => {
if (o.kind && s.kind !== o.kind) return false;
if (!words.length) return true;
const kindWords = [CATALOG_KIND_TEXT[s.kind], o.kindText?.(s.kind) ?? ""].join(" ");
const hay = [s.name, s.id, ...(s.tags ?? []), kindWords].join(" ").toLowerCase();
return words.every((w) => hay.includes(w));
});
}