peppa/packages/core/src/connections.ts
peppa-bot 5019e1ad80
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 53с
peppa/build build: success за 36с
peppa/test test: success за 1546с
peppa-ci / ci (pull_request) Successful in 28m56s
Merge branch 'main' into task/pep-259
Миграция сроков разрешений переименована в 0034 (0033 заняла PEP-252).

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

1455 lines
82 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-234 Access Hub: a user's own external services («Подключения»). The key is stored
// encrypted (crypto.ts, rotated with PEPPA_SECRET — secrets-audit encryptedColumns) and is
// decrypted only here, in the server-side gateway `callConnection`, right before the request.
// No function returns it: not to the owner, a superadmin, an agent, the journal or MCP.
// Deny by default: an agent may call an operation only with an explicit grant of the owner for
// the agent's project (and the agent, or any agent of the project). See the change
// pep-234-access-hub (design.md — threat model).
import { asIs, m as tr } from "@peppa/shared/i18n";
import { agents, connectionGrants, connectionLog, connections, keyPrefix, projects, sessions, settings, users, type Db } from "@peppa/db";
import { and, asc, count, desc, eq, gt, inArray, isNotNull, isNull, sql } from "drizzle-orm";
import { lookup as dnsLookup, type LookupAddress } from "node:dns";
import { request as httpRequest, type IncomingMessage } from "node:http";
import { request as httpsRequest } from "node:https";
import { isIP } from "node:net";
import { getSetting, setSetting } from "./settings.ts";
import { isBlockedAddress, isGatewayProtocol, normalizeProtocolConfig, PROTOCOL_OPERATIONS, protocolAddress, protocolSecretError, ProtocolConfigError, type ConnectionProtocol, type GatewayProtocol } from "./connection-protocols.ts";
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";
import { connectionKeyForms, maskConnectionKey } from "./connection-mask.ts";
import { projectForUser } from "./users.ts";
import { pausedProjectIds } from "./project-pause.ts";
export { isBlockedAddress } from "./connection-protocols.ts";
export const CONNECTION_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const;
export type ConnectionMethod = (typeof CONNECTION_METHODS)[number];
export const CONNECTION_NAME_MAX = 60;
export const CONNECTION_SECRET_MAX_BYTES = 8 * 1024;
export const CONNECTION_BODY_MAX_BYTES = 64 * 1024;
export const CONNECTION_RESPONSE_MAX_BYTES = 256 * 1024;
export const CONNECTION_TIMEOUT_MS = 15_000;
/** Gateway calls per session per minute. */
export const CONNECTION_RATE_PER_MIN = 60;
export const CONNECTION_MAX_OPERATIONS = 20;
/** Why a call was refused or failed — stored in the journal, words for people in REASON_TEXT. */
export type ConnectionReason =
| "no_session"
| "not_isolated"
| "unknown_connection"
| "ambiguous_connection"
| "revoked"
| "needs_login"
| "no_grant"
| "expired"
| "idle_revoked"
| "operation_denied"
| "read_denied"
| "write_denied"
| "needs_approval"
| "owner_check"
| "bad_path"
| "bad_request"
| "rate_limited"
| "blocked_address"
| "redirect"
| "too_large"
| "timeout"
| "upstream_error"
// PEP-251
| "wrong_protocol"
| "auth_failed"
| "host_key_changed"
| "not_read_query"
| "outside_root"
| "not_found"
| "query_error";
export const CONNECTION_REASON_TEXT: Record<ConnectionReason, string> = {
no_session: tr("запрос не от агента FORGE"),
not_isolated: tr("агент работает без изоляции"),
unknown_connection: tr("нет такого подключения"),
ambiguous_connection: tr("несколько подключений с таким названием"),
revoked: tr("подключение отозвано"),
needs_login: tr("нужно заново войти в сервис"),
no_grant: tr("нет разрешения для проекта или агента"),
expired: tr("срок доступа истёк"),
idle_revoked: tr("доступ снят владельцем: им долго не пользовались"),
operation_denied: tr("операция не разрешена"),
read_denied: tr("чтение не разрешено"),
write_denied: tr("запись не разрешена"),
needs_approval: tr("нужно подтверждение владельца, а подтверждения пока не поддерживаются"),
owner_check: tr("проверка ключа владельцем"),
bad_path: tr("недопустимый путь"),
bad_request: tr("недопустимый запрос"),
rate_limited: tr("слишком много запросов"),
blocked_address: tr("адрес сервиса недоступен"),
redirect: tr("сервис перенаправил запрос"),
too_large: tr("слишком большой ответ"),
timeout: tr("сервис не ответил вовремя"),
upstream_error: tr("сервис недоступен"),
wrong_protocol: tr("у этого подключения другие операции"),
auth_failed: tr("сервис не принял пароль или ключ"),
host_key_changed: tr("ключ сервера изменился"),
not_read_query: tr("запрос не только читает данные"),
outside_root: tr("путь вне разрешённой папки"),
not_found: tr("не найдено"),
query_error: tr("сервис вернул ошибку"),
};
export interface ConnectionView {
id: number;
name: string;
baseUrl: string;
authKind: CatalogAuth;
authHeader: string | null;
/** PEP-249: catalog card id, null = own service. */
catalogId: string | null;
/** PEP-249: short name for agents (`stripe`). */
slug: string;
/** PEP-251: http, or a database / server / storage / mailbox. */
protocol: ConnectionProtocol;
/** PEP-251: host, port, user… of a non-HTTP connection (never the secret). */
config: Record<string, unknown> | null;
checkStatus: ConnectionCheckStatus | null;
checkedAt: Date | null;
/** 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;
/** PEP-259: own threshold of «revoke after N hours without calls»; null — platform default. */
idleRevokeHours: number | null;
createdAt: Date;
grants: ConnectionGrantView[];
}
export interface ConnectionGrantView {
id: number;
projectId: number;
projectKey: string;
projectName: string;
agentId: number | null;
agentName: string | null;
operations: string[];
readMode: GrantMode;
writeMode: GrantMode;
createdAt: Date;
/** PEP-259: the term chosen; «Продлить» gives the same again. */
term: GrantTerm;
/** null — until revoked. */
expiresAt: Date | null;
lastUsedAt: Date | null;
/** When the owner is asked whether to revoke it if nobody uses it (null — never: threshold 0, or already asked). */
idleAskAt: Date | null;
/** The owner was asked «снять?» and has not answered (PEP-259: revoked only by the owner's answer). */
idleAskedAt: Date | null;
/** active; expired — the term is over; idle — revoked by the owner after a «no use» request. */
state: GrantState;
endedAt: Date | null;
/** Hours of the «no use» threshold (for «не используется 72 ч» / «снято: 72 ч без дела»). */
idleHours: number;
}
/** PEP-259: how long a grant lives. */
export type GrantTerm = "1h" | "1d" | "7d" | "forever";
export const GRANT_TERMS: GrantTerm[] = ["1h", "1d", "7d", "forever"];
export const GRANT_TERM_MS: Record<GrantTerm, number | null> = { "1h": 3600_000, "1d": 24 * 3600_000, "7d": 7 * 24 * 3600_000, forever: null };
export const GRANT_TERM_TEXT: Record<GrantTerm, string> = { "1h": tr("1 час"), "1d": tr("1 день"), "7d": tr("7 дней"), forever: tr("до отзыва") };
/** Default term of a grant given by a button (web form, an agent's request). */
export const DEFAULT_GRANT_TERM: GrantTerm = "1d";
export type GrantState = "active" | "expired" | "idle";
/** PEP-259: «Дать: чтение» / «Дать: полные права» (full = reading and writing at once; PEP-235 mode later). */
export type GrantRights = "read" | "full";
export const GRANT_RIGHTS: Record<GrantRights, { readMode: GrantMode; writeMode: GrantMode }> = { read: { readMode: "auto", writeMode: "off" }, full: { readMode: "auto", writeMode: "auto" } };
export const isGrantTerm = (v: unknown): v is GrantTerm => GRANT_TERMS.includes(v as GrantTerm);
/** PEP-259: platform default of «ask the owner to revoke a grant after N hours without calls» (0 — never). */
export function defaultIdleRevokeHours(env: NodeJS.ProcessEnv = process.env): number {
const n = Number(env.PEPPA_CONNECTION_IDLE_HOURS);
return env.PEPPA_CONNECTION_IDLE_HOURS != null && env.PEPPA_CONNECTION_IDLE_HOURS !== "" && Number.isFinite(n) && n >= 0 ? Math.floor(n) : 72;
}
export const IDLE_HOURS_CHOICES = [24, 72, 168, 0] as const;
const idleHoursOf = (c: { idleRevokeHours: number | null }) => c.idleRevokeHours ?? defaultIdleRevokeHours();
type GrantRow = typeof connectionGrants.$inferSelect;
/** The countdown of «no use» starts at the last call, otherwise at the grant (or the deploy that added the column). */
const idleAnchor = (g: Pick<GrantRow, "lastUsedAt" | "grantedAt" | "createdAt">) => Math.max(g.lastUsedAt?.getTime() ?? 0, (g.grantedAt ?? g.createdAt).getTime());
export function grantState(g: Pick<GrantRow, "endedAt" | "expiresAt">, now: Date): GrantState {
if (g.endedAt) return "idle";
if (g.expiresAt && g.expiresAt.getTime() <= now.getTime()) return "expired";
return "active";
}
function idleAskAt(g: Pick<GrantRow, "lastUsedAt" | "grantedAt" | "createdAt">, hours: number, ask?: IdleAsk | null): Date | null {
if (hours <= 0) return null;
// After «Оставить» (or an unanswered request) the next request comes a full threshold later.
const from = Math.max(idleAnchor(g), ask?.at ?? 0);
return new Date(from + hours * 3600_000);
}
/** PEP-259: the request «снять?» about one grant — `settings` `connections.idle.ask:<grantId>`. */
interface IdleAsk {
at: number;
kept?: boolean;
}
const IDLE_ASK = "connections.idle.ask:";
/** The request is open: asked, not answered «Оставить», and nobody used the grant since. */
const askOpen = (g: Pick<GrantRow, "lastUsedAt" | "grantedAt" | "createdAt">, ask: IdleAsk | null | undefined): ask is IdleAsk => !!ask && !ask.kept && ask.at >= idleAnchor(g);
async function idleAsks(db: Db, grantIds: number[]): Promise<Map<number, IdleAsk>> {
if (!grantIds.length) return new Map();
const rows = await db.select().from(settings).where(inArray(settings.key, grantIds.map((id) => `${IDLE_ASK}${id}`)));
return new Map(rows.map((r) => [Number(r.key.slice(IDLE_ASK.length)), r.value as IdleAsk]));
}
export type GrantMode = "off" | "auto" | "ask";
export const GRANT_MODES: GrantMode[] = ["off", "auto", "ask"];
export type ConnectionCheckStatus = "ok" | "bad_key" | "down" | "host_key";
export const CONNECTION_CHECK_TEXT: Record<ConnectionCheckStatus, string> = {
ok: tr("ключ работает"),
bad_key: tr("ключ не подходит"),
down: tr("сервис не отвечает"),
host_key: tr("ключ сервера изменился"),
};
export interface ConnectionLogView {
id: number;
connectionId: number | null;
connectionName: string | null;
projectKey: string | null;
agentName: string | null;
sessionId: number | null;
method: string;
path: string;
decision: "allowed" | "denied" | "failed";
reason: string | null;
statusCode: number | null;
/** PEP-254: how long the service took (from the result row). */
durationMs: number | null;
/** done — a decision or a result is written; running — the call is in flight; unfinished — started, no result (a crash in the middle). */
state: "done" | "running" | "unfinished";
createdAt: Date;
}
export const allowPrivate = (env: NodeJS.ProcessEnv = process.env) => env.PEPPA_CONNECTIONS_ALLOW_PRIVATE === "1";
const allowUnisolated = (env: NodeJS.ProcessEnv = process.env) => env.PEPPA_CONNECTIONS_UNISOLATED === "on";
// ---------- addresses ----------
/** The service address of a connection: https, no login/password, no query or fragment. */
export function parseBaseUrl(raw: string, env: NodeJS.ProcessEnv = process.env): string {
const bad = () => new PeppaError(tr("Адрес сервиса должен начинаться с https:// и не содержать логин, пароль, «?» и «#»"));
let u: URL;
try {
u = new URL(raw.trim());
} catch {
throw bad();
}
if (u.protocol !== "https:" && !(u.protocol === "http:" && allowPrivate(env))) throw bad();
if (u.username || u.password || u.search || u.hash || raw.includes("?") || raw.includes("#")) throw bad();
if (!u.hostname) throw bad();
if (!allowPrivate(env) && (isBlockedAddress(u.hostname.replace(/^\[|\]$/g, "")) || /^(localhost|.*\.localhost|.*\.local|.*\.internal)$/i.test(u.hostname))) throw new PeppaError(tr("Этот адрес сервиса недоступен: укажите адрес в интернете"));
return u.origin + u.pathname.replace(/\/+$/, "");
}
/**
* A path from an agent → the clean path (with its query) or null. Refuses everything that could
* step out of the base address or confuse a server: dot segments, `//`, `\`, encoded dots and
* slashes, control characters, a scheme or `@`.
*/
export function cleanPath(raw: string): { path: string; query: string } | null {
if (typeof raw !== "string" || !raw.startsWith("/") || raw.length > 2048) return null;
if (/[\u0000-\u001f\u007f\s\\#@]/.test(raw)) return null;
const [path, ...rest] = raw.split("?");
const query = rest.join("?");
if (!path || path.includes("//") || /%(2e|2f|5c|25|00)/i.test(path)) return null;
if (/:/.test(path)) return null;
if (path.split("/").some((seg) => seg === "." || seg === "..")) return null;
if (/[^A-Za-z0-9\-._~!$&'()*+,;=:@%/]/.test(path)) return null;
if (/[^A-Za-z0-9\-._~!$&'()*+,;=:@%/?]/.test(query)) return null;
return { path, query };
}
/** "GET /items/" → {method, prefix}; null when malformed. */
export function parseOperation(op: string): { method: ConnectionMethod; prefix: string } | null {
const m = op.trim().match(/^([A-Za-z]+)\s+(\/\S*)$/);
if (!m) return null;
const method = m[1]!.toUpperCase() as ConnectionMethod;
if (!CONNECTION_METHODS.includes(method)) return null;
const c = cleanPath(m[2]!);
if (!c || c.query) return null;
const prefix = c.path.length > 1 ? c.path.replace(/\/+$/, "") : "/";
return { method, prefix };
}
/** Prefix match on a segment boundary: "/items" covers "/items" and "/items/5", not "/itemsX". */
export function operationAllows(ops: string[], method: string, path: string): boolean {
return ops.some((o) => {
const p = parseOperation(o);
if (!p || p.method !== method.toUpperCase()) return false;
return p.prefix === "/" || path === p.prefix || path.startsWith(`${p.prefix}/`);
});
}
export function normalizeOperations(raw: string[] | string, o: { allowEmpty?: boolean } = {}): string[] {
const list = (Array.isArray(raw) ? raw : raw.split(/\r?\n|,/)).map((s) => s.trim()).filter(Boolean);
if (!list.length && o.allowEmpty) return [];
if (!list.length) throw new PeppaError(tr("Укажите хотя бы одну операцию, например «GET /items»"));
if (list.length > CONNECTION_MAX_OPERATIONS) throw new PeppaError(tr("Не больше {n} операций в одном разрешении", { n: CONNECTION_MAX_OPERATIONS }));
const out: string[] = [];
for (const o of list) {
const p = parseOperation(o);
if (!p) throw new PeppaError(tr("Операция «{op}» не распознана: нужен метод (GET, POST, PUT, PATCH, DELETE) и путь с «/»", { op: o.slice(0, 80) }));
out.push(`${p.method} ${p.prefix}`);
}
return [...new Set(out)];
}
// ---------- owner's management ----------
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("Подключение не найдено"));
return c;
}
function nameError(name: string): string | null {
if (!name || name.length > CONNECTION_NAME_MAX) return tr("Название подключения: от 1 до {n} символов", { n: CONNECTION_NAME_MAX });
if (/[\u0000-\u001f\u007f]/.test(name)) return tr("Название подключения содержит недопустимые символы");
return null;
}
function secretError(secret: string): string | null {
if (!secret) return tr("Ключ доступа пустой");
if (Buffer.byteLength(secret) > CONNECTION_SECRET_MAX_BYTES) return tr("Ключ доступа больше 8 КБ");
if (/[\r\n\u0000]/.test(secret)) return tr("Ключ доступа должен быть одной строкой");
return null;
}
const HEADER_RE = /^[A-Za-z][A-Za-z0-9-]{0,63}$/;
const FORBIDDEN_HEADERS = new Set(["host", "content-length", "content-type", "transfer-encoding", "connection", "cookie", "accept-encoding"]);
// ---------- PEP-254: one data key per connection (envelope) ----------
const SECRET_V2 = "v2.";
const SECRET_AAD = "connection-secret";
/**
* Encrypts a connection key with a fresh data key of its own; the data key goes under
* PEPPA_SECRET. Decrypting one connection's data key opens nothing else.
*/
export function sealConnectionSecret(secret: string): { secretEnc: string; dekEnc: string } {
const dek = newDataKey();
return { secretEnc: SECRET_V2 + sealWithKey(dek, secret, SECRET_AAD), dekEnc: encrypt(dek.toString("base64url")) };
}
/** The key of a connection (gateway and check only — never returned anywhere else). */
export function openConnectionSecret(c: { secretEnc: string | null; dekEnc: string | null }): string | null {
if (!c.secretEnc) return null;
if (!c.dekEnc || !c.secretEnc.startsWith(SECRET_V2)) return decrypt(c.secretEnc); // an old row
return openWithKey(Buffer.from(decrypt(c.dekEnc), "base64url"), c.secretEnc.slice(SECRET_V2.length), SECRET_AAD);
}
/**
* Moves connections stored before PEP-254 (secret under PEPPA_SECRET) to their own data key.
* The key is decrypted and re-encrypted inside this process only. Unreadable rows are skipped.
*/
export async function upgradeConnectionKeys(db: Db): Promise<{ upgraded: number; unreadable: number }> {
const rows = await db.select({ id: connections.id, secretEnc: connections.secretEnc }).from(connections).where(and(isNotNull(connections.secretEnc), isNull(connections.dekEnc)));
let upgraded = 0;
let unreadable = 0;
for (const r of rows) {
let plain: string;
try {
plain = decrypt(r.secretEnc!);
} catch {
unreadable++;
continue;
}
await db.update(connections).set(sealConnectionSecret(plain)).where(and(eq(connections.id, r.id), isNull(connections.dekEnc)));
upgraded++;
}
return { upgraded, unreadable };
}
export interface ConnectionInput {
/** Default: the catalog card's name. */
name?: string;
/** Required for an own service and for catalog cards with their own address (Gitea…). */
baseUrl?: string;
secret: string;
authKind?: CatalogAuth;
authHeader?: string | null;
/** PEP-249: a catalog card — address, key placement and rules come from it. */
catalogId?: string | null;
/** PEP-251: a database, a server, a storage or a mailbox instead of an HTTP service. */
protocol?: ConnectionProtocol;
/** PEP-251: the form fields of that protocol (host, port, user…). */
config?: Record<string, unknown>;
}
const QUERY_PARAM_RE = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
const PATH_KEY_RE = /^[A-Za-z0-9:_.-]{4,512}$/;
/** «Мой магазин» → «moi-magazin»; latin, digits and «-», ≤ 40. */
export function slugify(name: string): string {
const map: Record<string, string> = { а: "a", б: "b", в: "v", г: "g", д: "d", е: "e", ё: "e", ж: "zh", з: "z", и: "i", й: "i", к: "k", л: "l", м: "m", н: "n", о: "o", п: "p", р: "r", с: "s", т: "t", у: "u", ф: "f", х: "h", ц: "c", ч: "ch", ш: "sh", щ: "sh", ъ: "", ы: "y", ь: "", э: "e", ю: "yu", я: "ya", ә: "a", ғ: "g", қ: "k", ң: "n", ө: "o", ұ: "u", ү: "u", һ: "h", і: "i" };
const latin = [...name.toLowerCase()].map((ch) => map[ch] ?? ch).join("");
return latin.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, "");
}
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;
for (let i = 2; ; i++) if (!taken.has(`${root}-${i}`)) return `${root}-${i}`;
}
function keyShapeError(authKind: CatalogAuth, secret: string): string | null {
if (authKind === "basic" && !/^[^:]+:.+$/.test(secret)) return tr("Для этого сервиса вставьте ключ как «логин:пароль» через двоеточие");
if (authKind === "path" && !PATH_KEY_RE.test(secret)) return tr("Ключ доступа содержит недопустимые символы");
return null;
}
export async function createConnection(db: Db, userId: number, i: ConnectionInput): Promise<ConnectionView> {
if (i.protocol && i.protocol !== "http") return createProtocolConnection(db, userId, i);
const card = i.catalogId ? catalogService(i.catalogId) : null;
if (i.catalogId && !card) throw new PeppaError(tr("Такого сервиса нет в каталоге"));
const name = (i.name ?? "").trim() || card?.name || "";
const err = nameError(name) ?? secretError(i.secret);
if (err) throw new PeppaError(err);
let baseRaw = card && !card.baseEditable ? card.baseUrl : (i.baseUrl ?? "").trim();
if (!baseRaw) throw new PeppaError(tr("Укажите адрес сервиса"));
if (card?.baseEditable && baseRaw === card.baseUrl) throw new PeppaError(tr("Укажите адрес своего сервиса вместо образца"));
const baseUrl = parseBaseUrl(baseRaw);
const authKind: CatalogAuth = card ? card.auth : (["header", "basic", "query"] as const).find((k) => k === i.authKind) ?? "bearer";
const authHeader = card ? (card.authParam ?? null) : authKind === "header" || authKind === "query" ? (i.authHeader ?? "").trim() : null;
if (!card && authKind === "header" && (!HEADER_RE.test(authHeader!) || FORBIDDEN_HEADERS.has(authHeader!.toLowerCase()))) throw new PeppaError(tr("Имя заголовка для ключа: латинские буквы, цифры и дефис, например X-Api-Key"));
if (!card && authKind === "query" && !QUERY_PARAM_RE.test(authHeader!)) throw new PeppaError(tr("Имя параметра для ключа: латинские буквы, цифры, дефис и подчёркивание, например key"));
const shape = keyShapeError(authKind, i.secret);
if (shape) throw new PeppaError(shape);
const [dup] = await db.select({ id: connections.id }).from(connections).where(and(eq(connections.ownerId, userId), eq(connections.name, name)));
if (dup) throw new PeppaError(tr("Подключение «{name}» уже есть", { name }));
const slug = await freeSlug(db, userId, card?.id ?? slugify(name));
const [row] = await db.insert(connections).values({ ownerId: userId, name, baseUrl, authKind, authHeader, catalogId: card?.id ?? null, slug, ...sealConnectionSecret(i.secret) }).returning({ id: connections.id });
return (await listConnections(db, userId)).find((c) => c.id === row!.id)!;
}
// ---------- PEP-251: platform's own servers that may have internal addresses ----------
const INTERNAL_HOSTS_KEY = "connections.internal_hosts";
/** Host names / addresses a connection may reach although they resolve to internal addresses. */
export async function internalHosts(db: Db): Promise<string[]> {
return (await getSetting<string[]>(db, INTERNAL_HOSTS_KEY)) ?? [];
}
/** Superadmin only: FORGE's own product servers. Everyone else gets internal addresses refused. */
export async function setInternalHosts(db: Db, actor: { id: number; login: string }, hosts: string[]): Promise<string[]> {
const { isSuperadmin } = await import("./monitor.ts");
if (!(await isSuperadmin(db, actor))) throw new PeppaError(tr("Это может только администратор FORGE"));
return writeInternalHosts(db, hosts);
}
/** The CLI (an admin tool on the machine itself) writes the list without a web actor. */
export async function writeInternalHosts(db: Db, hosts: string[]): Promise<string[]> {
const list = [...new Set(hosts.map((h) => h.trim().toLowerCase().replace(/^\[|\]$/g, "")).filter(Boolean))];
if (list.length > 50 || list.some((h) => !/^[a-z0-9.:-]{1,253}$/.test(h))) throw new PeppaError(tr("Список адресов: имена серверов или IP-адреса, не больше 50"));
await setSetting(db, INTERNAL_HOSTS_KEY, list);
return list;
}
async function createProtocolConnection(db: Db, userId: number, i: ConnectionInput): Promise<ConnectionView> {
const protocol = i.protocol as GatewayProtocol;
if (!isGatewayProtocol(protocol)) throw new PeppaError(tr("Такого вида подключения нет"));
const name = (i.name ?? "").trim();
const err = nameError(name) ?? protocolSecretError(protocol, i.secret);
if (err) throw new PeppaError(err);
let config: Record<string, unknown>;
try {
config = { ...normalizeProtocolConfig(protocol, i.config ?? {}, { internal: await internalHosts(db), allowPrivate: allowPrivate() }) };
} catch (e) {
if (e instanceof ProtocolConfigError) throw new PeppaError(e.message);
throw e;
}
const [dup] = await db.select({ id: connections.id }).from(connections).where(and(eq(connections.ownerId, userId), eq(connections.name, name)));
if (dup) throw new PeppaError(tr("Подключение «{name}» уже есть", { name }));
const slug = await freeSlug(db, userId, slugify(name) || protocol);
const baseUrl = protocolAddress(protocol, config as never);
const [row] = await db.insert(connections).values({ ownerId: userId, name, baseUrl, authKind: "bearer", authHeader: null, catalogId: null, slug, protocol, config, ...sealConnectionSecret(i.secret) }).returning({ id: connections.id });
return (await listConnections(db, userId)).find((c) => c.id === row!.id)!;
}
/**
* PEP-251: the server showed a new key and the owner confirms it is theirs — the next contact
* pins whatever the server shows.
*/
export async function resetHostKey(db: Db, userId: number, connectionId: number): Promise<void> {
const c = await ownConnection(db, userId, connectionId);
if (c.protocol !== "ssh") throw new PeppaError(tr("У этого подключения нет ключа сервера"));
await db.update(connections).set({ config: { ...(c.config ?? {}), hostKey: null }, checkStatus: null, checkedAt: null, checkAlertedAt: null }).where(eq(connections.id, c.id));
for (const g of await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, c.id))) await logEvent(db, { projectId: g.projectId, type: "connection_host_key_reset", payload: { connectionId: c.id } });
}
/** 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 = isGatewayProtocol(c.protocol) ? protocolSecretError(c.protocol, secret) : (secretError(secret) ?? keyShapeError(c.authKind, secret));
if (err) throw new PeppaError(err);
// A new key: the old check result and the «key stopped working» message no longer apply.
await db.update(connections).set({ ...sealConnectionSecret(secret), status: "active", revokedAt: null, checkStatus: null, checkedAt: null, checkAlertedAt: null }).where(eq(connections.id, connectionId));
}
/**
* Instant revoke: the stored key is wiped, so the very next gateway call is refused (`revoked`)
* 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<{ remote: "revoked" | "failed" | "unsupported" | null }> {
const c = await ownConnection(db, userId, connectionId);
// 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, ...(remote ? { remote } : {}) } });
return { remote };
}
export async function deleteConnection(db: Db, userId: number, connectionId: number): Promise<void> {
await revokeConnection(db, userId, connectionId);
await db.delete(connectionGrants).where(eq(connectionGrants.connectionId, connectionId));
await db.delete(connections).where(eq(connections.id, connectionId));
}
export interface GrantInput {
projectId: number;
agentId?: number | null;
/** «Тонкая настройка»: «METHOD /prefix» lines; may be empty when a mode is on. */
operations?: string[] | string;
/** PEP-249: reading / writing by the catalog's read rule. */
readMode?: GrantMode;
writeMode?: GrantMode;
/** PEP-259: how long; default — until revoked (the web form and buttons default to 1 day). */
term?: GrantTerm;
/** «Дать: чтение / полные права» — sets both modes. */
rights?: GrantRights;
now?: Date;
}
const mode = (m: unknown): GrantMode => (GRANT_MODES.includes(m as GrantMode) ? (m as GrantMode) : "off");
export async function grantConnection(db: Db, userId: number, connectionId: number, g: GrantInput): Promise<ConnectionGrantView> {
const c = await ownConnection(db, userId, connectionId);
if (c.status !== "active") throw new PeppaError(tr("Подключение отозвано: сначала задайте новый ключ доступа"));
await projectForUser(db, userId, g.projectId); // the owner gives access only to their projects
const agentId = g.agentId ?? null;
if (agentId != null) {
const [a] = await db.select({ id: agents.id }).from(agents).where(eq(agents.id, agentId));
if (!a) throw new PeppaError(tr("Агент не найден"));
}
const readMode = g.rights ? GRANT_RIGHTS[g.rights].readMode : mode(g.readMode);
const writeMode = g.rights ? GRANT_RIGHTS[g.rights].writeMode : mode(g.writeMode);
const term: GrantTerm = isGrantTerm(g.term) ? g.term : "forever";
const now = g.now ?? new Date();
const life = { term, expiresAt: GRANT_TERM_MS[term] == null ? null : new Date(now.getTime() + GRANT_TERM_MS[term]!), grantedAt: now, endedAt: null, endReason: null };
const anyMode = readMode !== "off" || writeMode !== "off";
const operations = normalizeOperations(g.operations ?? [], { allowEmpty: true });
if (!anyMode && !operations.length) throw new PeppaError(tr("Разрешите чтение, запись или хотя бы одну операцию"));
const existing = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, c.id), eq(connectionGrants.projectId, g.projectId)))).find((x) => x.agentId === agentId);
let id: number;
if (existing) {
await db.update(connectionGrants).set({ operations, readMode, writeMode, createdBy: userId, ...life }).where(eq(connectionGrants.id, existing.id));
id = existing.id;
} else {
const [row] = await db.insert(connectionGrants).values({ connectionId: c.id, projectId: g.projectId, agentId, operations, readMode, writeMode, createdBy: userId, ...life }).returning({ id: connectionGrants.id });
id = row!.id;
}
await logEvent(db, { projectId: g.projectId, type: "connection_granted", payload: { connectionId: c.id, agentId, operations, readMode, writeMode, term } });
return (await grantViews(db, [c.id], now)).find((x) => x.id === id)!;
}
/** PEP-259 «Продлить»: the same term again from now; brings back an expired or revoked-for-idle grant. */
export async function extendGrant(db: Db, userId: number, grantId: number, o: { now?: Date } = {}): Promise<ConnectionGrantView> {
const [g] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grantId));
if (!g) throw new PeppaError(tr("Разрешение не найдено"));
const c = await ownConnection(db, userId, g.connectionId);
if (c.status !== "active") throw new PeppaError(tr("Подключение отозвано: сначала задайте новый ключ доступа"));
const now = o.now ?? new Date();
const ms = GRANT_TERM_MS[g.term];
await db.update(connectionGrants).set({ expiresAt: ms == null ? null : new Date(now.getTime() + ms), grantedAt: now, endedAt: null, endReason: null }).where(eq(connectionGrants.id, g.id));
await logEvent(db, { projectId: g.projectId, type: "connection_grant_extended", payload: { connectionId: g.connectionId, agentId: g.agentId, term: g.term } });
return (await grantViews(db, [c.id], now)).find((x) => x.id === g.id)!;
}
/** PEP-259: the connection's «revoke a grant after N hours without calls»; null — platform default, 0 — never. */
export async function setConnectionIdleHours(db: Db, userId: number, connectionId: number, hours: number | null): Promise<void> {
const c = await ownConnection(db, userId, connectionId);
if (hours != null && (!Number.isInteger(hours) || hours < 0 || hours > 24 * 365)) throw new PeppaError(tr("Недопустимый срок"));
await db.update(connections).set({ idleRevokeHours: hours }).where(eq(connections.id, c.id));
}
export async function revokeGrant(db: Db, userId: number, grantId: number): Promise<void> {
const [g] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grantId));
if (!g) throw new PeppaError(tr("Разрешение не найдено"));
await ownConnection(db, userId, g.connectionId);
await db.delete(connectionGrants).where(eq(connectionGrants.id, grantId));
await logEvent(db, { projectId: g.projectId, type: "connection_grant_revoked", payload: { connectionId: g.connectionId, agentId: g.agentId } });
}
async function grantViews(db: Db, connectionIds: number[], now: Date = new Date()): Promise<Array<ConnectionGrantView & { connectionId: number }>> {
if (!connectionIds.length) return [];
const rows = await db
.select({
id: connectionGrants.id,
connectionId: connectionGrants.connectionId,
projectId: connectionGrants.projectId,
projectKey: projects.key,
projectName: projects.name,
agentId: connectionGrants.agentId,
agentName: agents.name,
operations: connectionGrants.operations,
readMode: connectionGrants.readMode,
writeMode: connectionGrants.writeMode,
createdAt: connectionGrants.createdAt,
term: connectionGrants.term,
expiresAt: connectionGrants.expiresAt,
grantedAt: connectionGrants.grantedAt,
lastUsedAt: connectionGrants.lastUsedAt,
endedAt: connectionGrants.endedAt,
idleRevokeHours: connections.idleRevokeHours,
})
.from(connectionGrants)
.innerJoin(projects, eq(projects.id, connectionGrants.projectId))
.innerJoin(connections, eq(connections.id, connectionGrants.connectionId))
.leftJoin(agents, eq(agents.id, connectionGrants.agentId))
.where(inArray(connectionGrants.connectionId, connectionIds))
.orderBy(asc(projects.key), asc(connectionGrants.id));
const asks = await idleAsks(db, rows.map((r) => r.id));
return rows.map(({ grantedAt, idleRevokeHours, ...r }) => {
const idleHours = idleHoursOf({ idleRevokeHours });
const state = grantState(r, now);
const ask = asks.get(r.id);
const open = state === "active" && askOpen({ ...r, grantedAt }, ask);
return { ...r, state, idleHours, idleAskedAt: open ? new Date(ask!.at) : null, idleAskAt: state === "active" && !open ? idleAskAt({ ...r, grantedAt }, idleHours, ask) : null };
});
}
/** Short name for agents; connections made before PEP-249 get one from their name. */
export const connectionSlug = (r: { id: number; name: string; slug: string | null }) => r.slug || slugify(r.name) || `c${r.id}`;
/** The user's own connections with grants; never the key. */
export async function listConnections(db: Db, userId: number, o: { now?: Date } = {}): Promise<ConnectionView[]> {
const rows = await db.select().from(connections).where(eq(connections.ownerId, userId)).orderBy(asc(connections.name));
const grants = await grantViews(db, rows.map((r) => r.id), o.now);
return rows.map((r) => ({
id: r.id,
name: r.name,
baseUrl: r.baseUrl,
authKind: r.authKind,
authHeader: r.authHeader,
catalogId: r.catalogId,
slug: connectionSlug(r),
protocol: r.protocol,
config: r.config ?? null,
checkStatus: r.checkStatus,
checkedAt: r.checkedAt,
status: r.status,
hasKey: !!r.secretEnc,
oauthProvider: r.oauthProvider ?? null,
oauthScopes: r.oauthScopes ?? [],
revokedAt: r.revokedAt,
lastUsedAt: r.lastUsedAt,
idleRevokeHours: r.idleRevokeHours,
createdAt: r.createdAt,
grants: grants.filter((g) => g.connectionId === r.id).map(({ connectionId: _, ...g }) => g),
}));
}
/** The owner's journal (all their connections, or one). */
export async function connectionJournal(db: Db, userId: number, o: { connectionId?: number; limit?: number; now?: Date } = {}): Promise<ConnectionLogView[]> {
const calls = await db
.select({
id: connectionLog.id,
connectionId: connectionLog.connectionId,
connectionName: connectionLog.connectionName,
projectKey: sql<string | null>`coalesce(${connectionLog.projectKey}, ${projects.key})`,
agentName: connectionLog.agentName,
sessionId: connectionLog.sessionId,
method: connectionLog.method,
path: connectionLog.path,
decision: connectionLog.decision,
reason: connectionLog.reason,
statusCode: connectionLog.statusCode,
durationMs: connectionLog.durationMs,
createdAt: connectionLog.createdAt,
})
.from(connectionLog)
.leftJoin(projects, eq(projects.id, connectionLog.projectId))
.where(and(eq(connectionLog.ownerId, userId), eq(connectionLog.kind, "call"), o.connectionId != null ? eq(connectionLog.connectionId, o.connectionId) : undefined))
.orderBy(desc(connectionLog.id))
.limit(Math.min(o.limit ?? 100, 500));
// PEP-254: an allowed call is written before the request; its result is a row of its own.
const ids = calls.filter((c) => c.decision === "allowed" && c.statusCode == null).map((c) => c.id);
const results = ids.length ? await db.select().from(connectionLog).where(and(eq(connectionLog.ownerId, userId), eq(connectionLog.kind, "result"), inArray(connectionLog.parentId, ids))) : [];
const byParent = new Map(results.map((r) => [r.parentId!, r]));
const now = (o.now ?? new Date()).getTime();
return calls.map((c) => {
const r = byParent.get(c.id);
if (r) return { ...c, decision: r.decision, reason: r.reason, statusCode: r.statusCode, durationMs: r.durationMs, state: "done" as const };
const open = c.decision === "allowed" && c.statusCode == null && ids.includes(c.id);
if (!open) return { ...c, state: "done" as const };
return { ...c, state: now - c.createdAt.getTime() > CONNECTION_TIMEOUT_MS * 2 ? ("unfinished" as const) : ("running" as const) };
});
}
/** Agents to choose from in a grant (the platform's team). */
export async function grantableAgents(db: Db): Promise<Array<{ id: number; name: string }>> {
return db.select({ id: agents.id, name: agents.name }).from(agents).orderBy(asc(agents.name));
}
// ---------- agent side ----------
export interface SessionCtx {
id: number;
projectId: number;
agentId: number | null;
agentName: string | null;
container: string | null;
}
export const agentIsolated = (s: SessionCtx, env: NodeJS.ProcessEnv = process.env) => !!s.container || allowUnisolated(env);
/** false: the session's agent runs outside a container and the gateway refuses it. */
export async function sessionIsolated(db: Db, sessionId: number): Promise<boolean> {
const s = await sessionCtx(db, sessionId);
return !!s && agentIsolated(s);
}
export async function sessionCtx(db: Db, sessionId: number | null | undefined): Promise<SessionCtx | null> {
if (sessionId == null) return null;
const [s] = await db
.select({ id: sessions.id, projectId: sessions.projectId, agentId: sessions.agentId, agentName: agents.name, container: sessions.container })
.from(sessions)
.leftJoin(agents, eq(agents.id, sessions.agentId))
.where(eq(sessions.id, sessionId));
return s ?? null;
}
export interface AgentConnection {
id: number;
name: string;
/** Short name to call it by (`stripe`). */
slug: string;
/** Catalog service name, null = own service. */
service: string | null;
baseUrl: string;
docsUrl: string | null;
readMode: GrantMode;
writeMode: GrantMode;
operations: string[];
checkStatus: ConnectionCheckStatus | null;
/** PEP-251: http — call_connection; others — use_connection with these operations. */
protocol: ConnectionProtocol;
protocolOperations: Array<{ name: string; kind: "read" | "write"; args: string[]; help: string }>;
/** PEP-259: the latest end among the agent's live grants; null — at least one is until revoked. */
expiresAt: Date | null;
}
const RANK: Record<GrantMode, number> = { off: 0, ask: 1, auto: 2 };
/** The widest of several grants: auto > ask > off. */
export const widest = (a: GrantMode, b: GrantMode): GrantMode => (RANK[b] > RANK[a] ? b : a);
/** What this session's agent may use: active connections granted to its project and agent. */
export async function agentConnections(db: Db, sessionId: number, o: { now?: Date } = {}): Promise<AgentConnection[]> {
const now = o.now ?? new Date();
const s = await sessionCtx(db, sessionId);
// Like the gateway: an unisolated agent is refused, so it is shown nothing.
if (!s || !agentIsolated(s)) return [];
const rows = await db
.select({ c: connections, g: connectionGrants, 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), 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;
if (grantState(r.g, now) !== "active") continue;
const card = catalogService(r.c.catalogId);
const proto = r.c.protocol;
const protocolOperations = isGatewayProtocol(proto) ? Object.entries(PROTOCOL_OPERATIONS[proto]).map(([name, op]) => ({ name, ...op })) : [];
const first = !by.has(r.c.id);
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, protocol: proto, protocolOperations, expiresAt: null };
c.expiresAt = first ? r.g.expiresAt : c.expiresAt && r.g.expiresAt ? (r.g.expiresAt > c.expiresAt ? r.g.expiresAt : c.expiresAt) : null;
c.operations = [...new Set([...c.operations, ...r.operations])];
c.readMode = widest(c.readMode, r.readMode);
c.writeMode = widest(c.writeMode, r.writeMode);
by.set(r.c.id, c);
}
return [...by.values()];
}
/**
* The gateway's decision for one agent request over its grants (PEP-249): a «Тонкая настройка»
* line allows; otherwise the request is read or write by the catalog rule and the widest mode
* decides — auto runs, ask waits for the owner (PEP-235; until then refused), off refuses.
*/
export function grantDecision(catalogId: string | null, grants: Array<{ operations: string[]; readMode: GrantMode; writeMode: GrantMode }>, method: string, path: string): ConnectionReason | null {
if (operationAllows(grants.flatMap((g) => g.operations), method, path)) return null;
const kind = classifyRequest(catalogId, method, path);
const m = grants.reduce<GrantMode>((acc, g) => widest(acc, kind === "read" ? g.readMode : g.writeMode), "off");
if (m === "auto") return null;
if (m === "ask") return "needs_approval";
// No mode at all and only fine-grained lines: keep PEP-234's wording.
if (grants.every((g) => g.readMode === "off" && g.writeMode === "off")) return "operation_denied";
return kind === "read" ? "read_denied" : "write_denied";
}
/** Target URL and headers of a request with the key in its place; null — the path escapes the base. */
function buildRequest(conn: typeof connections.$inferSelect, secret: string, clean: { path: string; query: string }, contentType: string | null, body: Buffer | null): { url: URL; headers: Record<string, string> } | null {
const card = catalogService(conn.catalogId);
const base = new URL(conn.baseUrl);
const basePath = base.pathname.replace(/\/$/, "");
// Only Telegram's catalog card uses it: the key goes right after the base as «/bot<key>».
const keyPath = conn.authKind === "path" ? `${basePath}/bot${secret}` : basePath;
const params = new URLSearchParams(clean.query);
if (conn.authKind === "query" && conn.authHeader) {
params.delete(conn.authHeader); // the agent can't pass its own key
params.set(conn.authHeader, secret);
}
const qs = params.toString();
const url = new URL(base.origin + keyPath + clean.path + (qs ? `?${qs}` : ""));
if (url.origin !== base.origin || !(url.pathname === keyPath || url.pathname.startsWith(`${keyPath}/`))) return null;
// Only these headers reach the service: the agent can't add or override any other.
const headers: Record<string, string> = { "user-agent": "PeppaFactory-AccessHub/1", accept: "*/*" };
for (const [k, v] of Object.entries(card?.headers ?? {})) headers[k.toLowerCase()] = v;
if (contentType) headers["content-type"] = contentType;
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" || conn.authKind === "oauth") headers.authorization = `Bearer ${secret}`;
return { url, headers };
}
export type GrantedRow = { c: typeof connections.$inferSelect; g: typeof connectionGrants.$inferSelect; agentId: number | null; operations: string[]; readMode: GrantMode; writeMode: GrantMode };
/** The connection among those granted to this session's project (never by a bare id of someone else). */
export async function findGranted(db: Db, s: SessionCtx, connection: string | number): Promise<{ matches: GrantedRow[] } | { reason: "ambiguous_connection" | "unknown_connection" }> {
const granted = await db
.select({ c: connections, g: connectionGrants, agentId: connectionGrants.agentId, operations: connectionGrants.operations, readMode: connectionGrants.readMode, writeMode: connectionGrants.writeMode })
.from(connectionGrants)
.innerJoin(connections, eq(connections.id, connectionGrants.connectionId))
.where(eq(connectionGrants.projectId, s.projectId));
const want = String(connection).trim();
const byId = /^\d+$/.test(want) ? granted.filter((g) => g.c.id === Number(want)) : [];
const byName = granted.filter((g) => g.c.name === want);
const matches = byId.length ? byId : byName.length ? byName : granted.filter((g) => connectionSlug(g.c) === want.toLowerCase());
const ids = new Set(matches.map((g) => g.c.id));
if (ids.size > 1) return { reason: "ambiguous_connection" };
if (!ids.size) return { reason: "unknown_connection" };
return { matches };
}
/**
* PEP-259: the grants of this agent that still work. With none left, the reason: no grant at all,
* the term is over, or it was revoked for no use.
*/
export function liveGrants(matches: GrantedRow[], agentId: number | null, now: Date): { mine: GrantedRow[] } | { reason: "no_grant" | "expired" | "idle_revoked" } {
const ours = matches.filter((g) => g.agentId == null || g.agentId === agentId);
if (!ours.length) return { reason: "no_grant" };
const mine = ours.filter((g) => grantState(g.g, now) === "active");
if (!mine.length) return { reason: ours.some((g) => grantState(g.g, now) === "expired") ? "expired" : "idle_revoked" };
return { mine };
}
/** The grant is in use: the idle countdown starts again. */
export async function touchGrants(db: Db, grants: GrantedRow[], now: Date): Promise<void> {
if (grants.length) await db.update(connectionGrants).set({ lastUsedAt: now }).where(inArray(connectionGrants.id, grants.map((g) => g.g.id)));
}
/** Calls of this session in the last minute (one budget for every kind of connection). */
export async function recentCalls(db: Db, sessionId: number, now: Date): Promise<number> {
const [{ n }] = (await db.select({ n: count() }).from(connectionLog).where(and(eq(connectionLog.sessionId, sessionId), eq(connectionLog.kind, "call"), gt(connectionLog.createdAt, new Date(now.getTime() - 60_000))))) as [{ n: number }];
return n;
}
// ---------- 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). */
connection: string | number;
method: string;
path: string;
body?: string | null;
contentType?: string | null;
}
export type ConnectionResult =
| { ok: true; status: number; contentType: string | null; body: string; truncated: boolean }
| { ok: false; reason: ConnectionReason; status?: number };
/** One outbound request, injectable in tests. */
export type ConnectionFetch = (o: { url: URL; method: string; headers: Record<string, string>; body: Buffer | null; allowInternal?: boolean }) => Promise<{ status: number; contentType: string | null; body: Buffer; truncated: boolean; location?: boolean }>;
export class Refused extends Error {
reason: ConnectionReason;
constructor(reason: ConnectionReason) {
super(reason);
this.reason = reason;
}
}
/**
* Real request: a fresh socket per call (no keep-alive reuse past the address check), no redirects, every address the host resolves to at connect time is checked
* (so DNS rebinding can't swap a public name for 127.0.0.1), size and time limits.
*/
export const defaultConnectionFetch: ConnectionFetch = ({ url, method, headers, body, allowInternal }) =>
new Promise((resolve, reject) => {
const guardedLookup = (host: string, opts: object, cb: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family?: number) => void) => {
dnsLookup(host, { ...opts, all: true }, (err, addrs) => {
if (err) return cb(err, "", 4);
const list = addrs as LookupAddress[];
if (!list.length || (!allowPrivate() && !allowInternal && list.some((a) => isBlockedAddress(a.address)))) return cb(Object.assign(new Error("blocked address"), { code: "PEPPA_BLOCKED" }), "", 4);
if ((opts as { all?: boolean }).all) return cb(null, list);
cb(null, list[0]!.address, list[0]!.family);
});
};
const literal = url.hostname.replace(/^\[|\]$/g, "");
if (isIP(literal) && !allowPrivate() && !allowInternal && isBlockedAddress(literal)) return reject(new Refused("blocked_address"));
const req = (url.protocol === "https:" ? httpsRequest : httpRequest)(url, { method, headers, lookup: guardedLookup as never, timeout: CONNECTION_TIMEOUT_MS, agent: false }, (res: IncomingMessage) => {
const chunks: Buffer[] = [];
let size = 0;
let truncated = false;
res.on("data", (c: Buffer) => {
if (truncated) return;
size += c.length;
if (size > CONNECTION_RESPONSE_MAX_BYTES) {
truncated = true;
chunks.push(c.subarray(0, c.length - (size - CONNECTION_RESPONSE_MAX_BYTES)));
res.destroy();
return;
}
chunks.push(c);
});
const done = () => resolve({ status: res.statusCode ?? 0, contentType: (res.headers["content-type"] as string | undefined) ?? null, body: Buffer.concat(chunks), truncated, location: !!res.headers.location });
res.on("end", done);
res.on("close", done);
res.on("error", () => (truncated ? done() : reject(new Refused("upstream_error"))));
});
req.on("timeout", () => req.destroy(new Refused("timeout")));
req.on("error", (e: NodeJS.ErrnoException) => reject(e instanceof Refused ? e : new Refused(e.code === "PEPPA_BLOCKED" ? "blocked_address" : "upstream_error")));
if (body) req.write(body);
req.end();
});
const CONTENT_TYPE_RE = /^[a-z]+\/[a-z0-9.+-]+(;\s*charset=[a-z0-9-]+)?$/i;
/**
* The gateway: decides, injects the key, calls the service, masks the key in the answer and
* writes one journal row (method, path without query, decision, reason — never a key or a body).
*/
export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?: ConnectionFetch; now?: Date; env?: NodeJS.ProcessEnv } = {}): Promise<ConnectionResult> {
const now = o.now ?? new Date();
const method = String(call.method ?? "").toUpperCase();
const rawPath = String(call.path ?? "");
const logPath = (rawPath.split("?")[0] ?? "").slice(0, 300) || "/";
const s = await sessionCtx(db, call.sessionId);
let conn: typeof connections.$inferSelect | null = null;
// PEP-254: every row goes into the owner's hash chain; an allowed call is written BEFORE the request.
const record = async (decision: ConnectionJournalDecision, reason: ConnectionReason | null, statusCode: number | null, extra: { kind?: "call" | "result"; parentId?: number; durationMs?: number } = {}): Promise<number | null> => {
if (!conn) return null; // nothing to attribute: an unknown connection is not someone's journal
return appendJournal(db, {
ownerId: conn.ownerId,
kind: extra.kind ?? "call",
parentId: extra.parentId ?? null,
connectionId: conn.id,
connectionName: conn.name,
projectId: s?.projectId ?? null,
sessionId: s?.id ?? null,
agentId: s?.agentId ?? null,
agentName: s?.agentName ?? null,
method: method.slice(0, 10) || "?",
path: logPath,
decision,
reason,
statusCode,
durationMs: extra.durationMs ?? null,
createdAt: extra.kind === "result" ? new Date(now.getTime() + (extra.durationMs ?? 0)) : now,
});
};
const deny = async (reason: ConnectionReason): Promise<ConnectionResult> => {
await record("denied", reason, null);
return { ok: false, reason };
};
if (!s) return { ok: false, reason: "no_session" };
const found = await findGranted(db, s, call.connection);
if ("reason" in found) return { ok: false, reason: found.reason };
const matches = found.matches;
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");
if (conn.protocol !== "http") return deny("wrong_protocol");
const live = liveGrants(matches, s.agentId, now);
if ("reason" in live) return deny(live.reason);
const mine = live.mine;
if (!CONNECTION_METHODS.includes(method as ConnectionMethod)) return deny("bad_request");
const clean = cleanPath(rawPath);
if (!clean) return deny("bad_path");
const refusal = grantDecision(conn.catalogId, mine, method, clean.path);
if (refusal) return deny(refusal);
const body = call.body == null || call.body === "" ? null : Buffer.from(String(call.body));
if (body && (body.length > CONNECTION_BODY_MAX_BYTES || method === "GET")) return deny("bad_request");
const contentType = call.contentType?.trim() || (body ? "application/json" : null);
if (contentType && !CONTENT_TYPE_RE.test(contentType)) return deny("bad_request");
if ((await recentCalls(db, s.id, now)) >= CONNECTION_RATE_PER_MIN) return deny("rate_limited");
// 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.
let built = buildRequest(conn, cred.secret, clean, contentType, body);
if (!built) return deny("bad_path");
// Written before the service is called: a crash in the middle leaves «started, no result».
const callId = (await record("allowed", null, null))!;
// PEP-259: the grant is in use — the idle countdown starts again (even if the service then fails).
await touchGrants(db, mine, now);
const started = Date.now();
const result = (decision: ConnectionJournalDecision, reason: ConnectionReason | null, statusCode: number | null) =>
record(decision, reason, statusCode, { kind: "result", parentId: callId, durationMs: Date.now() - started });
try {
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 };
}
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).
// PEP-258: every recognisable form of the key (base64, URL, hex, JSON, wrapped, cut at the limit).
const forms = connectionKeyForms(cred.secret, conn.authKind);
const text = maskConnectionKey(res.body.toString("utf8"), forms, { truncated: res.truncated });
const answerType = res.contentType == null ? null : maskConnectionKey(res.contentType, forms);
return { ok: true, status: res.status, contentType: answerType, body: text, truncated: res.truncated };
} catch (e) {
const reason = e instanceof Refused ? e.reason : "upstream_error";
await result(reason === "blocked_address" ? "denied" : "failed", reason, null);
return { ok: false, reason };
}
}
// ---------- PEP-249: checking a connection ----------
export const CONNECTION_CHECK_EVERY_MS = 24 * 3600_000;
const CHECK_BATCH = 10;
export interface ConnectionCheckResult {
status: ConnectionCheckStatus;
/** Own service without a check call: it answered, the key will show itself on the first request. */
reachableOnly?: boolean;
httpStatus?: number;
checkedAt: Date;
}
/** What a check answer means (pure — tested per catalog card). */
export function judgeCheck(check: CatalogCheck | null, res: { status: number; body: string } | null): { status: ConnectionCheckStatus; reachableOnly?: boolean } {
if (!res) return { status: "down" };
if (!check) {
if (res.status === 401 || res.status === 403) return { status: "bad_key" };
return res.status > 0 && res.status < 500 ? { status: "ok", reachableOnly: true } : { status: "down" };
}
const badKey = check.badKey ?? [401, 403];
if (badKey.includes(res.status)) return { status: "bad_key" };
const ok = check.ok ? check.ok.includes(res.status) : res.status >= 200 && res.status < 300;
if (ok) return check.bodyIncludes && !res.body.replace(/\s+/g, "").includes(check.bodyIncludes) ? { status: "bad_key" } : { status: "ok" };
return { status: "down" };
}
export interface ConnectionCheckOptions {
fetch?: ConnectionFetch;
now?: Date;
/** PEP-251: database / SSH / mail drivers (tests: mocks). */
drivers?: import("./connection-drivers.ts").GatewayDrivers;
/** PEP-252: who tells the owner that a sign-in ended (tests). */
notify?: (db: Db, c: { id: number; ownerId: number; name: string }) => Promise<void>;
}
async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: ConnectionCheckOptions): Promise<ConnectionCheckResult & { relogin?: boolean }> {
if (conn.protocol !== "http") return (await import("./connection-gateway.ts")).protocolCheck(db, conn, o);
const now = o.now ?? new Date();
const check = catalogService(conn.catalogId)?.check ?? null;
const method = check?.method ?? "GET";
const raw = check?.path ?? "/";
const clean = cleanPath(raw) ?? { path: "/", query: "" };
let res: { status: number; body: string } | null = null;
// PEP-254: the check is journaled like a gateway call — the call first, its result after.
const entry = { ownerId: conn.ownerId, connectionId: conn.id, connectionName: conn.name, method, path: clean.path.slice(0, 300), createdAt: now };
const callId = appendJournal(db, { ...entry, kind: "call", decision: "allowed", reason: "owner_check", statusCode: null });
const started = Date.now();
let relogin = false;
try {
let cred = await connectionCredential(db, conn, { now, notify: o.notify });
const send = async (c: ConnectionCredential & { ok: true }) => {
const built = buildRequest(conn, c.secret, clean, null, null);
if (!built) return null;
// Own service: the check is the base address itself (no trailing «/» added).
if (!check) built.url.pathname = built.url.pathname.replace(/\/$/, "") || "/";
const r = await (o.fetch ?? defaultConnectionFetch)({ url: built.url, method, headers: built.headers, body: null });
return r.status >= 300 && r.status < 400 && r.location ? null : { status: r.status, body: r.body.toString("utf8") };
};
if (!cred.ok) relogin = cred.reason === "needs_login";
else {
res = await send(cred);
// PEP-252: a sign-in token the service no longer takes — refresh once, like the gateway.
if (res?.status === 401 && cred.refreshable && !cred.refreshed) {
cred = await connectionCredential(db, conn, { now, force: true, notify: o.notify });
if (!cred.ok) relogin = cred.reason === "needs_login";
else res = await send(cred);
}
}
} catch {
res = null;
}
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, ...(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: ConnectionCheckOptions = {}): 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);
}
/**
* Daily check (watchdog): active connections with a key not checked for a day. A key that
* stopped working sends its owner ONE message (`check_alerted_at`); a working check or a new key
* clears the mark.
*/
export async function connectionCheckTick(db: Db, o: ConnectionCheckOptions & { notify?: (db: Db, conn: { id: number; ownerId: number; name: string }) => Promise<void> } = {}): Promise<number> {
if (process.env.PEPPA_CONNECTION_CHECK === "off") return 0;
const now = o.now ?? new Date();
const due = (await db.select().from(connections).where(eq(connections.status, "active")).orderBy(asc(connections.checkedAt)))
.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, drivers: o.drivers, 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 });
}
}
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) });
const key = `connection-key:${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);
}
// ---------- PEP-259: terms and the «no use» request ----------
/** Revoked and expired grants stay visible (extend in one click) this long, then go. */
export const GRANT_KEEP_ENDED_MS = 30 * 24 * 3600_000;
const IDLE_DIGEST = "connections.idle.digest:";
const IDLE_DIGEST_SENT = "connections.idle.sent:";
const DIGEST_EVERY_MS = 24 * 3600_000;
/** Buttons in one request message (Telegram keeps it readable). */
const DIGEST_BUTTONS = 5;
export interface IdleDigestItem {
grantId: number;
connection: string;
project: string;
agent: string | null;
hours: number;
}
/**
* Watchdog tick (PEP-259, PM: revoked only on request): a live grant nobody called for the
* connection's threshold (default 72 h) is NOT revoked — its owner gets a request «снять?»
* (one summary a day, buttons «Снять» / «Оставить» in Telegram and on «Подключения»). The
* agent keeps working meanwhile; unanswered, the request comes again a threshold later.
* Paused projects are skipped. Ended grants older than 30 days are deleted.
* Returns how many grants were asked about.
*/
export async function grantExpiryTick(db: Db, o: { now?: Date; notify?: (db: Db, ownerId: number, items: IdleDigestItem[]) => Promise<void> } = {}): Promise<number> {
if (process.env.PEPPA_CONNECTION_IDLE === "off") return 0;
const now = o.now ?? new Date();
const paused = await pausedProjectIds(db);
const rows = await db
.select({ g: connectionGrants, c: connections, projectKey: projects.key, agentName: agents.name })
.from(connectionGrants)
.innerJoin(connections, eq(connections.id, connectionGrants.connectionId))
.innerJoin(projects, eq(projects.id, connectionGrants.projectId))
.leftJoin(agents, eq(agents.id, connectionGrants.agentId))
.where(and(isNull(connectionGrants.endedAt), eq(connections.status, "active")));
const asks = await idleAsks(db, rows.map((r) => r.g.id));
let asked = 0;
for (const r of rows) {
if (paused.has(r.g.projectId) || grantState(r.g, now) !== "active") continue;
const hours = idleHoursOf(r.c);
const ask = asks.get(r.g.id);
if (askOpen(r.g, ask) && now.getTime() - ask.at < hours * 3600_000) continue;
const at = idleAskAt(r.g, hours, ask);
if (!at || at.getTime() > now.getTime()) continue;
asked++;
await setSetting(db, `${IDLE_ASK}${r.g.id}`, { at: now.getTime() } satisfies IdleAsk);
await logEvent(db, { projectId: r.g.projectId, type: "connection_grant_idle", payload: { connectionId: r.c.id, grantId: r.g.id, agentId: r.g.agentId, hours } });
const key = `${IDLE_DIGEST}${r.c.ownerId}`;
const list = ((await getSetting<IdleDigestItem[]>(db, key)) ?? []).filter((i) => i.grantId !== r.g.id);
list.push({ grantId: r.g.id, connection: r.c.name, project: r.projectKey, agent: r.agentName, hours });
await setSetting(db, key, list.slice(-50));
}
// Ended long ago — gone (the journal keeps the history).
const old = new Date(now.getTime() - GRANT_KEEP_ENDED_MS);
const gone = await db
.delete(connectionGrants)
.where(sql`(${connectionGrants.endedAt} is not null and ${connectionGrants.endedAt} < ${old.getTime()}) or (${connectionGrants.endedAt} is null and ${connectionGrants.expiresAt} is not null and ${connectionGrants.expiresAt} < ${old.getTime()})`)
.returning({ id: connectionGrants.id });
if (gone.length) await db.delete(settings).where(inArray(settings.key, gone.map((g) => `${IDLE_ASK}${g.id}`)));
// One request a day per owner, only with grants still waiting for the answer.
for (const d of await db.select().from(settings).where(keyPrefix(settings.key, IDLE_DIGEST))) {
const ownerId = Number(d.key.slice(IDLE_DIGEST.length));
const queued = (d.value as IdleDigestItem[] | null) ?? [];
if (!Number.isFinite(ownerId) || !queued.length) continue;
const sent = await getSetting<number>(db, `${IDLE_DIGEST_SENT}${ownerId}`);
if (sent != null && now.getTime() - sent < DIGEST_EVERY_MS) continue;
const still = await idleAsks(db, queued.map((i) => i.grantId));
const live = await db.select().from(connectionGrants).where(inArray(connectionGrants.id, queued.map((i) => i.grantId)));
const items = queued.filter((i) => {
const g = live.find((x) => x.id === i.grantId);
return g && !g.endedAt && askOpen(g, still.get(i.grantId));
});
await setSetting(db, d.key, []);
if (!items.length) continue;
await setSetting(db, `${IDLE_DIGEST_SENT}${ownerId}`, now.getTime());
await (o.notify ?? tellIdleGrants)(db, ownerId, items);
}
return asked;
}
/** Telegram button data of the request: `cg:<grantId>:r|k` (revoke / keep). */
export function idleGrantCallback(grantId: number, decision: "revoke" | "keep"): string {
return `cg:${grantId}:${decision === "revoke" ? "r" : "k"}`;
}
export function parseIdleGrantCallback(data: string): { grantId: number; decision: "revoke" | "keep" } | null {
const mm = /^cg:(\d+):([rk])$/.exec(data);
return mm ? { grantId: Number(mm[1]), decision: mm[2] === "r" ? "revoke" : "keep" } : null;
}
/** The owner's request: grants nobody used — revoke? Master chat + Telegram/push (night quiet is the outbox's). */
export async function tellIdleGrants(db: Db, ownerId: number, items: IdleDigestItem[]): Promise<void> {
const lines = items.slice(0, 10).map((i) =>
i.agent
? tr("— «{name}» в {project}, агент {agent}: {hours} ч без дела", { name: asIs(i.connection), project: asIs(i.project), agent: asIs(i.agent), hours: i.hours })
: tr("— «{name}» в {project}: {hours} ч без дела", { name: asIs(i.connection), project: asIs(i.project), hours: i.hours }),
);
const more = items.length > 10 ? [tr("и ещё {n}", { n: items.length - 10 })] : [];
const text = [tr("Агенты давно не пользуются разрешениями: {n}. Снять их? Пока вы не решили, доступ остаётся. Решить можно кнопками ниже или в разделе «Подключения».", { n: items.length }), ...lines, ...more].join("\n");
const label = (i: IdleDigestItem) => clip(i.agent ? `${i.connection} · ${i.project} · ${i.agent}` : `${i.connection} · ${i.project}`, 40);
const keyboard = items.slice(0, DIGEST_BUTTONS).map((i) => [
{ text: tr("Снять: {name}", { name: asIs(label(i)) }), callback_data: idleGrantCallback(i.grantId, "revoke") },
{ text: tr("Оставить"), callback_data: idleGrantCallback(i.grantId, "keep") },
]);
const key = `connection-idle:${ownerId}:${Date.now()}`;
await addMasterMessage(db, ownerId, { kind: "event", important: true, text, dedupeKey: `master:${key}`, url: "/connections" }).catch(() => null);
const [u] = await db.select().from(users).where(eq(users.id, ownerId));
if (!u) return;
await deliverToUser(db, u, {
event: "questions",
dedupeKey: `${key}:${u.telegramChatId}`,
pushKey: `${key}:u${u.id}`,
telegram: { params: { text, reply_markup: { inline_keyboard: keyboard } } },
push: { title: tr("FORGE"), body: text, url: "/connections", tag: "connection-idle" },
}).catch(() => null);
}
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
/**
* The owner's answer to the «no use» request (web or Telegram button). Only the connection's
* owner decides. «Снять» ends the grant (journal REVOKE, `idle_revoked` for the agent; «Продлить»
* brings it back); «Оставить» keeps it and the next request comes a full threshold later.
* Returns the toast text.
*/
export async function decideIdleGrant(db: Db, userId: number, grantId: number, decision: "revoke" | "keep", o: { now?: Date } = {}): Promise<string> {
const now = o.now ?? new Date();
const [r] = await db
.select({ g: connectionGrants, c: connections, projectKey: projects.key, agentName: agents.name })
.from(connectionGrants)
.innerJoin(connections, eq(connections.id, connectionGrants.connectionId))
.innerJoin(projects, eq(projects.id, connectionGrants.projectId))
.leftJoin(agents, eq(agents.id, connectionGrants.agentId))
.where(eq(connectionGrants.id, grantId));
if (!r || r.c.ownerId !== userId) throw new PeppaError(tr("Разрешение не найдено"));
if (r.g.endedAt) return tr("Разрешение уже снято");
if (decision === "keep") {
await setSetting(db, `${IDLE_ASK}${grantId}`, { at: now.getTime(), kept: true } satisfies IdleAsk);
await logEvent(db, { projectId: r.g.projectId, type: "connection_grant_kept", payload: { connectionId: r.c.id, grantId, agentId: r.g.agentId } });
return tr("Разрешение оставлено");
}
const hours = idleHoursOf(r.c);
await db.update(connectionGrants).set({ endedAt: now, endReason: "idle" }).where(and(eq(connectionGrants.id, grantId), isNull(connectionGrants.endedAt)));
await db.delete(settings).where(eq(settings.key, `${IDLE_ASK}${grantId}`));
await appendJournal(db, {
ownerId: r.c.ownerId,
kind: "call",
connectionId: r.c.id,
connectionName: r.c.name,
projectId: r.g.projectId,
projectKey: r.projectKey,
agentId: r.g.agentId,
agentName: r.agentName,
method: "REVOKE",
path: "/",
decision: "denied",
reason: "idle_revoked",
statusCode: null,
createdAt: now,
});
await logEvent(db, { projectId: r.g.projectId, type: "connection_grant_revoked", payload: { connectionId: r.c.id, grantId, agentId: r.g.agentId, reason: "idle", hours } });
return tr("Разрешение снято");
}