Diffinery

codician/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

895 lines · 58.2 KBRaw History
1import type { Env } from "../env.js";
2import type { RepoMeta, Role } from "../repo/types.js";
3import { ROLE_LEVEL } from "../repo/types.js";
4import { HttpError, RESERVED_LOGINS, isValidLogin, isValidName, newId, now, randomToken, sha256 } from "./util.js";
5import { mailForAudit, tokenCreated } from "../mail/notify.js";
6import { enqueueMail } from "../mail/send.js";
7import { archivePrefix, deletePrefixes } from "./storage-keys.js";
8import { inviteProof } from "../auth/invite-proof.js";
9
10export interface Account {
11 id: string;
12 login: string;
13 kind: "user" | "org" | "agent";
14 name: string | null;
15 email: string | null;
16 status: "active" | "pending" | "disabled";
17 site_admin: number;
18 owner_id: string | null;
19 agent_policy: string | null;
20 /** Profile picture version (R2 avatars/<id>/<version>/<size>.webp), null for initials. */
21 avatar_version: number | null;
22 /** "light", "dark" or null (follow the system). */
23 appearance: string | null;
24 /** Organizations: the role every member gets on its repositories ("none", "read", "write" or "admin"). */
25 base_role: string | null;
26 created_at: string;
27}
28
29export interface Repo {
30 id: string;
31 owner_id: string;
32 owner_login: string;
33 owner_kind: "user" | "org" | "agent";
34 name: string;
35 description: string;
36 visibility: "private" | "public";
37 default_branch: string;
38 archived: number;
39 created_at: string;
40 updated_at: string;
41 pushed_at: string | null;
42 /** JSON array of topic names (GitHub's repository topics). */
43 topics?: string;
44 /** Project website (GitHub's `homepage`). */
45 homepage?: string;
46}
47
48export type TokenScope = "read" | "write" | "admin";
49
50export type BaseRole = "none" | "read" | "write" | "admin";
51export const BASE_ROLES: readonly BaseRole[] = ["none", "read", "write", "admin"];
52
53/** An organization's base permission; unset means read, the default for new organizations. */
54export function baseRole(org: Pick<Account, "base_role">): BaseRole {
55 return BASE_ROLES.find((r) => r === org.base_role) ?? "read";
56}
57
58/** Repositories are public or private; GitHub's "internal" is refused like any other value. */
59export function repoVisibility(v: unknown): Repo["visibility"] | undefined {
60 if (v === undefined || v === null || v === "") return undefined;
61 if (v === "public" || v === "private") return v;
62 throw new HttpError(422, "visibility must be public or private", { errors: [{ resource: "Repository", code: "invalid", field: "visibility" }] });
63}
64
65/** Data access for the global directory in D1. */
66export class Directory {
67 constructor(private env: Env) {}
68
69 private get db() {
70 return this.env.DB;
71 }
72
73 // ---------------------------------------------------------------- accounts
74
75 async account(id: string): Promise<Account | null> {
76 return this.db.prepare("SELECT * FROM accounts WHERE id = ?").bind(id).first<Account>();
77 }
78
79 async accountByLogin(login: string): Promise<Account | null> {
80 return this.db.prepare("SELECT * FROM accounts WHERE login = ?").bind(login).first<Account>();
81 }
82
83 async accountByEmail(email: string): Promise<Account | null> {
84 return this.db.prepare("SELECT * FROM accounts WHERE email = ? AND kind = 'user'").bind(email).first<Account>();
85 }
86
87 /**
88 * Only a verified email address makes a bootstrap administrator. Logins on the list are
89 * ignored: whoever creates an account picks its login, so a login proves nothing.
90 */
91 private isBootstrapAdmin(email: string): boolean {
92 const list = (this.env.BOOTSTRAP_ADMINS ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
93 return list.includes(email.toLowerCase());
94 }
95
96 private async uniqueLogin(base: string): Promise<string> {
97 let candidate = base.replace(/[^A-Za-z0-9-]/g, "-").replace(/^-+|-+$/g, "").slice(0, 39) || "user";
98 for (let i = 0; i < 50; i++) {
99 const tryLogin = i === 0 ? candidate : `${candidate}-${i + 1}`;
100 if (!RESERVED_LOGINS.has(tryLogin.toLowerCase()) && !(await this.accountByLogin(tryLogin))) return tryLogin;
101 }
102 candidate = `${candidate}-${randomToken(3)}`;
103 return candidate;
104 }
105
106 /** Find or create the user behind a verified email (Access recovery, invite links, dev sign-in). */
107 async userForEmail(email: string, hints: { name?: string; login?: string; id?: string } = {}): Promise<Account> {
108 const existing = await this.accountByEmail(email);
109 if (existing) {
110 if (existing.status === "pending" && this.isBootstrapAdmin(email)) {
111 await this.db.prepare("UPDATE accounts SET status = 'active', site_admin = 1 WHERE id = ?").bind(existing.id).run();
112 return { ...existing, status: "active", site_admin: 1 };
113 }
114 return existing;
115 }
116 const admin = this.isBootstrapAdmin(email);
117 const login = await this.uniqueLogin(hints.login ?? email.split("@")[0]!);
118 const id = hints.id ?? newId();
119 const hasInvite = await this.db.prepare("SELECT 1 FROM invites WHERE email = ? AND accepted_at IS NULL AND expires_at > ?").bind(email, now()).first();
120 await this.db
121 .prepare("INSERT INTO accounts (id, login, kind, name, email, status, site_admin, created_at) VALUES (?, ?, 'user', ?, ?, ?, ?, ?)")
122 .bind(id, login, hints.name ?? null, email, admin || hasInvite ? "active" : "pending", admin ? 1 : 0, now())
123 .run();
124 if (hasInvite) await this.acceptInvitesForEmail(id, email);
125 return (await this.account(id))!;
126 }
127
128 /** Rename an account and change its display name (and an organization's base permission) in one write, after checking every field. */
129 async updateAccount(id: string, patch: { login?: string; name?: unknown; baseRole?: unknown }): Promise<void> {
130 if (patch.name !== undefined && patch.name !== null && typeof patch.name !== "string") throw new HttpError(422, "name must be a string", { errors: [{ resource: "Account", code: "invalid", field: "name" }] });
131 if (patch.baseRole !== undefined && !BASE_ROLES.includes(patch.baseRole as BaseRole)) throw new HttpError(422, "base permission must be none, read, write or admin", { errors: [{ resource: "Organization", code: "invalid", field: "default_repository_permission" }] });
132 if (patch.login && !isValidLogin(patch.login)) throw new HttpError(422, "invalid or reserved login");
133 if (patch.login) {
134 const clash = await this.accountByLogin(patch.login);
135 if (clash && clash.id !== id) throw new HttpError(422, "login already taken");
136 }
137 // A blank display name clears it, so pages fall back to the login.
138 const name = patch.name === undefined ? undefined : (patch.name as string | null)?.trim() || null;
139 const before = patch.login ? await this.account(id) : null;
140 await this.db
141 .prepare("UPDATE accounts SET login = COALESCE(?, login), name = CASE WHEN ? THEN ? ELSE name END, base_role = CASE WHEN kind = 'org' THEN COALESCE(?, base_role) ELSE base_role END WHERE id = ?")
142 .bind(patch.login ?? null, name === undefined ? 0 : 1, name ?? null, (patch.baseRole as string | undefined) ?? null, id)
143 .run();
144 if (patch.login && before && before.login.toLowerCase() !== patch.login.toLowerCase()) {
145 // The old login keeps leading here (repository URLs, the profile) until another account takes it.
146 await this.db.batch([
147 this.db.prepare("DELETE FROM login_redirects WHERE login = ?").bind(patch.login),
148 this.db.prepare("INSERT OR REPLACE INTO login_redirects (login, account_id, created_at) VALUES (?, ?, ?)").bind(before.login, id, now()),
149 ]);
150 }
151 if (patch.login) {
152 // Repos keep their ids; their Durable Objects cache the owner login, so refresh them.
153 const repos = await this.db.prepare("SELECT id FROM repos WHERE owner_id = ?").bind(id).all<{ id: string }>();
154 for (const r of repos.results) {
155 await this.env.REPO.get(this.env.REPO.idFromName(r.id)).updateMeta({ owner: patch.login });
156 await this.forgetArchives(r.id);
157 }
158 }
159 }
160
161 async setAppearance(id: string, appearance: "light" | "dark" | null): Promise<void> {
162 await this.db.prepare("UPDATE accounts SET appearance = ? WHERE id = ?").bind(appearance, id).run();
163 }
164
165 /** Point an account at a new profile picture version (null: back to initials). */
166 async setAvatarVersion(id: string, version: number | null): Promise<void> {
167 await this.db.prepare("UPDATE accounts SET avatar_version = ? WHERE id = ?").bind(version, id).run();
168 }
169
170 async createOrg(login: string, name: string, creator: Account): Promise<Account> {
171 if (!isValidLogin(login)) throw new HttpError(422, "invalid or reserved organization name");
172 if (await this.accountByLogin(login)) throw new HttpError(422, "name already taken");
173 const id = newId();
174 const t = now();
175 await this.db.batch([
176 this.db.prepare("INSERT INTO accounts (id, login, kind, name, status, base_role, created_at) VALUES (?, ?, 'org', ?, 'active', 'read', ?)").bind(id, login, name || login, t),
177 this.db.prepare("INSERT INTO org_members (org_id, user_id, role, created_at) VALUES (?, ?, 'owner', ?)").bind(id, creator.id, t),
178 ]);
179 return (await this.account(id))!;
180 }
181
182 /**
183 * Delete an organization. Refused while it still owns repositories (transfer or delete them first),
184 * container images or an import in progress. Its agents are disabled (their tokens revoked), its
185 * members, pending invitations, secrets and variables removed, and its login freed. The account row
186 * stays, disabled under a placeholder login, because the audit log, import history and its agents
187 * still refer to it. Repositories transferred out of it keep redirecting from their old URLs.
188 */
189 async deleteOrg(org: Account): Promise<void> {
190 if (org.kind !== "org") throw new HttpError(404, "not an organization");
191 const count = async (q: string) => (await this.db.prepare(q).bind(org.id).first<{ n: number }>())?.n ?? 0;
192 const repos = await count("SELECT count(*) AS n FROM repos WHERE owner_id = ?");
193 if (repos) throw new HttpError(422, `${org.login} still owns ${repos} ${repos === 1 ? "repository" : "repositories"}; transfer or delete ${repos === 1 ? "it" : "them"} before deleting the organization`);
194 const images = await count("SELECT count(*) AS n FROM packages WHERE owner_id = ?");
195 if (images) throw new HttpError(422, `${org.login} still owns ${images} container ${images === 1 ? "image" : "images"}; delete ${images === 1 ? "it" : "them"} before deleting the organization`);
196 const imports = await count("SELECT count(*) AS n FROM imports WHERE target_owner_id = ? AND status IN ('draft', 'queued', 'running')");
197 if (imports) throw new HttpError(422, `an import into ${org.login} is still in progress; wait for it to finish or cancel it first`);
198 const agents = await this.db.prepare("SELECT id FROM accounts WHERE kind = 'agent' AND owner_id = ? AND status != 'disabled'").bind(org.id).all<{ id: string }>();
199 for (const a of agents.results) await this.setStatus(a.id, "disabled");
200 await this.db.batch([
201 this.db.prepare("DELETE FROM org_members WHERE org_id = ?").bind(org.id),
202 this.db.prepare("DELETE FROM invites WHERE org_id = ? AND accepted_at IS NULL").bind(org.id),
203 this.db.prepare("DELETE FROM org_secrets WHERE org_id = ?").bind(org.id),
204 this.db.prepare("DELETE FROM org_secret_repos WHERE org_id = ?").bind(org.id),
205 this.db.prepare("DELETE FROM org_variables WHERE org_id = ?").bind(org.id),
206 this.db.prepare("DELETE FROM login_redirects WHERE account_id = ?").bind(org.id),
207 this.db.prepare("UPDATE accounts SET login = ?, status = 'disabled' WHERE id = ?").bind(`deleted-${org.id}`, org.id),
208 ]);
209 }
210
211 /** Whether an account sees an organization's settings such as its base permission: members, the
212 * organization's own agents, agents of members, and site admins. */
213 async inOrg(orgId: string, account: Account): Promise<boolean> {
214 if (account.site_admin) return true;
215 if (account.kind === "agent") return account.owner_id === orgId || (!!account.owner_id && !!(await this.orgRole(orgId, account.owner_id)));
216 return !!(await this.orgRole(orgId, account.id));
217 }
218
219 async orgRole(orgId: string, userId: string): Promise<"owner" | "admin" | "member" | null> {
220 const r = await this.db.prepare("SELECT role FROM org_members WHERE org_id = ? AND user_id = ?").bind(orgId, userId).first<{ role: "owner" | "admin" | "member" }>();
221 return r?.role ?? null;
222 }
223
224 async orgsFor(userId: string): Promise<Array<Account & { role: string }>> {
225 const r = await this.db.prepare("SELECT a.*, m.role FROM org_members m JOIN accounts a ON a.id = m.org_id WHERE m.user_id = ? ORDER BY a.login").bind(userId).all<Account & { role: string }>();
226 return r.results;
227 }
228
229 async orgMembers(orgId: string): Promise<Array<Account & { role: string }>> {
230 const r = await this.db.prepare("SELECT a.*, m.role FROM org_members m JOIN accounts a ON a.id = m.user_id WHERE m.org_id = ? ORDER BY a.login").bind(orgId).all<Account & { role: string }>();
231 return r.results;
232 }
233
234 async setOrgMember(orgId: string, userId: string, role: "owner" | "admin" | "member" | null, by?: Account): Promise<void> {
235 const previous = await this.orgRole(orgId, userId);
236 await this.writeOrgMember(orgId, userId, role);
237 if (previous !== role) {
238 const org = await this.account(orgId);
239 if (!org) return;
240 await enqueueMail(this.env, [{ kind: "org_membership", data: { org: org.login, role, previous, by: by && by.id !== userId ? by.login : undefined }, to: { accountId: userId }, reason: "account", at: now() }]);
241 // A heads-up on Diffinery too when someone else adds you.
242 if (role && !previous && by && by.id !== userId) await this.notify([userId], { kind: "org_membership", title: `${by.login} added you to ${org.login} as ${role === "admin" ? "an admin" : `a${role === "owner" ? "n" : ""} ${role}`}`, url: `/${org.login}` });
243 }
244 }
245
246 /**
247 * Add someone to an organization by username or email, like GitHub's "Add people": a username joins
248 * right away and gets a heads-up; an email address gets an invitation that joins the organization
249 * when accepted (creating the account if there is none).
250 */
251 async addOrgPerson(org: Account, by: Account, who: string, role: "owner" | "admin" | "member"): Promise<{ added: Account } | { invited: { email: string; url: string } }> {
252 const q = who.trim().replace(/^@/, "");
253 if (!q) throw new HttpError(422, "enter a username or an email address");
254 const email = q.includes("@");
255 if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(q)) throw new HttpError(422, "enter a valid email address");
256 // An email address always gets an invitation, even when it belongs to an account: adding the
257 // account directly would tell the admin its username, and the person hasn't agreed to join.
258 if (email) {
259 const inv = await this.createInvite(by, { email: q, orgId: org.id, role });
260 return { invited: { email: q, url: inv.url } };
261 }
262 const user = await this.accountByLogin(q);
263 if (user) {
264 if (user.kind !== "user") throw new HttpError(422, `${user.login} is not a person; agents belong to an organization through Settings → Agents`);
265 if (user.status === "disabled") throw new HttpError(422, `${user.login}'s account is disabled`);
266 if (await this.orgRole(org.id, user.id)) throw new HttpError(422, `${user.login} is already a member of ${org.login}`);
267 // An admin vouching for someone waiting for an invite lets them in.
268 if (user.status === "pending") await this.setStatus(user.id, "active");
269 await this.setOrgMember(org.id, user.id, role, by);
270 return { added: user };
271 }
272 throw new HttpError(404, `no one has the username ${q}; to invite someone new, enter their email address`);
273 }
274
275 /** Add a collaborator by username (a person or an agent), or invite an email address. */
276 async addRepoPerson(repo: Repo, by: Account, who: string, role: Role): Promise<{ added: Account } | { invited: { email: string; url: string } }> {
277 const q = who.trim().replace(/^@/, "");
278 if (!q) throw new HttpError(422, "enter a username or an email address");
279 const email = q.includes("@");
280 if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(q)) throw new HttpError(422, "enter a valid email address");
281 // As for organizations, an email address always gets an invitation.
282 if (email) {
283 const inv = await this.createInvite(by, { email: q, repoId: repo.id, role });
284 return { invited: { email: q, url: inv.url } };
285 }
286 const account = await this.accountByLogin(q);
287 if (account) {
288 if (account.kind === "org") throw new HttpError(422, `${account.login} is an organization; add its people instead`);
289 if (account.status === "disabled") throw new HttpError(422, `${account.login}'s account is disabled`);
290 if (account.status === "pending") await this.setStatus(account.id, "active");
291 await this.setCollaborator(repo.id, account.id, role);
292 if (account.id !== by.id) await this.notify([account.id], { repoId: repo.id, kind: "repo_access", title: `${by.login} gave you ${role} access to ${repo.owner_login}/${repo.name}`, url: `/${repo.owner_login}/${repo.name}` });
293 return { added: account };
294 }
295 throw new HttpError(404, `no one has the username ${q}; to invite someone new, enter their email address`);
296 }
297
298 /** Revoke a pending invitation to an organization, a repository, or (neither) the site. False if there was none. */
299 async revokeInvite(id: string, scope: { orgId?: string; repoId?: string }): Promise<boolean> {
300 const r = await this.db
301 .prepare("DELETE FROM invites WHERE id = ? AND accepted_at IS NULL AND org_id IS ? AND repo_id IS ?")
302 .bind(id, scope.orgId ?? null, scope.repoId ?? null)
303 .run();
304 return (r.meta?.changes ?? 0) > 0;
305 }
306
307 private async writeOrgMember(orgId: string, userId: string, role: "owner" | "admin" | "member" | null): Promise<void> {
308 // Removing or demoting the last owner would leave nobody able to manage the organization.
309 if (role !== "owner" && (await this.orgRole(orgId, userId)) === "owner") {
310 const owners = await this.db.prepare("SELECT count(*) AS n FROM org_members WHERE org_id = ? AND role = 'owner' AND user_id != ?").bind(orgId, userId).first<{ n: number }>();
311 if (!owners?.n) throw new HttpError(422, "an organization needs at least one owner; make someone else an owner first");
312 }
313 if (role === null) {
314 // Their grants on the organization's repositories (including the admin grant for repositories they
315 // created) go too, for them and their agents. Roles are computed per request, so tokens lose access at once.
316 await this.db.batch([
317 this.db.prepare("DELETE FROM org_members WHERE org_id = ? AND user_id = ?").bind(orgId, userId),
318 this.db
319 .prepare("DELETE FROM repo_access WHERE repo_id IN (SELECT id FROM repos WHERE owner_id = ?) AND account_id IN (SELECT ? UNION SELECT id FROM accounts WHERE kind = 'agent' AND owner_id = ?)")
320 .bind(orgId, userId, userId),
321 ]);
322 return;
323 }
324 await this.db.prepare("INSERT INTO org_members (org_id, user_id, role, created_at) VALUES (?, ?, ?, ?) ON CONFLICT(org_id, user_id) DO UPDATE SET role = excluded.role").bind(orgId, userId, role, now()).run();
325 }
326
327 async users(): Promise<Account[]> {
328 return (await this.db.prepare("SELECT * FROM accounts WHERE kind = 'user' ORDER BY login").all<Account>()).results;
329 }
330
331 async setStatus(id: string, status: Account["status"]): Promise<void> {
332 const before = await this.account(id);
333 await this.db.prepare("UPDATE accounts SET status = ? WHERE id = ?").bind(status, id).run();
334 if (status === "disabled") await this.db.prepare("UPDATE tokens SET revoked_at = ? WHERE account_id = ? AND revoked_at IS NULL").bind(now(), id).run();
335 // A disabled account's browser sessions end too.
336 if (status === "disabled") await this.db.prepare("DELETE FROM sessions WHERE account_id = ?").bind(id).run();
337 // People hear when they are disabled or enabled again (not when an invite activates them).
338 if (before?.kind === "user" && before.status !== status && (status === "disabled" || before.status === "disabled")) {
339 await enqueueMail(this.env, [{ kind: "account_status", data: { status: status === "disabled" ? "disabled" : "active" }, to: { accountId: id }, reason: "account", at: now() }]);
340 }
341 }
342
343 // ---------------------------------------------------------------- agents
344
345 async createAgent(owner: Account, input: { login: string; name?: string; orgId?: string; policy?: Record<string, unknown> }): Promise<Account> {
346 if (!isValidLogin(input.login)) throw new HttpError(422, "invalid or reserved agent name");
347 const login = input.login.endsWith("[bot]") ? input.login : `${input.login}`;
348 if (await this.accountByLogin(login)) throw new HttpError(422, "name already taken");
349 const id = newId();
350 const ownerId = input.orgId ?? owner.id;
351 if (input.orgId) {
352 const role = await this.orgRole(input.orgId, owner.id);
353 if (role !== "owner" && role !== "admin") throw new HttpError(403, "only organization admins can create organization agents");
354 }
355 const policy = { maxRole: "write", canMergeProtected: false, budgetUsdMonthly: null, ...input.policy };
356 await this.db
357 .prepare("INSERT INTO accounts (id, login, kind, name, status, owner_id, agent_policy, created_at) VALUES (?, ?, 'agent', ?, 'active', ?, ?, ?)")
358 .bind(id, login, input.name?.trim() || login, ownerId, JSON.stringify(policy), now())
359 .run();
360 return (await this.account(id))!;
361 }
362
363 async agentsOwnedBy(ownerIds: string[]): Promise<Account[]> {
364 if (!ownerIds.length) return [];
365 const q = `SELECT * FROM accounts WHERE kind = 'agent' AND owner_id IN (${ownerIds.map(() => "?").join(",")}) ORDER BY login`;
366 return (await this.db.prepare(q).bind(...ownerIds).all<Account>()).results;
367 }
368
369 // ---------------------------------------------------------------- tokens
370
371 /** `importId`: a GitHub import's short-lived push token (see imports/service.ts). */
372 async createToken(account: Account, input: { name: string; scopes?: TokenScope[]; repoIds?: string[] | null; expiresInDays?: number; importId?: string }): Promise<{ token: string; id: string; expiresAt: string }> {
373 const days = Math.min(Math.max(input.expiresInDays ?? 90, 1), 366);
374 const token = `dfy_${randomToken(30)}`;
375 const id = newId();
376 const expiresAt = new Date(Date.now() + days * 86400_000).toISOString();
377 await this.db
378 .prepare("INSERT INTO tokens (id, account_id, name, token_hash, prefix, scopes, repo_ids, expires_at, created_at, import_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
379 .bind(id, account.id, input.name || "token", await sha256(token), token.slice(0, 10), JSON.stringify(input.scopes?.length ? input.scopes : ["write"]), input.repoIds ? JSON.stringify(input.repoIds) : null, expiresAt, now(), input.importId ?? null)
380 .run();
381 // An import's own push token is server-managed and short-lived: no "new token" email.
382 if (!input.importId) await tokenCreated(this.env, this, account, { name: input.name || "token", scopes: input.scopes?.length ? input.scopes : ["write"] }).catch((e) => console.error("token email failed", e));
383 return { token, id, expiresAt };
384 }
385
386 async tokens(accountId: string): Promise<Array<{ id: string; name: string; prefix: string; scopes: string[]; repoIds: string[] | null; expiresAt: string; lastUsedAt: string | null; createdAt: string }>> {
387 // Import push tokens (import_id set) are server-managed and hidden from the personal token list.
388 const r = await this.db.prepare("SELECT * FROM tokens WHERE account_id = ? AND revoked_at IS NULL AND import_id IS NULL ORDER BY created_at DESC").bind(accountId).all<Record<string, string | null>>();
389 return r.results.map((t) => ({ id: t.id!, name: t.name!, prefix: t.prefix!, scopes: JSON.parse(t.scopes!), repoIds: t.repo_ids ? JSON.parse(t.repo_ids) : null, expiresAt: t.expires_at!, lastUsedAt: t.last_used_at ?? null, createdAt: t.created_at! }));
390 }
391
392 async revokeToken(accountId: string, id: string): Promise<void> {
393 await this.db.prepare("UPDATE tokens SET revoked_at = ? WHERE id = ? AND account_id = ?").bind(now(), id, accountId).run();
394 }
395
396 async verifyToken(token: string): Promise<{ id: string; account: Account; scopes: TokenScope[]; repoIds: string[] | null; importId: string | null } | null> {
397 const row = await this.db.prepare("SELECT * FROM tokens WHERE token_hash = ?").bind(await sha256(token)).first<Record<string, string | null>>();
398 if (!row || row.revoked_at || row.expires_at! < now()) return null;
399 const account = await this.account(row.account_id!);
400 if (!account || account.status !== "active") return null;
401 if (!row.last_used_at || Date.now() - Date.parse(row.last_used_at) > 3600_000) {
402 await this.db.prepare("UPDATE tokens SET last_used_at = ? WHERE id = ?").bind(now(), row.id!).run();
403 }
404 return { id: row.id!, account, scopes: JSON.parse(row.scopes!), repoIds: row.repo_ids ? JSON.parse(row.repo_ids) : null, importId: row.import_id ?? null };
405 }
406
407 /** Revoke a token by id whoever owns it (server-managed tokens such as an import's push token). */
408 async revokeTokenById(id: string): Promise<void> {
409 await this.db.prepare("UPDATE tokens SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL").bind(now(), id).run();
410 }
411
412 /** Revoke every live token an import ever minted (not only the current one), so a stale token can never push. */
413 async revokeTokensByImport(importId: string): Promise<void> {
414 await this.db.prepare("UPDATE tokens SET revoked_at = ? WHERE import_id = ? AND revoked_at IS NULL").bind(now(), importId).run();
415 }
416
417 // ---------------------------------------------------------------- invites
418
419 async createInvite(inviter: Account, input: { email: string; orgId?: string; repoId?: string; role: string }): Promise<{ id: string; url: string; token: string }> {
420 if (input.orgId) {
421 if (input.role !== "member" && input.role !== "admin" && input.role !== "owner") throw new HttpError(422, "role must be member, admin or owner");
422 if (input.role === "owner" && !inviter.site_admin && (await this.orgRole(input.orgId, inviter.id)) !== "owner") throw new HttpError(403, "only owners can invite owners");
423 }
424 // One open invitation per address and organization or repository. The email column is NOCASE,
425 // so Bob@x.com and bob@x.com count as the same person.
426 const pending = await this.db
427 .prepare("SELECT 1 FROM invites WHERE email = ? AND org_id IS ? AND repo_id IS ? AND accepted_at IS NULL AND expires_at > ?")
428 .bind(input.email, input.orgId ?? null, input.repoId ?? null, now())
429 .first();
430 if (pending) throw new HttpError(422, `${input.email} already has a pending invitation; revoke it first to send a new one`);
431 // An address that already belongs to a member still gets an invitation (accepting it changes
432 // nothing): refusing would tell the inviter whose address it is.
433 const existing = await this.accountByEmail(input.email);
434 const token = randomToken(24);
435 const id = newId();
436 await this.db
437 .prepare("INSERT INTO invites (id, org_id, repo_id, email, role, token_hash, invited_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
438 .bind(id, input.orgId ?? null, input.repoId ?? null, input.email, input.role, await sha256(token), inviter.id, now(), new Date(Date.now() + 14 * 86400_000).toISOString())
439 .run();
440 // If the person already exists, activate them now so the invite also works from the dashboard.
441 if (existing?.status === "pending") await this.setStatus(existing.id, "active");
442 const url = `${this.env.PUBLIC_URL}/invite/${token}`;
443 await this.mailInvite({ id, email: input.email, org_id: input.orgId ?? null, repo_id: input.repoId ?? null, role: input.role, invited_by: inviter.id, expires_at: new Date(Date.now() + 14 * 86400_000).toISOString() }, token);
444 return { id, url, token };
445 }
446
447 /**
448 * Email an invitation to its address. Only this emailed link carries the proof that lets
449 * someone create an account for the address (auth/invite-proof.ts); the plain link shown to
450 * the inviter leads to a page that sends this email.
451 */
452 async mailInvite(inv: { id: string; email: string; org_id: string | null; repo_id: string | null; role: string; invited_by: string | null; expires_at: string }, token: string): Promise<void> {
453 const proof = await inviteProof(this.env, await sha256(token));
454 const url = `${this.env.PUBLIC_URL}/invite/${token}?proof=${proof}`;
455 const inviter = inv.invited_by ? await this.account(inv.invited_by) : null;
456 const org = inv.org_id ? await this.account(inv.org_id) : null;
457 const repo = inv.repo_id ? await this.repoById(inv.repo_id) : null;
458 const existing = await this.accountByEmail(inv.email);
459 await enqueueMail(this.env, [
460 {
461 kind: "invite",
462 data: { inviter: inviter?.login ?? "diffinery", url, org: org?.login, repo: repo ? `${repo.owner_login}/${repo.name}` : undefined, role: inv.role, expiresAt: inv.expires_at },
463 to: existing ? { accountId: existing.id } : { email: inv.email },
464 reason: "invitation",
465 at: now(),
466 },
467 ]);
468 }
469
470 async invites(filter: { orgId?: string; repoId?: string; site?: boolean; pending?: boolean }): Promise<Array<{ id: string; email: string; role: string; createdAt: string; expiresAt: string; acceptedAt: string | null; invitedBy: string | null }>> {
471 const r = await this.db
472 .prepare(
473 `SELECT i.*, a.login AS inviter FROM invites i LEFT JOIN accounts a ON a.id = i.invited_by WHERE (? IS NULL OR i.org_id = ?) AND (? IS NULL OR i.repo_id = ?)${filter.site ? " AND i.org_id IS NULL AND i.repo_id IS NULL" : ""}${filter.pending ? " AND i.accepted_at IS NULL AND i.expires_at > ?" : ""} ORDER BY i.created_at DESC LIMIT 200`,
474 )
475 .bind(filter.orgId ?? null, filter.orgId ?? null, filter.repoId ?? null, filter.repoId ?? null, ...(filter.pending ? [now()] : []))
476 .all<Record<string, string | null>>();
477 return r.results.map((i) => ({ id: i.id!, email: i.email!, role: i.role!, createdAt: i.created_at!, expiresAt: i.expires_at!, acceptedAt: i.accepted_at ?? null, invitedBy: i.inviter ?? null }));
478 }
479
480 async acceptInvite(token: string, user: Account): Promise<{ orgId: string | null; repoId: string | null }> {
481 const inv = await this.db.prepare("SELECT * FROM invites WHERE token_hash = ?").bind(await sha256(token)).first<Record<string, string | null>>();
482 if (!inv || inv.accepted_at || inv.expires_at! < now()) throw new HttpError(404, "this invite is invalid or has expired");
483 if (inv.email && inv.email.toLowerCase() !== (user.email ?? "").toLowerCase()) throw new HttpError(403, `this invite was sent to ${inv.email}; sign in with that address`);
484 await this.applyInvite(inv, user);
485 return { orgId: inv.org_id ?? null, repoId: inv.repo_id ?? null };
486 }
487
488 private async acceptInvitesForEmail(userId: string, email: string): Promise<void> {
489 const user = (await this.account(userId))!;
490 const r = await this.db.prepare("SELECT * FROM invites WHERE email = ? AND accepted_at IS NULL AND expires_at > ?").bind(email, now()).all<Record<string, string | null>>();
491 for (const inv of r.results) await this.applyInvite(inv, user);
492 }
493
494 private async applyInvite(inv: Record<string, string | null>, user: Account): Promise<void> {
495 const stmts = [this.db.prepare("UPDATE invites SET accepted_at = ?, accepted_by = ? WHERE id = ?").bind(now(), user.id, inv.id!), this.db.prepare("UPDATE accounts SET status = 'active' WHERE id = ? AND status = 'pending'").bind(user.id)];
496 if (inv.org_id) stmts.push(this.db.prepare("INSERT INTO org_members (org_id, user_id, role, created_at) VALUES (?, ?, ?, ?) ON CONFLICT(org_id, user_id) DO NOTHING").bind(inv.org_id, user.id, inv.role === "admin" || inv.role === "owner" ? inv.role : "member", now()));
497 if (inv.repo_id) stmts.push(this.db.prepare("INSERT OR REPLACE INTO repo_access (repo_id, account_id, role) VALUES (?, ?, ?)").bind(inv.repo_id, user.id, inv.role));
498 await this.db.batch(stmts);
499 const org = inv.org_id ? await this.account(inv.org_id) : null;
500 const repo = inv.repo_id ? await this.repoById(inv.repo_id) : null;
501 if (inv.invited_by && inv.invited_by !== user.id) {
502 await enqueueMail(this.env, [
503 { kind: "invite_accepted", data: { login: user.login, email: user.email ?? inv.email ?? "", org: org?.login, repo: repo ? `${repo.owner_login}/${repo.name}` : undefined }, to: { accountId: inv.invited_by }, reason: "account", at: now() },
504 ]);
505 }
506 }
507
508 async requestAccess(accountId: string, note: string): Promise<void> {
509 await this.db.prepare("INSERT OR REPLACE INTO access_requests (account_id, note, created_at) VALUES (?, ?, ?)").bind(accountId, note.slice(0, 500), now()).run();
510 const who = await this.account(accountId);
511 const admins = await this.db.prepare("SELECT id FROM accounts WHERE kind = 'user' AND site_admin = 1 AND status = 'active' LIMIT 20").all<{ id: string }>();
512 if (who) await enqueueMail(this.env, admins.results.map((a) => ({ kind: "access_request" as const, data: { email: who.email ?? "", login: who.login, note: note.slice(0, 500) }, to: { accountId: a.id }, reason: "admin" as const, at: now() })));
513 }
514
515 async accessRequests(): Promise<Array<{ account: Account; note: string; createdAt: string }>> {
516 const r = await this.db.prepare("SELECT a.*, r.note AS req_note, r.created_at AS req_at FROM access_requests r JOIN accounts a ON a.id = r.account_id WHERE a.status = 'pending' ORDER BY r.created_at").all<Account & { req_note: string; req_at: string }>();
517 return r.results.map((x) => ({ account: x, note: x.req_note, createdAt: x.req_at }));
518 }
519
520 // ---------------------------------------------------------------- repositories
521
522 async repo(owner: string, name: string): Promise<Repo | null> {
523 return this.db
524 .prepare("SELECT r.*, a.login AS owner_login, a.kind AS owner_kind FROM repos r JOIN accounts a ON a.id = r.owner_id WHERE a.login = ? AND r.name = ?")
525 .bind(owner, name.replace(/\.git$/, ""))
526 .first<Repo>();
527 }
528
529 async repoById(id: string): Promise<Repo | null> {
530 return this.db.prepare("SELECT r.*, a.login AS owner_login, a.kind AS owner_kind FROM repos r JOIN accounts a ON a.id = r.owner_id WHERE r.id = ?").bind(id).first<Repo>();
531 }
532
533 /** Repositories an account can see. */
534 async reposVisibleTo(account: Account, ownerId?: string): Promise<Repo[]> {
535 if (account.status !== "active") return [];
536 if (account.kind === "agent") {
537 const owner = account.owner_id ? await this.account(account.owner_id) : null;
538 if (!owner || owner.status !== "active") return [];
539 }
540 const params: unknown[] = [];
541 let q = "SELECT r.*, a.login AS owner_login, a.kind AS owner_kind FROM repos r JOIN accounts a ON a.id = r.owner_id";
542 const subjectId = account.kind === "agent" ? account.owner_id! : account.id;
543 if (!account.site_admin) {
544 q += ` WHERE (r.visibility = 'public' OR r.owner_id = ? OR r.owner_id IN (SELECT m.org_id FROM org_members m JOIN accounts o ON o.id = m.org_id WHERE m.user_id = ? AND (m.role != 'member' OR COALESCE(o.base_role, 'read') != 'none')) OR r.id IN (SELECT repo_id FROM repo_access WHERE account_id IN (?, ?)))`;
545 params.push(subjectId, subjectId, account.id, subjectId);
546 } else q += " WHERE 1 = 1";
547 if (ownerId) {
548 q += " AND r.owner_id = ?";
549 params.push(ownerId);
550 }
551 q += " ORDER BY COALESCE(r.pushed_at, r.updated_at) DESC LIMIT 500";
552 return (await this.db.prepare(q).bind(...params).all<Repo>()).results;
553 }
554
555 /** Public repositories, most recently pushed first (for the sitemap). */
556 async publicRepos(limit: number): Promise<Repo[]> {
557 return (
558 await this.db
559 .prepare("SELECT r.*, a.login AS owner_login, a.kind AS owner_kind FROM repos r JOIN accounts a ON a.id = r.owner_id WHERE r.visibility = 'public' ORDER BY COALESCE(r.pushed_at, r.updated_at) DESC LIMIT ?")
560 .bind(limit)
561 .all<Repo>()
562 ).results;
563 }
564
565 /** `o.authorized`: the caller already checked that `creator` may create repositories for `owner` (GitHub imports). */
566 async createRepo(owner: Account, creator: Account, input: { name: string; description?: string; visibility?: string; defaultBranch?: string }, o: { authorized?: boolean } = {}): Promise<Repo> {
567 if (!isValidName(input.name)) throw new HttpError(422, "invalid repository name: use letters, numbers, '.', '-' and '_'");
568 // Like GitHub, a member who creates an organization repository administers it, whatever the base permission.
569 let creatorGrant: string | null = null;
570 if (o.authorized) {
571 // checked by the caller
572 } else if (owner.kind === "org") {
573 const subject = creator.kind === "agent" ? creator.owner_id! : creator.id;
574 const role = await this.orgRole(owner.id, subject);
575 if (!role && !creator.site_admin) throw new HttpError(403, "you are not a member of this organization");
576 if (role === "member") creatorGrant = subject;
577 } else if (owner.id !== creator.id && !creator.site_admin) throw new HttpError(403, "you can only create repositories for yourself or your organizations");
578 if (await this.repo(owner.login, input.name)) throw new HttpError(422, "a repository with this name already exists");
579 const id = newId();
580 const t = now();
581 const branch = input.defaultBranch || "main";
582 await this.db.batch([
583 this.db
584 .prepare("INSERT INTO repos (id, owner_id, name, description, visibility, default_branch, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
585 .bind(id, owner.id, input.name, input.description ?? "", repoVisibility(input.visibility) ?? "private", branch, t, t),
586 ...(creatorGrant ? [this.db.prepare("INSERT INTO repo_access (repo_id, account_id, role) VALUES (?, ?, 'admin')").bind(id, creatorGrant)] : []),
587 // A new repository at a moved one's old name takes it over for good, as on GitHub.
588 ...this.claimName(owner.login, input.name),
589 ]);
590 const meta: RepoMeta = { repoId: id, ownerId: owner.id, owner: owner.login, name: input.name, defaultBranch: branch, ownerKind: owner.kind === "org" ? "org" : "user", archived: false };
591 const stub = this.env.REPO.get(this.env.REPO.idFromName(id));
592 await stub.init(meta);
593 if (owner.kind === "org") {
594 const vars = await this.orgVariables(owner.id);
595 if (vars.length) await stub.setOrgVariables(Object.fromEntries(vars.map((v) => [v.name, v.value])));
596 }
597 return (await this.repoById(id))!;
598 }
599
600 async updateRepo(repo: Repo, patch: { name?: string; description?: string; visibility?: string; defaultBranch?: string; archived?: boolean; homepage?: string; topics?: string[] }): Promise<Repo> {
601 if (patch.name && !isValidName(patch.name)) throw new HttpError(422, "invalid repository name");
602 const renamed = !!patch.name && patch.name !== repo.name;
603 if (renamed && patch.name!.toLowerCase() !== repo.name.toLowerCase() && (await this.repo(repo.owner_login, patch.name!))) {
604 throw new HttpError(422, "a repository with this name already exists", { errors: [{ resource: "Repository", code: "custom", field: "name", message: "name already exists on this account" }] });
605 }
606 await this.db.batch([
607 this.db
608 .prepare("UPDATE repos SET name = COALESCE(?, name), description = COALESCE(?, description), visibility = COALESCE(?, visibility), default_branch = COALESCE(?, default_branch), archived = COALESCE(?, archived), updated_at = ? WHERE id = ?")
609 .bind(patch.name ?? null, patch.description ?? null, repoVisibility(patch.visibility) ?? null, patch.defaultBranch ?? null, patch.archived === undefined ? null : patch.archived ? 1 : 0, now(), repo.id),
610 // A rename leaves a redirect from the old name, like a transfer.
611 ...(renamed ? [this.leaveRedirect(repo), ...this.claimName(repo.owner_login, patch.name!)] : []),
612 ]);
613 if (patch.homepage !== undefined || patch.topics !== undefined) {
614 await this.db
615 .prepare("UPDATE repos SET homepage = COALESCE(?, homepage), topics = COALESCE(?, topics) WHERE id = ?")
616 .bind(patch.homepage ?? null, patch.topics ? JSON.stringify(patch.topics.slice(0, 20)) : null, repo.id)
617 .run();
618 }
619 if (patch.name || patch.defaultBranch) await this.env.REPO.get(this.env.REPO.idFromName(repo.id)).updateMeta({ name: patch.name ?? repo.name, defaultBranch: patch.defaultBranch ?? repo.default_branch });
620 // The repository's object lands pull requests by itself (auto-merge, the merge queue): it must know, and stop.
621 if (patch.archived !== undefined) await this.env.REPO.get(this.env.REPO.idFromName(repo.id)).setArchived(patch.archived);
622 if (renamed) await this.forgetArchives(repo.id);
623 return (await this.repoById(repo.id))!;
624 }
625
626 async deleteRepo(repo: Repo): Promise<void> {
627 await this.db.batch([
628 this.db.prepare("DELETE FROM repo_access WHERE repo_id = ?").bind(repo.id),
629 this.db.prepare("DELETE FROM schedules WHERE repo_id = ?").bind(repo.id),
630 // A deleted repository's old names stop redirecting.
631 this.db.prepare("DELETE FROM repo_redirects WHERE repo_id = ?").bind(repo.id),
632 this.db.prepare("DELETE FROM repos WHERE id = ?").bind(repo.id),
633 ]);
634 // Wipes the Durable Object's storage, then the repository's R2 objects.
635 await this.env.REPO.get(this.env.REPO.idFromName(repo.id)).destroy();
636 }
637
638 /**
639 * Move a repository to another owner, like GitHub's transfer, optionally renaming it. The repository
640 * keeps its id, so its Durable Object (git data, issues, pull requests, runs, secrets, variables,
641 * environments, webhooks, deploy keys, caches) and its R2 objects stay where they are; its packages
642 * move with it, and the old owner/name redirects to the new one. The caller has checked that `by`
643 * administers the repository; this checks the rest: only people transfer, a personal repository only
644 * by its owner, and only to `by`'s own account or an organization `by` owns or administers.
645 */
646 async transferRepo(repo: Repo, by: Account, target: Account, newName?: string): Promise<Repo> {
647 if (by.kind !== "user" || by.status !== "active") throw new HttpError(403, "only people can transfer repositories");
648 if (repo.owner_kind !== "org" && repo.owner_id !== by.id && !by.site_admin) throw new HttpError(403, "only the owner can transfer a personal repository");
649 if (target.kind === "agent" || target.status !== "active") throw new HttpError(422, "repositories can only be transferred to a person or an organization", { errors: [{ resource: "Repository", code: "invalid", field: "new_owner" }] });
650 const targetRole = target.kind === "org" ? await this.orgRole(target.id, by.id) : null;
651 if (target.kind === "user" ? target.id !== by.id : targetRole !== "owner" && targetRole !== "admin") {
652 throw new HttpError(403, "you can transfer repositories only to your own account or to an organization you own or administer");
653 }
654 if (target.id === repo.owner_id) throw new HttpError(422, `${repo.owner_login}/${repo.name} already belongs to ${target.login}`, { errors: [{ resource: "Repository", code: "invalid", field: "new_owner" }] });
655 const name = newName?.trim() || repo.name;
656 if (!isValidName(name)) throw new HttpError(422, "invalid repository name: use letters, numbers, '.', '-' and '_'", { errors: [{ resource: "Repository", code: "invalid", field: "new_name" }] });
657 if (await this.repo(target.login, name)) throw new HttpError(422, `${target.login} already has a repository named ${name}`, { errors: [{ resource: "Repository", code: "custom", field: "name", message: "name already exists on this account" }] });
658 // Packages linked to the repository move with it; an image of the same name under the target would collide.
659 const clash = await this.db
660 .prepare("SELECT p.name FROM packages p WHERE p.owner_id = ? AND p.name IN (SELECT name FROM packages WHERE repo_id = ?) LIMIT 1")
661 .bind(target.id, repo.id)
662 .first<{ name: string }>();
663 if (clash) throw new HttpError(422, `${target.login} already has a container image named ${clash.name}; this repository's image of that name would replace it`);
664 // An import filling the repository works by its owner and name; let it finish first.
665 const stub = this.env.REPO.get(this.env.REPO.idFromName(repo.id));
666 if (await stub.importLockHolder()) throw new HttpError(423, "repository is locked by an import in progress; transfer it once the import finishes");
667 const t = now();
668 await this.db.batch([
669 this.db.prepare("UPDATE repos SET owner_id = ?, name = ?, updated_at = ? WHERE id = ?").bind(target.id, name, t, repo.id),
670 this.leaveRedirect(repo),
671 ...this.claimName(target.login, name),
672 this.db.prepare("INSERT OR REPLACE INTO package_redirects (owner_login, name, package_id, created_at) SELECT ?, name, id, ? FROM packages WHERE repo_id = ?").bind(repo.owner_login, t, repo.id),
673 this.db.prepare("DELETE FROM package_redirects WHERE owner_login = ? AND name IN (SELECT name FROM packages WHERE repo_id = ?)").bind(target.login, repo.id),
674 this.db.prepare("UPDATE packages SET owner_id = ?, updated_at = ? WHERE repo_id = ?").bind(target.id, t, repo.id),
675 // Direct collaborators stay, and a new personal owner needs no grant of its own. Grants that came
676 // with the old organization go, as when someone leaves it: its members' (including the admin grant
677 // of whoever created the repository), their agents' and the organization's own agents'.
678 this.db.prepare("DELETE FROM repo_access WHERE repo_id = ? AND account_id = ?").bind(repo.id, target.id),
679 ...(repo.owner_kind === "org"
680 ? [
681 this.db
682 .prepare("DELETE FROM repo_access WHERE repo_id = ? AND account_id IN (SELECT user_id FROM org_members WHERE org_id = ? UNION SELECT id FROM accounts WHERE kind = 'agent' AND (owner_id = ? OR owner_id IN (SELECT user_id FROM org_members WHERE org_id = ?)))")
683 .bind(repo.id, repo.owner_id, repo.owner_id, repo.owner_id),
684 ]
685 : []),
686 ]);
687 // The Durable Object keeps its id; refresh what it knows about its owner, and swap in the new owner's organization variables.
688 await stub.updateMeta({ owner: target.login, ownerId: target.id, ownerKind: target.kind === "org" ? "org" : "user", name });
689 const vars = target.kind === "org" ? await this.orgVariables(target.id) : [];
690 await stub.setOrgVariables(Object.fromEntries(vars.map((v) => [v.name, v.value])));
691 await this.forgetArchives(repo.id);
692 return (await this.repoById(repo.id))!;
693 }
694
695 /** Cached zipballs and tarballs are named after the owner and repository; drop them when either changes (they are rebuilt on the next download). */
696 private async forgetArchives(repoId: string): Promise<void> {
697 await deletePrefixes(this.env.BUCKET, [archivePrefix(repoId)]).catch((e) => console.error("could not drop cached archives", repoId, e));
698 }
699
700 // ---------------------------------------------------------------- redirects (transfers and renames)
701
702 /** Remember a repository's current owner/name before it moves, so the old URLs lead to it. */
703 private leaveRedirect(repo: Repo): D1PreparedStatement {
704 return this.db.prepare("INSERT OR REPLACE INTO repo_redirects (owner_login, name, repo_id, created_at) VALUES (?, ?, ?, ?)").bind(repo.owner_login, repo.name, repo.id, now());
705 }
706
707 /**
708 * A repository now lives at owner/name: an older redirect from there stops applying, and so do
709 * redirects of images named after it (<owner>/<name> and <owner>/<name>/...), which its own
710 * workflows push to.
711 */
712 private claimName(ownerLogin: string, name: string): D1PreparedStatement[] {
713 return [
714 this.db.prepare("DELETE FROM repo_redirects WHERE owner_login = ? AND name = ?").bind(ownerLogin, name),
715 this.db.prepare("DELETE FROM package_redirects WHERE owner_login = ? AND (name = ? OR substr(name, 1, length(?) + 1) = lower(?) || '/')").bind(ownerLogin, name.toLowerCase(), name, name),
716 ];
717 }
718
719 /**
720 * Where an owner/name that holds no repository now leads: a transferred or renamed repository, or one
721 * under a renamed owner. Callers must apply the same visibility check as for a direct load, so a
722 * redirect never shows that a private repository exists.
723 */
724 async movedRepo(owner: string, name: string): Promise<Repo | null> {
725 const bare = name.replace(/\.git$/, "");
726 const direct = await this.db.prepare("SELECT repo_id FROM repo_redirects WHERE owner_login = ? AND name = ?").bind(owner, bare).first<{ repo_id: string }>();
727 if (direct) return this.repoById(direct.repo_id);
728 const account = await this.renamedAccount(owner);
729 if (!account) return null;
730 const moved = await this.repo(account.login, bare);
731 if (moved) return moved;
732 const again = await this.db.prepare("SELECT repo_id FROM repo_redirects WHERE owner_login = ? AND name = ?").bind(account.login, bare).first<{ repo_id: string }>();
733 return again ? this.repoById(again.repo_id) : null;
734 }
735
736 /** The account that used to have this login, while no account has it now. */
737 async renamedAccount(login: string): Promise<Account | null> {
738 if (await this.accountByLogin(login)) return null;
739 return this.db.prepare("SELECT a.* FROM login_redirects l JOIN accounts a ON a.id = l.account_id WHERE l.login = ? AND a.status = 'active'").bind(login).first<Account>();
740 }
741
742 async setTopics(repoId: string, topics: string[]): Promise<void> {
743 await this.db.prepare("UPDATE repos SET topics = ?, updated_at = ? WHERE id = ?").bind(JSON.stringify(topics), now(), repoId).run();
744 }
745
746 // ---------------------------------------------------------------- organization variables
747
748 async orgVariables(orgId: string): Promise<Array<{ name: string; value: string; updated_at: string }>> {
749 return (await this.db.prepare("SELECT name, value, updated_at FROM org_variables WHERE org_id = ? ORDER BY name").bind(orgId).all<{ name: string; value: string; updated_at: string }>()).results;
750 }
751
752 /** Set (or, with null, delete) organization variables, then copy the set into each of the organization's repositories. */
753 async setOrgVariables(orgId: string, changes: Record<string, string | null>): Promise<void> {
754 const stmts = Object.entries(changes).map(([name, value]) =>
755 value === null
756 ? this.db.prepare("DELETE FROM org_variables WHERE org_id = ? AND name = ?").bind(orgId, name.toUpperCase())
757 : this.db.prepare("INSERT OR REPLACE INTO org_variables (org_id, name, value, updated_at) VALUES (?, ?, ?, ?)").bind(orgId, name.toUpperCase(), value, now()),
758 );
759 if (stmts.length) await this.db.batch(stmts);
760 await this.syncOrgVariables(orgId);
761 }
762
763 /**
764 * Add organization variables only where none exists (ON CONFLICT DO NOTHING), used by imports so
765 * an import never overwrites a value an org admin already set. Returns which names were added and
766 * which were skipped because a variable of that name already existed.
767 */
768 async addOrgVariablesIfAbsent(orgId: string, vars: Record<string, string>): Promise<{ added: string[]; skipped: string[] }> {
769 const before = new Set((await this.orgVariables(orgId)).map((v) => v.name));
770 const added: string[] = [];
771 const skipped: string[] = [];
772 const stmts: D1PreparedStatement[] = [];
773 for (const [rawName, value] of Object.entries(vars)) {
774 const name = rawName.toUpperCase();
775 if (before.has(name)) {
776 skipped.push(name);
777 continue;
778 }
779 added.push(name);
780 stmts.push(this.db.prepare("INSERT INTO org_variables (org_id, name, value, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(org_id, name) DO NOTHING").bind(orgId, name, value, now()));
781 }
782 if (stmts.length) {
783 await this.db.batch(stmts);
784 await this.syncOrgVariables(orgId);
785 }
786 return { added, skipped };
787 }
788
789 /**
790 * Copy the organization's current variable set into each of its repositories' Durable Objects.
791 * Every repository is tried even when one fails, and failures get a second try. Any still failing
792 * make this throw, so the caller can repeat the (idempotent) change: the variables themselves are
793 * already saved, and each copy is the whole set, so a later sync brings a stale repository current.
794 */
795 private async syncOrgVariables(orgId: string): Promise<void> {
796 const vars = Object.fromEntries((await this.orgVariables(orgId)).map((v) => [v.name, v.value]));
797 let ids = (await this.db.prepare("SELECT id FROM repos WHERE owner_id = ?").bind(orgId).all<{ id: string }>()).results.map((r) => r.id);
798 for (let attempt = 0; attempt < 2 && ids.length; attempt++) {
799 const results = await Promise.allSettled(ids.map((id) => this.env.REPO.get(this.env.REPO.idFromName(id)).setOrgVariables(vars)));
800 ids = ids.filter((_, i) => results[i]!.status === "rejected");
801 }
802 if (ids.length) throw new HttpError(503, `the variables were saved, but ${ids.length} ${ids.length === 1 ? "repository wasn't" : "repositories weren't"} updated; repeat the request to finish`);
803 }
804
805 /** The highest role an agent may ever hold (its policy's maxRole, default write). */
806 agentMaxRole(account: Account): Role {
807 const policy = account.agent_policy ? (JSON.parse(account.agent_policy) as { maxRole?: Role }) : {};
808 return policy.maxRole ?? "write";
809 }
810
811 async touchPushed(repoId: string): Promise<void> {
812 await this.db.prepare("UPDATE repos SET pushed_at = ?, updated_at = ? WHERE id = ?").bind(now(), now(), repoId).run();
813 }
814
815 async collaborators(repoId: string): Promise<Array<{ account: Account; role: Role }>> {
816 const r = await this.db.prepare("SELECT a.*, x.role AS access_role FROM repo_access x JOIN accounts a ON a.id = x.account_id WHERE x.repo_id = ? ORDER BY a.login").bind(repoId).all<Account & { access_role: Role }>();
817 return r.results.map((x) => ({ account: x, role: x.access_role }));
818 }
819
820 async setCollaborator(repoId: string, accountId: string, role: Role | null): Promise<void> {
821 const previous = (await this.db.prepare("SELECT role FROM repo_access WHERE repo_id = ? AND account_id = ?").bind(repoId, accountId).first<{ role: Role }>())?.role ?? null;
822 if (role) await this.db.prepare("INSERT OR REPLACE INTO repo_access (repo_id, account_id, role) VALUES (?, ?, ?)").bind(repoId, accountId, role).run();
823 else await this.db.prepare("DELETE FROM repo_access WHERE repo_id = ? AND account_id = ?").bind(repoId, accountId).run();
824 const repo = previous !== role ? await this.repoById(repoId) : null;
825 if (repo) await enqueueMail(this.env, [{ kind: "repo_access", data: { repo: `${repo.owner_login}/${repo.name}`, role, previous }, to: { accountId }, reason: "account", at: now() }]);
826 }
827
828 /** Effective role of an account on a repository (null = no access). */
829 async roleFor(account: Account, repo: Repo): Promise<Role | null> {
830 if (account.status !== "active") return null;
831 if (account.kind === "agent") {
832 if (!account.owner_id) return null;
833 const owner = await this.account(account.owner_id);
834 if (!owner || owner.status !== "active") return null;
835 const ownerRole = owner.kind === "org" ? (repo.owner_id === owner.id ? "admin" : null) : await this.roleFor(owner, repo);
836 if (!ownerRole) return null;
837 const explicit = await this.db.prepare("SELECT role FROM repo_access WHERE repo_id = ? AND account_id = ?").bind(repo.id, account.id).first<{ role: Role }>();
838 const policy = account.agent_policy ? (JSON.parse(account.agent_policy) as { maxRole?: Role }) : {};
839 const cap: Role = explicit?.role ?? policy.maxRole ?? "write";
840 return ROLE_LEVEL[ownerRole] < ROLE_LEVEL[cap] ? ownerRole : cap;
841 }
842 if (account.site_admin) return "admin";
843 let best: Role | null = null;
844 const bump = (r: Role | null) => {
845 if (r && (!best || ROLE_LEVEL[r] > ROLE_LEVEL[best])) best = r;
846 };
847 if (repo.owner_id === account.id) bump("admin");
848 if (repo.owner_kind === "org") {
849 // Owners and admins administer every repository; members get the organization's base permission.
850 const m = await this.db
851 .prepare("SELECT m.role, o.base_role FROM org_members m JOIN accounts o ON o.id = m.org_id WHERE m.org_id = ? AND m.user_id = ?")
852 .bind(repo.owner_id, account.id)
853 .first<{ role: string; base_role: string | null }>();
854 if (m?.role === "owner" || m?.role === "admin") bump("admin");
855 else if (m?.role === "member") {
856 const base = baseRole(m);
857 if (base !== "none") bump(base);
858 }
859 }
860 const explicit = await this.db.prepare("SELECT role FROM repo_access WHERE repo_id = ? AND account_id = ?").bind(repo.id, account.id).first<{ role: Role }>();
861 bump(explicit?.role ?? null);
862 if (repo.visibility !== "private") bump("read");
863 return best;
864 }
865
866 // ---------------------------------------------------------------- notifications and audit
867
868 async notify(accountIds: string[], n: { repoId?: string; kind: string; title: string; url: string }): Promise<void> {
869 const unique = [...new Set(accountIds)];
870 if (!unique.length) return;
871 await this.db.batch(unique.map((id) => this.db.prepare("INSERT INTO notifications (id, account_id, repo_id, kind, title, url, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)").bind(newId(), id, n.repoId ?? null, n.kind, n.title, n.url, now())));
872 }
873
874 async notifications(accountId: string, unreadOnly = false): Promise<Array<{ id: string; kind: string; title: string; url: string; createdAt: string; readAt: string | null }>> {
875 const r = await this.db.prepare(`SELECT * FROM notifications WHERE account_id = ? ${unreadOnly ? "AND read_at IS NULL" : ""} ORDER BY created_at DESC LIMIT 100`).bind(accountId).all<Record<string, string | null>>();
876 return r.results.map((n) => ({ id: n.id!, kind: n.kind!, title: n.title!, url: n.url!, createdAt: n.created_at!, readAt: n.read_at ?? null }));
877 }
878
879 async markRead(accountId: string, id?: string): Promise<void> {
880 await this.db.prepare(`UPDATE notifications SET read_at = ? WHERE account_id = ? ${id ? "AND id = ?" : ""} AND read_at IS NULL`).bind(...(id ? [now(), accountId, id] : [now(), accountId])).run();
881 }
882
883 async audit(entry: { actorId?: string; actorLogin?: string; onBehalfOf?: string; action: string; target?: string; detail?: unknown; at?: string }): Promise<void> {
884 await this.db
885 .prepare("INSERT INTO audit_log (id, at, actor_id, actor_login, on_behalf_of, action, target, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
886 .bind(newId(), entry.at ?? now(), entry.actorId ?? null, entry.actorLogin ?? null, entry.onBehalfOf ?? null, entry.action, entry.target ?? null, entry.detail ? JSON.stringify(entry.detail) : null)
887 .run();
888 // Security emails (sign-ins, passkeys, tokens, push protection…) hang off the audit log.
889 await mailForAudit(this.env, this, entry).catch((e) => console.error("security email failed", entry.action, e));
890 }
891
892 async auditLog(limit = 200): Promise<Array<Record<string, string | null>>> {
893 return (await this.db.prepare("SELECT * FROM audit_log ORDER BY at DESC LIMIT ?").bind(limit).all<Record<string, string | null>>()).results;
894 }
895}