peppa/packages/runner/src/share.ts
Асель efeac4500b PEP-64: public by default, change visibility (runner, web, MCP, CLI), tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 03:39:17 +05:00

188 lines
8.1 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.

// Sharing a project: Peppa membership plus collaborator access to its Gitea repo;
// where the repo is and who can see it (PEP-15).
import {
addMember,
getUser,
getUserByLogin,
giteaForBot,
isLocalUser,
giteaForUser,
PeppaError,
removeMember,
listMembers,
type GiteaClient,
type RepoInfo,
type Project,
type User,
} from "@peppa/core";
import type { Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
/** Gitea clients that may administer the project's repo: its owner, then peppa-bot. */
export async function repoAdmins(db: Db, project: Project): Promise<GiteaClient[]> {
const out: GiteaClient[] = [];
const owner = project.ownerId ? await getUser(db, project.ownerId) : null;
if (owner) {
try {
out.push(await giteaForUser(db, owner));
} catch {}
}
try {
out.push(giteaForBot());
} catch {}
return out;
}
export interface ShareResult {
login: string;
status: "added" | "invited";
/** False when Peppa could not add the person as a repo collaborator in Gitea. */
repoAccess: boolean;
}
/** Owner adds a person (by Gitea login) to the project and to its repo (write). */
export async function shareProject(db: Db, actor: User, project: Project, loginInput: string): Promise<ShareResult> {
if (project.ownerId !== actor.id) throw new PeppaError("Участниками управляет только владелец проекта");
const login = loginInput.trim().replace(/^@/, "");
if (!login) throw new PeppaError("Укажите логин Gitea");
// PEP-68: a local Peppa user (no Gitea account) becomes a member without repo access.
const local = await localUser(db, login);
if (local) {
const status = await addMember(db, project, local.login, actor.id);
describeCache.delete(project.id);
return { login: local.login, status, repoAccess: false };
}
const clients = await repoAdmins(db, project);
if (!clients.length) throw new PeppaError("Нет доступа к Gitea — войдите заново");
const account = await clients[0]!.getUserByLogin(login);
if (!account) throw new PeppaError(`Пользователь «${login}» не найден в Gitea`);
const status = await addMember(db, project, account.login, actor.id);
let repoAccess = false;
for (const c of clients) {
try {
await c.addCollaborator(project.giteaOwner, project.giteaRepo, account.login, "write");
repoAccess = true;
break;
} catch {}
}
describeCache.delete(project.id);
return { login: account.login, status, repoAccess };
}
/** Owner removes a member/invitation, or a member leaves. */
export async function unshareProject(db: Db, actor: User, project: Project, loginInput: string): Promise<void> {
const login = loginInput.trim().replace(/^@/, "");
const self = actor.login.toLowerCase() === login.toLowerCase();
if (project.ownerId !== actor.id && !self) throw new PeppaError("Участниками управляет только владелец проекта");
if (!(await removeMember(db, project.id, login))) throw new PeppaError(`«${login}» не участник проекта`);
describeCache.delete(project.id);
if (await localUser(db, login)) return; // not a Gitea collaborator; the same Gitea login may be someone else
for (const c of await repoAdmins(db, project)) {
try {
await c.removeCollaborator(project.giteaOwner, project.giteaRepo, login);
break;
} catch {}
}
}
async function localUser(db: Db, login: string): Promise<User | null> {
const u = (await getUserByLogin(db, login)) ?? (await getUserByLogin(db, login.toLowerCase()));
return u && isLocalUser(u) ? u : null;
}
/** Owner adds every member (not pending invites) as a repo collaborator; returns who failed. */
export async function grantRepoAccess(db: Db, actor: User, project: Project): Promise<{ granted: string[]; failed: string[] }> {
if (project.ownerId !== actor.id) throw new PeppaError("Участниками управляет только владелец проекта");
const clients = await repoAdmins(db, project);
const { members } = await listMembers(db, project);
const granted: string[] = [];
const failed: string[] = [];
for (const m of members) {
if (isLocalUser(m)) continue; // PEP-68: no Gitea account to add
let ok = false;
for (const c of clients) {
try {
await c.addCollaborator(project.giteaOwner, project.giteaRepo, m.login, "write");
ok = true;
break;
} catch {}
}
(ok ? granted : failed).push(m.login);
}
describeCache.delete(project.id);
return { granted, failed };
}
export type Visibility = "public" | "private";
/**
* Changes the visibility of the project's Gitea repo (PEP-64): owner's client, then peppa-bot.
* With `actor` (web, MCP) only the project owner may do it; without (CLI on Peppa's machine) anyone.
*/
export async function setProjectVisibility(db: Db, project: Project, visibility: Visibility, opts: { actor?: User } = {}): Promise<RepoInfo> {
if (visibility !== "public" && visibility !== "private") throw new PeppaError(`Видимость: public или private, не «${visibility}»`);
if (opts.actor && project.ownerId !== opts.actor.id) throw new PeppaError("Видимость репозитория меняет только владелец проекта");
const fullName = `${project.giteaOwner}/${project.giteaRepo}`;
const clients = await repoAdmins(db, project);
if (!clients.length) throw new PeppaError("Нет доступа к Gitea — войдите заново");
let last: unknown = null;
let done = false;
for (const c of clients) {
try {
await c.setRepoPrivate(project.giteaOwner, project.giteaRepo, visibility === "private");
done = true;
break;
} catch (e) {
last = e;
}
}
describeCache.delete(project.id);
if (!done) {
const status = (last as { status?: number } | null)?.status;
const why = status === 403 || status === 401 ? "нет прав администратора в Gitea" : status === 404 ? "репозиторий не найден в Gitea" : ((last as Error | null)?.message ?? "Gitea не ответил");
throw new PeppaError(`Не удалось сменить видимость ${fullName}: ${why}`);
}
return describeRepo(db, project, { fresh: true });
}
const DESCRIBE_TIMEOUT_MS = 5000;
const DESCRIBE_CACHE_MS = 60_000;
// The project page refreshes every few seconds; Gitea is asked at most once a minute per project.
const describeCache = new Map<number, { at: number; info: RepoInfo }>();
/** Where the project's repo is and who can see it, asked from Gitea (owner's client, then peppa-bot). */
export async function describeRepo(db: Db, project: Project, opts: { fresh?: boolean } = {}): Promise<RepoInfo> {
const hit = describeCache.get(project.id);
if (!opts.fresh && hit && Date.now() - hit.at < DESCRIBE_CACHE_MS) return hit.info;
const info = await askRepo(db, project);
if (info.private !== null) describeCache.set(project.id, { at: Date.now(), info });
return info;
}
async function askRepo(db: Db, project: Project): Promise<RepoInfo> {
const fullName = `${project.giteaOwner}/${project.giteaRepo}`;
const fallback: RepoInfo = { fullName, url: `${loadEnv().GITEA_URL}/${fullName}`, private: null, ownerKind: null, collaborators: null };
for (const c of await repoAdmins(db, project)) {
const ask = async (): Promise<RepoInfo | null> => {
const [repo, isOrg, collaborators] = await Promise.all([
c.getRepo(project.giteaOwner, project.giteaRepo),
c.isOrg(project.giteaOwner).catch(() => null),
c.listCollaborators(project.giteaOwner, project.giteaRepo).catch(() => null),
]);
if (!repo) return null;
return {
fullName: repo.full_name,
url: repo.html_url,
private: repo.private,
ownerKind: isOrg === null ? null : isOrg ? "org" : "user",
collaborators: collaborators ? collaborators.map((u) => u.login) : null,
};
};
const timeout = new Promise<null>((r) => setTimeout(() => r(null), DESCRIBE_TIMEOUT_MS).unref());
const info = await Promise.race([ask(), timeout]).catch(() => null);
if (info) return info;
}
return fallback;
}