198 lines
8.9 KiB
TypeScript
198 lines
8.9 KiB
TypeScript
// Sharing a project: Peppa membership plus collaborator access to its Gitea repo;
|
||
// where the repo is and who can see it (PEP-15).
|
||
import { m } from "@peppa/shared/i18n";
|
||
import {
|
||
addMember,
|
||
getUser,
|
||
getUserByLogin,
|
||
giteaForBot,
|
||
isLocalUser,
|
||
giteaForUser,
|
||
PeppaError,
|
||
removeMember,
|
||
listMembers,
|
||
type GiteaClient,
|
||
type RepoInfo,
|
||
type Project,
|
||
type User,
|
||
isSuperadmin,
|
||
} 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;
|
||
}
|
||
|
||
/** PEP-88: the owner manages the project; a superadmin manages every project. */
|
||
export async function managesProject(db: Db, actor: User, project: Pick<Project, "ownerId">): Promise<boolean> {
|
||
return project.ownerId === actor.id || (await isSuperadmin(db, actor));
|
||
}
|
||
|
||
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 (!(await managesProject(db, actor, project))) throw new PeppaError(m("Участниками управляет только владелец проекта"));
|
||
const login = loginInput.trim().replace(/^@/, "");
|
||
if (!login) throw new PeppaError(m("Укажите логин участника"));
|
||
// 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(m("Нет доступа к коду проекта — войдите заново"));
|
||
const account = await clients[0]!.getUserByLogin(login);
|
||
if (!account) throw new PeppaError(m("Пользователь «{login}» не найден", { login }));
|
||
|
||
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 (!self && !(await managesProject(db, actor, project))) throw new PeppaError(m("Участниками управляет только владелец проекта"));
|
||
if (!(await removeMember(db, project.id, login))) throw new PeppaError(m("«{login}» не участник проекта", { 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 (!(await managesProject(db, actor, project))) throw new PeppaError(m("Участниками управляет только владелец проекта"));
|
||
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(m("Видимость: public или private, не «{value}»", { value: visibility }));
|
||
if (opts.actor && !(await managesProject(db, opts.actor, project))) throw new PeppaError(m("Видимость кода проекта меняет только владелец проекта"));
|
||
const fullName = `${project.giteaOwner}/${project.giteaRepo}`;
|
||
const clients = await repoAdmins(db, project);
|
||
if (!clients.length) throw new PeppaError(m("Нет доступа к коду проекта — войдите заново"));
|
||
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 ? m("нет прав администратора на код проекта") : status === 404 ? m("код проекта не найден") : ((last as Error | null)?.message ?? m("код проекта сейчас недоступен"));
|
||
throw new PeppaError(m("Не удалось сменить видимость {repo}: {error}", { repo: fullName, error: 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 }>();
|
||
|
||
/** Drops the cached repo info (the repo moved or changed outside this module). */
|
||
export const forgetRepoInfo = (projectId: number) => void describeCache.delete(projectId);
|
||
|
||
/** 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;
|
||
}
|