@app-vitals/agent-admin 1.59.0 → 1.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,10 +7,7 @@
7
7
  * `{ error }` bodies as readable messages. No key is ever read back.
8
8
  */
9
9
 
10
- import type { SettingsNav } from "./admin-ui-settings-layout.ts";
11
10
  import type { Context, Hono, MiddlewareHandler } from "hono";
12
- import { readPrivateKeyField } from "./github-enterprise-pem-upload.ts";
13
- import { warningCodeFor } from "./github-enterprise-warnings.ts";
14
11
  import type { AdminUIEnv } from "./admin-ui.ts";
15
12
  import {
16
13
  ADMIN_GITHUB_ENTERPRISE_PATH as BASE,
@@ -18,11 +15,16 @@ import {
18
15
  type GheStatus,
19
16
  renderGithubEnterpriseSettingsPage,
20
17
  } from "./admin-ui-github-enterprise-pages.ts";
18
+ import type { SettingsNav } from "./admin-ui-settings-layout.ts";
19
+ import { readPrivateKeyField } from "./github-enterprise-pem-upload.ts";
20
+ import { warningCodeFor } from "./github-enterprise-warnings.ts";
21
21
 
22
22
  export interface AdminGithubEnterpriseRouteDeps {
23
23
  requireAuth: MiddlewareHandler<AdminUIEnv>;
24
24
  /** Calls the GHE-1.3 API app (its `.request`), e.g. `/github-enterprise/apps`. */
25
25
  api: (path: string, init?: RequestInit) => Response | Promise<Response>;
26
+ /** Accounts for the per-account App selector; omitted hides it. */
27
+ accounts?: { listWithCounts: () => Promise<{ id: string; name: string }[]> };
26
28
  /** Settings sidebar nav (SGL-2.2). */
27
29
  settingsNav?: SettingsNav;
28
30
  html: (content: string, opts?: { status?: number }) => Response;
@@ -90,14 +92,24 @@ export function registerAdminGithubEnterpriseRoutes(
90
92
  return { ok: false, status: res.status, error };
91
93
  }
92
94
 
95
+ /** Selected account (query), as an API query suffix and a redirect suffix. */
96
+ const scopeOf = (c: Context<AdminUIEnv>) => {
97
+ const accountId = c.req.query("accountId")?.trim() || undefined;
98
+ const q = accountId ? `accountId=${encodeURIComponent(accountId)}` : "";
99
+ return { accountId, q };
100
+ };
101
+ const withQuery = (path: string, q: string) =>
102
+ q ? `${path}${path.includes("?") ? "&" : "?"}${q}` : path;
103
+
93
104
  async function renderPage(
94
105
  c: Context<AdminUIEnv>,
95
106
  flash: { error?: string; notice?: string; status?: number } = {},
96
107
  ): Promise<Response> {
108
+ const { accountId, q } = scopeOf(c);
97
109
  const statusRes = await call<GheStatus>(
98
110
  c,
99
111
  "GET",
100
- "/github-enterprise/apps",
112
+ withQuery("/github-enterprise/apps", q),
101
113
  );
102
114
  if (!statusRes.ok || !statusRes.data) {
103
115
  return deps.html(
@@ -114,8 +126,22 @@ export function registerAdminGithubEnterpriseRoutes(
114
126
  const status = statusRes.data;
115
127
  let orgs: GheOrgs | undefined;
116
128
  let orgsError: string | undefined;
117
- if (status.installer) {
118
- const r = await call<GheOrgs>(c, "GET", "/github-enterprise/orgs");
129
+ // With an account selected, the deployment-wide pair is the fallback.
130
+ let defaultStatus: GheStatus | undefined;
131
+ if (accountId) {
132
+ const d = await call<GheStatus>(c, "GET", "/github-enterprise/apps");
133
+ if (d.ok) defaultStatus = d.data;
134
+ }
135
+ let accounts: { id: string; name: string }[] | undefined;
136
+ if (deps.accounts) {
137
+ accounts = await deps.accounts.listWithCounts().catch(() => undefined);
138
+ }
139
+ if (status.installer ?? defaultStatus?.installer) {
140
+ const r = await call<GheOrgs>(
141
+ c,
142
+ "GET",
143
+ withQuery("/github-enterprise/orgs", q),
144
+ );
119
145
  if (r.ok) orgs = r.data;
120
146
  else orgsError = r.error;
121
147
  }
@@ -127,6 +153,9 @@ export function registerAdminGithubEnterpriseRoutes(
127
153
  isAdmin: c.var.isAdmin === true,
128
154
  ...(deps.settingsNav ? { nav: deps.settingsNav } : {}),
129
155
  status,
156
+ accountId,
157
+ accounts: accounts?.map((a) => ({ id: a.id, name: a.name })),
158
+ defaultStatus,
130
159
  orgs,
131
160
  orgsError,
132
161
  error: flash.error,
@@ -146,8 +175,10 @@ export function registerAdminGithubEnterpriseRoutes(
146
175
  return new FormData();
147
176
  }
148
177
  }
149
- const back = (c: Context<AdminUIEnv>, notice: string) =>
150
- c.redirect(`${BASE}?notice=${notice}`, 302);
178
+ const back = (c: Context<AdminUIEnv>, notice: string) => {
179
+ const { q } = scopeOf(c);
180
+ return c.redirect(`${BASE}?notice=${notice}${q ? `&${q}` : ""}`, 302);
181
+ };
151
182
  const fail = (c: Context<AdminUIEnv>, r: ApiResult<unknown>) =>
152
183
  renderPage(c, { error: r.error, status: r.status >= 400 ? r.status : 400 });
153
184
 
@@ -160,13 +191,19 @@ export function registerAdminGithubEnterpriseRoutes(
160
191
  const enterpriseSlug = field(form, "enterpriseSlug");
161
192
  const key = await readPrivateKeyField(form);
162
193
  if (!key.ok) return renderPage(c, { error: key.error, status: 400 });
163
- const r = await call(c, "PUT", `/github-enterprise/apps/${role}`, {
164
- appId: field(form, "appId"),
165
- slug: field(form, "slug"),
166
- ...(enterpriseSlug ? { enterpriseSlug } : {}),
167
- // Pasted or uploaded; never echoed back to the page.
168
- privateKey: key.pem,
169
- });
194
+ const { q } = scopeOf(c);
195
+ const r = await call(
196
+ c,
197
+ "PUT",
198
+ withQuery(`/github-enterprise/apps/${role}`, q),
199
+ {
200
+ appId: field(form, "appId"),
201
+ slug: field(form, "slug"),
202
+ ...(enterpriseSlug ? { enterpriseSlug } : {}),
203
+ // Pasted or uploaded; never echoed back to the page.
204
+ privateKey: key.pem,
205
+ },
206
+ );
170
207
  return r.ok ? back(c, "saved") : fail(c, r);
171
208
  });
172
209
 
@@ -180,7 +217,7 @@ export function registerAdminGithubEnterpriseRoutes(
180
217
  const r = await call<{ warnings?: string[] }>(
181
218
  c,
182
219
  "POST",
183
- `/github-enterprise/apps/${role}/validate`,
220
+ withQuery(`/github-enterprise/apps/${role}/validate`, scopeOf(c).q),
184
221
  );
185
222
  if (!r.ok) return fail(c, r);
186
223
  // Warnings ride the redirect as stable codes, never free text.
@@ -188,7 +225,7 @@ export function registerAdminGithubEnterpriseRoutes(
188
225
  .map(warningCodeFor)
189
226
  .filter((x): x is NonNullable<typeof x> => x !== undefined);
190
227
  return c.redirect(
191
- `${BASE}?notice=validated${codes.length ? `&warn=${codes.join(",")}` : ""}`,
228
+ `${BASE}?notice=validated${codes.length ? `&warn=${codes.join(",")}` : ""}${scopeOf(c).q ? `&${scopeOf(c).q}` : ""}`,
192
229
  302,
193
230
  );
194
231
  },
@@ -201,7 +238,11 @@ export function registerAdminGithubEnterpriseRoutes(
201
238
  async (c) => {
202
239
  const role = c.req.param("role");
203
240
  if (!isRole(role)) return new Response("Not Found", { status: 404 });
204
- const r = await call(c, "DELETE", `/github-enterprise/apps/${role}`);
241
+ const r = await call(
242
+ c,
243
+ "DELETE",
244
+ withQuery(`/github-enterprise/apps/${role}`, scopeOf(c).q),
245
+ );
205
246
  return r.ok ? back(c, "deleted") : fail(c, r);
206
247
  },
207
248
  );
package/src/admin-ui.ts CHANGED
@@ -22,7 +22,6 @@
22
22
  * Allowed users are controlled by the adminAllowedEmails allowlist in deps.
23
23
  */
24
24
 
25
- import type { GheOrgs } from "./admin-ui-github-enterprise-pages.ts";
26
25
  import { join } from "node:path";
27
26
  import { isGithubLogin } from "@app-vitals/agent-lib/github-login";
28
27
  import { isOrgRepo } from "@app-vitals/agent-lib/org-repo";
@@ -51,6 +50,7 @@ import { runWithSettingsNav } from "./admin-ui-account-nav.ts";
51
50
  import { renderZeroQuotaNotice } from "./admin-ui-account-pages.ts";
52
51
  import { registerAdminAccountsRoutes } from "./admin-ui-accounts.ts";
53
52
  import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
53
+ import type { GheOrgs } from "./admin-ui-github-enterprise-pages.ts";
54
54
  import {
55
55
  type GithubAccessPreviewView,
56
56
  renderGithubAccessError,
@@ -4091,6 +4091,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4091
4091
  requireAuth,
4092
4092
  settingsNav,
4093
4093
  api: githubEnterpriseApi,
4094
+ ...(accountServices ? { accounts: accountServices.accounts } : {}),
4094
4095
  html,
4095
4096
  });
4096
4097
  }
package/src/agents-api.ts CHANGED
@@ -3403,7 +3403,10 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3403
3403
  }
3404
3404
  if (!deps.githubAccessPreview)
3405
3405
  return c.json({ status: "unconfigured" as const }, 200);
3406
- const preview = await deps.githubAccessPreview(agent.githubUsername);
3406
+ const preview = await deps.githubAccessPreview(
3407
+ agent.githubUsername,
3408
+ agent.accountId,
3409
+ );
3407
3410
  return c.json(preview, 200);
3408
3411
  });
3409
3412
 
@@ -16,4 +16,6 @@ export type GithubAccessPreview =
16
16
 
17
17
  export type GithubAccessPreviewFn = (
18
18
  username: string,
19
+ /** The agent's account: its App pair, else the deployment-wide pair. */
20
+ accountId?: string | null,
19
21
  ) => Promise<GithubAccessPreview>;
@@ -388,11 +388,17 @@ describe("POST validate", () => {
388
388
  "/github-enterprise/apps/installer/validate",
389
389
  { method: "POST", headers: ADMIN },
390
390
  );
391
- const body = (await res.json()) as { ok: boolean; status: string; error: string };
391
+ const body = (await res.json()) as {
392
+ ok: boolean;
393
+ status: string;
394
+ error: string;
395
+ };
392
396
  expect(body).toMatchObject({ ok: false, status: "error" });
393
397
  expect(body.error).toContain("not installed on enterprise acme");
394
398
  expect(body.error).toContain("slug");
395
- expect(h.appService.rows.get("installer")?.lastValidationError).toBe(body.error);
399
+ expect(h.appService.rows.get("installer")?.lastValidationError).toBe(
400
+ body.error,
401
+ );
396
402
  });
397
403
 
398
404
  it("installer: a 404 on the token mint keeps the generic reason", async () => {
@@ -415,28 +421,48 @@ describe("POST validate", () => {
415
421
  "/github-enterprise/apps/installer/validate",
416
422
  { method: "POST", headers: ADMIN },
417
423
  );
418
- const body = (await res.json()) as { ok: boolean; status: string; warnings: string[] };
424
+ const body = (await res.json()) as {
425
+ ok: boolean;
426
+ status: string;
427
+ warnings: string[];
428
+ };
419
429
  expect(body).toMatchObject({ ok: true, status: "valid" });
420
430
  expect(body.warnings).toHaveLength(1);
421
- expect(body.warnings[0]).toContain("enterprise_organization_installation_repositories");
431
+ expect(body.warnings[0]).toContain(
432
+ "enterprise_organization_installation_repositories",
433
+ );
422
434
  });
423
435
 
424
436
  it("installer: read-only repositories permission also warns; write does not", async () => {
425
- const ro = build({ routes: { [MINT]: "access_token_repositories_read_only" } });
426
- await seed(ro);
427
- const r1 = await ro.app.request("/github-enterprise/apps/installer/validate", {
428
- method: "POST",
429
- headers: ADMIN,
437
+ const ro = build({
438
+ routes: { [MINT]: "access_token_repositories_read_only" },
430
439
  });
431
- expect(((await r1.json()) as { warnings: string[] }).warnings).toHaveLength(1);
440
+ await seed(ro);
441
+ const r1 = await ro.app.request(
442
+ "/github-enterprise/apps/installer/validate",
443
+ {
444
+ method: "POST",
445
+ headers: ADMIN,
446
+ },
447
+ );
448
+ expect(((await r1.json()) as { warnings: string[] }).warnings).toHaveLength(
449
+ 1,
450
+ );
432
451
 
433
452
  const full = build({ routes: { [MINT]: "access_token_all_permissions" } });
434
453
  await seed(full);
435
- const r2 = await full.app.request("/github-enterprise/apps/installer/validate", {
436
- method: "POST",
437
- headers: ADMIN,
454
+ const r2 = await full.app.request(
455
+ "/github-enterprise/apps/installer/validate",
456
+ {
457
+ method: "POST",
458
+ headers: ADMIN,
459
+ },
460
+ );
461
+ expect(await r2.json()).toMatchObject({
462
+ ok: true,
463
+ status: "valid",
464
+ warnings: [],
438
465
  });
439
- expect(await r2.json()).toMatchObject({ ok: true, status: "valid", warnings: [] });
440
466
  });
441
467
 
442
468
  it("lookup: warns (still valid) without Organization Members read; none with it", async () => {
@@ -460,29 +486,51 @@ describe("POST validate", () => {
460
486
 
461
487
  const h2 = build({ routes: { "GET /app": "app_get_all_permissions" } });
462
488
  await seedLookup(h2);
463
- const res2 = await h2.app.request("/github-enterprise/apps/lookup/validate", {
464
- method: "POST",
465
- headers: ADMIN,
489
+ const res2 = await h2.app.request(
490
+ "/github-enterprise/apps/lookup/validate",
491
+ {
492
+ method: "POST",
493
+ headers: ADMIN,
494
+ },
495
+ );
496
+ expect(await res2.json()).toMatchObject({
497
+ ok: true,
498
+ status: "valid",
499
+ warnings: [],
466
500
  });
467
- expect(await res2.json()).toMatchObject({ ok: true, status: "valid", warnings: [] });
468
501
  });
469
502
 
470
503
  it("warnings never flip validity: a missing required permission stays invalid, an error has none", async () => {
471
- const h = build({ routes: { [MINT]: "access_token_no_installer_permission" } });
504
+ const h = build({
505
+ routes: { [MINT]: "access_token_no_installer_permission" },
506
+ });
472
507
  await seed(h);
473
- const res = await h.app.request("/github-enterprise/apps/installer/validate", {
474
- method: "POST",
475
- headers: ADMIN,
508
+ const res = await h.app.request(
509
+ "/github-enterprise/apps/installer/validate",
510
+ {
511
+ method: "POST",
512
+ headers: ADMIN,
513
+ },
514
+ );
515
+ expect(await res.json()).toMatchObject({
516
+ ok: false,
517
+ status: "missing_permission",
476
518
  });
477
- expect(await res.json()).toMatchObject({ ok: false, status: "missing_permission" });
478
519
 
479
520
  const e = build({ routes: { [ENT]: "enterprise_installation_403" } });
480
521
  await seed(e);
481
- const r = await e.app.request("/github-enterprise/apps/installer/validate", {
482
- method: "POST",
483
- headers: ADMIN,
522
+ const r = await e.app.request(
523
+ "/github-enterprise/apps/installer/validate",
524
+ {
525
+ method: "POST",
526
+ headers: ADMIN,
527
+ },
528
+ );
529
+ expect(await r.json()).toMatchObject({
530
+ ok: false,
531
+ status: "error",
532
+ warnings: [],
484
533
  });
485
- expect(await r.json()).toMatchObject({ ok: false, status: "error", warnings: [] });
486
534
  });
487
535
 
488
536
  it("lookup: checks metadata read via GET /app", async () => {
@@ -772,3 +820,99 @@ describe("POST install", () => {
772
820
  expect((await post(h, { agentId: "agent-1" })).status).toBe(429);
773
821
  });
774
822
  });
823
+
824
+ describe("account-scoped routes", () => {
825
+ /** Records the accountId every appService method receives. */
826
+ function spied() {
827
+ const h = build();
828
+ const seen: Record<string, unknown[]> = {};
829
+ for (const m of [
830
+ "list",
831
+ "get",
832
+ "save",
833
+ "delete",
834
+ "getPrivateKey",
835
+ ] as const) {
836
+ const orig = (
837
+ h.appService as never as Record<string, (...a: unknown[]) => unknown>
838
+ )[m];
839
+ (h.appService as never as Record<string, unknown>)[m] = async (
840
+ ...args: unknown[]
841
+ ) => {
842
+ const acct =
843
+ m === "save"
844
+ ? (args[0] as { accountId?: string }).accountId
845
+ : args[m === "list" ? 0 : 1];
846
+ seen[m] = [...(seen[m] ?? []), acct];
847
+ return orig.apply(h.appService, args);
848
+ };
849
+ }
850
+ return { ...h, seen };
851
+ }
852
+
853
+ it("GET /apps, PUT, DELETE and validate pass the accountId query param", async () => {
854
+ const h = spied();
855
+ await h.app.request("/github-enterprise/apps?accountId=acct-1", {
856
+ headers: ADMIN,
857
+ });
858
+ expect(h.seen.list).toEqual(["acct-1"]);
859
+
860
+ const put = await h.app.request(
861
+ "/github-enterprise/apps/installer?accountId=acct-1",
862
+ {
863
+ method: "PUT",
864
+ headers: JSON_ADMIN,
865
+ body: JSON.stringify(installerBody),
866
+ },
867
+ );
868
+ expect(put.status).toBe(200);
869
+ expect(h.seen.save).toEqual(["acct-1"]);
870
+
871
+ const del = await h.app.request(
872
+ "/github-enterprise/apps/installer?accountId=acct-1",
873
+ { method: "DELETE", headers: ADMIN },
874
+ );
875
+ expect(del.status).toBe(204);
876
+ expect(h.seen.delete).toEqual(["acct-1"]);
877
+
878
+ await h.app.request(
879
+ "/github-enterprise/apps/installer/validate?accountId=acct-1",
880
+ { method: "POST", headers: ADMIN },
881
+ );
882
+ expect(h.seen.get?.[0]).toBe("acct-1");
883
+ });
884
+
885
+ it("omitting accountId targets the deployment-wide pair", async () => {
886
+ const h = spied();
887
+ await h.app.request("/github-enterprise/apps", { headers: ADMIN });
888
+ await h.app.request("/github-enterprise/orgs", { headers: ADMIN });
889
+ expect(h.seen.list).toEqual([undefined]);
890
+ expect(h.seen.get).toEqual([undefined]);
891
+ });
892
+
893
+ it("orgs and install read the account's installer App", async () => {
894
+ const h = spied();
895
+ await h.app.request("/github-enterprise/orgs?accountId=acct-1", {
896
+ headers: ADMIN,
897
+ });
898
+ expect(h.seen.get).toEqual(["acct-1"]);
899
+ const res = await h.app.request(
900
+ "/github-enterprise/orgs/org-1/install?accountId=acct-1",
901
+ {
902
+ method: "POST",
903
+ headers: JSON_ADMIN,
904
+ body: JSON.stringify({ agentId: "agent-1" }),
905
+ },
906
+ );
907
+ expect(res.status).toBe(409);
908
+ expect(h.seen.get).toEqual(["acct-1", "acct-1"]);
909
+ });
910
+
911
+ it("stays admin-only with an account param", async () => {
912
+ const h = spied();
913
+ const res = await h.app.request("/github-enterprise/apps?accountId=a", {
914
+ headers: { Authorization: "Bearer tok-read" },
915
+ });
916
+ expect(res.status).toBe(403);
917
+ });
918
+ });