Приёмка PEP-261, 27.11.2026: агенту дали полные права на срок, срок вышел; на новый запрос владелец нажал «Дать: чтение» — проект снова получил чтение и запись, а сообщение говорило «чтение». `grantFor` расширял права по строке прошлой выдачи и не смотрел, действует ли она. На живом сервере выдач ещё не было. - core/access-requests.ts: прошлая выдача расширяет новую, только пока она действует (`grantState` = active); права и операции истёкшей или снятой «без дела» не возвращаются. - Тест access-regrant.test.ts: истёкшие полные права и права, снятые «без дела» → «Дать: чтение» даёт только чтение (оба случая падали до исправления: writeMode auto вместо off); действующая выдача по-прежнему только расширяется. - Спека access-hub: уточнение требования и сценарий «Чтение после истёкших полных прав». Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
451 lines
25 KiB
TypeScript
451 lines
25 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, DEFAULT_GRANT_TERM, GRANT_RIGHTS, GRANT_TERM_TEXT, GRANT_TERMS, grantConnection, grantState, isBlockedAddress, isGrantTerm, listConnections, parseBaseUrl, type ConnectionInput, type ConnectionView, type GrantMode, type GrantRights, type GrantTerm } 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;
|
||
/** PEP-261: what was given, right after a grant (not stored on the request; the event has it). */
|
||
rights?: GrantRights;
|
||
term?: GrantTerm;
|
||
}
|
||
|
||
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). `canGrant` — the owner already has a fitting connection (PEP-261 buttons). */
|
||
export function accessRequestText(r: AccessRequestView, o: { canGrant?: boolean } = {}): 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 }), o.canGrant ? tr("Выберите, что дать агенту и на какой срок (обычно 1 день), или откажите.") : tr("Откройте запрос, чтобы подключить сервис или отказать.")].join("\n");
|
||
}
|
||
|
||
type InlineButton = { text: string; url?: string; callback_data?: string };
|
||
|
||
/** PEP-261: the step of the Telegram keyboard under an access request. */
|
||
export type AccessKeyboardStep = { step: "rights"; canGrant: boolean } | { step: "term"; rights: GrantRights };
|
||
|
||
/**
|
||
* Buttons under the owner's message: «Дать: чтение» · «Дать: полные права» (only with a fitting
|
||
* connection, otherwise «Подключить» — the request's card with the catalog's steps) · «Отказать»;
|
||
* after rights — the term (1 day first, the default) and «Назад».
|
||
* Callback data: `ar:<id>:r|f`, `ar:<id>:r|f:<term>`, `ar:<id>:back`, `ar:<id>:no`.
|
||
*/
|
||
export function accessRequestKeyboard(id: number, k: AccessKeyboardStep, o: { webUrl?: string } = {}): InlineButton[][] {
|
||
const base = (o.webUrl ?? process.env.PEPPA_WEB_URL ?? "").replace(/\/+$/, "");
|
||
const link = base.startsWith("https://") ? `${base}${accessRequestUrl(id)}` : null;
|
||
if (k.step === "term") {
|
||
const code = k.rights === "full" ? "f" : "r";
|
||
const terms = [DEFAULT_GRANT_TERM, ...GRANT_TERMS.filter((t) => t !== DEFAULT_GRANT_TERM)];
|
||
const label = k.rights === "full" ? tr("Полные права — на какой срок?") : tr("Чтение — на какой срок?");
|
||
return [
|
||
[{ text: label, callback_data: `ar:${id}:${code}:${DEFAULT_GRANT_TERM}` }],
|
||
terms.map((t) => ({ text: GRANT_TERM_TEXT[t], callback_data: `ar:${id}:${code}:${t}` })),
|
||
[{ text: tr("Назад"), callback_data: `ar:${id}:back` }],
|
||
];
|
||
}
|
||
return [
|
||
...(k.canGrant
|
||
? [[{ text: tr("Дать: чтение"), callback_data: `ar:${id}:r` }, { text: tr("Дать: полные права"), callback_data: `ar:${id}:f` }]]
|
||
: link
|
||
? [[{ text: tr("Подключить"), url: link }]]
|
||
: []),
|
||
[{ text: tr("Отказать"), callback_data: `ar:${id}:no` }],
|
||
...(k.canGrant && link ? [[{ text: tr("Посмотреть и решить"), url: link }]] : []),
|
||
];
|
||
}
|
||
|
||
export type AccessCallback = { id: number } & ({ action: "no" } | { action: "back" } | { action: "rights"; rights: GrantRights } | { action: "grant"; rights: GrantRights; term: GrantTerm });
|
||
|
||
/** `ar:…` → what was pressed; null — not ours or malformed. */
|
||
export function parseAccessCallback(data: string): AccessCallback | null {
|
||
const m = /^ar:(\d+):(no|back|r|f)(?::([a-z0-9]+))?$/.exec(String(data ?? ""));
|
||
if (!m) return null;
|
||
const id = Number(m[1]);
|
||
if (m[2] === "no" || m[2] === "back") return m[3] ? null : { id, action: m[2] };
|
||
const rights: GrantRights = m[2] === "f" ? "full" : "read";
|
||
if (!m[3]) return { id, action: "rights", rights };
|
||
return isGrantTerm(m[3]) ? { id, action: "grant", rights, term: m[3] } : null;
|
||
}
|
||
|
||
/** 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 canGrant = (await connectionsForRequest(db, r.ownerId, r).catch(() => ({ fit: [] }))).fit.length > 0;
|
||
const text = accessRequestText(r, { canGrant });
|
||
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 buttons = accessRequestKeyboard(r.id, { step: "rights", canGrant });
|
||
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);
|
||
|
||
/** PEP-261: what the owner gives — rights (default: what the agent asked for) and a term (default 1 day). */
|
||
export interface AccessGrantChoice {
|
||
rights?: GrantRights;
|
||
term?: GrantTerm;
|
||
}
|
||
type Given = { rights: GrantRights; term: GrantTerm };
|
||
const given = (r: AccessRequestView, c: AccessGrantChoice = {}): Given => ({ rights: c.rights === "full" || c.rights === "read" ? c.rights : r.mode === "write" ? "full" : "read", term: isGrantTerm(c.term) ? c.term : DEFAULT_GRANT_TERM });
|
||
|
||
/**
|
||
* Grant to the request's project (any of its agents) on the chosen term. A grant that works now only
|
||
* widens its modes. PEP-315: a grant whose term is over or that was revoked for no use gives nothing
|
||
* to the new one — «Дать: чтение» after expired full rights is reading only.
|
||
*/
|
||
async function grantFor(db: Db, userId: number, r: AccessRequestView, connectionId: number, g: Given): Promise<void> {
|
||
const [row] = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.projectId, r.projectId)))).filter((x) => x.agentId == null);
|
||
const prev = row && grantState(row, new Date()) === "active" ? row : undefined;
|
||
await grantConnection(db, userId, connectionId, {
|
||
projectId: r.projectId,
|
||
agentId: null,
|
||
operations: prev?.operations ?? [],
|
||
readMode: widest(prev?.readMode ?? "off", GRANT_RIGHTS[g.rights].readMode),
|
||
writeMode: widest(prev?.writeMode ?? "off", GRANT_RIGHTS[g.rights].writeMode),
|
||
term: g.term,
|
||
});
|
||
}
|
||
|
||
async function closeGranted(db: Db, userId: number, r: AccessRequestView, connectionId: number, g: Given): 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, rights: g.rights, term: g.term } });
|
||
return { ...(await getAccessRequest(db, r.id))!, ...g };
|
||
}
|
||
|
||
/** «Разрешить из уже подключённого». */
|
||
export async function grantAccessFromExisting(db: Db, userId: number, id: number, connectionId: number, choice: AccessGrantChoice = {}): Promise<AccessRequestView> {
|
||
const r = await ownOpen(db, userId, id);
|
||
const g = given(r, choice);
|
||
await grantFor(db, userId, r, connectionId, g); // grantConnection checks that the connection is the user's and active
|
||
return closeGranted(db, userId, r, connectionId, g);
|
||
}
|
||
|
||
export const NO_CONNECTION_TEXT = tr("Подключения ещё нет — откройте запрос и подключите сервис");
|
||
|
||
/** PEP-261: the owner's open request and the connection a button would give (the first fitting one). */
|
||
export async function accessButtonTarget(db: Db, userId: number, id: number): Promise<{ request: AccessRequestView; connection: ConnectionView }> {
|
||
const r = await ownOpen(db, userId, id);
|
||
const [connection] = (await connectionsForRequest(db, userId, r)).fit;
|
||
if (!connection) throw new PeppaError(NO_CONNECTION_TEXT);
|
||
return { request: r, connection };
|
||
}
|
||
|
||
/** PEP-261 «Дать: чтение / полные права» + term — under the message (Telegram) or in «Агенты просят доступ». */
|
||
export async function grantAccessByButton(db: Db, userId: number, id: number, choice: AccessGrantChoice): Promise<{ request: AccessRequestView; connection: ConnectionView }> {
|
||
const { connection } = await accessButtonTarget(db, userId, id);
|
||
return { request: await grantAccessFromExisting(db, userId, id, connection.id, choice), connection };
|
||
}
|
||
|
||
/** «Подключить и разрешить»: 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 }, choice: AccessGrantChoice = {}): Promise<{ request: AccessRequestView; connection: ConnectionView }> {
|
||
const r = await ownOpen(db, userId, id);
|
||
const g = given(r, choice);
|
||
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, g);
|
||
return { request: await closeGranted(db, userId, r, connection.id, g), 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))!;
|
||
}
|