368 lines
20 KiB
TypeScript
368 lines
20 KiB
TypeScript
// PEP-250 Access Hub: an agent asks the project's owner for access to an external service.
|
||
// The owner gets one message with a link to the request's card (only they can open it), adds the
|
||
// key once or allows an existing connection, or refuses with a reason. One open request per
|
||
// project × service; a repeated ask adds to it. Telling the agent about the decision is the
|
||
// runner's job (runner/access-requests.ts) — this module only stores, checks and notifies.
|
||
import { asIs, m as tr } from "@peppa/shared/i18n";
|
||
import { accessRequests, agents, connectionGrants, projects, sessions, tasks, users, type Db } from "@peppa/db";
|
||
import { and, desc, eq, inArray, type SQL } from "drizzle-orm";
|
||
import { lookup as dnsLookup } from "node:dns/promises";
|
||
import { logEvent } from "./audit.ts";
|
||
import { addMasterMessage } from "./chats.ts";
|
||
import { catalogService, CONNECTION_CATALOG, type CatalogService } from "./connection-catalog.ts";
|
||
import { agentConnections, createConnection, grantConnection, isBlockedAddress, listConnections, parseBaseUrl, type ConnectionInput, type ConnectionView, type GrantMode } from "./connections.ts";
|
||
import { PeppaError } from "./errors.ts";
|
||
import { deliverToUser } from "./notifications.ts";
|
||
import { guardUntrusted } from "./untrusted.ts";
|
||
|
||
export type AccessMode = "read" | "write";
|
||
export type AccessRequestStatus = "open" | "granted" | "denied" | "cancelled";
|
||
export const ACCESS_PURPOSE_MAX = 500;
|
||
export const ACCESS_REASON_MAX = 500;
|
||
/** How many recent requests an agent sees in list_requests. */
|
||
const AGENT_LIST_MAX = 20;
|
||
|
||
export interface AccessRequestView {
|
||
id: number;
|
||
projectId: number;
|
||
projectKey: string;
|
||
projectName: string;
|
||
ownerId: number;
|
||
taskId: number | null;
|
||
taskKey: string | null;
|
||
taskTitle: string | null;
|
||
sessionId: number | null;
|
||
agentName: string | null;
|
||
catalogId: string | null;
|
||
host: string | null;
|
||
/** Brand name of the catalog card, or the host. */
|
||
service: string;
|
||
purpose: string;
|
||
mode: AccessMode;
|
||
status: AccessRequestStatus;
|
||
reason: string | null;
|
||
connectionId: number | null;
|
||
repeats: number;
|
||
decidedAt: Date | null;
|
||
createdAt: Date;
|
||
updatedAt: Date;
|
||
}
|
||
|
||
export type HostLookup = (host: string) => Promise<string[]>;
|
||
const defaultLookup: HostLookup = async (host) => (await dnsLookup(host, { all: true, verbatim: true })).map((a) => a.address);
|
||
|
||
/**
|
||
* An address from an agent → an https origin in the open internet, checked like the gateway does
|
||
* (parseBaseUrl), plus DNS: a name resolving to a closed address is refused. A name that does not
|
||
* resolve is accepted — the gateway checks the address again on every call.
|
||
*/
|
||
export async function publicOrigin(raw: string, o: { lookup?: HostLookup; env?: NodeJS.ProcessEnv } = {}): Promise<string> {
|
||
const s = String(raw ?? "").trim();
|
||
if (!s || s.length > 300) throw new PeppaError(tr("Укажите адрес сервиса в интернете"));
|
||
const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : `https://${s}`;
|
||
let origin: string;
|
||
try {
|
||
const u = new URL(withScheme);
|
||
if (u.username || u.password) throw new Error("login");
|
||
// The path and the query of the agent's address don't matter: access is to the whole service.
|
||
origin = new URL(parseBaseUrl(`${u.protocol}//${u.host}`, o.env)).origin;
|
||
} catch (e) {
|
||
if (e instanceof PeppaError) throw e;
|
||
throw new PeppaError(tr("Адрес сервиса должен начинаться с https:// и не содержать логин, пароль, «?» и «#»"));
|
||
}
|
||
const host = new URL(origin).hostname.replace(/^\[|\]$/g, "");
|
||
if ((o.env ?? process.env).PEPPA_CONNECTIONS_ALLOW_PRIVATE === "1") return origin;
|
||
const ips = await (o.lookup ?? defaultLookup)(host).catch(() => [] as string[]);
|
||
if (ips.some(isBlockedAddress)) throw new PeppaError(tr("Этот адрес сервиса недоступен: укажите адрес в интернете"));
|
||
return origin;
|
||
}
|
||
|
||
/** A catalog card by its id or its name (case-insensitive). */
|
||
export function findCatalogService(q: string | null | undefined): CatalogService | null {
|
||
const s = String(q ?? "").trim().toLowerCase();
|
||
if (!s) return null;
|
||
return catalogService(s) ?? CONNECTION_CATALOG.find((c) => c.name.toLowerCase() === s) ?? null;
|
||
}
|
||
|
||
/** A catalog card from an env name: STRIPE_SECRET_KEY → stripe. */
|
||
export function catalogFromSecretName(name: string | null | undefined): CatalogService | null {
|
||
const words = String(name ?? "").toLowerCase().split(/_+/).filter(Boolean);
|
||
for (let n = Math.min(3, words.length); n >= 1; n--) {
|
||
for (const glue of ["-", ""]) {
|
||
const hit = catalogService(words.slice(0, n).join(glue));
|
||
if (hit) return hit;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
const serviceName = (r: { catalogId: string | null; host: string | null }) => catalogService(r.catalogId)?.name ?? (r.host ? new URL(r.host).host : "?");
|
||
|
||
async function views(db: Db, where: SQL | undefined, limit = 200): Promise<AccessRequestView[]> {
|
||
const rows = await db
|
||
.select({ r: accessRequests, projectKey: projects.key, projectName: projects.name, taskNumber: tasks.number, taskTitle: tasks.title })
|
||
.from(accessRequests)
|
||
.innerJoin(projects, eq(projects.id, accessRequests.projectId))
|
||
.leftJoin(tasks, eq(tasks.id, accessRequests.taskId))
|
||
.where(where)
|
||
.orderBy(desc(accessRequests.updatedAt), desc(accessRequests.id))
|
||
.limit(limit);
|
||
return rows.map(({ r, projectKey, projectName, taskNumber, taskTitle }) => ({
|
||
id: r.id,
|
||
projectId: r.projectId,
|
||
projectKey,
|
||
projectName,
|
||
ownerId: r.ownerId,
|
||
taskId: r.taskId,
|
||
taskKey: taskNumber != null ? `${projectKey}-${taskNumber}` : null,
|
||
taskTitle: taskTitle ?? null,
|
||
sessionId: r.sessionId,
|
||
agentName: r.agentName,
|
||
catalogId: r.catalogId,
|
||
host: r.host,
|
||
service: serviceName(r),
|
||
purpose: r.purpose,
|
||
mode: r.mode,
|
||
status: r.status,
|
||
reason: r.reason,
|
||
connectionId: r.connectionId,
|
||
repeats: r.repeats,
|
||
decidedAt: r.decidedAt,
|
||
createdAt: r.createdAt,
|
||
updatedAt: r.updatedAt,
|
||
}));
|
||
}
|
||
|
||
export async function getAccessRequest(db: Db, id: number): Promise<AccessRequestView | null> {
|
||
return (await views(db, eq(accessRequests.id, id), 1))[0] ?? null;
|
||
}
|
||
|
||
export interface AccessRequestInput {
|
||
sessionId: number | null | undefined;
|
||
/** A catalog id (`stripe`) or a card's name. */
|
||
service?: string | null;
|
||
/** An address or a host name of an own service. */
|
||
host?: string | null;
|
||
purpose: string;
|
||
mode?: AccessMode;
|
||
}
|
||
|
||
export interface AccessRequestResult {
|
||
request: AccessRequestView;
|
||
/** false — an open request for this service existed: the ask was added to it. */
|
||
created: boolean;
|
||
}
|
||
|
||
async function sessionOf(db: Db, sessionId: number | null | undefined) {
|
||
if (sessionId == null) throw new PeppaError("Access requests work only in sessions started by FORGE");
|
||
const [s] = await db
|
||
.select({ id: sessions.id, projectId: sessions.projectId, taskId: sessions.taskId, agentId: sessions.agentId, agentName: agents.name })
|
||
.from(sessions)
|
||
.leftJoin(agents, eq(agents.id, sessions.agentId))
|
||
.where(eq(sessions.id, sessionId));
|
||
if (!s) throw new PeppaError("Session not found");
|
||
return s;
|
||
}
|
||
|
||
/** Does this connection serve the requested service? */
|
||
const serves = (c: { catalogId: string | null; baseUrl: string }, r: { catalogId: string | null; host: string | null }) =>
|
||
r.catalogId ? c.catalogId === r.catalogId : !!r.host && safeOrigin(c.baseUrl) === r.host;
|
||
const safeOrigin = (u: string) => {
|
||
try {
|
||
return new URL(u).origin;
|
||
} catch {
|
||
return null;
|
||
}
|
||
};
|
||
|
||
/**
|
||
* The agent asks for access. Refused: no service, a closed address, access already given. An
|
||
* open request for the same project × service gets the ask added (`repeats`, write widens the
|
||
* mode) and no second message; a new one is announced to the project's owner.
|
||
*/
|
||
export async function requestAccess(db: Db, i: AccessRequestInput, o: { lookup?: HostLookup; now?: Date; auto?: boolean } = {}): Promise<AccessRequestResult> {
|
||
const s = await sessionOf(db, i.sessionId);
|
||
const purpose = String(i.purpose ?? "").replace(/\s+/g, " ").trim().slice(0, ACCESS_PURPOSE_MAX);
|
||
if (!purpose) throw new PeppaError("Say what the access is for (purpose): the owner decides by it");
|
||
const mode: AccessMode = i.mode === "write" ? "write" : "read";
|
||
let catalogId: string | null = null;
|
||
let host: string | null = null;
|
||
if (i.service) {
|
||
const card = findCatalogService(i.service);
|
||
if (card) catalogId = card.id;
|
||
else if (!i.host) throw new PeppaError(`No service «${String(i.service).slice(0, 60)}» in the catalog: pass its address as host (https://…)`);
|
||
}
|
||
if (!catalogId) {
|
||
if (!i.host) throw new PeppaError("Name the service (a catalog id like stripe) or its address (host)");
|
||
host = await publicOrigin(i.host, { lookup: o.lookup });
|
||
// An address of a catalog service is the catalog card (shared rules and steps for the owner).
|
||
const card = CONNECTION_CATALOG.find((c) => !c.baseEditable && safeOrigin(c.baseUrl) === host);
|
||
if (card) [catalogId, host] = [card.id, null];
|
||
}
|
||
const serviceKey = catalogId ?? host!;
|
||
const [project] = await db.select().from(projects).where(eq(projects.id, s.projectId));
|
||
if (!project) throw new PeppaError("Project not found");
|
||
if (project.ownerId == null) throw new PeppaError("This project has no owner to ask");
|
||
|
||
// Already allowed: no request, call it.
|
||
const have = (await agentConnections(db, s.id)).find((c) => serves(c, { catalogId, host }) && (mode === "read" ? c.readMode === "auto" : c.writeMode === "auto"));
|
||
if (have) throw new PeppaError(`You already have this access: call_connection("${have.slug}", …) (list_connections shows what is allowed)`);
|
||
|
||
const now = o.now ?? new Date();
|
||
const [open] = await db.select().from(accessRequests).where(and(eq(accessRequests.projectId, s.projectId), eq(accessRequests.serviceKey, serviceKey), eq(accessRequests.status, "open")));
|
||
if (open) {
|
||
const wider: AccessMode = open.mode === "write" || mode === "write" ? "write" : "read";
|
||
await db.update(accessRequests).set({ repeats: open.repeats + 1, mode: wider, updatedAt: now }).where(eq(accessRequests.id, open.id));
|
||
await logEvent(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type: "access_request_repeated", payload: { requestId: open.id, service: serviceKey, mode: wider } });
|
||
return { request: (await getAccessRequest(db, open.id))!, created: false };
|
||
}
|
||
// The purpose is the agent's text: kept as is, shown verbatim, checked for injection signs.
|
||
await guardUntrusted(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, source: "запрос доступа агента", text: purpose }).catch(() => null);
|
||
const [row] = await db
|
||
.insert(accessRequests)
|
||
.values({ projectId: s.projectId, ownerId: project.ownerId, taskId: s.taskId, sessionId: s.id, agentId: s.agentId, agentName: s.agentName, catalogId, host, serviceKey, purpose, mode, createdAt: now, updatedAt: now })
|
||
.returning({ id: accessRequests.id });
|
||
await logEvent(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type: "access_requested", payload: { requestId: row!.id, service: serviceKey, mode, auto: !!o.auto } });
|
||
const request = (await getAccessRequest(db, row!.id))!;
|
||
await announceAccessRequest(db, request).catch(() => null);
|
||
return { request, created: true };
|
||
}
|
||
|
||
export const accessRequestUrl = (id: number) => `/connections/requests/${id}`;
|
||
|
||
/** The text of the owner's message (master chat, Telegram, push). */
|
||
export function accessRequestText(r: AccessRequestView): string {
|
||
const who = r.agentName ? tr("Агент {name}", { name: asIs(r.agentName) }) : tr("Агент");
|
||
const where = r.taskKey ? tr("{project}, задача {task}", { project: asIs(r.projectName), task: r.taskKey }) : asIs(r.projectName);
|
||
const what = r.mode === "write" ? tr("{service} — читать и менять", { service: asIs(r.service) }) : tr("{service} — только читать", { service: asIs(r.service) });
|
||
return [tr("{who} просит доступ: {what}.", { who, what }), tr("Зачем: {purpose}", { purpose: asIs(r.purpose) }), tr("Проект: {where}", { where }), tr("Откройте запрос, чтобы подключить сервис или отказать.")].join("\n");
|
||
}
|
||
|
||
/** One message to the project's owner. Night quiet and the project's pause apply (outbox, deliverToUser). */
|
||
export async function announceAccessRequest(db: Db, r: AccessRequestView): Promise<void> {
|
||
const text = accessRequestText(r);
|
||
const url = accessRequestUrl(r.id);
|
||
await addMasterMessage(db, r.ownerId, { kind: "event", important: true, text, dedupeKey: `master:access-request:${r.id}`, url }).catch(() => null);
|
||
const [u] = await db.select().from(users).where(eq(users.id, r.ownerId));
|
||
if (!u) return;
|
||
const base = (process.env.PEPPA_WEB_URL ?? "").replace(/\/+$/, "");
|
||
const buttons = [...(base.startsWith("https://") ? [[{ text: tr("Посмотреть и решить"), url: `${base}${url}` }]] : []), [{ text: tr("Отказать"), callback_data: `ar:${r.id}:no` }]];
|
||
await deliverToUser(db, u, {
|
||
event: "questions",
|
||
projectId: r.projectId,
|
||
dedupeKey: `access-request:${r.id}:${u.telegramChatId}`,
|
||
pushKey: `access-request:${r.id}:u${u.id}`,
|
||
telegram: { params: { text, reply_markup: { inline_keyboard: buttons } } },
|
||
push: { title: tr("Агент просит доступ"), body: text, url, tag: `access-request:${r.id}` },
|
||
});
|
||
}
|
||
|
||
// ---------- the agent's side ----------
|
||
|
||
/** The project's recent requests for list_requests (the session's project only). */
|
||
export async function sessionAccessRequests(db: Db, sessionId: number | null | undefined): Promise<AccessRequestView[]> {
|
||
const s = await sessionOf(db, sessionId);
|
||
return views(db, eq(accessRequests.projectId, s.projectId), AGENT_LIST_MAX);
|
||
}
|
||
|
||
export async function cancelAccessRequest(db: Db, sessionId: number | null | undefined, id: number): Promise<AccessRequestView> {
|
||
const s = await sessionOf(db, sessionId);
|
||
const [r] = await db.select().from(accessRequests).where(eq(accessRequests.id, id));
|
||
if (!r || r.projectId !== s.projectId) throw new PeppaError(`Request #${id} not found in this project`);
|
||
if (r.status !== "open") throw new PeppaError(`Request #${id} is already ${r.status}`);
|
||
await db.update(accessRequests).set({ status: "cancelled", decidedAt: new Date(), updatedAt: new Date() }).where(eq(accessRequests.id, id));
|
||
await logEvent(db, { projectId: r.projectId, taskId: s.taskId, sessionId: s.id, type: "access_request_cancelled", payload: { requestId: id } });
|
||
return (await getAccessRequest(db, id))!;
|
||
}
|
||
|
||
// ---------- the owner's side ----------
|
||
|
||
/** The request for its owner only — someone else (a member, a superadmin) gets null → 404. */
|
||
export async function accessRequestForUser(db: Db, userId: number, id: number): Promise<AccessRequestView | null> {
|
||
const r = await getAccessRequest(db, id);
|
||
if (!r || r.ownerId !== userId) return null;
|
||
const [p] = await db.select({ ownerId: projects.ownerId, deletedAt: projects.deletedAt }).from(projects).where(eq(projects.id, r.projectId));
|
||
// Ownership moved on or the project is deleted: the old owner no longer decides.
|
||
if (!p || p.ownerId !== userId || p.deletedAt) return null;
|
||
return r;
|
||
}
|
||
|
||
async function ownOpen(db: Db, userId: number, id: number): Promise<AccessRequestView> {
|
||
const r = await accessRequestForUser(db, userId, id);
|
||
if (!r) throw new PeppaError(tr("Запрос не найден"));
|
||
if (r.status !== "open") throw new PeppaError(tr("По этому запросу уже есть решение"));
|
||
return r;
|
||
}
|
||
|
||
/** «Агенты просят доступ»: the user's open requests. */
|
||
export async function ownerAccessRequests(db: Db, userId: number): Promise<AccessRequestView[]> {
|
||
const list = await views(db, and(eq(accessRequests.ownerId, userId), eq(accessRequests.status, "open")));
|
||
const ids = [...new Set(list.map((r) => r.projectId))];
|
||
if (!ids.length) return [];
|
||
const own = new Set((await db.select({ id: projects.id, ownerId: projects.ownerId, deletedAt: projects.deletedAt }).from(projects).where(inArray(projects.id, ids))).filter((p) => p.ownerId === userId && !p.deletedAt).map((p) => p.id));
|
||
return list.filter((r) => own.has(r.projectId));
|
||
}
|
||
|
||
/** The owner's connections that can serve this request (same catalog card or address) first, then the rest. */
|
||
export async function connectionsForRequest(db: Db, userId: number, r: AccessRequestView): Promise<{ fit: ConnectionView[]; other: ConnectionView[] }> {
|
||
const all = (await listConnections(db, userId)).filter((c) => c.status === "active" && c.hasKey);
|
||
const fit = all.filter((c) => serves(c, r));
|
||
return { fit, other: all.filter((c) => !fit.includes(c)) };
|
||
}
|
||
|
||
const RANK: Record<GrantMode, number> = { off: 0, ask: 1, auto: 2 };
|
||
const widest = (a: GrantMode, b: GrantMode): GrantMode => (RANK[b] > RANK[a] ? b : a);
|
||
|
||
/** Grant to the request's project (any of its agents): read at once, write at once only if asked. An existing grant only widens. */
|
||
async function grantFor(db: Db, userId: number, r: AccessRequestView, connectionId: number): Promise<void> {
|
||
const [prev] = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.projectId, r.projectId)))).filter((g) => g.agentId == null);
|
||
await grantConnection(db, userId, connectionId, {
|
||
projectId: r.projectId,
|
||
agentId: null,
|
||
operations: prev?.operations ?? [],
|
||
readMode: widest(prev?.readMode ?? "off", "auto"),
|
||
writeMode: widest(prev?.writeMode ?? "off", r.mode === "write" ? "auto" : "off"),
|
||
});
|
||
}
|
||
|
||
async function closeGranted(db: Db, userId: number, r: AccessRequestView, connectionId: number): Promise<AccessRequestView> {
|
||
const now = new Date();
|
||
await db.update(accessRequests).set({ status: "granted", connectionId, decidedBy: userId, decidedAt: now, updatedAt: now }).where(eq(accessRequests.id, r.id));
|
||
await logEvent(db, { projectId: r.projectId, taskId: r.taskId, type: "access_granted", payload: { requestId: r.id, connectionId } });
|
||
return (await getAccessRequest(db, r.id))!;
|
||
}
|
||
|
||
/** «Разрешить из уже подключённого». */
|
||
export async function grantAccessFromExisting(db: Db, userId: number, id: number, connectionId: number): Promise<AccessRequestView> {
|
||
const r = await ownOpen(db, userId, id);
|
||
await grantFor(db, userId, r, connectionId); // grantConnection checks that the connection is the user's and active
|
||
return closeGranted(db, userId, r, connectionId);
|
||
}
|
||
|
||
/** «Подключить и разрешить»: the key is entered once — a new connection by the catalog card (or the requested address) and the grant. */
|
||
export async function connectAndGrantAccess(db: Db, userId: number, id: number, i: Omit<ConnectionInput, "catalogId"> & { secret: string }): Promise<{ request: AccessRequestView; connection: ConnectionView }> {
|
||
const r = await ownOpen(db, userId, id);
|
||
const card = catalogService(r.catalogId);
|
||
const input: ConnectionInput = card
|
||
? { name: i.name, secret: i.secret, catalogId: card.id, baseUrl: card.baseEditable ? i.baseUrl : undefined }
|
||
: { name: i.name || new URL(r.host!).host, secret: i.secret, baseUrl: i.baseUrl?.trim() || r.host!, authKind: i.authKind, authHeader: i.authHeader };
|
||
// Free name: «Stripe», «Stripe 2»…
|
||
const taken = new Set((await listConnections(db, userId)).map((c) => c.name));
|
||
const base = (input.name ?? "").trim() || card?.name || "";
|
||
let name = base;
|
||
for (let n = 2; taken.has(name); n++) name = `${base} ${n}`;
|
||
const connection = await createConnection(db, userId, { ...input, name });
|
||
await grantFor(db, userId, r, connection.id);
|
||
return { request: await closeGranted(db, userId, r, connection.id), connection };
|
||
}
|
||
|
||
/** «Отказать»: the reason (optional) reaches the agent. */
|
||
export async function denyAccessRequest(db: Db, userId: number, id: number, reason?: string | null): Promise<AccessRequestView> {
|
||
const r = await ownOpen(db, userId, id);
|
||
const why = String(reason ?? "").replace(/\s+/g, " ").trim().slice(0, ACCESS_REASON_MAX) || null;
|
||
const now = new Date();
|
||
await db.update(accessRequests).set({ status: "denied", reason: why, decidedBy: userId, decidedAt: now, updatedAt: now }).where(eq(accessRequests.id, id));
|
||
await logEvent(db, { projectId: r.projectId, taskId: r.taskId, type: "access_denied", payload: { requestId: id, reason: why } });
|
||
return (await getAccessRequest(db, id))!;
|
||
}
|