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.

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