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.

470 lines · 29.2 KBRaw History
1import type { Env } from "../env.js";
2import type { RepoMeta, Role } from "../repo/types.js";
3import { ROLE_LEVEL } from "../repo/types.js";
4import { HttpError, RESERVED_LOGINS, isValidLogin, isValidName, newId, now, randomToken, sha256 } from "./util.js";
5import { mailForAudit, tokenCreated } from "../mail/notify.js";
6import { enqueueMail } from "../mail/send.js";
7
8export interface Account {
9 id: string;
10 login: string;
11 kind: "user" | "org" | "agent";
12 name: string | null;
13 email: string | null;
14 status: "active" | "pending" | "disabled";
15 site_admin: number;
16 owner_id: string | null;
17 agent_policy: string | null;
18 created_at: string;
19}
20
21export interface Repo {
22 id: string;
23 owner_id: string;
24 owner_login: string;
25 owner_kind: "user" | "org" | "agent";
26 name: string;
27 description: string;
28 visibility: "private" | "internal" | "public";
29 default_branch: string;
30 archived: number;
31 created_at: string;
32 updated_at: string;
33 pushed_at: string | null;
34 /** JSON array of topic names (GitHub's repository topics). */
35 topics?: string;
36}
37
38export type TokenScope = "read" | "write" | "admin";
39
40/** Data access for the global directory in D1. */
41export class Directory {
42 constructor(private env: Env) {}
43
44 private get db() {
45 return this.env.DB;
46 }
47
48 // ---------------------------------------------------------------- accounts
49
50 async account(id: string): Promise<Account | null> {
51 return this.db.prepare("SELECT * FROM accounts WHERE id = ?").bind(id).first<Account>();
52 }
53
54 async accountByLogin(login: string): Promise<Account | null> {
55 return this.db.prepare("SELECT * FROM accounts WHERE login = ?").bind(login).first<Account>();
56 }
57
58 async accountByEmail(email: string): Promise<Account | null> {
59 return this.db.prepare("SELECT * FROM accounts WHERE email = ? AND kind = 'user'").bind(email).first<Account>();
60 }
61
62 private isBootstrapAdmin(email: string, login?: string): boolean {
63 const list = (this.env.BOOTSTRAP_ADMINS ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
64 return list.includes(email.toLowerCase()) || (!!login && list.includes(login.toLowerCase()));
65 }
66
67 private async uniqueLogin(base: string): Promise<string> {
68 let candidate = base.replace(/[^A-Za-z0-9-]/g, "-").replace(/^-+|-+$/g, "").slice(0, 39) || "user";
69 for (let i = 0; i < 50; i++) {
70 const tryLogin = i === 0 ? candidate : `${candidate}-${i + 1}`;
71 if (!RESERVED_LOGINS.has(tryLogin.toLowerCase()) && !(await this.accountByLogin(tryLogin))) return tryLogin;
72 }
73 candidate = `${candidate}-${randomToken(3)}`;
74 return candidate;
75 }
76
77 /** Find or create the user behind a verified email (Access recovery, invite links, dev sign-in). */
78 async userForEmail(email: string, hints: { name?: string; login?: string; id?: string } = {}): Promise<Account> {
79 const existing = await this.accountByEmail(email);
80 if (existing) {
81 if (existing.status === "pending" && this.isBootstrapAdmin(email, existing.login)) {
82 await this.db.prepare("UPDATE accounts SET status = 'active', site_admin = 1 WHERE id = ?").bind(existing.id).run();
83 return { ...existing, status: "active", site_admin: 1 };
84 }
85 return existing;
86 }
87 const admin = this.isBootstrapAdmin(email, hints.login);
88 const login = await this.uniqueLogin(hints.login ?? email.split("@")[0]!);
89 const id = hints.id ?? newId();
90 const hasInvite = await this.db.prepare("SELECT 1 FROM invites WHERE email = ? AND accepted_at IS NULL AND expires_at > ?").bind(email, now()).first();
91 await this.db
92 .prepare("INSERT INTO accounts (id, login, kind, name, email, status, site_admin, created_at) VALUES (?, ?, 'user', ?, ?, ?, ?, ?)")
93 .bind(id, login, hints.name ?? null, email, admin || hasInvite ? "active" : "pending", admin ? 1 : 0, now())
94 .run();
95 if (hasInvite) await this.acceptInvitesForEmail(id, email);
96 return (await this.account(id))!;
97 }
98
99 async updateAccount(id: string, patch: { login?: string; name?: string }): Promise<void> {
100 if (patch.login && !isValidLogin(patch.login)) throw new HttpError(422, "invalid or reserved login");
101 if (patch.login) {
102 const clash = await this.accountByLogin(patch.login);
103 if (clash && clash.id !== id) throw new HttpError(422, "login already taken");
104 }
105 await this.db.prepare("UPDATE accounts SET login = COALESCE(?, login), name = COALESCE(?, name) WHERE id = ?").bind(patch.login ?? null, patch.name ?? null, id).run();
106 if (patch.login) {
107 // Repos keep their ids; their Durable Objects cache the owner login, so refresh them.
108 const repos = await this.db.prepare("SELECT id FROM repos WHERE owner_id = ?").bind(id).all<{ id: string }>();
109 for (const r of repos.results) await this.env.REPO.get(this.env.REPO.idFromName(r.id)).updateMeta({ owner: patch.login });
110 }
111 }
112
113 async createOrg(login: string, name: string, creator: Account): Promise<Account> {
114 if (!isValidLogin(login)) throw new HttpError(422, "invalid or reserved organization name");
115 if (await this.accountByLogin(login)) throw new HttpError(422, "name already taken");
116 const id = newId();
117 const t = now();
118 await this.db.batch([
119 this.db.prepare("INSERT INTO accounts (id, login, kind, name, status, created_at) VALUES (?, ?, 'org', ?, 'active', ?)").bind(id, login, name || login, t),
120 this.db.prepare("INSERT INTO org_members (org_id, user_id, role, created_at) VALUES (?, ?, 'owner', ?)").bind(id, creator.id, t),
121 ]);
122 return (await this.account(id))!;
123 }
124
125 async orgRole(orgId: string, userId: string): Promise<"owner" | "admin" | "member" | null> {
126 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" }>();
127 return r?.role ?? null;
128 }
129
130 async orgsFor(userId: string): Promise<Array<Account & { role: string }>> {
131 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 }>();
132 return r.results;
133 }
134
135 async orgMembers(orgId: string): Promise<Array<Account & { role: string }>> {
136 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 }>();
137 return r.results;
138 }
139
140 async setOrgMember(orgId: string, userId: string, role: "owner" | "admin" | "member" | null): Promise<void> {
141 const previous = await this.orgRole(orgId, userId);
142 await this.writeOrgMember(orgId, userId, role);
143 if (previous !== role) {
144 const org = await this.account(orgId);
145 if (org) await enqueueMail(this.env, [{ kind: "org_membership", data: { org: org.login, role, previous }, to: { accountId: userId }, reason: "account", at: now() }]);
146 }
147 }
148
149 private async writeOrgMember(orgId: string, userId: string, role: "owner" | "admin" | "member" | null): Promise<void> {
150 if (role === null) {
151 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 }>();
152 if ((await this.orgRole(orgId, userId)) === "owner" && !owners?.n) throw new HttpError(422, "an organization needs at least one owner");
153 await this.db.prepare("DELETE FROM org_members WHERE org_id = ? AND user_id = ?").bind(orgId, userId).run();
154 // Removing someone revokes their tokens' reach immediately: roles are computed per request.
155 return;
156 }
157 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();
158 }
159
160 async users(): Promise<Account[]> {
161 return (await this.db.prepare("SELECT * FROM accounts WHERE kind = 'user' ORDER BY login").all<Account>()).results;
162 }
163
164 async setStatus(id: string, status: Account["status"]): Promise<void> {
165 const before = await this.account(id);
166 await this.db.prepare("UPDATE accounts SET status = ? WHERE id = ?").bind(status, id).run();
167 if (status === "disabled") await this.db.prepare("UPDATE tokens SET revoked_at = ? WHERE account_id = ? AND revoked_at IS NULL").bind(now(), id).run();
168 // A disabled account's browser sessions end too.
169 if (status === "disabled") await this.db.prepare("DELETE FROM sessions WHERE account_id = ?").bind(id).run();
170 // People hear when they are disabled or enabled again (not when an invite activates them).
171 if (before?.kind === "user" && before.status !== status && (status === "disabled" || before.status === "disabled")) {
172 await enqueueMail(this.env, [{ kind: "account_status", data: { status: status === "disabled" ? "disabled" : "active" }, to: { accountId: id }, reason: "account", at: now() }]);
173 }
174 }
175
176 // ---------------------------------------------------------------- agents
177
178 async createAgent(owner: Account, input: { login: string; name?: string; orgId?: string; policy?: Record<string, unknown> }): Promise<Account> {
179 if (!isValidLogin(input.login)) throw new HttpError(422, "invalid or reserved agent name");
180 const login = input.login.endsWith("[bot]") ? input.login : `${input.login}`;
181 if (await this.accountByLogin(login)) throw new HttpError(422, "name already taken");
182 const id = newId();
183 const ownerId = input.orgId ?? owner.id;
184 if (input.orgId) {
185 const role = await this.orgRole(input.orgId, owner.id);
186 if (role !== "owner" && role !== "admin") throw new HttpError(403, "only organization admins can create organization agents");
187 }
188 const policy = { maxRole: "write", canMergeProtected: false, budgetUsdMonthly: null, ...input.policy };
189 await this.db
190 .prepare("INSERT INTO accounts (id, login, kind, name, status, owner_id, agent_policy, created_at) VALUES (?, ?, 'agent', ?, 'active', ?, ?, ?)")
191 .bind(id, login, input.name ?? login, ownerId, JSON.stringify(policy), now())
192 .run();
193 return (await this.account(id))!;
194 }
195
196 async agentsOwnedBy(ownerIds: string[]): Promise<Account[]> {
197 if (!ownerIds.length) return [];
198 const q = `SELECT * FROM accounts WHERE kind = 'agent' AND owner_id IN (${ownerIds.map(() => "?").join(",")}) ORDER BY login`;
199 return (await this.db.prepare(q).bind(...ownerIds).all<Account>()).results;
200 }
201
202 // ---------------------------------------------------------------- tokens
203
204 async createToken(account: Account, input: { name: string; scopes?: TokenScope[]; repoIds?: string[] | null; expiresInDays?: number }): Promise<{ token: string; id: string; expiresAt: string }> {
205 const days = Math.min(Math.max(input.expiresInDays ?? 90, 1), 366);
206 const token = `dfy_${randomToken(30)}`;
207 const id = newId();
208 const expiresAt = new Date(Date.now() + days * 86400_000).toISOString();
209 await this.db
210 .prepare("INSERT INTO tokens (id, account_id, name, token_hash, prefix, scopes, repo_ids, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
211 .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())
212 .run();
213 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));
214 return { token, id, expiresAt };
215 }
216
217 async tokens(accountId: string): Promise<Array<{ id: string; name: string; prefix: string; scopes: string[]; repoIds: string[] | null; expiresAt: string; lastUsedAt: string | null; createdAt: string }>> {
218 const r = await this.db.prepare("SELECT * FROM tokens WHERE account_id = ? AND revoked_at IS NULL ORDER BY created_at DESC").bind(accountId).all<Record<string, string | null>>();
219 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! }));
220 }
221
222 async revokeToken(accountId: string, id: string): Promise<void> {
223 await this.db.prepare("UPDATE tokens SET revoked_at = ? WHERE id = ? AND account_id = ?").bind(now(), id, accountId).run();
224 }
225
226 async verifyToken(token: string): Promise<{ account: Account; scopes: TokenScope[]; repoIds: string[] | null } | null> {
227 const row = await this.db.prepare("SELECT * FROM tokens WHERE token_hash = ?").bind(await sha256(token)).first<Record<string, string | null>>();
228 if (!row || row.revoked_at || row.expires_at! < now()) return null;
229 const account = await this.account(row.account_id!);
230 if (!account || account.status !== "active") return null;
231 if (!row.last_used_at || Date.now() - Date.parse(row.last_used_at) > 3600_000) {
232 await this.db.prepare("UPDATE tokens SET last_used_at = ? WHERE id = ?").bind(now(), row.id!).run();
233 }
234 return { account, scopes: JSON.parse(row.scopes!), repoIds: row.repo_ids ? JSON.parse(row.repo_ids) : null };
235 }
236
237 // ---------------------------------------------------------------- invites
238
239 async createInvite(inviter: Account, input: { email: string; orgId?: string; repoId?: string; role: string }): Promise<{ id: string; url: string; token: string }> {
240 const token = randomToken(24);
241 const id = newId();
242 await this.db
243 .prepare("INSERT INTO invites (id, org_id, repo_id, email, role, token_hash, invited_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
244 .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())
245 .run();
246 // If the person already exists, activate them now so the invite also works from the dashboard.
247 const existing = await this.accountByEmail(input.email);
248 if (existing?.status === "pending") await this.setStatus(existing.id, "active");
249 const url = `${this.env.PUBLIC_URL}/invite/${token}`;
250 const org = input.orgId ? await this.account(input.orgId) : null;
251 const repo = input.repoId ? await this.repoById(input.repoId) : null;
252 await enqueueMail(this.env, [
253 {
254 kind: "invite",
255 data: { inviter: inviter.login, url, org: org?.login, repo: repo ? `${repo.owner_login}/${repo.name}` : undefined, role: input.role, expiresAt: new Date(Date.now() + 14 * 86400_000).toISOString() },
256 to: existing ? { accountId: existing.id } : { email: input.email },
257 reason: "invitation",
258 at: now(),
259 },
260 ]);
261 return { id, url, token };
262 }
263
264 async invites(filter: { orgId?: string }): Promise<Array<{ id: string; email: string; role: string; createdAt: string; expiresAt: string; acceptedAt: string | null }>> {
265 const r = await this.db.prepare("SELECT * FROM invites WHERE (? IS NULL OR org_id = ?) ORDER BY created_at DESC LIMIT 200").bind(filter.orgId ?? null, filter.orgId ?? null).all<Record<string, string | null>>();
266 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 }));
267 }
268
269 async acceptInvite(token: string, user: Account): Promise<{ orgId: string | null; repoId: string | null }> {
270 const inv = await this.db.prepare("SELECT * FROM invites WHERE token_hash = ?").bind(await sha256(token)).first<Record<string, string | null>>();
271 if (!inv || inv.accepted_at || inv.expires_at! < now()) throw new HttpError(404, "this invite is invalid or has expired");
272 if (inv.email && user.email && inv.email.toLowerCase() !== user.email.toLowerCase()) throw new HttpError(403, `this invite was sent to ${inv.email}; sign in with that address`);
273 await this.applyInvite(inv, user);
274 return { orgId: inv.org_id ?? null, repoId: inv.repo_id ?? null };
275 }
276
277 private async acceptInvitesForEmail(userId: string, email: string): Promise<void> {
278 const user = (await this.account(userId))!;
279 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>>();
280 for (const inv of r.results) await this.applyInvite(inv, user);
281 }
282
283 private async applyInvite(inv: Record<string, string | null>, user: Account): Promise<void> {
284 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)];
285 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()));
286 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));
287 await this.db.batch(stmts);
288 const org = inv.org_id ? await this.account(inv.org_id) : null;
289 const repo = inv.repo_id ? await this.repoById(inv.repo_id) : null;
290 if (inv.invited_by && inv.invited_by !== user.id) {
291 await enqueueMail(this.env, [
292 { 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() },
293 ]);
294 }
295 }
296
297 async requestAccess(accountId: string, note: string): Promise<void> {
298 await this.db.prepare("INSERT OR REPLACE INTO access_requests (account_id, note, created_at) VALUES (?, ?, ?)").bind(accountId, note.slice(0, 500), now()).run();
299 const who = await this.account(accountId);
300 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 }>();
301 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() })));
302 }
303
304 async accessRequests(): Promise<Array<{ account: Account; note: string; createdAt: string }>> {
305 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 }>();
306 return r.results.map((x) => ({ account: x, note: x.req_note, createdAt: x.req_at }));
307 }
308
309 // ---------------------------------------------------------------- repositories
310
311 async repo(owner: string, name: string): Promise<Repo | null> {
312 return this.db
313 .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 = ?")
314 .bind(owner, name.replace(/\.git$/, ""))
315 .first<Repo>();
316 }
317
318 async repoById(id: string): Promise<Repo | null> {
319 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>();
320 }
321
322 /** Repositories an account can see. */
323 async reposVisibleTo(account: Account, ownerId?: string): Promise<Repo[]> {
324 if (account.status !== "active") return [];
325 if (account.kind === "agent") {
326 const owner = account.owner_id ? await this.account(account.owner_id) : null;
327 if (!owner || owner.status !== "active") return [];
328 }
329 const params: unknown[] = [];
330 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";
331 const subjectId = account.kind === "agent" ? account.owner_id! : account.id;
332 if (!account.site_admin) {
333 q += ` WHERE (r.visibility IN ('internal', 'public') OR r.owner_id = ? OR r.owner_id IN (SELECT org_id FROM org_members WHERE user_id = ?) OR r.id IN (SELECT repo_id FROM repo_access WHERE account_id IN (?, ?)))`;
334 params.push(subjectId, subjectId, account.id, subjectId);
335 } else q += " WHERE 1 = 1";
336 if (ownerId) {
337 q += " AND r.owner_id = ?";
338 params.push(ownerId);
339 }
340 q += " ORDER BY COALESCE(r.pushed_at, r.updated_at) DESC LIMIT 500";
341 return (await this.db.prepare(q).bind(...params).all<Repo>()).results;
342 }
343
344 /** Public repositories, most recently pushed first (for the sitemap). */
345 async publicRepos(limit: number): Promise<Repo[]> {
346 return (
347 await this.db
348 .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 ?")
349 .bind(limit)
350 .all<Repo>()
351 ).results;
352 }
353
354 async createRepo(owner: Account, creator: Account, input: { name: string; description?: string; visibility?: Repo["visibility"]; defaultBranch?: string }): Promise<Repo> {
355 if (!isValidName(input.name)) throw new HttpError(422, "invalid repository name: use letters, numbers, '.', '-' and '_'");
356 if (owner.kind === "org") {
357 const role = await this.orgRole(owner.id, creator.kind === "agent" ? creator.owner_id! : creator.id);
358 if (!role && !creator.site_admin) throw new HttpError(403, "you are not a member of this organization");
359 } else if (owner.id !== creator.id && !creator.site_admin) throw new HttpError(403, "you can only create repositories for yourself or your organizations");
360 if (await this.repo(owner.login, input.name)) throw new HttpError(422, "a repository with this name already exists");
361 const id = newId();
362 const t = now();
363 const branch = input.defaultBranch || "main";
364 await this.db
365 .prepare("INSERT INTO repos (id, owner_id, name, description, visibility, default_branch, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
366 .bind(id, owner.id, input.name, input.description ?? "", input.visibility ?? "private", branch, t, t)
367 .run();
368 const meta: RepoMeta = { repoId: id, ownerId: owner.id, owner: owner.login, name: input.name, defaultBranch: branch, ownerKind: owner.kind === "org" ? "org" : "user" };
369 await this.env.REPO.get(this.env.REPO.idFromName(id)).init(meta);
370 return (await this.repoById(id))!;
371 }
372
373 async updateRepo(repo: Repo, patch: { name?: string; description?: string; visibility?: Repo["visibility"]; defaultBranch?: string; archived?: boolean }): Promise<Repo> {
374 if (patch.name && !isValidName(patch.name)) throw new HttpError(422, "invalid repository name");
375 await this.db
376 .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 = ?")
377 .bind(patch.name ?? null, patch.description ?? null, patch.visibility ?? null, patch.defaultBranch ?? null, patch.archived === undefined ? null : patch.archived ? 1 : 0, now(), repo.id)
378 .run();
379 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 });
380 return (await this.repoById(repo.id))!;
381 }
382
383 async deleteRepo(repo: Repo): Promise<void> {
384 await this.db.batch([this.db.prepare("DELETE FROM repo_access WHERE repo_id = ?").bind(repo.id), this.db.prepare("DELETE FROM schedules WHERE repo_id = ?").bind(repo.id), this.db.prepare("DELETE FROM repos WHERE id = ?").bind(repo.id)]);
385 // R2 objects under repos/<id>/ are removed by the cleanup job; the DO's storage is wiped here.
386 await this.env.REPO.get(this.env.REPO.idFromName(repo.id)).destroy();
387 }
388
389 async setTopics(repoId: string, topics: string[]): Promise<void> {
390 await this.db.prepare("UPDATE repos SET topics = ?, updated_at = ? WHERE id = ?").bind(JSON.stringify(topics), now(), repoId).run();
391 }
392
393 async touchPushed(repoId: string): Promise<void> {
394 await this.db.prepare("UPDATE repos SET pushed_at = ?, updated_at = ? WHERE id = ?").bind(now(), now(), repoId).run();
395 }
396
397 async collaborators(repoId: string): Promise<Array<{ account: Account; role: Role }>> {
398 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 }>();
399 return r.results.map((x) => ({ account: x, role: x.access_role }));
400 }
401
402 async setCollaborator(repoId: string, accountId: string, role: Role | null): Promise<void> {
403 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;
404 if (role) await this.db.prepare("INSERT OR REPLACE INTO repo_access (repo_id, account_id, role) VALUES (?, ?, ?)").bind(repoId, accountId, role).run();
405 else await this.db.prepare("DELETE FROM repo_access WHERE repo_id = ? AND account_id = ?").bind(repoId, accountId).run();
406 const repo = previous !== role ? await this.repoById(repoId) : null;
407 if (repo) await enqueueMail(this.env, [{ kind: "repo_access", data: { repo: `${repo.owner_login}/${repo.name}`, role, previous }, to: { accountId }, reason: "account", at: now() }]);
408 }
409
410 /** Effective role of an account on a repository (null = no access). */
411 async roleFor(account: Account, repo: Repo): Promise<Role | null> {
412 if (account.status !== "active") return null;
413 if (account.kind === "agent") {
414 if (!account.owner_id) return null;
415 const owner = await this.account(account.owner_id);
416 if (!owner || owner.status !== "active") return null;
417 const ownerRole = owner.kind === "org" ? (repo.owner_id === owner.id ? "admin" : null) : await this.roleFor(owner, repo);
418 if (!ownerRole) return null;
419 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 }>();
420 const policy = account.agent_policy ? (JSON.parse(account.agent_policy) as { maxRole?: Role }) : {};
421 const cap: Role = explicit?.role ?? policy.maxRole ?? "write";
422 return ROLE_LEVEL[ownerRole] < ROLE_LEVEL[cap] ? ownerRole : cap;
423 }
424 if (account.site_admin) return "admin";
425 let best: Role | null = null;
426 const bump = (r: Role | null) => {
427 if (r && (!best || ROLE_LEVEL[r] > ROLE_LEVEL[best])) best = r;
428 };
429 if (repo.owner_id === account.id) bump("admin");
430 if (repo.owner_kind === "org") {
431 const orgRole = await this.orgRole(repo.owner_id, account.id);
432 if (orgRole === "owner" || orgRole === "admin") bump("admin");
433 else if (orgRole === "member") bump("write");
434 }
435 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 }>();
436 bump(explicit?.role ?? null);
437 if (repo.visibility !== "private") bump("read");
438 return best;
439 }
440
441 // ---------------------------------------------------------------- notifications and audit
442
443 async notify(accountIds: string[], n: { repoId?: string; kind: string; title: string; url: string }): Promise<void> {
444 const unique = [...new Set(accountIds)];
445 if (!unique.length) return;
446 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())));
447 }
448
449 async notifications(accountId: string, unreadOnly = false): Promise<Array<{ id: string; kind: string; title: string; url: string; createdAt: string; readAt: string | null }>> {
450 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>>();
451 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 }));
452 }
453
454 async markRead(accountId: string, id?: string): Promise<void> {
455 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();
456 }
457
458 async audit(entry: { actorId?: string; actorLogin?: string; onBehalfOf?: string; action: string; target?: string; detail?: unknown; at?: string }): Promise<void> {
459 await this.db
460 .prepare("INSERT INTO audit_log (id, at, actor_id, actor_login, on_behalf_of, action, target, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
461 .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)
462 .run();
463 // Security emails (sign-ins, passkeys, tokens, push protection…) hang off the audit log.
464 await mailForAudit(this.env, this, entry).catch((e) => console.error("security email failed", entry.action, e));
465 }
466
467 async auditLog(limit = 200): Promise<Array<Record<string, string | null>>> {
468 return (await this.db.prepare("SELECT * FROM audit_log ORDER BY at DESC LIMIT ?").bind(limit).all<Record<string, string | null>>()).results;
469 }
470}