| 1 | import type { Env } from "../env.js"; |
| 2 | import type { RepoMeta, Role } from "../repo/types.js"; |
| 3 | import { ROLE_LEVEL } from "../repo/types.js"; |
| 4 | import { HttpError, RESERVED_LOGINS, isValidLogin, isValidName, newId, now, randomToken, sha256 } from "./util.js"; |
| 5 | import { mailForAudit, tokenCreated } from "../mail/notify.js"; |
| 6 | import { enqueueMail } from "../mail/send.js"; |
| 7 | |
| 8 | export 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 | /** Profile picture version (R2 avatars/<id>/<version>/<size>.webp), null for initials. */ |
| 19 | avatar_version: number | null; |
| 20 | /** "light", "dark" or null (follow the system). */ |
| 21 | appearance: string | null; |
| 22 | /** Organizations: the role every member gets on its repositories ("none", "read", "write" or "admin"). */ |
| 23 | base_role: string | null; |
| 24 | created_at: string; |
| 25 | } |
| 26 | |
| 27 | export interface Repo { |
| 28 | id: string; |
| 29 | owner_id: string; |
| 30 | owner_login: string; |
| 31 | owner_kind: "user" | "org" | "agent"; |
| 32 | name: string; |
| 33 | description: string; |
| 34 | visibility: "private" | "public"; |
| 35 | default_branch: string; |
| 36 | archived: number; |
| 37 | created_at: string; |
| 38 | updated_at: string; |
| 39 | pushed_at: string | null; |
| 40 | /** JSON array of topic names (GitHub's repository topics). */ |
| 41 | topics?: string; |
| 42 | /** Project website (GitHub's `homepage`). */ |
| 43 | homepage?: string; |
| 44 | } |
| 45 | |
| 46 | export type TokenScope = "read" | "write" | "admin"; |
| 47 | |
| 48 | export type BaseRole = "none" | "read" | "write" | "admin"; |
| 49 | export const BASE_ROLES: readonly BaseRole[] = ["none", "read", "write", "admin"]; |
| 50 | |
| 51 | /** An organization's base permission; unset means read, the default for new organizations. */ |
| 52 | export function baseRole(org: Pick<Account, "base_role">): BaseRole { |
| 53 | return BASE_ROLES.find((r) => r === org.base_role) ?? "read"; |
| 54 | } |
| 55 | |
| 56 | /** Repositories are public or private; GitHub's "internal" is refused like any other value. */ |
| 57 | export function repoVisibility(v: unknown): Repo["visibility"] | undefined { |
| 58 | if (v === undefined || v === null || v === "") return undefined; |
| 59 | if (v === "public" || v === "private") return v; |
| 60 | throw new HttpError(422, "visibility must be public or private", { errors: [{ resource: "Repository", code: "invalid", field: "visibility" }] }); |
| 61 | } |
| 62 | |
| 63 | /** Data access for the global directory in D1. */ |
| 64 | export class Directory { |
| 65 | constructor(private env: Env) {} |
| 66 | |
| 67 | private get db() { |
| 68 | return this.env.DB; |
| 69 | } |
| 70 | |
| 71 | // ---------------------------------------------------------------- accounts |
| 72 | |
| 73 | async account(id: string): Promise<Account | null> { |
| 74 | return this.db.prepare("SELECT * FROM accounts WHERE id = ?").bind(id).first<Account>(); |
| 75 | } |
| 76 | |
| 77 | async accountByLogin(login: string): Promise<Account | null> { |
| 78 | return this.db.prepare("SELECT * FROM accounts WHERE login = ?").bind(login).first<Account>(); |
| 79 | } |
| 80 | |
| 81 | async accountByEmail(email: string): Promise<Account | null> { |
| 82 | return this.db.prepare("SELECT * FROM accounts WHERE email = ? AND kind = 'user'").bind(email).first<Account>(); |
| 83 | } |
| 84 | |
| 85 | private isBootstrapAdmin(email: string, login?: string): boolean { |
| 86 | const list = (this.env.BOOTSTRAP_ADMINS ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean); |
| 87 | return list.includes(email.toLowerCase()) || (!!login && list.includes(login.toLowerCase())); |
| 88 | } |
| 89 | |
| 90 | private async uniqueLogin(base: string): Promise<string> { |
| 91 | let candidate = base.replace(/[^A-Za-z0-9-]/g, "-").replace(/^-+|-+$/g, "").slice(0, 39) || "user"; |
| 92 | for (let i = 0; i < 50; i++) { |
| 93 | const tryLogin = i === 0 ? candidate : `${candidate}-${i + 1}`; |
| 94 | if (!RESERVED_LOGINS.has(tryLogin.toLowerCase()) && !(await this.accountByLogin(tryLogin))) return tryLogin; |
| 95 | } |
| 96 | candidate = `${candidate}-${randomToken(3)}`; |
| 97 | return candidate; |
| 98 | } |
| 99 | |
| 100 | /** Find or create the user behind a verified email (Access recovery, invite links, dev sign-in). */ |
| 101 | async userForEmail(email: string, hints: { name?: string; login?: string; id?: string } = {}): Promise<Account> { |
| 102 | const existing = await this.accountByEmail(email); |
| 103 | if (existing) { |
| 104 | if (existing.status === "pending" && this.isBootstrapAdmin(email, existing.login)) { |
| 105 | await this.db.prepare("UPDATE accounts SET status = 'active', site_admin = 1 WHERE id = ?").bind(existing.id).run(); |
| 106 | return { ...existing, status: "active", site_admin: 1 }; |
| 107 | } |
| 108 | return existing; |
| 109 | } |
| 110 | const admin = this.isBootstrapAdmin(email, hints.login); |
| 111 | const login = await this.uniqueLogin(hints.login ?? email.split("@")[0]!); |
| 112 | const id = hints.id ?? newId(); |
| 113 | const hasInvite = await this.db.prepare("SELECT 1 FROM invites WHERE email = ? AND accepted_at IS NULL AND expires_at > ?").bind(email, now()).first(); |
| 114 | await this.db |
| 115 | .prepare("INSERT INTO accounts (id, login, kind, name, email, status, site_admin, created_at) VALUES (?, ?, 'user', ?, ?, ?, ?, ?)") |
| 116 | .bind(id, login, hints.name ?? null, email, admin || hasInvite ? "active" : "pending", admin ? 1 : 0, now()) |
| 117 | .run(); |
| 118 | if (hasInvite) await this.acceptInvitesForEmail(id, email); |
| 119 | return (await this.account(id))!; |
| 120 | } |
| 121 | |
| 122 | /** Rename an account and change its display name (and an organization's base permission) in one write, after checking every field. */ |
| 123 | async updateAccount(id: string, patch: { login?: string; name?: unknown; baseRole?: unknown }): Promise<void> { |
| 124 | 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" }] }); |
| 125 | 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" }] }); |
| 126 | if (patch.login && !isValidLogin(patch.login)) throw new HttpError(422, "invalid or reserved login"); |
| 127 | if (patch.login) { |
| 128 | const clash = await this.accountByLogin(patch.login); |
| 129 | if (clash && clash.id !== id) throw new HttpError(422, "login already taken"); |
| 130 | } |
| 131 | // A blank display name clears it, so pages fall back to the login. |
| 132 | const name = patch.name === undefined ? undefined : (patch.name as string | null)?.trim() || null; |
| 133 | await this.db |
| 134 | .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 = ?") |
| 135 | .bind(patch.login ?? null, name === undefined ? 0 : 1, name ?? null, (patch.baseRole as string | undefined) ?? null, id) |
| 136 | .run(); |
| 137 | if (patch.login) { |
| 138 | // Repos keep their ids; their Durable Objects cache the owner login, so refresh them. |
| 139 | const repos = await this.db.prepare("SELECT id FROM repos WHERE owner_id = ?").bind(id).all<{ id: string }>(); |
| 140 | for (const r of repos.results) await this.env.REPO.get(this.env.REPO.idFromName(r.id)).updateMeta({ owner: patch.login }); |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | async setAppearance(id: string, appearance: "light" | "dark" | null): Promise<void> { |
| 145 | await this.db.prepare("UPDATE accounts SET appearance = ? WHERE id = ?").bind(appearance, id).run(); |
| 146 | } |
| 147 | |
| 148 | /** Point an account at a new profile picture version (null: back to initials). */ |
| 149 | async setAvatarVersion(id: string, version: number | null): Promise<void> { |
| 150 | await this.db.prepare("UPDATE accounts SET avatar_version = ? WHERE id = ?").bind(version, id).run(); |
| 151 | } |
| 152 | |
| 153 | async createOrg(login: string, name: string, creator: Account): Promise<Account> { |
| 154 | if (!isValidLogin(login)) throw new HttpError(422, "invalid or reserved organization name"); |
| 155 | if (await this.accountByLogin(login)) throw new HttpError(422, "name already taken"); |
| 156 | const id = newId(); |
| 157 | const t = now(); |
| 158 | await this.db.batch([ |
| 159 | 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), |
| 160 | this.db.prepare("INSERT INTO org_members (org_id, user_id, role, created_at) VALUES (?, ?, 'owner', ?)").bind(id, creator.id, t), |
| 161 | ]); |
| 162 | return (await this.account(id))!; |
| 163 | } |
| 164 | |
| 165 | /** Whether an account sees an organization's settings such as its base permission: members, the |
| 166 | * organization's own agents, agents of members, and site admins. */ |
| 167 | async inOrg(orgId: string, account: Account): Promise<boolean> { |
| 168 | if (account.site_admin) return true; |
| 169 | if (account.kind === "agent") return account.owner_id === orgId || (!!account.owner_id && !!(await this.orgRole(orgId, account.owner_id))); |
| 170 | return !!(await this.orgRole(orgId, account.id)); |
| 171 | } |
| 172 | |
| 173 | async orgRole(orgId: string, userId: string): Promise<"owner" | "admin" | "member" | null> { |
| 174 | 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" }>(); |
| 175 | return r?.role ?? null; |
| 176 | } |
| 177 | |
| 178 | async orgsFor(userId: string): Promise<Array<Account & { role: string }>> { |
| 179 | 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 }>(); |
| 180 | return r.results; |
| 181 | } |
| 182 | |
| 183 | async orgMembers(orgId: string): Promise<Array<Account & { role: string }>> { |
| 184 | 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 }>(); |
| 185 | return r.results; |
| 186 | } |
| 187 | |
| 188 | async setOrgMember(orgId: string, userId: string, role: "owner" | "admin" | "member" | null, by?: Account): Promise<void> { |
| 189 | const previous = await this.orgRole(orgId, userId); |
| 190 | await this.writeOrgMember(orgId, userId, role); |
| 191 | if (previous !== role) { |
| 192 | const org = await this.account(orgId); |
| 193 | if (!org) return; |
| 194 | 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() }]); |
| 195 | // A heads-up on Diffinery too when someone else adds you. |
| 196 | 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}` }); |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | /** |
| 201 | * Add someone to an organization by username or email, like GitHub's "Add people": people with an |
| 202 | * account join right away and get a heads-up; an email without an account gets an invitation that |
| 203 | * creates the account and joins the organization. |
| 204 | */ |
| 205 | async addOrgPerson(org: Account, by: Account, who: string, role: "owner" | "admin" | "member"): Promise<{ added: Account } | { invited: { email: string; url: string } }> { |
| 206 | const q = who.trim().replace(/^@/, ""); |
| 207 | if (!q) throw new HttpError(422, "enter a username or an email address"); |
| 208 | const email = q.includes("@"); |
| 209 | if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(q)) throw new HttpError(422, "enter a valid email address"); |
| 210 | const user = email ? await this.accountByEmail(q) : await this.accountByLogin(q); |
| 211 | if (user) { |
| 212 | if (user.kind !== "user") throw new HttpError(422, `${user.login} is not a person; agents belong to an organization through Settings → Agents`); |
| 213 | if (user.status === "disabled") throw new HttpError(422, `${user.login}'s account is disabled`); |
| 214 | if (await this.orgRole(org.id, user.id)) throw new HttpError(422, `${user.login} is already a member of ${org.login}`); |
| 215 | // An admin vouching for someone waiting for an invite lets them in. |
| 216 | if (user.status === "pending") await this.setStatus(user.id, "active"); |
| 217 | await this.setOrgMember(org.id, user.id, role, by); |
| 218 | return { added: user }; |
| 219 | } |
| 220 | if (!email) throw new HttpError(404, `no one has the username ${q}; to invite someone new, enter their email address`); |
| 221 | const inv = await this.createInvite(by, { email: q, orgId: org.id, role }); |
| 222 | return { invited: { email: q, url: inv.url } }; |
| 223 | } |
| 224 | |
| 225 | /** Add a collaborator by username (a person or an agent) or email; a new email gets an invitation. */ |
| 226 | async addRepoPerson(repo: Repo, by: Account, who: string, role: Role): Promise<{ added: Account } | { invited: { email: string; url: string } }> { |
| 227 | const q = who.trim().replace(/^@/, ""); |
| 228 | if (!q) throw new HttpError(422, "enter a username or an email address"); |
| 229 | const email = q.includes("@"); |
| 230 | if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(q)) throw new HttpError(422, "enter a valid email address"); |
| 231 | const account = email ? await this.accountByEmail(q) : await this.accountByLogin(q); |
| 232 | if (account) { |
| 233 | if (account.kind === "org") throw new HttpError(422, `${account.login} is an organization; add its people instead`); |
| 234 | if (account.status === "disabled") throw new HttpError(422, `${account.login}'s account is disabled`); |
| 235 | if (account.status === "pending") await this.setStatus(account.id, "active"); |
| 236 | await this.setCollaborator(repo.id, account.id, role); |
| 237 | 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}` }); |
| 238 | return { added: account }; |
| 239 | } |
| 240 | if (!email) throw new HttpError(404, `no one has the username ${q}; to invite someone new, enter their email address`); |
| 241 | const inv = await this.createInvite(by, { email: q, repoId: repo.id, role }); |
| 242 | return { invited: { email: q, url: inv.url } }; |
| 243 | } |
| 244 | |
| 245 | /** Revoke a pending invitation to an organization, a repository, or (neither) the site. False if there was none. */ |
| 246 | async revokeInvite(id: string, scope: { orgId?: string; repoId?: string }): Promise<boolean> { |
| 247 | const r = await this.db |
| 248 | .prepare("DELETE FROM invites WHERE id = ? AND accepted_at IS NULL AND org_id IS ? AND repo_id IS ?") |
| 249 | .bind(id, scope.orgId ?? null, scope.repoId ?? null) |
| 250 | .run(); |
| 251 | return (r.meta?.changes ?? 0) > 0; |
| 252 | } |
| 253 | |
| 254 | private async writeOrgMember(orgId: string, userId: string, role: "owner" | "admin" | "member" | null): Promise<void> { |
| 255 | // Removing or demoting the last owner would leave nobody able to manage the organization. |
| 256 | if (role !== "owner" && (await this.orgRole(orgId, userId)) === "owner") { |
| 257 | 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 }>(); |
| 258 | if (!owners?.n) throw new HttpError(422, "an organization needs at least one owner; make someone else an owner first"); |
| 259 | } |
| 260 | if (role === null) { |
| 261 | // Their grants on the organization's repositories (including the admin grant for repositories they |
| 262 | // created) go too, for them and their agents. Roles are computed per request, so tokens lose access at once. |
| 263 | await this.db.batch([ |
| 264 | this.db.prepare("DELETE FROM org_members WHERE org_id = ? AND user_id = ?").bind(orgId, userId), |
| 265 | this.db |
| 266 | .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 = ?)") |
| 267 | .bind(orgId, userId, userId), |
| 268 | ]); |
| 269 | return; |
| 270 | } |
| 271 | 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(); |
| 272 | } |
| 273 | |
| 274 | async users(): Promise<Account[]> { |
| 275 | return (await this.db.prepare("SELECT * FROM accounts WHERE kind = 'user' ORDER BY login").all<Account>()).results; |
| 276 | } |
| 277 | |
| 278 | async setStatus(id: string, status: Account["status"]): Promise<void> { |
| 279 | const before = await this.account(id); |
| 280 | await this.db.prepare("UPDATE accounts SET status = ? WHERE id = ?").bind(status, id).run(); |
| 281 | if (status === "disabled") await this.db.prepare("UPDATE tokens SET revoked_at = ? WHERE account_id = ? AND revoked_at IS NULL").bind(now(), id).run(); |
| 282 | // A disabled account's browser sessions end too. |
| 283 | if (status === "disabled") await this.db.prepare("DELETE FROM sessions WHERE account_id = ?").bind(id).run(); |
| 284 | // People hear when they are disabled or enabled again (not when an invite activates them). |
| 285 | if (before?.kind === "user" && before.status !== status && (status === "disabled" || before.status === "disabled")) { |
| 286 | await enqueueMail(this.env, [{ kind: "account_status", data: { status: status === "disabled" ? "disabled" : "active" }, to: { accountId: id }, reason: "account", at: now() }]); |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | // ---------------------------------------------------------------- agents |
| 291 | |
| 292 | async createAgent(owner: Account, input: { login: string; name?: string; orgId?: string; policy?: Record<string, unknown> }): Promise<Account> { |
| 293 | if (!isValidLogin(input.login)) throw new HttpError(422, "invalid or reserved agent name"); |
| 294 | const login = input.login.endsWith("[bot]") ? input.login : `${input.login}`; |
| 295 | if (await this.accountByLogin(login)) throw new HttpError(422, "name already taken"); |
| 296 | const id = newId(); |
| 297 | const ownerId = input.orgId ?? owner.id; |
| 298 | if (input.orgId) { |
| 299 | const role = await this.orgRole(input.orgId, owner.id); |
| 300 | if (role !== "owner" && role !== "admin") throw new HttpError(403, "only organization admins can create organization agents"); |
| 301 | } |
| 302 | const policy = { maxRole: "write", canMergeProtected: false, budgetUsdMonthly: null, ...input.policy }; |
| 303 | await this.db |
| 304 | .prepare("INSERT INTO accounts (id, login, kind, name, status, owner_id, agent_policy, created_at) VALUES (?, ?, 'agent', ?, 'active', ?, ?, ?)") |
| 305 | .bind(id, login, input.name?.trim() || login, ownerId, JSON.stringify(policy), now()) |
| 306 | .run(); |
| 307 | return (await this.account(id))!; |
| 308 | } |
| 309 | |
| 310 | async agentsOwnedBy(ownerIds: string[]): Promise<Account[]> { |
| 311 | if (!ownerIds.length) return []; |
| 312 | const q = `SELECT * FROM accounts WHERE kind = 'agent' AND owner_id IN (${ownerIds.map(() => "?").join(",")}) ORDER BY login`; |
| 313 | return (await this.db.prepare(q).bind(...ownerIds).all<Account>()).results; |
| 314 | } |
| 315 | |
| 316 | // ---------------------------------------------------------------- tokens |
| 317 | |
| 318 | /** `importId`: a GitHub import's short-lived push token (see imports/service.ts). */ |
| 319 | async createToken(account: Account, input: { name: string; scopes?: TokenScope[]; repoIds?: string[] | null; expiresInDays?: number; importId?: string }): Promise<{ token: string; id: string; expiresAt: string }> { |
| 320 | const days = Math.min(Math.max(input.expiresInDays ?? 90, 1), 366); |
| 321 | const token = `dfy_${randomToken(30)}`; |
| 322 | const id = newId(); |
| 323 | const expiresAt = new Date(Date.now() + days * 86400_000).toISOString(); |
| 324 | await this.db |
| 325 | .prepare("INSERT INTO tokens (id, account_id, name, token_hash, prefix, scopes, repo_ids, expires_at, created_at, import_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") |
| 326 | .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) |
| 327 | .run(); |
| 328 | // An import's own push token is server-managed and short-lived: no "new token" email. |
| 329 | 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)); |
| 330 | return { token, id, expiresAt }; |
| 331 | } |
| 332 | |
| 333 | async tokens(accountId: string): Promise<Array<{ id: string; name: string; prefix: string; scopes: string[]; repoIds: string[] | null; expiresAt: string; lastUsedAt: string | null; createdAt: string }>> { |
| 334 | // Import push tokens (import_id set) are server-managed and hidden from the personal token list. |
| 335 | 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>>(); |
| 336 | 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! })); |
| 337 | } |
| 338 | |
| 339 | async revokeToken(accountId: string, id: string): Promise<void> { |
| 340 | await this.db.prepare("UPDATE tokens SET revoked_at = ? WHERE id = ? AND account_id = ?").bind(now(), id, accountId).run(); |
| 341 | } |
| 342 | |
| 343 | async verifyToken(token: string): Promise<{ id: string; account: Account; scopes: TokenScope[]; repoIds: string[] | null; importId: string | null } | null> { |
| 344 | const row = await this.db.prepare("SELECT * FROM tokens WHERE token_hash = ?").bind(await sha256(token)).first<Record<string, string | null>>(); |
| 345 | if (!row || row.revoked_at || row.expires_at! < now()) return null; |
| 346 | const account = await this.account(row.account_id!); |
| 347 | if (!account || account.status !== "active") return null; |
| 348 | if (!row.last_used_at || Date.now() - Date.parse(row.last_used_at) > 3600_000) { |
| 349 | await this.db.prepare("UPDATE tokens SET last_used_at = ? WHERE id = ?").bind(now(), row.id!).run(); |
| 350 | } |
| 351 | 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 }; |
| 352 | } |
| 353 | |
| 354 | /** Revoke a token by id whoever owns it (server-managed tokens such as an import's push token). */ |
| 355 | async revokeTokenById(id: string): Promise<void> { |
| 356 | await this.db.prepare("UPDATE tokens SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL").bind(now(), id).run(); |
| 357 | } |
| 358 | |
| 359 | /** Revoke every live token an import ever minted (not only the current one), so a stale token can never push. */ |
| 360 | async revokeTokensByImport(importId: string): Promise<void> { |
| 361 | await this.db.prepare("UPDATE tokens SET revoked_at = ? WHERE import_id = ? AND revoked_at IS NULL").bind(now(), importId).run(); |
| 362 | } |
| 363 | |
| 364 | // ---------------------------------------------------------------- invites |
| 365 | |
| 366 | async createInvite(inviter: Account, input: { email: string; orgId?: string; repoId?: string; role: string }): Promise<{ id: string; url: string; token: string }> { |
| 367 | if (input.orgId) { |
| 368 | if (input.role !== "member" && input.role !== "admin" && input.role !== "owner") throw new HttpError(422, "role must be member, admin or owner"); |
| 369 | if (input.role === "owner" && !inviter.site_admin && (await this.orgRole(input.orgId, inviter.id)) !== "owner") throw new HttpError(403, "only owners can invite owners"); |
| 370 | } |
| 371 | // One open invitation per address and organization or repository. The email column is NOCASE, |
| 372 | // so Bob@x.com and bob@x.com count as the same person. |
| 373 | const pending = await this.db |
| 374 | .prepare("SELECT 1 FROM invites WHERE email = ? AND org_id IS ? AND repo_id IS ? AND accepted_at IS NULL AND expires_at > ?") |
| 375 | .bind(input.email, input.orgId ?? null, input.repoId ?? null, now()) |
| 376 | .first(); |
| 377 | if (pending) throw new HttpError(422, `${input.email} already has a pending invitation; revoke it first to send a new one`); |
| 378 | const existing = await this.accountByEmail(input.email); |
| 379 | if (existing && input.orgId && (await this.orgRole(input.orgId, existing.id))) throw new HttpError(422, `${existing.login} is already a member of this organization`); |
| 380 | const token = randomToken(24); |
| 381 | const id = newId(); |
| 382 | await this.db |
| 383 | .prepare("INSERT INTO invites (id, org_id, repo_id, email, role, token_hash, invited_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)") |
| 384 | .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()) |
| 385 | .run(); |
| 386 | // If the person already exists, activate them now so the invite also works from the dashboard. |
| 387 | if (existing?.status === "pending") await this.setStatus(existing.id, "active"); |
| 388 | const url = `${this.env.PUBLIC_URL}/invite/${token}`; |
| 389 | const org = input.orgId ? await this.account(input.orgId) : null; |
| 390 | const repo = input.repoId ? await this.repoById(input.repoId) : null; |
| 391 | await enqueueMail(this.env, [ |
| 392 | { |
| 393 | kind: "invite", |
| 394 | 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() }, |
| 395 | to: existing ? { accountId: existing.id } : { email: input.email }, |
| 396 | reason: "invitation", |
| 397 | at: now(), |
| 398 | }, |
| 399 | ]); |
| 400 | return { id, url, token }; |
| 401 | } |
| 402 | |
| 403 | 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 }>> { |
| 404 | const r = await this.db |
| 405 | .prepare( |
| 406 | `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`, |
| 407 | ) |
| 408 | .bind(filter.orgId ?? null, filter.orgId ?? null, filter.repoId ?? null, filter.repoId ?? null, ...(filter.pending ? [now()] : [])) |
| 409 | .all<Record<string, string | null>>(); |
| 410 | 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 })); |
| 411 | } |
| 412 | |
| 413 | async acceptInvite(token: string, user: Account): Promise<{ orgId: string | null; repoId: string | null }> { |
| 414 | const inv = await this.db.prepare("SELECT * FROM invites WHERE token_hash = ?").bind(await sha256(token)).first<Record<string, string | null>>(); |
| 415 | if (!inv || inv.accepted_at || inv.expires_at! < now()) throw new HttpError(404, "this invite is invalid or has expired"); |
| 416 | 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`); |
| 417 | await this.applyInvite(inv, user); |
| 418 | return { orgId: inv.org_id ?? null, repoId: inv.repo_id ?? null }; |
| 419 | } |
| 420 | |
| 421 | private async acceptInvitesForEmail(userId: string, email: string): Promise<void> { |
| 422 | const user = (await this.account(userId))!; |
| 423 | 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>>(); |
| 424 | for (const inv of r.results) await this.applyInvite(inv, user); |
| 425 | } |
| 426 | |
| 427 | private async applyInvite(inv: Record<string, string | null>, user: Account): Promise<void> { |
| 428 | 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)]; |
| 429 | 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())); |
| 430 | 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)); |
| 431 | await this.db.batch(stmts); |
| 432 | const org = inv.org_id ? await this.account(inv.org_id) : null; |
| 433 | const repo = inv.repo_id ? await this.repoById(inv.repo_id) : null; |
| 434 | if (inv.invited_by && inv.invited_by !== user.id) { |
| 435 | await enqueueMail(this.env, [ |
| 436 | { 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() }, |
| 437 | ]); |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | async requestAccess(accountId: string, note: string): Promise<void> { |
| 442 | await this.db.prepare("INSERT OR REPLACE INTO access_requests (account_id, note, created_at) VALUES (?, ?, ?)").bind(accountId, note.slice(0, 500), now()).run(); |
| 443 | const who = await this.account(accountId); |
| 444 | 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 }>(); |
| 445 | 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() }))); |
| 446 | } |
| 447 | |
| 448 | async accessRequests(): Promise<Array<{ account: Account; note: string; createdAt: string }>> { |
| 449 | 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 }>(); |
| 450 | return r.results.map((x) => ({ account: x, note: x.req_note, createdAt: x.req_at })); |
| 451 | } |
| 452 | |
| 453 | // ---------------------------------------------------------------- repositories |
| 454 | |
| 455 | async repo(owner: string, name: string): Promise<Repo | null> { |
| 456 | return this.db |
| 457 | .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 = ?") |
| 458 | .bind(owner, name.replace(/\.git$/, "")) |
| 459 | .first<Repo>(); |
| 460 | } |
| 461 | |
| 462 | async repoById(id: string): Promise<Repo | null> { |
| 463 | 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>(); |
| 464 | } |
| 465 | |
| 466 | /** Repositories an account can see. */ |
| 467 | async reposVisibleTo(account: Account, ownerId?: string): Promise<Repo[]> { |
| 468 | if (account.status !== "active") return []; |
| 469 | if (account.kind === "agent") { |
| 470 | const owner = account.owner_id ? await this.account(account.owner_id) : null; |
| 471 | if (!owner || owner.status !== "active") return []; |
| 472 | } |
| 473 | const params: unknown[] = []; |
| 474 | 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"; |
| 475 | const subjectId = account.kind === "agent" ? account.owner_id! : account.id; |
| 476 | if (!account.site_admin) { |
| 477 | 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 (?, ?)))`; |
| 478 | params.push(subjectId, subjectId, account.id, subjectId); |
| 479 | } else q += " WHERE 1 = 1"; |
| 480 | if (ownerId) { |
| 481 | q += " AND r.owner_id = ?"; |
| 482 | params.push(ownerId); |
| 483 | } |
| 484 | q += " ORDER BY COALESCE(r.pushed_at, r.updated_at) DESC LIMIT 500"; |
| 485 | return (await this.db.prepare(q).bind(...params).all<Repo>()).results; |
| 486 | } |
| 487 | |
| 488 | /** Public repositories, most recently pushed first (for the sitemap). */ |
| 489 | async publicRepos(limit: number): Promise<Repo[]> { |
| 490 | return ( |
| 491 | await this.db |
| 492 | .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 ?") |
| 493 | .bind(limit) |
| 494 | .all<Repo>() |
| 495 | ).results; |
| 496 | } |
| 497 | |
| 498 | /** `o.authorized`: the caller already checked that `creator` may create repositories for `owner` (GitHub imports). */ |
| 499 | async createRepo(owner: Account, creator: Account, input: { name: string; description?: string; visibility?: string; defaultBranch?: string }, o: { authorized?: boolean } = {}): Promise<Repo> { |
| 500 | if (!isValidName(input.name)) throw new HttpError(422, "invalid repository name: use letters, numbers, '.', '-' and '_'"); |
| 501 | // Like GitHub, a member who creates an organization repository administers it, whatever the base permission. |
| 502 | let creatorGrant: string | null = null; |
| 503 | if (o.authorized) { |
| 504 | // checked by the caller |
| 505 | } else if (owner.kind === "org") { |
| 506 | const subject = creator.kind === "agent" ? creator.owner_id! : creator.id; |
| 507 | const role = await this.orgRole(owner.id, subject); |
| 508 | if (!role && !creator.site_admin) throw new HttpError(403, "you are not a member of this organization"); |
| 509 | if (role === "member") creatorGrant = subject; |
| 510 | } else if (owner.id !== creator.id && !creator.site_admin) throw new HttpError(403, "you can only create repositories for yourself or your organizations"); |
| 511 | if (await this.repo(owner.login, input.name)) throw new HttpError(422, "a repository with this name already exists"); |
| 512 | const id = newId(); |
| 513 | const t = now(); |
| 514 | const branch = input.defaultBranch || "main"; |
| 515 | await this.db.batch([ |
| 516 | this.db |
| 517 | .prepare("INSERT INTO repos (id, owner_id, name, description, visibility, default_branch, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") |
| 518 | .bind(id, owner.id, input.name, input.description ?? "", repoVisibility(input.visibility) ?? "private", branch, t, t), |
| 519 | ...(creatorGrant ? [this.db.prepare("INSERT INTO repo_access (repo_id, account_id, role) VALUES (?, ?, 'admin')").bind(id, creatorGrant)] : []), |
| 520 | ]); |
| 521 | const meta: RepoMeta = { repoId: id, ownerId: owner.id, owner: owner.login, name: input.name, defaultBranch: branch, ownerKind: owner.kind === "org" ? "org" : "user" }; |
| 522 | const stub = this.env.REPO.get(this.env.REPO.idFromName(id)); |
| 523 | await stub.init(meta); |
| 524 | if (owner.kind === "org") { |
| 525 | const vars = await this.orgVariables(owner.id); |
| 526 | if (vars.length) await stub.setOrgVariables(Object.fromEntries(vars.map((v) => [v.name, v.value]))); |
| 527 | } |
| 528 | return (await this.repoById(id))!; |
| 529 | } |
| 530 | |
| 531 | async updateRepo(repo: Repo, patch: { name?: string; description?: string; visibility?: string; defaultBranch?: string; archived?: boolean; homepage?: string; topics?: string[] }): Promise<Repo> { |
| 532 | if (patch.name && !isValidName(patch.name)) throw new HttpError(422, "invalid repository name"); |
| 533 | await this.db |
| 534 | .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 = ?") |
| 535 | .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) |
| 536 | .run(); |
| 537 | if (patch.homepage !== undefined || patch.topics !== undefined) { |
| 538 | await this.db |
| 539 | .prepare("UPDATE repos SET homepage = COALESCE(?, homepage), topics = COALESCE(?, topics) WHERE id = ?") |
| 540 | .bind(patch.homepage ?? null, patch.topics ? JSON.stringify(patch.topics.slice(0, 20)) : null, repo.id) |
| 541 | .run(); |
| 542 | } |
| 543 | 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 }); |
| 544 | return (await this.repoById(repo.id))!; |
| 545 | } |
| 546 | |
| 547 | async deleteRepo(repo: Repo): Promise<void> { |
| 548 | 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)]); |
| 549 | // R2 objects under repos/<id>/ are removed by the cleanup job; the DO's storage is wiped here. |
| 550 | await this.env.REPO.get(this.env.REPO.idFromName(repo.id)).destroy(); |
| 551 | } |
| 552 | |
| 553 | async setTopics(repoId: string, topics: string[]): Promise<void> { |
| 554 | await this.db.prepare("UPDATE repos SET topics = ?, updated_at = ? WHERE id = ?").bind(JSON.stringify(topics), now(), repoId).run(); |
| 555 | } |
| 556 | |
| 557 | // ---------------------------------------------------------------- organization variables |
| 558 | |
| 559 | async orgVariables(orgId: string): Promise<Array<{ name: string; value: string; updated_at: string }>> { |
| 560 | 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; |
| 561 | } |
| 562 | |
| 563 | /** Set (or, with null, delete) organization variables, then copy the set into each of the organization's repositories. */ |
| 564 | async setOrgVariables(orgId: string, changes: Record<string, string | null>): Promise<void> { |
| 565 | const stmts = Object.entries(changes).map(([name, value]) => |
| 566 | value === null |
| 567 | ? this.db.prepare("DELETE FROM org_variables WHERE org_id = ? AND name = ?").bind(orgId, name.toUpperCase()) |
| 568 | : this.db.prepare("INSERT OR REPLACE INTO org_variables (org_id, name, value, updated_at) VALUES (?, ?, ?, ?)").bind(orgId, name.toUpperCase(), value, now()), |
| 569 | ); |
| 570 | if (stmts.length) await this.db.batch(stmts); |
| 571 | await this.syncOrgVariables(orgId); |
| 572 | } |
| 573 | |
| 574 | /** |
| 575 | * Add organization variables only where none exists (ON CONFLICT DO NOTHING), used by imports so |
| 576 | * an import never overwrites a value an org admin already set. Returns which names were added and |
| 577 | * which were skipped because a variable of that name already existed. |
| 578 | */ |
| 579 | async addOrgVariablesIfAbsent(orgId: string, vars: Record<string, string>): Promise<{ added: string[]; skipped: string[] }> { |
| 580 | const before = new Set((await this.orgVariables(orgId)).map((v) => v.name)); |
| 581 | const added: string[] = []; |
| 582 | const skipped: string[] = []; |
| 583 | const stmts: D1PreparedStatement[] = []; |
| 584 | for (const [rawName, value] of Object.entries(vars)) { |
| 585 | const name = rawName.toUpperCase(); |
| 586 | if (before.has(name)) { |
| 587 | skipped.push(name); |
| 588 | continue; |
| 589 | } |
| 590 | added.push(name); |
| 591 | 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())); |
| 592 | } |
| 593 | if (stmts.length) { |
| 594 | await this.db.batch(stmts); |
| 595 | await this.syncOrgVariables(orgId); |
| 596 | } |
| 597 | return { added, skipped }; |
| 598 | } |
| 599 | |
| 600 | /** Copy the organization's current variable set into each of its repositories' Durable Objects. */ |
| 601 | private async syncOrgVariables(orgId: string): Promise<void> { |
| 602 | const vars = Object.fromEntries((await this.orgVariables(orgId)).map((v) => [v.name, v.value])); |
| 603 | const repos = await this.db.prepare("SELECT id FROM repos WHERE owner_id = ?").bind(orgId).all<{ id: string }>(); |
| 604 | for (const r of repos.results) await this.env.REPO.get(this.env.REPO.idFromName(r.id)).setOrgVariables(vars); |
| 605 | } |
| 606 | |
| 607 | /** The highest role an agent may ever hold (its policy's maxRole, default write). */ |
| 608 | agentMaxRole(account: Account): Role { |
| 609 | const policy = account.agent_policy ? (JSON.parse(account.agent_policy) as { maxRole?: Role }) : {}; |
| 610 | return policy.maxRole ?? "write"; |
| 611 | } |
| 612 | |
| 613 | async touchPushed(repoId: string): Promise<void> { |
| 614 | await this.db.prepare("UPDATE repos SET pushed_at = ?, updated_at = ? WHERE id = ?").bind(now(), now(), repoId).run(); |
| 615 | } |
| 616 | |
| 617 | async collaborators(repoId: string): Promise<Array<{ account: Account; role: Role }>> { |
| 618 | 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 }>(); |
| 619 | return r.results.map((x) => ({ account: x, role: x.access_role })); |
| 620 | } |
| 621 | |
| 622 | async setCollaborator(repoId: string, accountId: string, role: Role | null): Promise<void> { |
| 623 | 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; |
| 624 | if (role) await this.db.prepare("INSERT OR REPLACE INTO repo_access (repo_id, account_id, role) VALUES (?, ?, ?)").bind(repoId, accountId, role).run(); |
| 625 | else await this.db.prepare("DELETE FROM repo_access WHERE repo_id = ? AND account_id = ?").bind(repoId, accountId).run(); |
| 626 | const repo = previous !== role ? await this.repoById(repoId) : null; |
| 627 | if (repo) await enqueueMail(this.env, [{ kind: "repo_access", data: { repo: `${repo.owner_login}/${repo.name}`, role, previous }, to: { accountId }, reason: "account", at: now() }]); |
| 628 | } |
| 629 | |
| 630 | /** Effective role of an account on a repository (null = no access). */ |
| 631 | async roleFor(account: Account, repo: Repo): Promise<Role | null> { |
| 632 | if (account.status !== "active") return null; |
| 633 | if (account.kind === "agent") { |
| 634 | if (!account.owner_id) return null; |
| 635 | const owner = await this.account(account.owner_id); |
| 636 | if (!owner || owner.status !== "active") return null; |
| 637 | const ownerRole = owner.kind === "org" ? (repo.owner_id === owner.id ? "admin" : null) : await this.roleFor(owner, repo); |
| 638 | if (!ownerRole) return null; |
| 639 | 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 }>(); |
| 640 | const policy = account.agent_policy ? (JSON.parse(account.agent_policy) as { maxRole?: Role }) : {}; |
| 641 | const cap: Role = explicit?.role ?? policy.maxRole ?? "write"; |
| 642 | return ROLE_LEVEL[ownerRole] < ROLE_LEVEL[cap] ? ownerRole : cap; |
| 643 | } |
| 644 | if (account.site_admin) return "admin"; |
| 645 | let best: Role | null = null; |
| 646 | const bump = (r: Role | null) => { |
| 647 | if (r && (!best || ROLE_LEVEL[r] > ROLE_LEVEL[best])) best = r; |
| 648 | }; |
| 649 | if (repo.owner_id === account.id) bump("admin"); |
| 650 | if (repo.owner_kind === "org") { |
| 651 | // Owners and admins administer every repository; members get the organization's base permission. |
| 652 | const m = await this.db |
| 653 | .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 = ?") |
| 654 | .bind(repo.owner_id, account.id) |
| 655 | .first<{ role: string; base_role: string | null }>(); |
| 656 | if (m?.role === "owner" || m?.role === "admin") bump("admin"); |
| 657 | else if (m?.role === "member") { |
| 658 | const base = baseRole(m); |
| 659 | if (base !== "none") bump(base); |
| 660 | } |
| 661 | } |
| 662 | 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 }>(); |
| 663 | bump(explicit?.role ?? null); |
| 664 | if (repo.visibility !== "private") bump("read"); |
| 665 | return best; |
| 666 | } |
| 667 | |
| 668 | // ---------------------------------------------------------------- notifications and audit |
| 669 | |
| 670 | async notify(accountIds: string[], n: { repoId?: string; kind: string; title: string; url: string }): Promise<void> { |
| 671 | const unique = [...new Set(accountIds)]; |
| 672 | if (!unique.length) return; |
| 673 | 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()))); |
| 674 | } |
| 675 | |
| 676 | async notifications(accountId: string, unreadOnly = false): Promise<Array<{ id: string; kind: string; title: string; url: string; createdAt: string; readAt: string | null }>> { |
| 677 | 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>>(); |
| 678 | 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 })); |
| 679 | } |
| 680 | |
| 681 | async markRead(accountId: string, id?: string): Promise<void> { |
| 682 | 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(); |
| 683 | } |
| 684 | |
| 685 | async audit(entry: { actorId?: string; actorLogin?: string; onBehalfOf?: string; action: string; target?: string; detail?: unknown; at?: string }): Promise<void> { |
| 686 | await this.db |
| 687 | .prepare("INSERT INTO audit_log (id, at, actor_id, actor_login, on_behalf_of, action, target, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") |
| 688 | .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) |
| 689 | .run(); |
| 690 | // Security emails (sign-ins, passkeys, tokens, push protection…) hang off the audit log. |
| 691 | await mailForAudit(this.env, this, entry).catch((e) => console.error("security email failed", entry.action, e)); |
| 692 | } |
| 693 | |
| 694 | async auditLog(limit = 200): Promise<Array<Record<string, string | null>>> { |
| 695 | return (await this.db.prepare("SELECT * FROM audit_log ORDER BY at DESC LIMIT ?").bind(limit).all<Record<string, string | null>>()).results; |
| 696 | } |
| 697 | } |