- users.password_hash/password_set_at/disabled_at (migration 0002_local_users) - core/local-users.ts: scrypt, passwordLogin with attempt limits, create/reset/disable - isSuperadmin(db, user) = platform.admins; isUserAllowed honours disabled_at - web: /auth/password + login form, /users for superadmins, Settings → password - Gitea login with a local user's login is refused (giteaLoginRefusal) - local users: projects in peppa-bot namespace, members without Gitea collaboration - CLI: peppa user add|passwd|disable|enable; tests in testkit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
156 lines
6.4 KiB
TypeScript
156 lines
6.4 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 {
|
|
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 };
|
|
}
|
|
|
|
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;
|
|
}
|