Diffinery

homeflare/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.

2660 lines · 119.1 KBRaw History
1/** @jsxImportSource hono/jsx */
2import { raw } from "hono/html";
3import { OAuth } from "../auth/oauth.js";
4import { ConnectedApps } from "./oauth.js";
5import type { Child, FC } from "hono/jsx";
6import { requireAccount, requireRecentSignIn, type AppContext } from "../auth/principal.js";
7import { OrgAgentSettings, orgAgentData } from "../agentic/org-web.js";
8import { baseRole, type Account, type Directory, type Repo, type TokenScope } from "../lib/directory.js";
9import { loadRepo } from "../http/common.js";
10import { movedLoginPath } from "../lib/redirects.js";
11import { GHOST, HttpError } from "../lib/util.js";
12import { parseAutoMergeDefault } from "../repo/auto-merge.js";
13import type { Role } from "../repo/types.js";
14import { ICONS } from "./assets.js";
15import { KCheckbox, KRadio, KSelect } from "./kumo.js";
16import { csrfToken } from "./csrf.js";
17import { Auth } from "../auth/sessions.js";
18import { repoCreated } from "../mail/notify.js";
19import { browserAccount, deviceLabel, invitePasskeyPage, localPath } from "./auth.js";
20import { deleteCookie, getCookie, setCookie } from "hono/cookie";
21import { APPEARANCE_COOKIE, Actor, Avatar, CopyButton, Form, ROLES, Time, cap, LOGIN_PATTERN, PendingInvites, act, ago, flash, post, publicUrl, render, repoUrl, type Stub, type WebApp, prm } from "./ui.js";
22import type { FormData } from "./csrf.js";
23import { purgeAvatarCache, removeAvatar, setAvatar } from "../http/avatars.js";
24import { MAX_AVATAR_BYTES } from "../lib/image.js";
25import { gatherToday } from "../agentic/today.js";
26import { ContactMessages } from "../lib/contact.js";
27import { EarlyAccess } from "../lib/early-access.js";
28import { COLLAPSED_COOKIE, Rows, Section, TodayView, collapsedSections } from "../agentic/web.js";
29import { landingPage } from "./site.js";
30import { serverErrors } from "../lib/server-errors.js";
31import { indexNowStatus } from "./indexnow.js";
32import { ComputePausedBanner, KillSwitchesPage } from "./kill-switches.js";
33import { changePause, changeSuspension, cleanReason, type Stopped } from "../lib/killswitch.js";
34import { blockList, cleanResolution, openReportCount, report, reports, setReportState, suspend, suspendReason, unsuspend, visibleTo } from "../lib/moderation.js";
35import { BlockList, hasBlocked, ProfileMenu, ReportDetail, ReportsList, SuspendControl } from "./moderation.js";
36
37// ---------------------------------------------------------------- shared bits
38
39const RepoList: FC<{ repos: Repo[]; showOwner?: boolean; empty?: Child }> = ({ repos, showOwner = true, empty }) =>
40 repos.length ? (
41 <ul class="list">
42 {repos.map((r) => (
43 <li>
44 <span class="st faint">{raw(r.visibility === "private" ? ICONS.lock : ICONS.repo)}</span>
45 <div class="grow">
46 <a class="title" href={repoUrl(r)}>
47 {showOwner ? `${r.owner_login}/` : ""}
48 {r.name}
49 </a>{" "}
50 <span class="badge">{r.visibility}</span> {r.archived ? <span class="badge amber">archived</span> : null}
51 {r.description ? <div class="meta">{r.description}</div> : null}
52 </div>
53 <span class="small muted nowrap">Updated {ago(r.pushed_at ?? r.updated_at)}</span>
54 </li>
55 ))}
56 </ul>
57 ) : (
58 <div class="empty">{empty ?? "No repositories yet."}</div>
59 );
60
61function parsePolicy(a: Account): { maxRole?: Role } {
62 try {
63 return a.agent_policy ? (JSON.parse(a.agent_policy) as { maxRole?: Role }) : {};
64 } catch {
65 return {};
66 }
67}
68
69async function adminOrgs(c: AppContext, me: Account): Promise<Array<Account & { role: string }>> {
70 return (await c.get("dir").orgsFor(me.id)).filter((o) => o.role === "owner" || o.role === "admin");
71}
72
73/** Whether `me` may manage an agent (its owner, an admin of its owning org, or a site admin). */
74async function canManageAgent(c: AppContext, me: Account, agent: Account): Promise<boolean> {
75 if (agent.kind !== "agent" || !agent.owner_id) return false;
76 if (me.site_admin || agent.owner_id === me.id) return true;
77 const role = await c.get("dir").orgRole(agent.owner_id, me.id);
78 return role === "owner" || role === "admin";
79}
80
81// ---------------------------------------------------------------- profile pictures (people and organizations)
82
83const TOO_BIG = "That picture is larger than 5 MB. Use a smaller file.";
84
85/** Current picture, an upload control and a Remove button. Uploads go to `action`, removal to `${action}/delete`. */
86const AvatarSection: FC<{ account: Account; action: string; t: string }> = ({ account, action, t }) => (
87 <div class="box">
88 <div class="head">
89 <h2>Profile picture</h2>
90 </div>
91 <div class="body avpick">
92 <span data-avatar-preview>
93 <Avatar login={account.login} kind={account.kind} size="xl" version={account.avatar_version} />
94 </span>
95 <div class="grow">
96 <Form action={action} t={t} avatar>
97 <div class="field">
98 <label for="avatar-file">Upload a new picture</label>
99 <input id="avatar-file" name="avatar" type="file" accept="image/jpeg,image/png,image/webp" required />
100 <div class="hint">JPEG, PNG or WebP, up to 5 MB. It is cropped to a centred square.</div>
101 </div>
102 <div class="row">
103 <button class="btn primary">Save picture</button>
104 <span class="muted small" data-avatar-status aria-live="polite"></span>
105 </div>
106 </Form>
107 {account.avatar_version ? (
108 <Form action={`${action}/delete`} t={t} class="mt" confirm={account.kind === "org" ? `Remove the picture of ${account.login}?` : "Remove your profile picture?"}>
109 <button class="btn sm danger">Remove picture</button>
110 <span class="muted small" style="margin-left:8px">
111 Shows initials instead.
112 </span>
113 </Form>
114 ) : null}
115 </div>
116 </div>
117 </div>
118);
119
120/** Refuse oversized uploads before the form body is parsed. */
121function avatarSizeGuard(web: WebApp, path: string, back: (c: AppContext) => string): void {
122 web.use(path, async (c, next) => {
123 if (c.req.method === "POST" && Number(c.req.header("content-length") ?? 0) > MAX_AVATAR_BYTES + 64 * 1024) {
124 flash(c, "error", TOO_BIG);
125 return c.redirect(back(c), 303);
126 }
127 await next();
128 });
129}
130
131async function uploadAvatar(c: AppContext, f: FormData, me: Account, account: Account): Promise<void> {
132 const file = f.file("avatar");
133 if (!file) throw new HttpError(422, "Choose a picture to upload.");
134 if (file.size > MAX_AVATAR_BYTES) throw new HttpError(413, TOO_BIG);
135 await setAvatar(c, account, new Uint8Array(await file.arrayBuffer()));
136 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: me.id, actorLogin: me.login, action: "avatar.update", target: account.login, detail: { kind: account.kind, via: "web" } }));
137}
138
139async function deleteAvatar(c: AppContext, me: Account, account: Account): Promise<void> {
140 await removeAvatar(c, account);
141 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: me.id, actorLogin: me.login, action: "avatar.remove", target: account.login, detail: { kind: account.kind, via: "web" } }));
142}
143
144const SCOPES: TokenScope[] = ["read", "write", "admin"];
145const BASE_ROLE_OPTIONS = [
146 { value: "none", label: "No permission: members see only repositories they're given" },
147 { value: "read", label: "Read: members can clone and view" },
148 { value: "write", label: "Write: members can also push" },
149 { value: "admin", label: "Admin: members can also change settings" },
150];
151
152// ---------------------------------------------------------------- dashboard (visitors get the landing page, web/site.tsx)
153
154/** The icon for a notification, by the event that raised it. */
155function noteIcon(kind: string): string {
156 if (kind === "run_failed") return ICONS.failure;
157 if (kind.startsWith("pull_request")) return ICONS.pr;
158 if (kind === "issues") return ICONS.issueOpen;
159 if (kind.endsWith("comment")) return ICONS.comment;
160 if (kind === "org_membership") return ICONS.org;
161 if (kind === "repo_access") return ICONS.repo;
162 if (kind === "invitation" || kind === "early_access" || kind === "contact") return ICONS.envelope;
163 return ICONS.bell;
164}
165
166/** A person's pending invitations to organizations and repositories, each with Accept and Decline. */
167const MyInvitations: FC<{ invites: Awaited<ReturnType<Directory["invitesFor"]>>; t: string }> = ({ invites, t }) => (
168 <div class="box">
169 {invites.length ? (
170 <ul class="list">
171 {invites.map((i) => (
172 <li>
173 <div class="grow">
174 <b>{i.org ?? i.repo}</b>
175 <span class="badge" style="margin-left:6px">
176 {cap(i.role)}
177 </span>
178 <div class="muted small">
179 {i.org ? "Organization" : "Repository"} · invited {i.invitedBy ? `by ${i.invitedBy} ` : ""}
180 <Time at={i.createdAt} /> · expires {new Date(i.expiresAt).toLocaleDateString("en-US", { dateStyle: "medium" })}
181 </div>
182 </div>
183 <Form action={`/settings/invitations/${encodeURIComponent(i.id)}/accept`} t={t} class="inline">
184 <button class="btn sm primary">Accept</button>
185 </Form>
186 <Form action={`/settings/invitations/${encodeURIComponent(i.id)}/decline`} t={t} class="inline">
187 <button class="btn sm">Decline</button>
188 </Form>
189 </li>
190 ))}
191 </ul>
192 ) : (
193 <div class="empty">No pending invitations.</div>
194 )}
195 </div>
196);
197
198export function registerAccount(web: WebApp): void {
199 web.get("/", async (c) => {
200 const p = c.get("principal");
201 if (p.type !== "account") return landingPage(c);
202 const me = p.account;
203 const t = csrfToken(c);
204 if (me.status === "disabled") {
205 return render(
206 c,
207 { title: "Account disabled", status: 403 },
208 <div class="blank" style="max-width:560px;margin:48px auto">
209 <h1>Your account is disabled</h1>
210 <p class="muted m0">Contact an administrator of this Diffinery instance if you think this is a mistake.</p>
211 </div>,
212 );
213 }
214 if (me.status === "pending") {
215 const invites = await c.get("dir").invitesFor(me);
216 return render(
217 c,
218 { title: "Waiting for an invite" },
219 <div class="box" style="max-width:600px;margin:48px auto">
220 <div class="body">
221 <h1>Waiting for an invite</h1>
222 <p class="muted">
223 You are signed in as <b>{me.email ?? me.login}</b>, but this Diffinery instance is invite-only. Ask someone with access to invite your email address, or send a request to the administrators.
224 </p>
225 {invites.length ? (
226 <>
227 <h3>Your invitations</h3>
228 <MyInvitations invites={invites} t={t} />
229 </>
230 ) : null}
231 <Form action="/request-access" t={t}>
232 <div class="field">
233 <label for="note">Note to the administrators</label>
234 <textarea id="note" name="note" maxlength={500} placeholder="Who are you, and what would you like to work on?" style="min-height:90px"></textarea>
235 </div>
236 <button class="btn primary">Request access</button>
237 </Form>
238 </div>
239 </div>,
240 );
241 }
242 const dir = c.get("dir");
243 // Read once, for the sidebar and for Today.
244 const visible = dir.reposVisibleTo(me);
245 const memberships = dir.orgsFor(me.id);
246 const [repos, orgs, notes, today] = await Promise.all([
247 visible,
248 memberships,
249 dir.notifications(me.id, true),
250 // The morning view (agentic/today.ts); the dashboard still renders if it fails.
251 gatherToday(c.env, dir, me, { visible, orgs: memberships }).catch((e: unknown) => {
252 console.error("today failed", e);
253 return null;
254 }),
255 ]);
256 const mine = repos.filter((r) => r.owner_id === me.id || orgs.some((o) => o.id === r.owner_id));
257 const others = repos.filter((r) => !mine.includes(r));
258 // Someone who owns nothing yet but works in others' repositories sees those instead.
259 const side = mine.length ? mine : others;
260 const collapsed = collapsedSections(getCookie(c, COLLAPSED_COOKIE));
261 return render(
262 c,
263 { title: "Today" },
264 <div class="grid left">
265 {/* On phones, Today comes first and the repository list after it. */}
266 <aside class="side after">
267 <section>
268 <div class="row between mb">
269 <h3 class="m0">{mine.length || !others.length ? "Your repositories" : "Repositories"}</h3>
270 <a class="btn sm primary" href="/new">
271 {raw(ICONS.plus)} New
272 </a>
273 </div>
274 {side.length ? (
275 <div class="nav">
276 {side.slice(0, 40).map((r) => (
277 <a href={repoUrl(r)} class="nowrap" style="overflow:hidden;text-overflow:ellipsis">
278 <Avatar login={r.owner_login} /> {r.owner_login}/<b>{r.name}</b>
279 </a>
280 ))}
281 </div>
282 ) : (
283 <p class="muted small">You have no repositories yet.</p>
284 )}
285 </section>
286 <section>
287 <h3>Organizations</h3>
288 <div class="nav">
289 {orgs.map((o) => (
290 <a href={`/${o.login}`}>
291 <Avatar login={o.login} version={o.avatar_version} /> {o.login} <span class="faint small">{o.role}</span>
292 </a>
293 ))}
294 <a href="/settings/orgs" class="muted">
295 {raw(ICONS.plus)} New organization
296 </a>
297 </div>
298 </section>
299 </aside>
300 <div>
301 {repos.length === 0 ? (
302 <div class="box">
303 <div class="body">
304 <h2>Welcome to Diffinery, {me.name || me.login}</h2>
305 <ol class="muted" style="padding-left:20px">
306 <li>
307 <a href="/new">Create a repository</a> (or an <a href="/settings/orgs">organization</a> to share work with friends).
308 </li>
309 <li>
310 <a href="/settings/tokens">Create a personal access token</a> — Git uses it as the password over HTTPS.
311 </li>
312 <li>Push your code, open pull requests and add workflows under <code>.github/workflows</code>.</li>
313 <li>
314 Invite people from an organization's <b>People</b> page or a repository's <b>Settings → Collaborators</b>.
315 </li>
316 </ol>
317 </div>
318 </div>
319 ) : today ? (
320 <TodayView today={today} name={me.name || me.login} collapsed={collapsed} />
321 ) : null}
322 {notes.length ? (
323 <Section
324 id="notifications"
325 icon={ICONS.bell}
326 title="Unread notifications"
327 count={notes.length}
328 collapsed={collapsed}
329 action={
330 <a class="small manage" href="/notifications">
331 View all
332 </a>
333 }
334 >
335 <Rows
336 items={notes.slice(0, 8)}
337 row={(n) => (
338 <li>
339 <div class="grow">
340 <a class="title" href={`/notifications/${n.id}`}>
341 {n.title}
342 </a>
343 <div class="meta">
344 {n.kind.replace(/_/g, " ")} · <Time at={n.createdAt} />
345 </div>
346 </div>
347 </li>
348 )}
349 />
350 </Section>
351 ) : null}
352 <div class="box">
353 <div class="head">
354 <h2>Repositories</h2>
355 <span class="muted small">{repos.length} you can access</span>
356 </div>
357 <RepoList repos={[...mine, ...others].slice(0, 100)} empty={<a href="/new">Create your first repository</a>} />
358 </div>
359 </div>
360 </div>,
361 );
362 });
363
364 post(web, "/request-access", async (c, f) => {
365 const p = c.get("principal");
366 if (p.type !== "account") throw new HttpError(401, "sign in required");
367 if (p.account.status !== "pending") return c.redirect("/", 303);
368 return act(c, "/", async () => c.get("dir").requestAccess(p.account.id, f.s("note")), "Request sent. An administrator will review it.");
369 });
370
371 // ---------------------------------------------------------------- new repository
372
373 const NewRepoForm: FC<{ t: string; me: Account; orgs: Array<Account & { role: string }>; values: Record<string, string>; error?: string }> = ({ t, me, orgs, values, error }) => (
374 <div style="max-width:720px;margin:0 auto">
375 <h1>Create a new repository</h1>
376 <p class="muted">
377 A repository holds your project's files, history, issues, pull requests and workflows. Already on GitHub? <a href="/new/import">Import a repository</a>.
378 </p>
379 {error ? <div class="flash error">{error}</div> : null}
380 <Form action="/new" t={t} class="box">
381 <div class="body">
382 <div class="row" style="align-items:flex-end">
383 <div class="field" style="min-width:180px">
384 <label for="owner">Owner</label>
385 <KSelect
386 id="owner"
387 name="owner"
388 block
389 label="Owner"
390 value={orgs.some((o) => o.login === values.owner) ? values.owner : me.login}
391 options={[me.login, ...orgs.map((o) => o.login)].map((l) => ({ value: l, label: l }))}
392 />
393 </div>
394 <div class="field" style="padding-bottom:8px">/</div>
395 <div class="field grow">
396 <label for="name">Repository name</label>
397 <input id="name" name="name" type="text" required pattern="[A-Za-z0-9][A-Za-z0-9._\-]{0,99}" value={values.name} autofocus autocomplete="off" />
398 </div>
399 </div>
400 <div class="field">
401 <label for="description">
402 Description <span class="faint">(optional)</span>
403 </label>
404 <input id="description" name="description" type="text" value={values.description} maxlength={350} />
405 </div>
406 <div class="field">
407 <label>Visibility</label>
408 <KRadio
409 name="visibility"
410 label="Visibility"
411 value={values.visibility || "private"}
412 items={(
413 [
414 ["private", "Private", "Only you, collaborators and organization members can see it."],
415 ["public", "Public", "Anyone on the internet can see and clone it."],
416 ] as const
417 ).map(([v, l, d]) => ({ value: v, label: l, description: d }))}
418 />
419 </div>
420 <div class="field" style="max-width:280px">
421 <label for="branch">Default branch</label>
422 <input id="branch" name="default_branch" type="text" value={values.default_branch || "main"} />
423 </div>
424 <button class="btn primary">Create repository</button>
425 </div>
426 </Form>
427 </div>
428 );
429
430 web.get("/new", async (c) => {
431 const me = requireAccount(c);
432 const orgs = await c.get("dir").orgsFor(me.id);
433 return render(c, { title: "New repository" }, <NewRepoForm t={csrfToken(c)} me={me} orgs={orgs} values={{ owner: c.req.query("owner") ?? me.login }} />);
434 });
435
436 post(web, "/new", async (c, f) => {
437 const me = requireAccount(c);
438 const dir = c.get("dir");
439 const values = { owner: f.s("owner"), name: f.s("name").trim(), description: f.s("description").trim(), visibility: f.s("visibility"), default_branch: f.s("default_branch").trim() };
440 try {
441 const owner = values.owner === me.login ? me : await dir.accountByLogin(values.owner);
442 if (!owner || owner.kind === "agent") throw new HttpError(422, "unknown owner");
443 const visibility = (["private", "public"] as const).find((v) => v === values.visibility) ?? "private";
444 const repo = await dir.createRepo(owner, me, { name: values.name, description: values.description, visibility, defaultBranch: values.default_branch || "main" });
445 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "repo.create", target: `${repo.owner_login}/${repo.name}` }));
446 c.executionCtx.waitUntil(repoCreated(c.env, dir, repo, me, { viaToken: false }));
447 return c.redirect(repoUrl(repo), 303);
448 } catch (e) {
449 if (!(e instanceof HttpError) || e.status >= 500) throw e;
450 const orgs = await dir.orgsFor(me.id);
451 return render(c, { title: "New repository", status: e.status }, <NewRepoForm t={csrfToken(c)} me={me} orgs={orgs} values={values} error={e.detail} />);
452 }
453 });
454
455 // ---------------------------------------------------------------- notifications
456
457 web.get("/notifications", async (c) => {
458 const me = requireAccount(c);
459 const t = csrfToken(c);
460 const all = c.req.query("all") === "1";
461 const notes = await c.get("dir").notifications(me.id, !all);
462 return render(
463 c,
464 { title: "Notifications" },
465 <div style="max-width:900px;margin:0 auto">
466 <div class="row between mb">
467 <h1 class="m0">Notifications</h1>
468 <div class="row">
469 <div class="subnav">
470 <a href="/notifications" class={!all ? "on" : ""}>
471 Unread
472 </a>
473 <a href="/notifications?all=1" class={all ? "on" : ""}>
474 All
475 </a>
476 </div>
477 <Form action="/notifications/read" t={t} class="inline">
478 <button class="btn">{raw(ICONS.check)} Mark all as read</button>
479 </Form>
480 <a class="btn icon" href="/settings/notifications" title="Notification settings" aria-label="Notification settings">
481 {raw(ICONS.gear)}
482 </a>
483 </div>
484 </div>
485 <div class="box">
486 {notes.length ? (
487 <ul class="list">
488 {notes.map((n) => (
489 <li>
490 <span class={`st ${n.readAt ? "faint" : ""}`} style={n.readAt ? "" : n.kind === "run_failed" ? "color:var(--red)" : "color:var(--accent)"}>
491 {raw(noteIcon(n.kind))}
492 </span>
493 <div class="grow">
494 <a class="title" href={`/notifications/${n.id}`} style={n.readAt ? "font-weight:400" : ""}>
495 {n.title}
496 </a>
497 <div class="meta">
498 {n.kind.replace(/_/g, " ")} · <Time at={n.createdAt} />
499 </div>
500 </div>
501 {!n.readAt ? (
502 <Form action="/notifications/read" t={t} class="inline">
503 <input type="hidden" name="id" value={n.id} />
504 <button class="btn sm" title="Mark as read">
505 {raw(ICONS.check)}
506 </button>
507 </Form>
508 ) : null}
509 </li>
510 ))}
511 </ul>
512 ) : (
513 <div class="empty">{all ? "No notifications." : "All caught up — no unread notifications."}</div>
514 )}
515 </div>
516 </div>,
517 );
518 });
519
520 web.get("/notifications/:id", async (c) => {
521 const me = requireAccount(c);
522 const dir = c.get("dir");
523 const id = prm(c, "id");
524 const n = (await dir.notifications(me.id)).find((x) => x.id === id);
525 if (!n) throw new HttpError(404, "notification not found");
526 await dir.markRead(me.id, id);
527 const base = publicUrl(c);
528 let to = n.url;
529 if (to.startsWith(base)) to = to.slice(base.length) || "/";
530 return c.redirect(localPath(to) ?? "/notifications", 302);
531 });
532
533 post(web, "/notifications/read", async (c, f) => {
534 const me = requireAccount(c);
535 const id = f.s("id");
536 return act(c, c.req.header("referer")?.includes("/notifications") ? "/notifications" : "/", async () => c.get("dir").markRead(me.id, id || undefined));
537 });
538
539 // ---------------------------------------------------------------- invites
540
541 web.get("/invite/:token", async (c) => {
542 const p = c.get("principal");
543 if (p.type !== "account") return invitePasskeyPage(c, prm(c, "token"));
544 if (p.account.status === "disabled") throw new HttpError(403, "your account is disabled");
545 return render(
546 c,
547 { title: "Accept invite" },
548 <div class="box" style="max-width:560px;margin:48px auto">
549 <div class="body">
550 <h1>You have been invited</h1>
551 <p class="muted">
552 Accept this invite as <b>{p.account.login}</b> ({p.account.email ?? "no email"}). Invites only work for the email address they were sent to.
553 </p>
554 <Form action={`/invite/${encodeURIComponent(prm(c, "token"))}`} t={csrfToken(c)}>
555 <button class="btn primary">Accept invite</button>
556 </Form>
557 </div>
558 </div>,
559 );
560 });
561
562 post(web, "/invite/:token", async (c) => {
563 const p = c.get("principal");
564 if (p.type !== "account") throw new HttpError(401, "sign in to accept this invite");
565 if (p.account.status === "disabled") throw new HttpError(403, "your account is disabled");
566 const dir = c.get("dir");
567 const res = await dir.acceptInvite(prm(c, "token"), p.account);
568 let to = "/";
569 if (res.repoId) {
570 const r = await dir.repoById(res.repoId);
571 if (r) to = repoUrl(r);
572 } else if (res.orgId) {
573 const o = await dir.account(res.orgId);
574 if (o) to = `/${o.login}`;
575 }
576 c.executionCtx.waitUntil(dir.audit({ actorId: p.account.id, actorLogin: p.account.login, action: "invite.accept", target: to }));
577 return c.redirect(to, 303);
578 });
579
580 // ---------------------------------------------------------------- palette data
581
582 web.get("/-/palette.json", async (c) => {
583 const me = requireAccount(c);
584 const repos = (await c.get("dir").reposVisibleTo(me)).slice(0, 300).map((r) => `${r.owner_login}/${r.name}`);
585 const param = c.req.query("repo") ?? "";
586 let files: string[] = [];
587 let ref: string | undefined;
588 const m = /^([A-Za-z0-9][\w.-]*)\/([A-Za-z0-9][\w.-]*)$/.exec(param);
589 if (m) {
590 try {
591 const { stub, repo } = await loadRepo(c, m[1]!, m[2]!, "read");
592 ref = c.req.query("ref") || repo.default_branch;
593 files = await listFiles(stub, ref);
594 } catch {
595 files = [];
596 }
597 }
598 return c.json({ repos, files, ref }, 200, { "cache-control": "private, max-age=30" });
599 });
600
601 // ---------------------------------------------------------------- personal settings
602
603 registerSettings(web);
604 registerProfiles(web);
605}
606
607/** Breadth-first file listing for "go to file" (bounded). */
608async function listFiles(stub: Stub, ref: string): Promise<string[]> {
609 const out: string[] = [];
610 let queue = [""];
611 let reads = 0;
612 while (queue.length && reads < 120 && out.length < 5000) {
613 const batch = queue.slice(0, 12);
614 queue = queue.slice(12);
615 reads += batch.length;
616 const trees = await Promise.all(batch.map((p) => stub.tree(ref, p).catch(() => null)));
617 for (const t of trees) {
618 if (!t) continue;
619 for (const it of t.items) {
620 if (it.type === "tree") {
621 if (!/^(node_modules|\.git|vendor|dist|target)$/.test(it.name)) queue.push(it.path);
622 } else if (it.type === "blob") out.push(it.path);
623 }
624 }
625 }
626 return out.slice(0, 5000);
627}
628
629// ---------------------------------------------------------------- /settings
630
631const AUTO_MERGE_METHODS = [
632 { value: "default", label: "As the branch merges" },
633 { value: "squash", label: "Squash and merge" },
634 { value: "merge", label: "Create a merge commit" },
635 { value: "rebase", label: "Rebase and merge" },
636];
637
638export type SettingsTab = "profile" | "account" | "appearance" | "pull-requests" | "security" | "tokens" | "apps" | "installations" | "github-runners" | "agents" | "model-access" | "orgs" | "invitations" | "notifications" | "email-address" | "blocked" | "linked" | "admin" | "reports" | "email" | "audit" | "kill-switches" | "errors" | "security-reports" | "status" | "early-access" | "contact" | "search-engines";
639/** The site administration pages: they show when hosted compute is paused. */
640export const ADMIN_TABS: readonly SettingsTab[] = ["admin", "early-access", "contact", "reports", "email", "audit", "kill-switches", "errors", "security-reports", "status", "search-engines"];
641
642/** The number of confirmed early access requests waiting, next to Early access in the sidebar (lib/early-access.ts). */
643const EarlyAccessWaiting = async ({ db }: { db?: D1Database }) => {
644 const n = db ? await new EarlyAccess(db).waiting().catch(() => 0) : 0;
645 return n ? (
646 <span class="badge blue" style="margin-left:6px" title={`${n} confirmed request${n === 1 ? "" : "s"} waiting`}>
647 {n}
648 </span>
649 ) : (
650 <></>
651 );
652};
653
654/** The number of new contact messages, next to Contact messages in the sidebar (lib/contact.ts). */
655const ContactWaiting = async ({ db }: { db?: D1Database }) => {
656 const n = db ? await new ContactMessages(db).waiting().catch(() => 0) : 0;
657 return n ? (
658 <span class="badge blue" style="margin-left:6px" title={`${n} new message${n === 1 ? "" : "s"}`}>
659 {n}
660 </span>
661 ) : (
662 <></>
663 );
664};
665
666/** On People and invitations: a pointer to the early access requests waiting, when there are any. */
667const EarlyAccessCallout = async ({ db }: { db: D1Database }) => {
668 const n = await new EarlyAccess(db).waiting().catch(() => 0);
669 return n ? (
670 <div class="flash notice row between" style="gap:12px">
671 <span>
672 {n} confirmed early access request{n === 1 ? " is" : "s are"} waiting for you to invite or decline.
673 </span>
674 <a class="btn sm" href="/settings/admin/early-access">
675 Review requests
676 </a>
677 </div>
678 ) : (
679 <></>
680 );
681};
682
683/** The Settings sidebar. `db` lets it show how many early access requests and contact messages wait (site administrators only). */
684export const SettingsNav: FC<{ me: Account; tab: SettingsTab; db?: D1Database }> = ({ me, tab, db }) => (
685 <aside class="side vt-side">
686 <section>
687 <div class="row mb">
688 <Avatar login={me.login} size="lg" version={me.avatar_version} />
689 <div>
690 <b>{me.name || me.login}</b>
691 <div class="muted small">{me.login}</div>
692 </div>
693 </div>
694 <div class="nav">
695 <a href="/settings" class={tab === "profile" ? "on" : ""}>
696 Profile
697 </a>
698 <a href="/settings/account" class={tab === "account" ? "on" : ""}>
699 Account
700 </a>
701 <a href="/settings/appearance" class={tab === "appearance" ? "on" : ""}>
702 Appearance
703 </a>
704 <a href="/settings/pull-requests" class={tab === "pull-requests" ? "on" : ""}>
705 Pull requests
706 </a>
707 <a href="/settings/security" class={tab === "security" ? "on" : ""}>
708 Passkeys and sessions
709 </a>
710 <a href="/settings/tokens" class={tab === "tokens" ? "on" : ""}>
711 Access tokens
712 </a>
713 <a href="/settings/agents" class={tab === "agents" ? "on" : ""}>
714 Agents
715 </a>
716 <a href="/settings/installations" class={tab === "installations" ? "on" : ""}>
717 Installed apps
718 </a>
719 <a href="/settings/apps" class={tab === "apps" ? "on" : ""}>
720 Apps
721 </a>
722 <a href="/settings/github-runners" class={tab === "github-runners" ? "on" : ""}>
723 GitHub runners
724 </a>
725 <a href="/settings/model-access" class={tab === "model-access" ? "on" : ""}>
726 Model access
727 </a>
728 <a href="/settings/orgs" class={tab === "orgs" ? "on" : ""}>
729 Organizations
730 </a>
731 <a href="/settings/invitations" class={tab === "invitations" ? "on" : ""}>
732 Invitations
733 </a>
734 <a href="/settings/notifications" class={tab === "notifications" ? "on" : ""}>
735 Notifications
736 </a>
737 <a href="/settings/email" class={tab === "email-address" ? "on" : ""}>
738 Email
739 </a>
740 <a href="/settings/blocked-users" class={tab === "blocked" ? "on" : ""}>
741 Blocked users
742 </a>
743 <a href="/settings/linked-accounts" class={tab === "linked" ? "on" : ""}>
744 Linked accounts
745 </a>
746 <a href="/imports">Imports</a>
747 {me.site_admin ? (
748 <>
749 <h4>Site administration</h4>
750 <a href="/settings/admin" class={tab === "admin" ? "on" : ""}>
751 People and invitations
752 </a>
753 <a href="/settings/admin/early-access" class={tab === "early-access" ? "on" : ""}>
754 Early access
755 <EarlyAccessWaiting db={db} />
756 </a>
757 <a href="/settings/admin/contact" class={tab === "contact" ? "on" : ""}>
758 Contact messages
759 <ContactWaiting db={db} />
760 </a>
761 <a href="/settings/admin/reports" class={tab === "reports" ? "on" : ""}>
762 Reports
763 </a>
764 <a href="/settings/admin/email" class={tab === "email" ? "on" : ""}>
765 Email
766 </a>
767 <a href="/settings/admin/kill-switches" class={tab === "kill-switches" ? "on" : ""}>
768 Kill switches
769 </a>
770 <a href="/settings/admin/security-reports" class={tab === "security-reports" ? "on" : ""}>
771 Security reports
772 </a>
773 <a href="/settings/admin/status" class={tab === "status" ? "on" : ""}>
774 Status
775 </a>
776 <a href="/settings/admin/search-engines" class={tab === "search-engines" ? "on" : ""}>
777 Search engines
778 </a>
779 <a href="/settings/audit" class={tab === "audit" ? "on" : ""}>
780 Audit log
781 </a>
782 <a href="/settings/admin/errors" class={tab === "errors" ? "on" : ""}>
783 Server errors
784 </a>
785 </>
786 ) : null}
787 </div>
788 </section>
789 </aside>
790);
791
792const TokenOnce: FC<{ token: string; title: string; c: AppContext; note?: Child }> = ({ token, title, c, note }) => (
793 <div class="box" style="border-color:var(--amber)">
794 <div class="body">
795 <h3>{title}</h3>
796 <p class="muted">Copy it now — it will not be shown again.</p>
797 <div class="row">
798 <div class="secret grow">{token}</div>
799 <CopyButton text={token} size="base" />
800 </div>
801 {note}
802 <details class="mt">
803 <summary class="small" style="cursor:pointer">
804 How to use it
805 </summary>
806 <pre class="cmd mt">
807 {`# Git over HTTPS: use your username and this token as the password\ngit clone ${publicUrl(c)}/OWNER/REPO.git\n\n# Remember it (or use your OS keychain helper)\ngit config --global credential.helper store\n\n# HTTP APIs and MCP clients\nAuthorization: Bearer <token>`}
808 </pre>
809 </details>
810 </div>
811 </div>
812);
813
814function registerSettings(web: WebApp): void {
815 const page = (c: AppContext, me: Account, tab: SettingsTab, title: string, body: Child, status?: number) =>
816 render(
817 c,
818 { title, status },
819 <div class="grid left">
820 <SettingsNav me={me} tab={tab} db={c.env.DB} />
821 <div>
822 {ADMIN_TABS.includes(tab) ? <ComputePausedBanner env={c.env} /> : null}
823 {body}
824 </div>
825 </div>,
826 );
827
828 // Profile
829 web.get("/settings", async (c) => {
830 const me = requireAccount(c);
831 const t = csrfToken(c);
832 return page(
833 c,
834 me,
835 "profile",
836 "Settings",
837 <>
838 <h1>Profile</h1>
839 <AvatarSection account={me} action="/settings/avatar" t={t} />
840 <Form action="/settings/profile" t={t} class="box">
841 <div class="body">
842 <div class="field">
843 <label for="login">Username</label>
844 <input id="login" name="login" type="text" value={me.login} required pattern={LOGIN_PATTERN} />
845 <div class="hint">Changing your username changes the URLs of your repositories. Existing clones need a new remote URL.</div>
846 </div>
847 <div class="field">
848 <label for="name">Display name</label>
849 <input id="name" name="name" type="text" value={me.name ?? ""} />
850 </div>
851 <dl class="kv mb">
852 <dt>Email</dt>
853 <dd>{me.email ?? "—"}</dd>
854 <dt>Account type</dt>
855 <dd>{me.kind}</dd>
856 <dt>Joined</dt>
857 <dd>
858 <Time at={me.created_at} />
859 </dd>
860 <dt>Site admin</dt>
861 <dd>{me.site_admin ? "yes" : "no"}</dd>
862 </dl>
863 <button class="btn primary">Save profile</button>
864 </div>
865 </Form>
866 </>,
867 );
868 });
869
870 post(web, "/settings/profile", async (c, f) => {
871 const me = requireAccount(c);
872 return act(
873 c,
874 "/settings",
875 async () => {
876 const login = f.s("login").trim();
877 if (login && login !== me.login) requireRecentSignIn(c, "/settings");
878 await c.get("dir").updateAccount(me.id, { login: login && login !== me.login ? login : undefined, name: f.s("name").trim() });
879 // The old login's cached picture must not outlive the rename.
880 if (login && login !== me.login) c.executionCtx.waitUntil(purgeAvatarCache(c, me.login, [me.avatar_version]));
881 },
882 "Profile saved.",
883 );
884 });
885
886 // Appearance
887 web.get("/settings/appearance", async (c) => {
888 const me = requireAccount(c);
889 const current = me.appearance === "light" || me.appearance === "dark" ? me.appearance : "auto";
890 return page(
891 c,
892 me,
893 "appearance",
894 "Appearance",
895 <>
896 <h1>Appearance</h1>
897 <p class="muted">Choose how Diffinery looks to you. The choice follows your account to every browser you sign in to.</p>
898 <Form action="/settings/appearance" t={csrfToken(c)} class="box">
899 <div class="body">
900 <div class="field">
901 <label>Theme</label>
902 <KRadio
903 name="appearance"
904 label="Theme"
905 value={current}
906 items={(
907 [
908 ["auto", "Sync with system", "Light or dark, following your device's setting."],
909 ["light", "Light", "Always light."],
910 ["dark", "Dark", "Always dark."],
911 ] as const
912 ).map(([v, l, d]) => ({ value: v, label: <span class="theme-opt"><span class={`theme-prev ${v}`} aria-hidden="true"><i /><i /><i /></span>{l}</span>, description: d }))}
913 />
914 </div>
915 <button class="btn primary">Save appearance</button>
916 </div>
917 </Form>
918 </>,
919 );
920 });
921
922 post(web, "/settings/appearance", async (c, f) => {
923 const me = requireAccount(c);
924 const v = f.s("appearance");
925 const appearance = v === "light" || v === "dark" ? v : null;
926 await c.get("dir").setAppearance(me.id, appearance);
927 // Signed-out pages (sign-in, invites) in this browser keep the choice too.
928 if (appearance) setCookie(c, APPEARANCE_COOKIE, appearance, { path: "/", secure: true, sameSite: "Lax", maxAge: 400 * 86400 });
929 else deleteCookie(c, APPEARANCE_COOKIE, { path: "/", secure: true });
930 flash(c, "notice", "Appearance saved.");
931 return c.redirect("/settings/appearance", 303);
932 });
933
934 // Pull requests: turn on auto-merge for the pull requests you open (repo/auto-merge.ts applyOwn).
935 web.get("/settings/pull-requests", async (c) => {
936 const me = requireAccount(c);
937 const current = parseAutoMergeDefault(me.auto_merge);
938 return page(
939 c,
940 me,
941 "pull-requests",
942 "Pull requests",
943 <>
944 <h1>Pull requests</h1>
945 <p class="muted">
946 Have your pull requests merge by themselves once their checks pass. See <a href="/docs/collaboration/merge-on-green">Merge on green automatically</a>.
947 </p>
948 <Form action="/settings/pull-requests" t={csrfToken(c)} class="box">
949 <div class="body fbody">
950 <div class="fchecks">
951 <KCheckbox
952 name="auto_merge"
953 checked={!!current}
954 label="Turn on auto-merge for pull requests I open"
955 description="As you open a pull request (or mark your draft ready), Diffinery turns on auto-merge for you, in every repository, wherever the branch has required checks. It merges once those pass and every rule of the branch is met, approvals included; it never skips a rule. Turn it off on any one pull request from its page, or open it with diffinery pr create --no-auto."
956 />
957 </div>
958 <div class="fgrid c3">
959 <div class="field">
960 <label for="am-method">Merge method</label>
961 <KSelect id="am-method" name="method" label="Merge method" block value={current ?? "default"} options={AUTO_MERGE_METHODS} />
962 <div class="hint">Where a branch requires linear history, a merge commit becomes the branch's own method.</div>
963 </div>
964 </div>
965 <div class="factions">
966 <button class="btn primary">Save</button>
967 </div>
968 </div>
969 </Form>
970 <p class="small muted">
971 Your agents have the same setting, in <a href="/settings/agents">Agents</a>. To make a repository's pull requests merge when its checks pass, an admin opens its Settings → <b>Merge on green</b>.
972 </p>
973 </>,
974 );
975 });
976
977 post(web, "/settings/pull-requests", async (c, f) => {
978 const me = requireAccount(c);
979 const v = f.b("auto_merge") ? (parseAutoMergeDefault(f.s("method")) ?? "default") : null;
980 await c.get("dir").setAutoMerge(me.id, v);
981 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: me.id, actorLogin: me.login, action: "account.auto_merge", target: me.login, detail: { merge_method: v } }));
982 flash(c, "notice", v ? "Auto-merge now turns on by itself for pull requests you open." : "Auto-merge no longer turns on by itself for your pull requests.");
983 return c.redirect("/settings/pull-requests", 303);
984 });
985
986 avatarSizeGuard(web, "/settings/avatar", () => "/settings");
987 post(web, "/settings/avatar", async (c, f) => {
988 const me = requireAccount(c);
989 return act(c, "/settings", () => uploadAvatar(c, f, me, me), "Profile picture updated.");
990 });
991
992 post(web, "/settings/avatar/delete", async (c) => {
993 const me = requireAccount(c);
994 return act(c, "/settings", () => deleteAvatar(c, me, me), "Profile picture removed.");
995 });
996
997 // Passkeys and sessions
998 web.get("/settings/security", async (c) => {
999 const me = requireAccount(c);
1000 const t = csrfToken(c);
1001 const auth = new Auth(c.env);
1002 const p = c.get("principal");
1003 const current = p.type === "account" ? p.sessionId : undefined;
1004 const [keys, sessions] = await Promise.all([auth.passkeys(me.id), auth.sessions(me.id)]);
1005 const recovery = !!(c.env.ACCESS_TEAM_DOMAIN && c.env.ACCESS_AUD);
1006 return page(
1007 c,
1008 me,
1009 "security",
1010 "Passkeys and sessions",
1011 <>
1012 <h1>Passkeys and sessions</h1>
1013 <p class="muted">You sign in to Diffinery with passkeys instead of a password. A passkey lives on your device or in your password manager and is unlocked with your fingerprint, face or screen lock.</p>
1014 <div class="box">
1015 <div class="head">
1016 <h2>Passkeys</h2>
1017 <span class="badge">{keys.length}</span>
1018 </div>
1019 {keys.length ? (
1020 <ul class="list">
1021 {keys.map((k) => (
1022 <li>
1023 <span class="st faint">{raw(ICONS.key)}</span>
1024 <div class="grow">
1025 <b>{k.name}</b> {k.backed_up ? <span class="badge blue" title="Backed up by your password manager or platform, so it syncs to your other devices">synced</span> : <span class="badge" title="Stored only on one device or security key">this device only</span>}
1026 <div class="meta">
1027 Added <Time at={k.created_at} /> · {k.last_used_at ? <>last used <Time at={k.last_used_at} /></> : "never used to sign in"}
1028 </div>
1029 </div>
1030 {keys.length > 1 ? (
1031 <Form action={`/settings/security/passkeys/${encodeURIComponent(k.id)}/delete`} t={t} class="inline" confirm={`Remove the passkey "${k.name}"? Sessions it signed in are signed out.`}>
1032 <button class="btn sm danger">Remove</button>
1033 </Form>
1034 ) : (
1035 <span class="small faint" title="Add another passkey before removing this one">Only passkey</span>
1036 )}
1037 </li>
1038 ))}
1039 </ul>
1040 ) : (
1041 <div class="empty">No passkeys yet. Add one so you can sign in.</div>
1042 )}
1043 <div class="body" style="border-top:1px solid var(--border)">
1044 <form data-passkey="register" data-next="/settings/security">
1045 <div class="formrow">
1046 <div class="field grow">
1047 <label for="pklabel">Add a passkey</label>
1048 <input id="pklabel" name="label" type="text" maxlength={100} placeholder={deviceLabel(c.req.header("user-agent"))} />
1049 </div>
1050 <button class="btn primary">{raw(ICONS.key)} Add a passkey</button>
1051 </div>
1052 <div class="hint">Add one on each device you use, or keep it in a password manager that syncs.</div>
1053 </form>
1054 <div class="mt">
1055 <div class="flash error" data-passkey-msg role="alert" hidden></div>
1056 </div>
1057 </div>
1058 </div>
1059 <div class="box">
1060 <div class="head">
1061 <h2>Signed-in browsers</h2>
1062 <span class="badge">{sessions.length}</span>
1063 </div>
1064 {sessions.length ? (
1065 <ul class="list">
1066 {sessions.map((s) => (
1067 <li>
1068 <div class="grow">
1069 <b>{deviceLabel(s.user_agent ?? undefined)}</b> {s.id === current ? <span class="badge green">this browser</span> : null}
1070 <div class="meta">
1071 Signed in <Time at={s.created_at} /> with {s.method === "access" ? "email recovery" : s.method === "link" ? "a sign-in link" : "a passkey"} · active <Time at={s.last_seen_at} />
1072 </div>
1073 </div>
1074 {s.id !== current ? (
1075 <Form action={`/settings/security/sessions/${encodeURIComponent(s.id)}/revoke`} t={t} class="inline" confirm={`Sign out ${deviceLabel(s.user_agent ?? undefined)}?`}>
1076 <button class="btn sm">Sign out</button>
1077 </Form>
1078 ) : null}
1079 </li>
1080 ))}
1081 </ul>
1082 ) : (
1083 <div class="empty">No browser sessions.</div>
1084 )}
1085 <div class="body small muted" style="border-top:1px solid var(--border)">
1086 A browser stays signed in for 30 days after you last use it, and at most 90 days after you sign in. Adding passkeys, creating tokens and agents, and deleting or transferring repositories ask you to sign in again when your sign-in is more than 2 hours old. Recovering your account by email or with a sign-in link signs out every other browser; access tokens keep working.
1087 </div>
1088 {sessions.some((s) => s.id !== current) ? (
1089 <div class="body" style="border-top:1px solid var(--border)">
1090 <Form action="/settings/security/sessions/others" t={t} class="inline" confirm="Sign out every other browser?">
1091 <button class="btn">Sign out everywhere else</button>
1092 </Form>
1093 </div>
1094 ) : null}
1095 </div>
1096 <p class="muted small">
1097 Lost every passkey? {recovery ? <>Use <a href="/auth/access">email recovery</a>, then add a new passkey here.</> : "Ask a site administrator for a one-time sign-in link."} Git, the CLI and agents use <a href="/settings/tokens">access tokens</a> instead of passkeys.
1098 </p>
1099 </>,
1100 );
1101 });
1102
1103 post(web, "/settings/security/passkeys/:id/delete", async (c) => {
1104 const me = browserAccount(c);
1105 const auth = new Auth(c.env);
1106 const id = prm(c, "id");
1107 return act(
1108 c,
1109 "/settings/security",
1110 async () => {
1111 const keys = await auth.passkeys(me.id);
1112 const key = keys.find((k) => k.id === id);
1113 if (!key) throw new HttpError(404, "passkey not found");
1114 if (keys.length < 2) throw new HttpError(422, "Add another passkey before removing your last one.");
1115 requireRecentSignIn(c, "/settings/security");
1116 const p = c.get("principal");
1117 await auth.deletePasskey(me.id, id, p.type === "account" ? (p.sessionId ?? null) : null);
1118 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: me.id, actorLogin: me.login, action: "passkey.remove", detail: { name: key.name } }));
1119 },
1120 "Passkey removed.",
1121 );
1122 });
1123
1124 post(web, "/settings/security/sessions/:id/revoke", async (c) => {
1125 const me = browserAccount(c);
1126 const id = prm(c, "id");
1127 return act(
1128 c,
1129 "/settings/security",
1130 async () => {
1131 if (!(await new Auth(c.env).endSessionById(me.id, id))) throw new HttpError(404, "That browser is already signed out.");
1132 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: me.id, actorLogin: me.login, action: "session.revoke" }));
1133 },
1134 "Signed out of that browser.",
1135 );
1136 });
1137
1138 post(web, "/settings/security/sessions/others", async (c) => {
1139 const me = browserAccount(c);
1140 const p = c.get("principal");
1141 return act(c, "/settings/security", async () => void (await new Auth(c.env).endOtherSessions(me.id, p.type === "account" ? (p.sessionId ?? null) : null)), "Signed out of every other browser.");
1142 });
1143
1144 // Tokens
1145 const tokensPage = async (c: AppContext, me: Account, created?: { token: string }) => {
1146 const dir = c.get("dir");
1147 const t = csrfToken(c);
1148 const [tokens, repos, grants] = await Promise.all([dir.tokens(me.id), dir.reposVisibleTo(me), new OAuth(c.env, dir).grantsFor(me.id)]);
1149 const repoName = new Map(repos.map((r) => [r.id, `${r.owner_login}/${r.name}`]));
1150 return page(
1151 c,
1152 me,
1153 "tokens",
1154 "Access tokens",
1155 <>
1156 <h1>Personal access tokens</h1>
1157 <p class="muted">Tokens authenticate Git over HTTPS, the REST API, the CLI and MCP clients. Use your username (or anything) as the Git username and the token as the password.</p>
1158 <p class="muted">
1159 For the CLI you don't need one: run <code>diffinery login</code> and approve the sign-in in your browser. Each CLI sign-in gets its own token, listed here. Nor for MCP apps such as claude.ai, Claude Code and Codex: they <a href="#connected-apps">connect through your browser</a> and appear under Connected apps.
1160 </p>
1161 {created ? <TokenOnce c={c} token={created.token} title="Your new token" /> : null}
1162 <div class="box">
1163 <div class="head">
1164 <h2>Active tokens</h2>
1165 </div>
1166 {tokens.length ? (
1167 <table class="tbl">
1168 <thead>
1169 <tr>
1170 <th>Name</th>
1171 <th>Scopes</th>
1172 <th>Repositories</th>
1173 <th>Expires</th>
1174 <th>Last used</th>
1175 <th />
1176 </tr>
1177 </thead>
1178 <tbody>
1179 {tokens.map((k) => (
1180 <tr>
1181 <td>
1182 <b>{k.name}</b> {k.client === "cli" ? <span class="badge" title="Created by signing in with diffinery login">CLI sign-in</span> : null}
1183 <div class="faint mono small">{k.prefix}…</div>
1184 </td>
1185 <td>{k.scopes.join(", ")}</td>
1186 <td class="small">{k.repoIds ? k.repoIds.map((id) => repoName.get(id) ?? id.slice(0, 8)).join(", ") : <span class="muted">all</span>}</td>
1187 <td class="small">{new Date(k.expiresAt).toLocaleDateString("en-US", { dateStyle: "medium" })}</td>
1188 <td class="small">{k.lastUsedAt ? ago(k.lastUsedAt) : <span class="muted">never</span>}</td>
1189 <td class="right">
1190 <Form action={`/settings/tokens/${k.id}/revoke`} t={t} class="inline" confirm={`Revoke token "${k.name}"? Anything using it stops working.`}>
1191 <button class="btn sm danger">Revoke</button>
1192 </Form>
1193 </td>
1194 </tr>
1195 ))}
1196 </tbody>
1197 </table>
1198 ) : (
1199 <div class="empty">No tokens yet.</div>
1200 )}
1201 </div>
1202 <ConnectedApps t={t} grants={grants} mcpUrl={`${publicUrl(c)}/mcp`} />
1203 <Form action="/settings/tokens" t={t} class="box">
1204 <div class="head">
1205 <h2>Create a token</h2>
1206 </div>
1207 <div class="body">
1208 <div class="row" style="align-items:flex-start">
1209 <div class="field grow">
1210 <label for="tname">Name</label>
1211 <input id="tname" name="name" type="text" required placeholder="laptop, ci, claude-code…" maxlength={80} />
1212 </div>
1213 <div class="field" style="width:140px">
1214 <label for="days">Expires in (days)</label>
1215 <input id="days" name="days" type="number" min={1} max={366} value="90" />
1216 </div>
1217 </div>
1218 <div class="field">
1219 <label>Scope</label>
1220 <KRadio name="scope" label="Scope" orientation="horizontal" value="write" items={SCOPES.map((s) => ({ value: s, label: cap(s) }))} />
1221 <div class="hint">read: clone and view · write: push, issues, pull requests, runs (up to maintain) · admin: everything you can do, including settings.</div>
1222 </div>
1223 <div class="field">
1224 <label for="repos">
1225 Restrict to repositories <span class="faint">(optional)</span>
1226 </label>
1227 <KSelect
1228 id="repos"
1229 name="repos"
1230 multiple
1231 block
1232 label="Restrict to repositories"
1233 placeholder="Every repository you can access"
1234 options={repos.map((r) => ({ value: String(r.id), label: `${r.owner_login}/${r.name}` }))}
1235 />
1236 <div class="hint">Leave empty for access to every repository you can access.</div>
1237 </div>
1238 <button class="btn primary">Create token</button>
1239 </div>
1240 </Form>
1241 </>,
1242 );
1243 };
1244
1245 web.get("/settings/tokens", async (c) => tokensPage(c, requireAccount(c)));
1246
1247 post(web, "/settings/tokens", async (c, f) => {
1248 const me = requireAccount(c);
1249 requireRecentSignIn(c, "/settings/tokens");
1250 const dir = c.get("dir");
1251 const scope = SCOPES.find((s) => s === f.s("scope")) ?? "write";
1252 const visible = new Set((await dir.reposVisibleTo(me)).map((r) => r.id));
1253 const repoIds = f.all("repos").filter((id) => visible.has(id));
1254 const name = f.s("name").trim() || "token";
1255 const created = await dir.createToken(me, { name, scopes: [scope], repoIds: repoIds.length ? repoIds : null, expiresInDays: parseInt(f.s("days"), 10) || 90 });
1256 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "token.create", target: me.login, detail: { name, scope, repos: repoIds.length } }));
1257 return tokensPage(c, me, created);
1258 });
1259
1260 post(web, "/settings/tokens/:id/revoke", async (c) => {
1261 const me = requireAccount(c);
1262 return act(
1263 c,
1264 "/settings/tokens",
1265 async () => {
1266 await c.get("dir").revokeToken(me.id, prm(c, "id"));
1267 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: me.id, actorLogin: me.login, action: "token.revoke", target: prm(c, "id") }));
1268 },
1269 "Token revoked.",
1270 );
1271 });
1272
1273 // Agents
1274 const agentsPage = async (c: AppContext, me: Account, created?: { token: string; agent: string }) => {
1275 const dir = c.get("dir");
1276 const t = csrfToken(c);
1277 const orgs = await adminOrgs(c, me);
1278 const agents = await dir.agentsOwnedBy([me.id, ...orgs.map((o) => o.id)]);
1279 const ownerName = new Map<string, string>([[me.id, me.login], ...orgs.map((o) => [o.id, o.login] as [string, string])]);
1280 const tokenLists = await Promise.all(agents.map((a) => dir.tokens(a.id)));
1281 return page(
1282 c,
1283 me,
1284 "agents",
1285 "Agents",
1286 <>
1287 <h1>Agents</h1>
1288 <p class="muted">
1289 Agents are accounts for AI tools and automation. They act on behalf of their owner, are capped by a policy, cannot push to protected or default branches, and their pull requests need a human approval. Give each agent its own token.
1290 </p>
1291 {created ? <TokenOnce c={c} token={created.token} title={`Token for ${created.agent}`} /> : null}
1292 <div class="box">
1293 <div class="head">
1294 <h2>Your agents</h2>
1295 </div>
1296 {agents.length ? (
1297 <ul class="list">
1298 {agents.map((a, i) => {
1299 const policy = parsePolicy(a);
1300 const toks = tokenLists[i] ?? [];
1301 return (
1302 <li style="display:block">
1303 <div class="row">
1304 <Actor login={a.login} kind="agent" version={a.avatar_version} />
1305 <span class="muted small">
1306 owned by <b>{ownerName.get(a.owner_id ?? "") ?? "?"}</b> · max role <b>{policy.maxRole ?? "write"}</b> · {a.status}
1307 </span>
1308 <span class="grow" />
1309 <Form action={`/settings/agents/${a.id}/status`} t={t} class="inline">
1310 <input type="hidden" name="status" value={a.status === "active" ? "disabled" : "active"} />
1311 <button class={`btn sm ${a.status === "active" ? "danger" : ""}`}>{a.status === "active" ? "Disable" : "Enable"}</button>
1312 </Form>
1313 </div>
1314 {toks.length ? (
1315 <div class="small muted mt" style="margin-top:6px">
1316 Tokens:{" "}
1317 {toks.map((k) => (
1318 <span class="row" style="display:inline-flex;gap:4px;margin-right:10px">
1319 <span class="mono">{k.name}</span> ({k.scopes.join(",")}, last used {k.lastUsedAt ? ago(k.lastUsedAt) : "never"})
1320 <Form action={`/settings/agents/${a.id}/tokens/${k.id}/revoke`} t={t} class="inline" confirm="Revoke this agent token?">
1321 <button class="btn sm link bad">revoke</button>
1322 </Form>
1323 </span>
1324 ))}
1325 </div>
1326 ) : null}
1327 <Form action={`/settings/agents/${a.id}/auto-merge`} t={t} class="row" style="margin-top:6px">
1328 <KCheckbox
1329 name="auto_merge"
1330 checked={!!parseAutoMergeDefault(a.auto_merge)}
1331 label="Merge its pull requests on green"
1332 description="Turns on auto-merge for each pull request it opens. Where a repository allows agents' auto-merge, they merge once required checks pass (and a person approved, unless the repository waives it); a workflow change still needs a person."
1333 />
1334 <button class="btn sm">Save</button>
1335 </Form>
1336 <details style="margin-top:6px">
1337 <summary class="small" style="cursor:pointer;color:var(--accent)">
1338 Create a token for {a.login}
1339 </summary>
1340 <Form action={`/settings/agents/${a.id}/token`} t={t} class="row mt" style="align-items:flex-end">
1341 <div class="field grow m0">
1342 <label>Name</label>
1343 <input name="name" type="text" required value="default" />
1344 </div>
1345 <div class="field m0">
1346 <label>Scope</label>
1347 <KSelect name="scope" label="Scope" value="write" options={SCOPES.map((s) => ({ value: s, label: cap(s) }))} />
1348 </div>
1349 <div class="field m0" style="width:110px">
1350 <label>Days</label>
1351 <input name="days" type="number" min={1} max={366} value="30" />
1352 </div>
1353 <button class="btn primary">Create token</button>
1354 </Form>
1355 </details>
1356 </li>
1357 );
1358 })}
1359 </ul>
1360 ) : (
1361 <div class="empty">No agents yet.</div>
1362 )}
1363 </div>
1364 <Form action="/settings/agents" t={t} class="box">
1365 <div class="head">
1366 <h2>Create an agent</h2>
1367 </div>
1368 <div class="body">
1369 <div class="row" style="align-items:flex-start">
1370 <div class="field grow">
1371 <label for="alogin">Agent username</label>
1372 <input id="alogin" name="login" type="text" required pattern={LOGIN_PATTERN} placeholder="review-bot" />
1373 </div>
1374 <div class="field grow">
1375 <label for="aname">Display name</label>
1376 <input id="aname" name="name" type="text" placeholder="Review bot" />
1377 </div>
1378 </div>
1379 <div class="row" style="align-items:flex-start">
1380 <div class="field grow">
1381 <label for="aowner">Owner</label>
1382 <KSelect
1383 id="aowner"
1384 name="owner"
1385 block
1386 label="Owner"
1387 value="me"
1388 options={[{ value: "me", label: `${me.login} (you)` }, ...orgs.map((o) => ({ value: String(o.id), label: `${o.login} (organization)` }))]}
1389 />
1390 <div class="hint">An agent can never do more than its owner.</div>
1391 </div>
1392 <div class="field grow">
1393 <label for="arole">Maximum role</label>
1394 <KSelect id="arole" name="maxRole" block label="Maximum role" value="write" options={ROLES.map((r) => ({ value: r, label: cap(r) }))} />
1395 </div>
1396 </div>
1397 <div class="fchecks mb">
1398 <KCheckbox
1399 name="auto_merge"
1400 label="Merge its pull requests on green"
1401 description="Turns on auto-merge for each pull request it opens, so it lands once required checks pass wherever a repository allows agents' auto-merge (Settings → Merge on green). You can change it later."
1402 />
1403 </div>
1404 <button class="btn primary">Create agent</button>
1405 </div>
1406 </Form>
1407 </>,
1408 );
1409 };
1410
1411 web.get("/settings/agents", async (c) => agentsPage(c, requireAccount(c)));
1412
1413 post(web, "/settings/agents", async (c, f) => {
1414 const me = requireAccount(c);
1415 requireRecentSignIn(c, "/settings/agents");
1416 const dir = c.get("dir");
1417 return act(
1418 c,
1419 "/settings/agents",
1420 async () => {
1421 const maxRole = ROLES.find((r) => r === f.s("maxRole")) ?? "write";
1422 const a = await dir.createAgent(me, { login: f.s("login").trim(), name: f.s("name").trim() || undefined, orgId: f.s("owner") && f.s("owner") !== "me" ? f.s("owner") : undefined, policy: { maxRole } });
1423 if (f.b("auto_merge")) await dir.setAutoMerge(a.id, "default");
1424 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "agent.create", target: a.login, detail: { maxRole, auto_merge: f.b("auto_merge") } }));
1425 },
1426 "Agent created. Create a token for it below.",
1427 );
1428 });
1429
1430 const loadAgent = async (c: AppContext, me: Account): Promise<Account> => {
1431 const agent = await c.get("dir").account(prm(c, "id"));
1432 if (!agent || !(await canManageAgent(c, me, agent))) throw new HttpError(404, "agent not found");
1433 return agent;
1434 };
1435
1436 post(web, "/settings/agents/:id/token", async (c, f) => {
1437 const me = requireAccount(c);
1438 requireRecentSignIn(c, "/settings/agents");
1439 const agent = await loadAgent(c, me);
1440 const dir = c.get("dir");
1441 const scope = SCOPES.find((s) => s === f.s("scope")) ?? "write";
1442 const created = await dir.createToken(agent, { name: f.s("name").trim() || "agent", scopes: [scope], expiresInDays: parseInt(f.s("days"), 10) || 30 });
1443 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "agent.token.create", target: agent.login, detail: { scope } }));
1444 return agentsPage(c, me, { token: created.token, agent: agent.login });
1445 });
1446
1447 post(web, "/settings/agents/:id/auto-merge", async (c, f) => {
1448 const me = requireAccount(c);
1449 const agent = await loadAgent(c, me);
1450 const on = f.b("auto_merge");
1451 return act(
1452 c,
1453 "/settings/agents",
1454 async () => {
1455 await c.get("dir").setAutoMerge(agent.id, on ? "default" : null);
1456 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: me.id, actorLogin: me.login, action: "agent.auto_merge", target: agent.login, detail: { merge_method: on ? "default" : null } }));
1457 },
1458 on ? `Auto-merge now turns on by itself for ${agent.login}'s pull requests.` : `Auto-merge no longer turns on by itself for ${agent.login}'s pull requests.`,
1459 );
1460 });
1461
1462 post(web, "/settings/agents/:id/tokens/:tid/revoke", async (c) => {
1463 const me = requireAccount(c);
1464 const agent = await loadAgent(c, me);
1465 return act(c, "/settings/agents", async () => c.get("dir").revokeToken(agent.id, prm(c, "tid")), "Token revoked.");
1466 });
1467
1468 post(web, "/settings/agents/:id/status", async (c, f) => {
1469 const me = requireAccount(c);
1470 const agent = await loadAgent(c, me);
1471 const status = f.s("status") === "active" ? "active" : "disabled";
1472 return act(c, "/settings/agents", async () => {
1473 await c.get("dir").setStatus(agent.id, status);
1474 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: me.id, actorLogin: me.login, action: `agent.${status === "active" ? "enable" : "disable"}`, target: agent.login }));
1475 });
1476 });
1477
1478 // Organizations
1479 // Invitations to organizations and repositories: someone added by username joins once they accept.
1480 // Blocked users (lib/moderation.ts): the people you blocked, and a form to block someone.
1481 web.get("/settings/blocked-users", async (c) => {
1482 const me = requireAccount(c);
1483 const t = csrfToken(c);
1484 return page(
1485 c,
1486 me,
1487 "blocked",
1488 "Blocked users",
1489 <>
1490 <h1>Blocked users</h1>
1491 <BlockList
1492 blocks={await blockList(c.env, me.id)}
1493 add="/settings/blocked-users"
1494 unblock={(login) => `/settings/blocked-users/${encodeURIComponent(login)}/unblock`}
1495 t={t}
1496 title="People you blocked"
1497 hint="They can still see your public repositories, but can't open issues or pull requests, comment or react in them, aren't collaborators on them, and can't invite you. You get no notifications from them. They aren't told."
1498 empty="You haven't blocked anyone."
1499 />
1500 </>,
1501 );
1502 });
1503
1504 web.get("/settings/invitations", async (c) => {
1505 const p = c.get("principal");
1506 // Someone still waiting for an invite sees theirs on the home page.
1507 if (p.type === "account" && p.account.status === "pending") return c.redirect("/", 303);
1508 const me = requireAccount(c);
1509 const invites = await c.get("dir").invitesFor(me);
1510 return page(
1511 c,
1512 me,
1513 "invitations",
1514 "Invitations",
1515 <>
1516 <h1>Invitations</h1>
1517 <p class="muted">Invitations to join an organization or collaborate on a repository. You get access once you accept; declining tells nobody, and the invitation goes away.</p>
1518 <MyInvitations invites={invites} t={csrfToken(c)} />
1519 </>,
1520 );
1521 });
1522
1523 for (const accept of [true, false]) {
1524 post(web, `/settings/invitations/:id/${accept ? "accept" : "decline"}`, async (c) => {
1525 const p = c.get("principal");
1526 if (p.type !== "account") throw new HttpError(401, "sign in required");
1527 // Someone waiting for an invite may accept one; that lets them in.
1528 if (p.account.status === "disabled") throw new HttpError(403, "your account is disabled");
1529 const dir = c.get("dir");
1530 const back = p.account.status === "pending" ? "/" : "/settings/invitations";
1531 return act(c, back, async () => {
1532 const res = await dir.answerInvite(prm(c, "id"), p.account, accept);
1533 c.executionCtx.waitUntil(dir.audit({ actorId: p.account.id, actorLogin: p.account.login, action: accept ? "invite.accept" : "invite.decline", detail: { id: prm(c, "id") } }));
1534 if (!accept) {
1535 flash(c, "notice", "Invitation declined.");
1536 return;
1537 }
1538 if (res.repoId) {
1539 const r = await dir.repoById(res.repoId);
1540 if (r) return repoUrl(r);
1541 } else if (res.orgId) {
1542 const o = await dir.account(res.orgId);
1543 if (o) return `/${o.login}`;
1544 }
1545 });
1546 });
1547 }
1548
1549 web.get("/settings/orgs", async (c) => {
1550 const me = requireAccount(c);
1551 const t = csrfToken(c);
1552 const orgs = await c.get("dir").orgsFor(me.id);
1553 return page(
1554 c,
1555 me,
1556 "orgs",
1557 "Organizations",
1558 <>
1559 <h1>Organizations</h1>
1560 <p class="muted">Organizations group people, agents and repositories. Members get the organization's base permission (read for new organizations) on its repositories; owners and admins manage everything.</p>
1561 <div class="box">
1562 {orgs.length ? (
1563 <ul class="list">
1564 {orgs.map((o) => (
1565 <li>
1566 <Avatar login={o.login} version={o.avatar_version} />
1567 <div class="grow">
1568 <a class="title" href={`/${o.login}`}>
1569 {o.login}
1570 </a>
1571 {o.name && o.name !== o.login ? <span class="muted"> · {o.name}</span> : null}
1572 </div>
1573 <span class="badge">{o.role}</span>
1574 </li>
1575 ))}
1576 </ul>
1577 ) : (
1578 <div class="empty">You are not a member of any organization.</div>
1579 )}
1580 </div>
1581 <Form action="/settings/orgs" t={t} class="box">
1582 <div class="head">
1583 <h2>New organization</h2>
1584 </div>
1585 <div class="body">
1586 <div class="row" style="align-items:flex-start">
1587 <div class="field grow">
1588 <label for="olog">Organization name</label>
1589 <input id="olog" name="login" type="text" required pattern={LOGIN_PATTERN} placeholder="my-team" />
1590 </div>
1591 <div class="field grow">
1592 <label for="oname">Display name</label>
1593 <input id="oname" name="name" type="text" />
1594 </div>
1595 </div>
1596 <button class="btn primary">Create organization</button>
1597 </div>
1598 </Form>
1599 </>,
1600 );
1601 });
1602
1603 post(web, "/settings/orgs", async (c, f) => {
1604 const me = requireAccount(c);
1605 const dir = c.get("dir");
1606 return act(c, "/settings/orgs", async () => {
1607 const org = await dir.createOrg(f.s("login").trim(), f.s("name").trim(), me);
1608 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "org.create", target: org.login }));
1609 return `/${org.login}?tab=people`;
1610 });
1611 });
1612
1613 // Site administration
1614 const requireSiteAdmin = (c: AppContext): Account => {
1615 const me = requireAccount(c);
1616 if (!me.site_admin) throw new HttpError(403, "site administrators only");
1617 return me;
1618 };
1619
1620 const adminPage = async (c: AppContext, me: Account, invite?: { url: string; title: string; note: string }) => {
1621 const dir = c.get("dir");
1622 const t = csrfToken(c);
1623 const [users, requests, invites] = await Promise.all([dir.users(), dir.accessRequests(), dir.invites({ site: true, pending: true })]);
1624 return page(
1625 c,
1626 me,
1627 "admin",
1628 "Site administration",
1629 <>
1630 <h1>Site administration</h1>
1631 {invite ? (
1632 <div class="box" style="border-color:var(--amber)">
1633 <div class="body">
1634 <h3>{invite.title}</h3>
1635 <p class="muted">{invite.note}</p>
1636 <div class="row">
1637 <div class="secret grow">{invite.url}</div>
1638 <CopyButton text={invite.url} size="base" />
1639 </div>
1640 </div>
1641 </div>
1642 ) : null}
1643 <EarlyAccessCallout db={c.env.DB} />
1644 <div class="box">
1645 <div class="head">
1646 <h2>Pending access requests</h2>
1647 <span class="badge">{requests.length}</span>
1648 </div>
1649 {requests.length ? (
1650 <ul class="list">
1651 {requests.map((r) => (
1652 <li>
1653 <Avatar login={r.account.login} version={r.account.avatar_version} />
1654 <div class="grow">
1655 <b>{r.account.email ?? r.account.login}</b> <span class="muted small">requested <Time at={r.createdAt} /></span>
1656 {r.note ? <div class="meta" style="white-space:pre-wrap">{r.note}</div> : null}
1657 </div>
1658 <Form action={`/settings/admin/users/${r.account.id}/status`} t={t} class="inline">
1659 <input type="hidden" name="status" value="active" />
1660 <button class="btn sm green">Approve</button>
1661 </Form>
1662 <Form action={`/settings/admin/users/${r.account.id}/status`} t={t} class="inline">
1663 <input type="hidden" name="status" value="disabled" />
1664 <button class="btn sm danger">Deny</button>
1665 </Form>
1666 </li>
1667 ))}
1668 </ul>
1669 ) : (
1670 <div class="empty">No pending requests.</div>
1671 )}
1672 </div>
1673 <Form action="/settings/admin/invite" t={t} class="box">
1674 <div class="head">
1675 <h2>Invite someone to this instance</h2>
1676 </div>
1677 <div class="body">
1678 <div class="formrow">
1679 <div class="field grow">
1680 <label for="iemail">Email address</label>
1681 <input id="iemail" name="email" type="email" required placeholder="[email protected]" />
1682 </div>
1683 <button class="btn primary">{raw(ICONS.envelope)} Send invitation</button>
1684 </div>
1685 <div class="hint">We email them a link. Opening it lets them pick a username and create a passkey.</div>
1686 </div>
1687 </Form>
1688 <PendingInvites invites={invites} revoke={(id) => `/settings/admin/invites/${id}/revoke`} t={t} roles={false} />
1689 <div class="box">
1690 <div class="head">
1691 <h2>Users</h2>
1692 <span class="badge">{users.length}</span>
1693 </div>
1694 <table class="tbl">
1695 <thead>
1696 <tr>
1697 <th>User</th>
1698 <th>Email</th>
1699 <th>Joined</th>
1700 <th>Status</th>
1701 <th>Site admin</th>
1702 <th />
1703 </tr>
1704 </thead>
1705 <tbody>
1706 {users.map((u) => (
1707 <tr>
1708 <td>
1709 <Actor login={u.login} kind="user" version={u.avatar_version} /> {u.site_admin ? <span class="badge blue">admin</span> : null}
1710 </td>
1711 <td class="small">{u.email ?? "—"}</td>
1712 <td class="small">{ago(u.created_at)}</td>
1713 <td>
1714 {u.suspended_at ? (
1715 <span class="badge red" title={`Suspended by ${u.suspended_by ?? "a site administrator"}: ${u.suspended_reason ?? ""}`}>
1716 suspended
1717 </span>
1718 ) : u.id === me.id ? (
1719 <span class="badge green">{u.status}</span>
1720 ) : (
1721 <Form action={`/settings/admin/users/${u.id}/status`} t={t} class="row" style="gap:6px;flex-wrap:nowrap">
1722 <KSelect name="status" size="sm" label={`Status of ${u.login}`} value={u.status} options={(["active", "pending", "disabled"] as const).map((s) => ({ value: s, label: cap(s) }))} />
1723 <button class="btn sm">Save</button>
1724 </Form>
1725 )}
1726 </td>
1727 <td>
1728 {u.site_admin ? (
1729 <Form action={`/settings/admin/users/${u.id}/site-admin`} t={t} class="inline" confirm={u.id === me.id ? "Stop being a site administrator? You lose access to these pages." : `Remove ${u.login} from the site administrators?`}>
1730 <input type="hidden" name="grant" value="0" />
1731 <button class="btn sm">Remove admin</button>
1732 </Form>
1733 ) : u.status === "active" ? (
1734 <Form action={`/settings/admin/users/${u.id}/site-admin`} t={t} class="inline" confirm={`Make ${u.login} a site administrator? They get admin on every repository and organization, and these pages.`}>
1735 <input type="hidden" name="grant" value="1" />
1736 <button class="btn sm">Make admin</button>
1737 </Form>
1738 ) : (
1739 <span class="faint small">—</span>
1740 )}
1741 </td>
1742 <td class="right nowrap">
1743 {u.id === me.id ? null : <SuspendControl u={u} t={t} />}{" "}
1744 <Form action={`/settings/admin/users/${u.id}/signin-link`} t={t} class="inline" confirm={`Create a one-time link that adds a passkey to ${u.login}? Only send it to them.`}>
1745 <button class="btn sm" title="For a lost passkey or a first sign-in">Sign-in link</button>
1746 </Form>{" "}
1747 <a class="btn sm danger" href={`/settings/admin/users/${u.id}/delete`}>
1748 Delete
1749 </a>
1750 </td>
1751 </tr>
1752 ))}
1753 </tbody>
1754 </table>
1755 </div>
1756 </>,
1757 );
1758 };
1759
1760 web.get("/settings/admin", async (c) => adminPage(c, requireSiteAdmin(c)));
1761
1762 post(web, "/settings/admin/users/:id/status", async (c, f) => {
1763 const me = requireSiteAdmin(c);
1764 const dir = c.get("dir");
1765 const status = (["active", "pending", "disabled"] as const).find((s) => s === f.s("status"));
1766 return act(
1767 c,
1768 "/settings/admin",
1769 async () => {
1770 if (!status) throw new HttpError(422, "invalid status");
1771 const target = await dir.account(prm(c, "id"));
1772 if (!target || target.kind !== "user") throw new HttpError(404, "user not found");
1773 if (target.id === me.id) throw new HttpError(422, "you cannot change your own status");
1774 await dir.setStatus(target.id, status);
1775 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: `user.${status}`, target: target.login }));
1776 },
1777 "User updated.",
1778 );
1779 });
1780
1781 post(web, "/settings/admin/users/:id/signin-link", async (c) => {
1782 const me = requireSiteAdmin(c);
1783 const dir = c.get("dir");
1784 const target = await dir.account(prm(c, "id"));
1785 if (!target || target.kind !== "user") throw new HttpError(404, "user not found");
1786 requireRecentSignIn(c, "/settings/admin");
1787 if (target.status === "disabled") throw new HttpError(422, "enable this account first");
1788 const link = await new Auth(c.env).createSigninLink(me, target);
1789 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "signin_link.create", target: target.login }));
1790 return adminPage(c, me, { url: link.url, title: `Sign-in link for ${target.login}`, note: `We emailed it to ${target.email ?? "them"}; you can also send it yourself. Send it only to them: it works once within 24 hours and adds a passkey to their account.` });
1791 });
1792
1793 // Suspension (lib/moderation.ts): with a reason, from the Users table or a report.
1794 const suspendTarget = async (c: AppContext) => {
1795 const user = await c.get("dir").accountByLogin(prm(c, "login"));
1796 if (!user || user.kind !== "user") throw new HttpError(404, "user not found");
1797 return user;
1798 };
1799 const backFrom = (f: { s(name: string): string }) => (/^\/settings\/admin(\/|$)/.test(f.s("back")) ? f.s("back") : "/settings/admin");
1800 post(web, "/settings/admin/users/:login/suspend", async (c, f) => {
1801 const me = requireSiteAdmin(c);
1802 return act(c, backFrom(f), async () => {
1803 const user = await suspendTarget(c);
1804 const stopped = await suspend(c.env, (e) => c.get("dir").audit(e), me, user, suspendReason(f.s("reason")), "web");
1805 flash(c, "notice", `Suspended ${user.login}.${stoppedNote(stopped)}`);
1806 });
1807 });
1808 post(web, "/settings/admin/users/:login/unsuspend", async (c, f) => {
1809 const me = requireSiteAdmin(c);
1810 return act(c, backFrom(f), async () => {
1811 const user = await suspendTarget(c);
1812 if (!(await unsuspend(c.env, (e) => c.get("dir").audit(e), me, user, "web"))) throw new HttpError(422, `${user.login} isn't suspended`);
1813 flash(c, "notice", `${user.login} is no longer suspended.`);
1814 });
1815 });
1816
1817 // Reports (lib/moderation.ts): the queue, one report, resolving and reopening.
1818 web.get("/settings/admin/reports", async (c) => {
1819 const me = requireSiteAdmin(c);
1820 const state = c.req.query("state") === "resolved" ? "resolved" : "open";
1821 const [list, open, resolved] = await Promise.all([reports(c.env, state, 100), openReportCount(c.env), reports(c.env, "resolved", 1)]);
1822 return page(c, me, "reports", "Reports", <ReportsList items={list.items} state={state} counts={{ open, resolved: resolved.total }} />);
1823 });
1824 web.get("/settings/admin/reports/:id", async (c) => {
1825 const me = requireSiteAdmin(c);
1826 const r = await report(c.env, prm(c, "id"));
1827 if (!r) throw new HttpError(404, "no report with that id");
1828 const account = r.account_id ? await c.get("dir").account(r.account_id) : null;
1829 return page(c, me, "reports", "Report", <ReportDetail r={r} t={csrfToken(c)} suspended={account?.kind === "user" && !account.site_admin && account.id !== me.id ? !!account.suspended_at : null} />);
1830 });
1831 for (const [path, state] of [["resolve", "resolved"], ["reopen", "open"]] as const) {
1832 post(web, `/settings/admin/reports/:id/${path}`, async (c, f) => {
1833 const me = requireSiteAdmin(c);
1834 const back = `/settings/admin/reports/${encodeURIComponent(prm(c, "id"))}`;
1835 return act(c, back, async () => {
1836 const note = state === "resolved" ? cleanResolution(f.s("resolution")) : null;
1837 const r = await setReportState(c.env, prm(c, "id"), me, state, note);
1838 if (!r) throw new HttpError(404, "no report with that id");
1839 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: me.id, actorLogin: me.login, action: state === "resolved" ? "report.resolve" : "report.reopen", target: r.target, detail: { id: r.id, ...(note ? { resolution: note } : {}), via: "web" } }));
1840 return state === "resolved" ? "/settings/admin/reports" : back;
1841 }, state === "resolved" ? "Report resolved." : "Report reopened.");
1842 });
1843 }
1844
1845 post(web, "/settings/admin/invite", async (c, f) => {
1846 const me = requireSiteAdmin(c);
1847 const email = f.s("email").trim();
1848 if (!/^[^\s@]+@[^\s@]+$/.test(email)) throw new HttpError(422, "enter a valid email address");
1849 const inv = await c.get("dir").createInvite(me, { email, role: "read" });
1850 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: me.id, actorLogin: me.login, action: "invite.create", target: email }));
1851 return adminPage(c, me, { url: inv.url, title: `Invite created for ${email}`, note: `We emailed it to ${email}; you can also send it yourself. It expires in 14 days and works once: they pick a username and create a passkey.` });
1852 });
1853
1854 post(web, "/settings/admin/invites/:id/revoke", async (c) => {
1855 const me = requireSiteAdmin(c);
1856 const dir = c.get("dir");
1857 return act(
1858 c,
1859 "/settings/admin",
1860 async () => {
1861 if (!(await dir.revokeInvite(prm(c, "id"), {}))) throw new HttpError(404, "this invitation was already used, revoked or never existed");
1862 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "invite.revoke", detail: { id: prm(c, "id") } }));
1863 },
1864 "Invitation revoked.",
1865 );
1866 });
1867
1868 // Kill switches (lib/killswitch.ts)
1869 web.get("/settings/admin/kill-switches", async (c) => {
1870 const me = requireSiteAdmin(c);
1871 return page(c, me, "kill-switches", "Kill switches", <KillSwitchesPage env={c.env} t={csrfToken(c)} />);
1872 });
1873 const KS = "/settings/admin/kill-switches";
1874 const auditFn = (c: AppContext) => (e: Parameters<Directory["audit"]>[0]) => c.get("dir").audit(e);
1875 const stoppedNote = (s: Stopped | null) => (s ? ` Stopped ${s.runs} runs, ${s.jobs} jobs and ${s.sandboxes} sandboxes${s.failed ? `; ${s.failed} repositories didn't answer, so their work stops when it next tries to start` : ""}.` : "");
1876 post(web, `${KS}/pause`, async (c, f) => {
1877 const me = requireSiteAdmin(c);
1878 return act(c, KS, async () => {
1879 const stopped = await changePause(c.env, auditFn(c), me, cleanReason(f.s("reason")), "web");
1880 flash(c, "notice", `Hosted compute is paused.${stoppedNote(stopped)}`);
1881 });
1882 });
1883 post(web, `${KS}/resume`, async (c) => {
1884 const me = requireSiteAdmin(c);
1885 return act(c, KS, async () => changePause(c.env, auditFn(c), me, null, "web").then(() => undefined), "Hosted compute is running again. Nothing that was stopped restarts.");
1886 });
1887 const accountTarget = async (c: AppContext, login: string) => {
1888 const account = await c.get("dir").accountByLogin(login.trim());
1889 if (!account || account.kind === "agent") throw new HttpError(404, "no person or organization with that name");
1890 return { kind: "account" as const, id: account.id, login: account.login };
1891 };
1892 const repoTarget = async (c: AppContext, owner: string, name: string) => {
1893 const repo = await c.get("dir").repo(owner.trim(), name.trim());
1894 if (!repo) throw new HttpError(404, "no repository with that name; use owner/name");
1895 return { kind: "repo" as const, id: repo.id, name: `${repo.owner_login}/${repo.name}` };
1896 };
1897 post(web, `${KS}/accounts`, async (c, f) => {
1898 const me = requireSiteAdmin(c);
1899 return act(c, KS, async () => {
1900 const target = await accountTarget(c, f.s("login"));
1901 const stopped = await changeSuspension(c.env, auditFn(c), me, target, cleanReason(f.s("reason")), "web");
1902 flash(c, "notice", `Actions are suspended for every repository of ${target.login}.${stoppedNote(stopped)}`);
1903 });
1904 });
1905 post(web, `${KS}/accounts/:login/lift`, async (c) => {
1906 const me = requireSiteAdmin(c);
1907 return act(c, KS, async () => {
1908 const target = await accountTarget(c, prm(c, "login"));
1909 await changeSuspension(c.env, auditFn(c), me, target, null, "web");
1910 flash(c, "notice", `Actions are no longer suspended for ${target.login}.`);
1911 });
1912 });
1913 post(web, `${KS}/repos`, async (c, f) => {
1914 const me = requireSiteAdmin(c);
1915 return act(c, KS, async () => {
1916 const [owner, name, extra] = f.s("repo").trim().replace(/^\/+|\/+$/g, "").split("/");
1917 if (!owner || !name || extra !== undefined) throw new HttpError(422, "enter the repository as owner/name");
1918 const target = await repoTarget(c, owner, name);
1919 const stopped = await changeSuspension(c.env, auditFn(c), me, target, cleanReason(f.s("reason")), "web");
1920 flash(c, "notice", `Actions are suspended for ${target.name}.${stoppedNote(stopped)}`);
1921 });
1922 });
1923 post(web, `${KS}/repos/:owner/:repo/lift`, async (c) => {
1924 const me = requireSiteAdmin(c);
1925 return act(c, KS, async () => {
1926 const target = await repoTarget(c, prm(c, "owner"), prm(c, "repo"));
1927 await changeSuspension(c.env, auditFn(c), me, target, null, "web");
1928 flash(c, "notice", `Actions are no longer suspended for ${target.name}.`);
1929 });
1930 });
1931
1932 web.get("/settings/audit", async (c) => {
1933 const me = requireSiteAdmin(c);
1934 const rows = await c.get("dir").auditLog(200);
1935 return page(
1936 c,
1937 me,
1938 "audit",
1939 "Audit log",
1940 <>
1941 <h1>Audit log</h1>
1942 <p class="muted">The 200 most recent security-relevant events.</p>
1943 <div class="box" style="overflow:auto">
1944 <table class="tbl">
1945 <thead>
1946 <tr>
1947 <th>When</th>
1948 <th>Actor</th>
1949 <th>Action</th>
1950 <th>Target</th>
1951 <th>Detail</th>
1952 </tr>
1953 </thead>
1954 <tbody>
1955 {rows.map((r) => (
1956 <tr>
1957 <td class="small nowrap">
1958 <Time at={r.at} />
1959 </td>
1960 <td class="small">
1961 {r.actor_login ?? "system"}
1962 {r.on_behalf_of ? <span class="muted"> for {r.on_behalf_of}</span> : null}
1963 </td>
1964 <td>
1965 <span class="badge">{r.action}</span>
1966 </td>
1967 <td class="small mono">{r.target ?? ""}</td>
1968 <td class="small mono muted" style="max-width:340px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title={r.detail ?? ""}>
1969 {r.detail ?? ""}
1970 </td>
1971 </tr>
1972 ))}
1973 </tbody>
1974 </table>
1975 {rows.length === 0 ? <div class="empty">No events yet.</div> : null}
1976 </div>
1977 </>,
1978 );
1979 });
1980
1981 // Unexpected server errors (lib/server-errors.ts); ?id= finds the one a 5xx answer's request ID names.
1982 web.get("/settings/admin/search-engines", async (c) => {
1983 const me = requireSiteAdmin(c);
1984 return page(c, me, "search-engines", "Search engines", <SearchEngines s={await indexNowStatus(c.env)} />);
1985 });
1986 web.get("/settings/admin/errors", async (c) => {
1987 const me = requireSiteAdmin(c);
1988 const id = c.req.query("id")?.trim() || undefined;
1989 const rows = await serverErrors(c.env, { id, limit: 200 });
1990 return page(
1991 c,
1992 me,
1993 "errors",
1994 "Server errors",
1995 <>
1996 <h1>Server errors</h1>
1997 <p class="muted">
1998 {id ? (
1999 <>
2000 The error with request ID <span class="mono">{id}</span>.
2001 </>
2002 ) : (
2003 <>
2004 The 200 most recent answers with a 5xx status. Each such answer carries its request ID (<span class="mono">request_id</span> and the <span class="mono">x-request-id</span> header).
2005 </>
2006 )}{" "}
2007 No request bodies, query strings or headers are kept.
2008 </p>
2009 <form method="get" action="/settings/admin/errors" class="row" style="gap:8px;margin-bottom:12px">
2010 <input type="search" name="id" placeholder="Request ID" value={id ?? ""} class="mono" style="flex:1;max-width:360px" />
2011 <button class="btn" type="submit">
2012 Find
2013 </button>
2014 {id ? (
2015 <a class="btn" href="/settings/admin/errors">
2016 Show all
2017 </a>
2018 ) : null}
2019 </form>
2020 <div class="box" style="overflow:auto">
2021 <table class="tbl">
2022 <thead>
2023 <tr>
2024 <th>When</th>
2025 <th>Request</th>
2026 <th>Status</th>
2027 <th>Error</th>
2028 </tr>
2029 </thead>
2030 <tbody>
2031 {rows.map((r) => (
2032 <tr>
2033 <td class="small nowrap">
2034 <Time at={r.at} />
2035 </td>
2036 <td class="small mono">
2037 <div>
2038 {r.method} {r.route ?? r.path}
2039 </div>
2040 <div class="muted">{r.id}</div>
2041 </td>
2042 <td>
2043 <span class="badge">{r.status}</span>
2044 </td>
2045 <td class="small mono" style="max-width:520px">
2046 {r.stack ? (
2047 <details>
2048 <summary style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{r.message}</summary>
2049 <pre class="muted" style="white-space:pre-wrap">{r.stack}</pre>
2050 </details>
2051 ) : (
2052 r.message
2053 )}
2054 </td>
2055 </tr>
2056 ))}
2057 </tbody>
2058 </table>
2059 {rows.length === 0 ? <div class="empty">{id ? "No error with that request ID; only the newest 500 are kept." : "No server errors."}</div> : null}
2060 </div>
2061 </>,
2062 );
2063 });
2064}
2065
2066// ---------------------------------------------------------------- site administration: search engines
2067
2068const SearchEngines: FC<{ s: Awaited<ReturnType<typeof indexNowStatus>> }> = ({ s }) => (
2069 <>
2070 <h1>Search engines</h1>
2071 <p class="muted">
2072 Diffinery tells search engines through <a href="https://www.indexnow.org">IndexNow</a> when public pages are added, change or go away: after each deploy, the site and docs pages it changed (and their Markdown versions and llms.txt), and every hour, public repositories pushed since. Private repositories and pages behind sign-in are never sent. See{" "}
2073 <a href="/docs/admin/site-administration#search-engines">the docs</a>.
2074 </p>
2075 <div class="box">
2076 <div class="body">
2077 {s.off ? (
2078 <p>
2079 <span class="badge">off</span> {s.off}.
2080 </p>
2081 ) : (
2082 <p>
2083 <span class="badge green">on</span> Key file:{" "}
2084 <a class="mono" href={s.keyLocation!}>
2085 {s.keyLocation}
2086 </a>
2087 </p>
2088 )}
2089 <p class="small muted" style="margin:0">
2090 Tracking {s.site} site and docs pages and {s.repos} public repositories; {s.queued} waiting to be submitted.
2091 {s.retryAt && Date.parse(s.retryAt) > Date.now() ? (
2092 <>
2093 {" "}
2094 Trying again <Time at={s.retryAt} />.
2095 </>
2096 ) : null}
2097 {s.reposCheckedAt ? (
2098 <>
2099 {" "}
2100 Repositories checked <Time at={s.reposCheckedAt} />.
2101 </>
2102 ) : null}
2103 </p>
2104 </div>
2105 </div>
2106 <h2>Submissions</h2>
2107 <div class="box" style="overflow:auto">
2108 <table class="tbl">
2109 <thead>
2110 <tr>
2111 <th>When</th>
2112 <th>URLs</th>
2113 <th>IndexNow</th>
2114 <th>Pages</th>
2115 </tr>
2116 </thead>
2117 <tbody>
2118 {s.submissions.map((r) => (
2119 <tr>
2120 <td class="small nowrap">
2121 <Time at={r.at} />
2122 </td>
2123 <td>{r.urls}</td>
2124 <td class="small">
2125 <span class={`badge${r.status === 200 || r.status === 202 ? " green" : " red"}`}>{r.status ?? "unreachable"}</span> <span class="muted">{r.endpoint ? `${r.endpoint}, ` : ""}{r.ms} ms</span>
2126 {r.error ? <div class="mono muted">{r.error}</div> : null}
2127 </td>
2128 <td class="small mono" style="max-width:520px">
2129 <details>
2130 <summary style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{r.paths.slice(0, 3).join(", ")}{r.urls > 3 ? ", …" : ""}</summary>
2131 <div class="muted" style="white-space:pre-wrap">
2132 {r.paths.join("\n")}
2133 {r.urls > r.paths.length ? `\n… and ${r.urls - r.paths.length} more` : ""}
2134 </div>
2135 </details>
2136 </td>
2137 </tr>
2138 ))}
2139 </tbody>
2140 </table>
2141 {s.submissions.length === 0 ? <div class="empty">Nothing submitted yet. The first submission follows within five minutes of a deploy.</div> : null}
2142 </div>
2143 </>
2144);
2145
2146// ---------------------------------------------------------------- /:owner profiles
2147
2148type OrgTab = "repositories" | "people" | "agents" | "settings";
2149
2150/** An organization's name and tab bar, shared by its profile tabs and its packages pages. */
2151export function OrgHeader({ org, role, isOwner, tab }: { org: Account; role: "owner" | "admin" | "member" | null; isOwner: boolean; tab: OrgTab | "packages" }) {
2152 const base = `/${org.login}`;
2153 return (
2154 <>
2155 <div class="row mb" style="gap:16px">
2156 <Avatar login={org.login} size="lg" version={org.avatar_version} />
2157 <div>
2158 <h1 class="m0">{org.name || org.login}</h1>
2159 <div class="muted small">
2160 Organization · {org.login}
2161 {role ? ` · you are ${role === "owner" ? "an owner" : `a${role === "admin" ? "n" : ""} ${role}`}` : ""}
2162 </div>
2163 </div>
2164 </div>
2165 <nav class="tabs mb vt-tabs" style="border-bottom:1px solid var(--border)">
2166 {(
2167 [
2168 ["repositories", "Repositories", true],
2169 ["people", "People", true],
2170 ["agents", "Agents", true],
2171 ["settings", "Settings", isOwner],
2172 ] as const
2173 )
2174 .filter((x) => x[2])
2175 .map(([k, label]) => (
2176 <a href={`${base}?tab=${k}`} class={tab === k ? "on" : ""}>
2177 {label}
2178 </a>
2179 ))}
2180 <a href={`${base}/-/packages`} class={tab === "packages" ? "on" : ""}>
2181 Packages
2182 </a>
2183 </nav>
2184 </>
2185 );
2186}
2187
2188const ROLE_LABEL: Record<string, string> = { owner: "Owner", admin: "Admin", member: "Member" };
2189
2190/** The invitation link right after inviting someone by email (it's also in their inbox). */
2191const InviteOnce: FC<{ email: string; url: string }> = ({ email, url }) => (
2192 <div class="box" style="border-color:var(--amber)">
2193 <div class="body">
2194 <h3>Invitation sent to {email}</h3>
2195 <p class="muted">We emailed them an invitation. You can also send them this link yourself. It works once and expires in 14 days: they join when they accept it, creating an account and passkey first if they don't have one.</p>
2196 <div class="row nowrap">
2197 <div class="secret grow">{url}</div>
2198 <CopyButton text={url} size="base" />
2199 </div>
2200 </div>
2201 </div>
2202);
2203
2204function registerProfiles(web: WebApp): void {
2205 const orgContext = async (c: AppContext) => {
2206 const me = requireAccount(c);
2207 const dir = c.get("dir");
2208 const org = await dir.accountByLogin(prm(c, "owner"));
2209 if (!org || (org.kind === "org" && org.status === "disabled")) throw new HttpError(404, "not found");
2210 if (org.kind !== "org") throw new HttpError(404, "not an organization");
2211 const role = await dir.orgRole(org.id, me.id);
2212 const isAdmin = !!me.site_admin || role === "owner" || role === "admin";
2213 const isOwner = !!me.site_admin || role === "owner";
2214 return { me, org, role, isAdmin, isOwner, dir };
2215 };
2216
2217 const profile = async (c: AppContext, invite?: { url: string; email: string }) => {
2218 const me = requireAccount(c);
2219 const dir = c.get("dir");
2220 const t = csrfToken(c);
2221 const acct = await dir.accountByLogin(prm(c, "owner"));
2222 if (!acct && prm(c, "owner").toLowerCase() === GHOST.login) {
2223 return render(
2224 c,
2225 { title: GHOST.login },
2226 <div style="max-width:720px;margin:24px auto" class="box">
2227 <div class="body row" style="gap:18px">
2228 <Avatar login={GHOST.login} size="xl" />
2229 <div>
2230 <h1 class="m0">{GHOST.login}</h1>
2231 <p class="muted">This is a placeholder for people who deleted their accounts. Issues, pull requests and comments they wrote in other people's repositories are shown as written by ghost.</p>
2232 </div>
2233 </div>
2234 </div>,
2235 );
2236 }
2237 if (!acct) {
2238 // A renamed person's or organization's old login leads to the new one.
2239 const renamed = await dir.renamedAccount(prm(c, "owner"));
2240 const url = new URL(c.req.url);
2241 if (renamed) return c.redirect(`${movedLoginPath(url.pathname, prm(c, "owner"), renamed.login) ?? `/${renamed.login}`}${url.search}`, 301);
2242 throw new HttpError(404, "not found");
2243 }
2244 // A deleted organization keeps its account row for the audit log (Directory.deleteOrg); its page is gone.
2245 if (acct.kind === "org" && acct.status === "disabled") throw new HttpError(404, "not found");
2246 // So does a deleted person's (accounts/lifecycle.ts).
2247 if (acct.deleted_at) throw new HttpError(404, "not found");
2248 // A suspended person's profile is hidden from everyone but site administrators (lib/moderation.ts).
2249 if (!visibleTo(acct, me)) throw new HttpError(404, "not found");
2250 if (acct.login !== prm(c, "owner")) return c.redirect(`/${acct.login}${new URL(c.req.url).search}`, 301);
2251
2252 if (acct.kind === "agent") {
2253 const owner = acct.owner_id ? await dir.account(acct.owner_id) : null;
2254 const policy = parsePolicy(acct);
2255 return render(
2256 c,
2257 { title: acct.login },
2258 <div style="max-width:720px;margin:24px auto" class="box">
2259 <div class="body row" style="gap:18px">
2260 <Avatar login={acct.login} kind="agent" size="xl" version={acct.avatar_version} />
2261 <div>
2262 <h1 class="m0">
2263 {acct.name || acct.login} <span class="badge agent">agent</span>
2264 </h1>
2265 <p class="muted">{acct.login}</p>
2266 <dl class="kv">
2267 <dt>Acts on behalf of</dt>
2268 <dd>{owner ? <a href={`/${owner.login}`}>{owner.login}</a> : "—"}</dd>
2269 <dt>Maximum role</dt>
2270 <dd>{policy.maxRole ?? "write"}</dd>
2271 <dt>Status</dt>
2272 <dd>{acct.status}</dd>
2273 <dt>Created</dt>
2274 <dd>
2275 <Time at={acct.created_at} />
2276 </dd>
2277 </dl>
2278 </div>
2279 </div>
2280 </div>,
2281 );
2282 }
2283
2284 const repos = await dir.reposVisibleTo(me, acct.id);
2285 if (acct.kind === "user") {
2286 const orgs = await dir.orgsFor(acct.id);
2287 return render(
2288 c,
2289 { title: acct.login },
2290 <div class="grid left">
2291 <aside class="side">
2292 <section>
2293 <Avatar login={acct.login} size="xl" version={acct.avatar_version} />
2294 <h1 class="mt m0">{acct.name || acct.login}</h1>
2295 <p class="muted">
2296 {acct.login} {acct.suspended_at ? <span class="badge red">suspended</span> : null}
2297 </p>
2298 {acct.id === me.id ? (
2299 <a class="btn sm" href="/settings">
2300 Edit profile
2301 </a>
2302 ) : me.kind === "user" ? (
2303 <ProfileMenu c={c} user={acct} blocked={await hasBlocked(c, me, acct)} />
2304 ) : null}
2305 </section>
2306 {orgs.length ? (
2307 <section>
2308 <h3>Organizations</h3>
2309 <div class="nav">
2310 {orgs.map((o) => (
2311 <a href={`/${o.login}`}>
2312 <Avatar login={o.login} version={o.avatar_version} /> {o.login}
2313 </a>
2314 ))}
2315 </div>
2316 </section>
2317 ) : null}
2318 </aside>
2319 <div>
2320 <div class="row between mb">
2321 <h2 class="m0">Repositories</h2>
2322 <div class="row">
2323 <a class="btn sm" href={`/${acct.login}/-/packages`}>
2324 {raw(ICONS.package)} Packages
2325 </a>
2326 {acct.id === me.id ? (
2327 <a class="btn sm primary" href="/new">
2328 {raw(ICONS.plus)} New
2329 </a>
2330 ) : null}
2331 </div>
2332 </div>
2333 <div class="box">
2334 <RepoList repos={repos} showOwner={false} />
2335 </div>
2336 </div>
2337 </div>,
2338 );
2339 }
2340
2341 // Organization
2342 const role = await dir.orgRole(acct.id, me.id);
2343 const isAdmin = !!me.site_admin || role === "owner" || role === "admin";
2344 const isOwner = !!me.site_admin || role === "owner";
2345 const requested = (c.req.query("tab") ?? "repositories") as OrgTab;
2346 // The old Invites tab is part of People now.
2347 const tab: OrgTab = invite || (requested as string) === "invites" ? "people" : (["repositories", "people", "agents", "settings"] as const).includes(requested) ? requested : "repositories";
2348 if (tab === "settings" && !isOwner) throw new HttpError(403, "organization owners only");
2349 let body: Child = null;
2350 const base = `/${acct.login}`;
2351 if (tab === "repositories") {
2352 body = (
2353 <>
2354 <div class="row between mb">
2355 <h2 class="m0">Repositories</h2>
2356 {role ? (
2357 <span class="row" style="gap:6px">
2358 {isAdmin ? (
2359 <a class="btn sm" href={`/new/import?owner=${encodeURIComponent(acct.login)}&mode=owner`}>
2360 Import from GitHub
2361 </a>
2362 ) : null}
2363 <a class="btn sm primary" href={`/new?owner=${encodeURIComponent(acct.login)}`}>
2364 {raw(ICONS.plus)} New repository
2365 </a>
2366 </span>
2367 ) : null}
2368 </div>
2369 <div class="box">
2370 <RepoList repos={repos} showOwner={false} />
2371 </div>
2372 </>
2373 );
2374 } else if (tab === "people") {
2375 const [members, invites] = await Promise.all([dir.orgMembers(acct.id), isAdmin ? dir.invites({ orgId: acct.id, pending: true }) : Promise.resolve([])]);
2376 const roles = (isOwner ? ["member", "admin", "owner"] : ["member", "admin"]).map((r) => ({ value: r, label: ROLE_LABEL[r]! }));
2377 body = (
2378 <>
2379 <div class="row between mb">
2380 <h2 class="m0">People</h2>
2381 <span class="muted small">
2382 {members.length} member{members.length === 1 ? "" : "s"}
2383 {invites.length ? ` · ${invites.length} pending invitation${invites.length === 1 ? "" : "s"}` : ""}
2384 </span>
2385 </div>
2386 {invite ? <InviteOnce email={invite.email} url={invite.url} /> : null}
2387 {isAdmin ? (
2388 <Form action={`${base}/-/org/people`} t={t} class="box">
2389 <div class="head">
2390 <h3>{raw(ICONS.userPlus)} Add people</h3>
2391 </div>
2392 <div class="body">
2393 <div class="formrow">
2394 <div class="field grow">
2395 <label for="who">Username or email</label>
2396 <input id="who" name="who" type="text" required autocomplete="off" spellcheck={false} placeholder="diffy or [email protected]" />
2397 </div>
2398 <div class="field">
2399 <label for="role">Role</label>
2400 <KSelect id="role" name="role" label="Role" value="member" options={roles} />
2401 </div>
2402 <button class="btn primary">Add</button>
2403 </div>
2404 <div class="hint">Everyone gets an invitation and joins {acct.login} when they accept it: a username in their Settings → Invitations (with an email and a notification), an email address by a link that also creates an account if they don't have one.</div>
2405 </div>
2406 </Form>
2407 ) : null}
2408 <div class="box">
2409 <table class="tbl">
2410 <thead>
2411 <tr>
2412 <th>Member</th>
2413 <th>Role</th>
2414 {isAdmin ? <th /> : null}
2415 </tr>
2416 </thead>
2417 <tbody>
2418 {members.map((m) => (
2419 <tr>
2420 <td>
2421 <Actor login={m.login} kind="user" version={m.avatar_version} /> {m.name && m.name !== m.login ? <span class="muted small">{m.name}</span> : null}
2422 </td>
2423 <td>
2424 {isAdmin && (isOwner || m.role !== "owner") ? (
2425 <Form action={`${base}/-/org/members`} t={t} class="row nowrap" style="gap:6px">
2426 <input type="hidden" name="login" value={m.login} />
2427 <KSelect name="role" size="sm" label={`Role of ${m.login}`} value={m.role} options={(isOwner ? ["owner", "admin", "member"] : ["admin", "member"]).map((r) => ({ value: r, label: ROLE_LABEL[r]! }))} />
2428 <button class="btn sm">Save</button>
2429 </Form>
2430 ) : (
2431 <span class="badge">{ROLE_LABEL[m.role] ?? m.role}</span>
2432 )}
2433 </td>
2434 {isAdmin ? (
2435 <td class="right">
2436 {isOwner || m.role !== "owner" ? (
2437 <Form action={`${base}/-/org/members`} t={t} class="inline" confirm={`Remove ${m.login} from ${acct.login}?`}>
2438 <input type="hidden" name="login" value={m.login} />
2439 <input type="hidden" name="role" value="remove" />
2440 <button class="btn sm danger">Remove</button>
2441 </Form>
2442 ) : null}
2443 </td>
2444 ) : null}
2445 </tr>
2446 ))}
2447 </tbody>
2448 </table>
2449 </div>
2450 <PendingInvites invites={invites} revoke={(id) => `${base}/-/org/invites/${id}/revoke`} t={t} />
2451 </>
2452 );
2453 } else if (tab === "agents") {
2454 const agents = await dir.agentsOwnedBy([acct.id]);
2455 body = (
2456 <>
2457 <div class="row between mb">
2458 <h2 class="m0">Agents</h2>
2459 {isAdmin ? (
2460 <a class="btn sm primary" href="/settings/agents">
2461 Manage agents
2462 </a>
2463 ) : null}
2464 </div>
2465 <div class="box">
2466 {agents.length ? (
2467 <ul class="list">
2468 {agents.map((a) => (
2469 <li>
2470 <Actor login={a.login} kind="agent" version={a.avatar_version} />
2471 <span class="grow" />
2472 <span class="muted small">max role {parsePolicy(a).maxRole ?? "write"}</span>
2473 <span class={`badge ${a.status === "active" ? "green" : ""}`}>{a.status}</span>
2474 </li>
2475 ))}
2476 </ul>
2477 ) : (
2478 <div class="empty">This organization has no agents.</div>
2479 )}
2480 </div>
2481 </>
2482 );
2483 } else {
2484 const agentData = await orgAgentData(c.env, acct.id);
2485 body = (
2486 <>
2487 <h2>Settings</h2>
2488 <AvatarSection account={acct} action={`${base}/-/org/avatar`} t={t} />
2489 <Form action={`${base}/-/org/settings`} t={t} class="box">
2490 <div class="body">
2491 <div class="field">
2492 <label>Organization name</label>
2493 <input name="login" type="text" value={acct.login} required pattern={LOGIN_PATTERN} />
2494 <div class="hint">Renaming changes every repository URL in this organization.</div>
2495 </div>
2496 <div class="field">
2497 <label>Display name</label>
2498 <input name="name" type="text" value={acct.name ?? ""} />
2499 </div>
2500 <div class="field">
2501 <label for="base_role">Base permission</label>
2502 <KSelect id="base_role" name="base_role" block label="Base permission" value={baseRole(acct)} options={BASE_ROLE_OPTIONS} />
2503 <div class="hint">What every member can do in all of this organization's repositories. Owners and admins always have admin access, and repository settings can give people more.</div>
2504 </div>
2505 <button class="btn primary">Save</button>
2506 </div>
2507 </Form>
2508 <OrgAgentSettings org={acct} data={agentData} t={t} />
2509 <BlockList
2510 blocks={await blockList(c.env, acct.id)}
2511 add={`${base}/-/org/blocks`}
2512 unblock={(login) => `${base}/-/org/blocks/${encodeURIComponent(login)}/unblock`}
2513 t={t}
2514 title="Blocked users"
2515 hint={`They can't open issues or pull requests, comment or react in ${acct.login}'s repositories, be added as collaborators or be invited to ${acct.login}. Members can't be blocked; remove them first.`}
2516 empty="This organization hasn't blocked anyone."
2517 />
2518 <div class="box" style="border-color:color-mix(in srgb,var(--red) 45%,transparent)">
2519 <div class="head" style="background:var(--red-soft)">
2520 <h2 class="bad">Danger zone</h2>
2521 </div>
2522 <Form action={`${base}/-/org/delete`} t={t} match={acct.login} class="body">
2523 <b>Delete this organization</b>
2524 <p class="muted small">
2525 Transfer or delete its repositories and container images first. Its members, invitations, secrets and variables are removed and its agents disabled; repositories transferred out of it keep their old URLs working. Type <b class="mono">{acct.login}</b> to confirm.
2526 </p>
2527 <div class="row">
2528 <input name="confirm" type="text" required autocomplete="off" style="max-width:320px" aria-label="Confirm organization name" />
2529 <button class="btn danger">Delete this organization</button>
2530 </div>
2531 </Form>
2532 </div>
2533 </>
2534 );
2535 }
2536 return render(
2537 c,
2538 { title: acct.login },
2539 <>
2540 <OrgHeader org={acct} role={role} isOwner={isOwner} tab={tab} />
2541 {body}
2542 </>,
2543 );
2544 };
2545
2546 web.get("/:owner", async (c) => profile(c));
2547
2548 // Add people: a username or an email. Both get an invitation to accept (Directory.addOrgPerson).
2549 post(web, "/:owner/-/org/people", async (c, f) => {
2550 const { me, org, isAdmin, isOwner, dir } = await orgContext(c);
2551 const back = `/${org.login}?tab=people`;
2552 const role = (["member", "admin", "owner"] as const).find((r) => r === f.s("role")) ?? "member";
2553 let invited: { email: string; url: string } | undefined;
2554 const res = await act(c, back, async () => {
2555 if (!isAdmin) throw new HttpError(403, "organization admins only");
2556 if (role === "owner" && !isOwner) throw new HttpError(403, "only owners can add owners");
2557 const r = await dir.addOrgPerson(org, me, f.s("who"), role);
2558 if ("added" in r) {
2559 flash(c, "notice", `Added ${r.added.login} to ${org.login} as ${ROLE_LABEL[role]!.toLowerCase()}. We let them know.`);
2560 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "org.member.set", target: org.login, detail: { user: r.added.login, role } }));
2561 } else if ("invitedUser" in r) {
2562 flash(c, "notice", r.renewed ? `${r.invitedUser.login} already had a pending invitation; it now offers the ${ROLE_LABEL[role]!.toLowerCase()} role.` : `Invited ${r.invitedUser.login} to ${org.login} as ${ROLE_LABEL[role]!.toLowerCase()}. They join once they accept.`);
2563 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "org.invite", target: org.login, detail: { user: r.invitedUser.login, role } }));
2564 } else {
2565 invited = r.invited;
2566 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "org.invite", target: org.login, detail: { email: r.invited.email, role } }));
2567 }
2568 });
2569 return invited ? profile(c, invited) : res;
2570 });
2571
2572 // The old invite form posts here.
2573 post(web, "/:owner/-/org/invites", async (c) => c.redirect(`/${prm(c, "owner")}?tab=people`, 303));
2574
2575 post(web, "/:owner/-/org/invites/:id/revoke", async (c) => {
2576 const { me, org, isAdmin, dir } = await orgContext(c);
2577 return act(
2578 c,
2579 `/${org.login}?tab=people`,
2580 async () => {
2581 if (!isAdmin) throw new HttpError(403, "organization admins only");
2582 if (!(await dir.revokeInvite(prm(c, "id"), { orgId: org.id }))) throw new HttpError(404, "this invitation was already used, revoked or never existed");
2583 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "org.invite.revoke", target: org.login, detail: { id: prm(c, "id") } }));
2584 },
2585 "Invitation revoked.",
2586 );
2587 });
2588
2589 post(web, "/:owner/-/org/members", async (c, f) => {
2590 const { me, org, isAdmin, isOwner, dir } = await orgContext(c);
2591 const back = `/${org.login}?tab=people`;
2592 return act(c, back, async () => {
2593 if (!isAdmin) throw new HttpError(403, "organization admins only");
2594 const user = await dir.accountByLogin(f.s("login").trim());
2595 if (!user || user.kind !== "user") throw new HttpError(404, "user not found");
2596 const current = await dir.orgRole(org.id, user.id);
2597 const role = f.s("role");
2598 if ((current === "owner" || role === "owner") && !isOwner) throw new HttpError(403, "only owners can manage owners");
2599 // Someone who isn't a member yet gets an invitation, as with Add people.
2600 if (!current && role !== "remove") {
2601 if (role !== "owner" && role !== "admin" && role !== "member") throw new HttpError(422, "invalid role");
2602 const r = await dir.addOrgPerson(org, me, user.login, role);
2603 if ("invitedUser" in r) flash(c, "notice", r.renewed ? `${user.login} already had a pending invitation; it now offers the ${ROLE_LABEL[role]!.toLowerCase()} role.` : `Invited ${user.login} to ${org.login} as ${ROLE_LABEL[role]!.toLowerCase()}. They join once they accept.`);
2604 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "added" in r ? "org.member.set" : "org.invite", target: org.login, detail: { user: user.login, role } }));
2605 return;
2606 }
2607 if (role === "remove") await dir.setOrgMember(org.id, user.id, null, me);
2608 else if (role === "owner" || role === "admin" || role === "member") await dir.setOrgMember(org.id, user.id, role, me);
2609 else throw new HttpError(422, "invalid role");
2610 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: role === "remove" ? "org.member.remove" : "org.member.set", target: org.login, detail: { user: user.login, role } }));
2611 });
2612 });
2613
2614 post(web, "/:owner/-/org/settings", async (c, f) => {
2615 const { me, org, isOwner, dir } = await orgContext(c);
2616 return act(c, `/${org.login}?tab=settings`, async () => {
2617 if (!isOwner) throw new HttpError(403, "organization owners only");
2618 const login = f.s("login").trim();
2619 // One validated write: a bad base permission doesn't leave a half-applied rename behind.
2620 await dir.updateAccount(org.id, { login: login && login !== org.login ? login : undefined, name: f.s("name").trim(), baseRole: f.s("base_role") || undefined });
2621 if (login && login !== org.login) c.executionCtx.waitUntil(purgeAvatarCache(c, org.login, [org.avatar_version]));
2622 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "org.update", target: org.login, detail: { login, base_role: f.s("base_role") || undefined } }));
2623 return `/${login || org.login}?tab=settings`;
2624 }, "Organization updated.");
2625 });
2626
2627 post(web, "/:owner/-/org/delete", async (c, f) => {
2628 const { me, org, isOwner, dir } = await orgContext(c);
2629 return act(
2630 c,
2631 `/${org.login}?tab=settings`,
2632 async () => {
2633 if (!isOwner) throw new HttpError(403, "organization owners only");
2634 if (f.s("confirm").trim() !== org.login) throw new HttpError(422, `type ${org.login} to confirm deletion`);
2635 requireRecentSignIn(c, `/${org.login}?tab=settings`);
2636 await dir.deleteOrg(org);
2637 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "org.delete", target: org.login }));
2638 return "/";
2639 },
2640 `Deleted ${org.login}.`,
2641 );
2642 });
2643
2644 avatarSizeGuard(web, "/:owner/-/org/avatar", (c) => `/${c.req.param("owner")}?tab=settings`);
2645 post(web, "/:owner/-/org/avatar", async (c, f) => {
2646 const { me, org, isOwner } = await orgContext(c);
2647 return act(c, `/${org.login}?tab=settings`, async () => {
2648 if (!isOwner) throw new HttpError(403, "organization owners only");
2649 await uploadAvatar(c, f, me, org);
2650 }, "Organization picture updated.");
2651 });
2652
2653 post(web, "/:owner/-/org/avatar/delete", async (c) => {
2654 const { me, org, isOwner } = await orgContext(c);
2655 return act(c, `/${org.login}?tab=settings`, async () => {
2656 if (!isOwner) throw new HttpError(403, "organization owners only");
2657 await deleteAvatar(c, me, org);
2658 }, "Organization picture removed.");
2659 });
2660}