~james/core

core/web/src/lib/api/access.ts -rw-r--r-- 1.4 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import type { Did } from "@atcute/lexicons/syntax";
import { error } from "@sveltejs/kit";
import type { BobbinContext, XrpcRequestInit } from "#lib/api/client.ts";
import { items } from "#lib/api/pagination.ts";

export type RepoRole = "owner" | "collaborator" | "none";

export interface RepoAccess {
	readonly role: RepoRole;
	readonly canPush: boolean;
	readonly canAdminister: boolean;
}

export const NO_ACCESS: RepoAccess = { role: "none", canPush: false, canAdminister: false };

export const accessFor = (role: RepoRole): RepoAccess => ({
	role,
	canPush: role !== "none",
	canAdminister: role === "owner"
});

export interface RepoIdentity {
	readonly ownerDid: string;
	readonly repoDid?: string;
}

const COLLABORATOR_PAGES = 5;

export const resolveRepoAccess = async (
	ctx: BobbinContext,
	repo: RepoIdentity,
	viewerDid: string | undefined,
	init?: XrpcRequestInit
): Promise<RepoAccess> => {
	if (!viewerDid) return NO_ACCESS;
	if (viewerDid === repo.ownerDid) return accessFor("owner");
	if (!repo.repoDid) return NO_ACCESS;
	for await (const collaborator of items(
		ctx,
		"org.tangled.repo.listCollaborators",
		{ subject: repo.repoDid as Did, limit: 100 },
		{ ...init, maxPages: COLLABORATOR_PAGES }
	)) {
		if (collaborator.subject === viewerDid) return accessFor("collaborator");
	}
	return NO_ACCESS;
};

export const requireRepoAdmin = (access: RepoAccess): void => {
	if (!access.canAdminister) error(403, "Only the repository owner can change this");
};