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.

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