@app-vitals/agent-admin 1.21.0 → 1.23.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.
@@ -3649,6 +3649,13 @@
3649
3649
  "null"
3650
3650
  ]
3651
3651
  },
3652
+ "warnings": {
3653
+ "type": "array",
3654
+ "items": {
3655
+ "type": "string"
3656
+ },
3657
+ "description": "Advisory, non-failing notes (e.g. missing optional permissions). Never change `ok`."
3658
+ },
3652
3659
  "app": {
3653
3660
  "$ref": "#/components/schemas/GithubEnterpriseApp"
3654
3661
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.21.0",
3
+ "version": "1.23.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@anthropic-ai/sdk": "0.135.0",
45
- "@app-vitals/agent-lib": "1.21.0",
45
+ "@app-vitals/agent-lib": "1.23.0",
46
46
  "@hono/zod-openapi": "^1.0.0",
47
47
  "@prisma/adapter-pg": "^7.10.0",
48
48
  "@prisma/client": "^7.10.0",
@@ -7,6 +7,7 @@
7
7
  * never renders a key (the status API only reports `keySet`).
8
8
  */
9
9
 
10
+ import { GHE_WARNINGS, type GheWarningCode } from "./github-enterprise-warnings.ts";
10
11
  import { renderAdminPage } from "./admin-ui-layout.ts";
11
12
  import { escapeHtml, renderAdminToolbar } from "./admin-ui-styles.ts";
12
13
 
@@ -58,6 +59,8 @@ export interface GithubEnterpriseSettingsPageOpts {
58
59
  agentId?: string;
59
60
  error?: string;
60
61
  notice?: string;
62
+ /** Warning codes from the last validate (carried via ?warn=); unknown codes are ignored. */
63
+ warnings?: string[];
61
64
  }
62
65
 
63
66
  const BASE = ADMIN_GITHUB_ENTERPRISE_PATH;
@@ -80,7 +83,7 @@ const ROLE_COPY = {
80
83
  },
81
84
  lookup: {
82
85
  title: "Lookup app",
83
- help: "Read-only App used to see which organizations the platform can look up. Needs the metadata (read) permission.",
86
+ help: "Read-only App used to see which organizations the platform can look up. Needs the metadata (read) permission. It must be installed on all repositories of each organization, not selected repositories only.",
84
87
  },
85
88
  } as const;
86
89
 
@@ -107,12 +110,26 @@ function postButton(
107
110
  return `<form method="POST" action="${action}" style="display:inline;margin:0"><button type="submit" class="btn ${cls}" style="font-size:12px;padding:4px 10px">${label}</button></form>`;
108
111
  }
109
112
 
110
- function appCard(role: "installer" | "lookup", app: GheApp | null): string {
113
+ function warningsBlock(role: "installer" | "lookup", codes: string[] | undefined): string {
114
+ return (codes ?? [])
115
+ .filter((c): c is GheWarningCode => c in GHE_WARNINGS && c.startsWith(`${role}_`))
116
+ .map(
117
+ (c) =>
118
+ `<div class="help-text gh-ent-warning" style="font-size:12px;margin-top:4px">Warning: ${escapeHtml(GHE_WARNINGS[c])}</div>`,
119
+ )
120
+ .join("");
121
+ }
122
+
123
+ function appCard(
124
+ role: "installer" | "lookup",
125
+ app: GheApp | null,
126
+ warnings?: string[],
127
+ ): string {
111
128
  const copy = ROLE_COPY[role];
112
129
  const action = `${BASE}/apps/${role}`;
113
130
  const summary = app
114
131
  ? `<p style="margin:8px 0">App ID <strong>${escapeHtml(app.appId)}</strong> &middot; slug <strong>${escapeHtml(app.slug)}</strong>${app.enterpriseSlug ? ` &middot; enterprise <strong>${escapeHtml(app.enterpriseSlug)}</strong>` : ""}</p>
115
- ${statusLine(app)}
132
+ ${statusLine(app)}${warningsBlock(role, warnings)}
116
133
  <div style="display:flex;gap:8px;margin:12px 0">${postButton(`${action}/validate`, "Validate")}${postButton(`${action}/delete`, "Delete", "btn-danger")}</div>`
117
134
  : `<p class="help-text" style="font-size:12px;margin:8px 0">Not configured.</p>`;
118
135
  const enterprise =
@@ -216,8 +233,8 @@ export function renderGithubEnterpriseSettingsPage(
216
233
  <div class="vos-page">
217
234
  <div class="page-header"><h1 class="page-title">GitHub Enterprise apps</h1></div>
218
235
  ${error}${notice}${emptyState}
219
- ${appCard("installer", status.installer)}
220
- ${appCard("lookup", status.lookup)}
236
+ ${appCard("installer", status.installer, opts.warnings)}
237
+ ${appCard("lookup", status.lookup, opts.warnings)}
221
238
  ${orgsCard(opts)}
222
239
  </div>`,
223
240
  });
@@ -39,6 +39,7 @@ describe("renderGithubEnterpriseSettingsPage", () => {
39
39
  expect(html).toContain("optional");
40
40
  expect(html).toContain("Installer app");
41
41
  expect(html).toContain("Lookup app");
42
+ expect(html).toContain("installed on all repositories");
42
43
  expect(html).toContain(
43
44
  'action="/admin/settings/github-enterprise/apps/installer"',
44
45
  );
@@ -102,6 +103,27 @@ describe("renderGithubEnterpriseSettingsPage", () => {
102
103
  expect(html).not.toContain("<b>x</b>");
103
104
  });
104
105
 
106
+ test("warnings render on the matching card only, as non-error notes", () => {
107
+ const html = renderGithubEnterpriseSettingsPage({
108
+ ...base,
109
+ status: { configured: true, installer: app(), lookup: app({ role: "lookup", enterpriseSlug: null }) },
110
+ warnings: ["installer_repositories_write"],
111
+ });
112
+ expect(html).toContain("enterprise_organization_installation_repositories");
113
+ expect(html.match(/gh-ent-warning/g)?.length).toBe(1);
114
+ expect(html).not.toContain("Organization Members");
115
+ });
116
+
117
+ test("unknown warning codes are ignored", () => {
118
+ const html = renderGithubEnterpriseSettingsPage({
119
+ ...base,
120
+ status: { configured: true, installer: app(), lookup: null },
121
+ warnings: ["<script>alert(1)</script>"],
122
+ });
123
+ expect(html).not.toContain("gh-ent-warning");
124
+ expect(html).not.toContain("<script>alert");
125
+ });
126
+
105
127
  test("key not set shows 'Key not set'", () => {
106
128
  const html = renderGithubEnterpriseSettingsPage({
107
129
  ...base,
@@ -97,6 +97,7 @@ function setup(opts: { isAdmin?: boolean; fetchStatus?: number } = {}) {
97
97
  expires_at: "2099-01-01T00:00:00Z",
98
98
  permissions: { enterprise_organization_installations: "write" },
99
99
  });
100
+ if (url.endsWith("/installation")) return json({ id: 1 });
100
101
  return json({});
101
102
  }) as unknown as typeof fetch;
102
103
  const api = createGithubEnterpriseApp({
@@ -219,6 +220,26 @@ describe("form posts", () => {
219
220
  expect(html).not.toContain("Not validated yet");
220
221
  });
221
222
 
223
+ it("shows non-failing permission warnings on the card after validate", async () => {
224
+ const { app } = setup();
225
+ await app.request(
226
+ `${BASE}/apps/installer`,
227
+ form({
228
+ appId: "42",
229
+ slug: "acme-inst",
230
+ enterpriseSlug: "acme",
231
+ privateKey: PEM,
232
+ }),
233
+ );
234
+ const res = await app.request(`${BASE}/apps/installer/validate`, form({}));
235
+ expect(res.status).toBe(302);
236
+ const loc = res.headers.get("location") as string;
237
+ expect(loc).toContain("warn=installer_repositories_write");
238
+ const html = await (await app.request(loc)).text();
239
+ expect(html).toContain("enterprise_organization_installation_repositories");
240
+ expect(html).toContain("gh-ent-warning");
241
+ });
242
+
222
243
  it("validate on an unconfigured role is a readable 404 message", async () => {
223
244
  const { app } = setup();
224
245
  const res = await app.request(`${BASE}/apps/lookup/validate`, form({}));
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import type { Context, Hono, MiddlewareHandler } from "hono";
11
+ import { warningCodeFor } from "./github-enterprise-warnings.ts";
11
12
  import type { AdminUIEnv } from "./admin-ui.ts";
12
13
  import {
13
14
  ADMIN_GITHUB_ENTERPRISE_PATH as BASE,
@@ -127,6 +128,7 @@ export function registerAdminGithubEnterpriseRoutes(
127
128
  agentId,
128
129
  error: flash.error,
129
130
  notice,
131
+ warnings: c.req.query("warn")?.split(",").filter(Boolean),
130
132
  }),
131
133
  { status: flash.status ?? 200 },
132
134
  );
@@ -173,12 +175,20 @@ export function registerAdminGithubEnterpriseRoutes(
173
175
  async (c) => {
174
176
  const role = c.req.param("role");
175
177
  if (!isRole(role)) return new Response("Not Found", { status: 404 });
176
- const r = await call(
178
+ const r = await call<{ warnings?: string[] }>(
177
179
  c,
178
180
  "POST",
179
181
  `/github-enterprise/apps/${role}/validate`,
180
182
  );
181
- return r.ok ? back(c, "validated") : fail(c, r);
183
+ if (!r.ok) return fail(c, r);
184
+ // Warnings ride the redirect as stable codes, never free text.
185
+ const codes = (r.data?.warnings ?? [])
186
+ .map(warningCodeFor)
187
+ .filter((x): x is NonNullable<typeof x> => x !== undefined);
188
+ return c.redirect(
189
+ `${BASE}?notice=validated${codes.length ? `&warn=${codes.join(",")}` : ""}`,
190
+ 302,
191
+ );
182
192
  },
183
193
  );
184
194
 
@@ -27,6 +27,8 @@ export interface GithubAccessOrg {
27
27
  status: GithubAccessOrgStatus;
28
28
  repos: GithubAccessRepo[];
29
29
  unresolved: number;
30
+ /** Optional cause shown in the partial-results banner. */
31
+ reason?: string;
30
32
  }
31
33
 
32
34
  /** JSON body of GET /agents/:id/github-access. */
@@ -127,9 +129,13 @@ export function renderGithubAccessResult(
127
129
  if (!access) return renderGithubAccessError("No preview was returned.");
128
130
 
129
131
  const orgs = access.orgs;
132
+ const reasons = orgs
133
+ .filter((o) => o.reason)
134
+ .map((o) => `${escapeHtml(o.org)}: ${escapeHtml(o.reason ?? "")}`)
135
+ .join("; ");
130
136
  const warn =
131
137
  !access.complete || orgs.some((o) => o.status !== "ok")
132
- ? `<div class="alert alert-warning">Partial results: some organizations or repos could not be checked${access.unresolved > 0 ? ` (${access.unresolved} unresolved)` : ""}. Repos that are not listed are unknown, not necessarily inaccessible.</div>`
138
+ ? `<div class="alert alert-warning">Partial results: some organizations or repos could not be checked${access.unresolved > 0 ? ` (${access.unresolved} unresolved)` : ""}. Repos that are not listed are unknown, not necessarily inaccessible.${reasons ? ` ${reasons}.` : ""}</div>`
133
139
  : "";
134
140
  if (orgs.length === 0) {
135
141
  return `${warn}<p class="empty-state">No organizations to check.</p>`;
@@ -173,6 +173,26 @@ describe("renderGithubAccessResult", () => {
173
173
  expect(html).toContain("Partial results");
174
174
  });
175
175
 
176
+ test("partial org with a reason shows the reason in the banner", () => {
177
+ const html = renderGithubAccessResult(
178
+ analysis({
179
+ complete: false,
180
+ orgs: [
181
+ {
182
+ org: "acme",
183
+ status: "partial",
184
+ repos: [],
185
+ unresolved: 0,
186
+ reason: "lookup app installed on selected repositories only <x>",
187
+ },
188
+ ],
189
+ }),
190
+ );
191
+ expect(html).toContain("Partial results");
192
+ expect(html).toContain("selected repositories only &lt;x&gt;");
193
+ expect(html).not.toContain("<x>");
194
+ });
195
+
176
196
  test("incomplete with all orgs ok still warns", () => {
177
197
  const html = renderGithubAccessResult(
178
198
  analysis({
@@ -671,5 +671,42 @@
671
671
  },
672
672
  "repository_selection": "all"
673
673
  }
674
+ },
675
+ "access_token_all_permissions": {
676
+ "status": 201,
677
+ "body": {
678
+ "token": "ghs_cassetteInstallationToken0000000000",
679
+ "expires_at": "2026-11-09T13:00:00Z",
680
+ "permissions": {
681
+ "enterprise_organization_installations": "write",
682
+ "enterprise_organization_installation_repositories": "write",
683
+ "metadata": "read"
684
+ },
685
+ "repository_selection": "all"
686
+ }
687
+ },
688
+ "access_token_repositories_read_only": {
689
+ "status": 201,
690
+ "body": {
691
+ "token": "ghs_cassetteInstallationToken0000000000",
692
+ "expires_at": "2026-11-09T13:00:00Z",
693
+ "permissions": {
694
+ "enterprise_organization_installations": "write",
695
+ "enterprise_organization_installation_repositories": "read",
696
+ "metadata": "read"
697
+ },
698
+ "repository_selection": "all"
699
+ }
700
+ },
701
+ "app_get_all_permissions": {
702
+ "status": 200,
703
+ "body": {
704
+ "id": 555,
705
+ "slug": "example-lookup-app",
706
+ "permissions": {
707
+ "metadata": "read",
708
+ "members": "read"
709
+ }
710
+ }
674
711
  }
675
712
  }
@@ -17,6 +17,24 @@
17
17
  }
18
18
  }
19
19
  },
20
+ "org_installation_selected": {
21
+ "status": 200,
22
+ "body": {
23
+ "id": 7001,
24
+ "app_id": 555,
25
+ "app_slug": "example-lookup",
26
+ "target_type": "Organization",
27
+ "account": {
28
+ "login": "acme-eng",
29
+ "id": 11,
30
+ "type": "Organization"
31
+ },
32
+ "repository_selection": "selected",
33
+ "permissions": {
34
+ "metadata": "read"
35
+ }
36
+ }
37
+ },
20
38
  "org_installation_403": {
21
39
  "status": 403,
22
40
  "body": {
@@ -381,6 +381,110 @@ describe("POST validate", () => {
381
381
  );
382
382
  });
383
383
 
384
+ it("installer: a 404 on the installation lookup names the enterprise and the likely causes", async () => {
385
+ const h = build({ routes: { [ENT]: "enterprise_installation_404" } });
386
+ await seed(h);
387
+ const res = await h.app.request(
388
+ "/github-enterprise/apps/installer/validate",
389
+ { method: "POST", headers: ADMIN },
390
+ );
391
+ const body = (await res.json()) as { ok: boolean; status: string; error: string };
392
+ expect(body).toMatchObject({ ok: false, status: "error" });
393
+ expect(body.error).toContain("not installed on enterprise acme");
394
+ expect(body.error).toContain("slug");
395
+ expect(h.appService.rows.get("installer")?.lastValidationError).toBe(body.error);
396
+ });
397
+
398
+ it("installer: a 404 on the token mint keeps the generic reason", async () => {
399
+ const h = build({ routes: { [MINT]: "access_token_404" } });
400
+ await seed(h);
401
+ const res = await h.app.request(
402
+ "/github-enterprise/apps/installer/validate",
403
+ { method: "POST", headers: ADMIN },
404
+ );
405
+ const body = (await res.json()) as { error: string };
406
+ expect(body.error).toBe(
407
+ "GitHub could not find the enterprise, organization or App for this request.",
408
+ );
409
+ });
410
+
411
+ it("installer: warns (still valid) when the repositories permission is missing", async () => {
412
+ const h = build();
413
+ await seed(h);
414
+ const res = await h.app.request(
415
+ "/github-enterprise/apps/installer/validate",
416
+ { method: "POST", headers: ADMIN },
417
+ );
418
+ const body = (await res.json()) as { ok: boolean; status: string; warnings: string[] };
419
+ expect(body).toMatchObject({ ok: true, status: "valid" });
420
+ expect(body.warnings).toHaveLength(1);
421
+ expect(body.warnings[0]).toContain("enterprise_organization_installation_repositories");
422
+ });
423
+
424
+ 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,
430
+ });
431
+ expect(((await r1.json()) as { warnings: string[] }).warnings).toHaveLength(1);
432
+
433
+ const full = build({ routes: { [MINT]: "access_token_all_permissions" } });
434
+ await seed(full);
435
+ const r2 = await full.app.request("/github-enterprise/apps/installer/validate", {
436
+ method: "POST",
437
+ headers: ADMIN,
438
+ });
439
+ expect(await r2.json()).toMatchObject({ ok: true, status: "valid", warnings: [] });
440
+ });
441
+
442
+ it("lookup: warns (still valid) without Organization Members read; none with it", async () => {
443
+ const seedLookup = (h: ReturnType<typeof build>) =>
444
+ h.appService.save({
445
+ role: "lookup",
446
+ appId: "555",
447
+ slug: "example-lookup-app",
448
+ privateKey: PEM,
449
+ });
450
+ const h = build({ routes: { "GET /app": "app_get_success" } });
451
+ await seedLookup(h);
452
+ const res = await h.app.request("/github-enterprise/apps/lookup/validate", {
453
+ method: "POST",
454
+ headers: ADMIN,
455
+ });
456
+ const body = (await res.json()) as { ok: boolean; warnings: string[] };
457
+ expect(body.ok).toBe(true);
458
+ expect(body.warnings).toHaveLength(1);
459
+ expect(body.warnings[0]).toContain("Members");
460
+
461
+ const h2 = build({ routes: { "GET /app": "app_get_all_permissions" } });
462
+ await seedLookup(h2);
463
+ const res2 = await h2.app.request("/github-enterprise/apps/lookup/validate", {
464
+ method: "POST",
465
+ headers: ADMIN,
466
+ });
467
+ expect(await res2.json()).toMatchObject({ ok: true, status: "valid", warnings: [] });
468
+ });
469
+
470
+ 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" } });
472
+ await seed(h);
473
+ const res = await h.app.request("/github-enterprise/apps/installer/validate", {
474
+ method: "POST",
475
+ headers: ADMIN,
476
+ });
477
+ expect(await res.json()).toMatchObject({ ok: false, status: "missing_permission" });
478
+
479
+ const e = build({ routes: { [ENT]: "enterprise_installation_403" } });
480
+ await seed(e);
481
+ const r = await e.app.request("/github-enterprise/apps/installer/validate", {
482
+ method: "POST",
483
+ headers: ADMIN,
484
+ });
485
+ expect(await r.json()).toMatchObject({ ok: false, status: "error", warnings: [] });
486
+ });
487
+
384
488
  it("lookup: checks metadata read via GET /app", async () => {
385
489
  const h = build({ routes: { "GET /app": "app_get_success" } });
386
490
  await h.appService.save({
@@ -51,6 +51,7 @@ import {
51
51
  import { GithubLookupClient } from "./github-lookup-client.ts";
52
52
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
53
53
  import { ErrorSchema } from "./openapi-schemas.ts";
54
+ import { resolveValidation } from "./github-enterprise-warnings.ts";
54
55
  import { UserRepoAccessResolver } from "./user-repo-access-resolver.ts";
55
56
 
56
57
  // ─── Deps ─────────────────────────────────────────────────────────────────────
@@ -164,6 +165,10 @@ const ValidateResultSchema = z
164
165
  requiredPermission: z.string(),
165
166
  grantedPermissions: z.record(z.string(), z.string()),
166
167
  error: z.string().nullable(),
168
+ warnings: z.array(z.string()).optional().openapi({
169
+ description:
170
+ "Advisory, non-failing notes (e.g. missing optional permissions). Never change `ok`.",
171
+ }),
167
172
  app: AppMetadataSchema.nullable(),
168
173
  })
169
174
  .openapi("GithubEnterpriseValidateResult");
@@ -687,6 +692,7 @@ export function createGithubEnterpriseApp(
687
692
  let granted: Record<string, string> = {};
688
693
  let status: "valid" | "missing_permission" | "error";
689
694
  let error: string | null = null;
695
+ let warnings: string[] = [];
690
696
  try {
691
697
  if (role === "installer") {
692
698
  if (!meta.enterpriseSlug) {
@@ -714,15 +720,19 @@ export function createGithubEnterpriseApp(
714
720
  })
715
721
  ).permissions;
716
722
  }
717
- status = required.levels.includes(granted[required.name] ?? "")
718
- ? "valid"
719
- : "missing_permission";
720
- if (status === "missing_permission") {
721
- error = `the App does not hold ${required.name} (${required.levels.join(" or ")})`;
722
- }
723
+ const resolved = resolveValidation(role, required, granted);
724
+ status = resolved.status;
725
+ error = resolved.error;
726
+ warnings = resolved.warnings;
723
727
  } catch (err) {
724
728
  status = "error";
725
- if (err instanceof GithubEnterpriseError) {
729
+ if (
730
+ err instanceof GithubEnterpriseError &&
731
+ err.kind === "not_found" &&
732
+ err.step === "installation_lookup"
733
+ ) {
734
+ error = `the App is not installed on enterprise ${meta.enterpriseSlug}, or the enterprise slug is wrong`;
735
+ } else if (err instanceof GithubEnterpriseError) {
726
736
  error = mapEnterpriseFailure(err.kind).message;
727
737
  } else if (err instanceof ApiError) {
728
738
  error = err.message;
@@ -742,6 +752,7 @@ export function createGithubEnterpriseApp(
742
752
  requiredPermission: required.name,
743
753
  grantedPermissions: granted,
744
754
  error,
755
+ warnings,
745
756
  app: updated ? serializeApp(updated) : null,
746
757
  },
747
758
  200,
@@ -117,6 +117,20 @@ function expectNoSecrets(e: Error) {
117
117
  }
118
118
 
119
119
  describe("getInstallationToken", () => {
120
+ it("tags a 404 on the enterprise installation lookup with its step (GHE-1.10)", async () => {
121
+ const { client } = makeClient({ [ENT]: "enterprise_installation_404" });
122
+ const e = await errOf(client.getInstallationToken());
123
+ expect(e.kind).toBe("not_found");
124
+ expect((e as { step?: string }).step).toBe("installation_lookup");
125
+ });
126
+
127
+ it("does not tag a 404 on the access-token mint as an installation lookup", async () => {
128
+ const { client } = makeClient({ [MINT]: "access_token_404" });
129
+ const e = await errOf(client.getInstallationToken());
130
+ expect(e.kind).toBe("not_found");
131
+ expect((e as { step?: string }).step).toBeUndefined();
132
+ });
133
+
120
134
  it("looks up the enterprise installation with a JWT then mints a token", async () => {
121
135
  const { client, calls } = makeClient({});
122
136
  const t = await client.getInstallationToken();
@@ -69,17 +69,20 @@ export class GithubEnterpriseError extends Error {
69
69
  readonly kind: GithubEnterpriseErrorKind;
70
70
  readonly status?: number;
71
71
  readonly retryAfterSeconds?: number;
72
+ /** Set when the failure came from the enterprise installation lookup step. */
73
+ readonly step?: "installation_lookup";
72
74
 
73
75
  constructor(
74
76
  kind: GithubEnterpriseErrorKind,
75
77
  message: string,
76
- opts?: { status?: number; retryAfterSeconds?: number },
78
+ opts?: { status?: number; retryAfterSeconds?: number; step?: "installation_lookup" },
77
79
  ) {
78
80
  super(message);
79
81
  this.name = "GithubEnterpriseError";
80
82
  this.kind = kind;
81
83
  this.status = opts?.status;
82
84
  this.retryAfterSeconds = opts?.retryAfterSeconds;
85
+ this.step = opts?.step;
83
86
  }
84
87
  }
85
88
 
@@ -210,12 +213,24 @@ export class GithubEnterpriseClient {
210
213
  now: this.now(),
211
214
  });
212
215
  const ent = encodeURIComponent(this.enterprise);
213
- const inst = await this.request<{ id?: number }>(
214
- "GET",
215
- `/enterprises/${ent}/installation`,
216
- jwt,
217
- "GitHub enterprise installation lookup",
218
- );
216
+ let inst: { data: { id?: number } };
217
+ try {
218
+ inst = await this.request<{ id?: number }>(
219
+ "GET",
220
+ `/enterprises/${ent}/installation`,
221
+ jwt,
222
+ "GitHub enterprise installation lookup",
223
+ );
224
+ } catch (err) {
225
+ if (err instanceof GithubEnterpriseError && err.kind === "not_found") {
226
+ throw new GithubEnterpriseError("not_found", err.message, {
227
+ status: err.status,
228
+ retryAfterSeconds: err.retryAfterSeconds,
229
+ step: "installation_lookup",
230
+ });
231
+ }
232
+ throw err;
233
+ }
219
234
  if (typeof inst.data?.id !== "number") {
220
235
  throw new GithubEnterpriseError(
221
236
  "unexpected",
@@ -0,0 +1,60 @@
1
+ /**
2
+ * admin/src/github-enterprise-warnings.ts
3
+ * GHE-1.10: pure validation logic for the enterprise GitHub Apps. Optional
4
+ * permission warnings are advisory: they are returned next to the result and
5
+ * never influence `status`, so a deployment that was valid stays valid.
6
+ * No key or token ever flows through here (only permission names/levels).
7
+ */
8
+
9
+ export type GheRole = "installer" | "lookup";
10
+ export type GheValidationStatus = "valid" | "missing_permission" | "error";
11
+
12
+ /** Warning code -> message. Codes are stable; the UI carries them in a redirect. */
13
+ export const GHE_WARNINGS = {
14
+ installer_repositories_write:
15
+ "The installer App lacks enterprise_organization_installation_repositories (write). It is not needed yet but will be required for repository management.",
16
+ lookup_members_read:
17
+ "The lookup App lacks the Organization Members (read) permission. Validation still passes; grant it to let the lookup see organization membership.",
18
+ } as const;
19
+
20
+ export type GheWarningCode = keyof typeof GHE_WARNINGS;
21
+
22
+ export function warningCodeFor(message: string): GheWarningCode | undefined {
23
+ return (Object.keys(GHE_WARNINGS) as GheWarningCode[]).find(
24
+ (k) => GHE_WARNINGS[k] === message,
25
+ );
26
+ }
27
+
28
+ export function permissionWarnings(
29
+ role: GheRole,
30
+ granted: Record<string, string>,
31
+ ): string[] {
32
+ if (role === "installer") {
33
+ return granted.enterprise_organization_installation_repositories === "write"
34
+ ? []
35
+ : [GHE_WARNINGS.installer_repositories_write];
36
+ }
37
+ return ["read", "write"].includes(granted.members ?? "")
38
+ ? []
39
+ : [GHE_WARNINGS.lookup_members_read];
40
+ }
41
+
42
+ /** Status comes from the required permission only; warnings ride alongside. */
43
+ export function resolveValidation(
44
+ role: GheRole,
45
+ required: { name: string; levels: readonly string[] },
46
+ granted: Record<string, string>,
47
+ ): {
48
+ status: "valid" | "missing_permission";
49
+ error: string | null;
50
+ warnings: string[];
51
+ } {
52
+ const ok = required.levels.includes(granted[required.name] ?? "");
53
+ return {
54
+ status: ok ? "valid" : "missing_permission",
55
+ error: ok
56
+ ? null
57
+ : `the App does not hold ${required.name} (${required.levels.join(" or ")})`,
58
+ warnings: permissionWarnings(role, granted),
59
+ };
60
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Unit tests for GHE-1.10 permission warnings: advisory only, never validity.
3
+ */
4
+
5
+ import { describe, expect, it } from "bun:test";
6
+ import {
7
+ GHE_WARNINGS,
8
+ permissionWarnings,
9
+ resolveValidation,
10
+ } from "./github-enterprise-warnings.ts";
11
+
12
+ describe("permissionWarnings", () => {
13
+ it("installer: warns unless the repositories permission is write", () => {
14
+ expect(permissionWarnings("installer", {})).toEqual([GHE_WARNINGS.installer_repositories_write]);
15
+ expect(
16
+ permissionWarnings("installer", { enterprise_organization_installation_repositories: "read" }),
17
+ ).toHaveLength(1);
18
+ expect(
19
+ permissionWarnings("installer", { enterprise_organization_installation_repositories: "write" }),
20
+ ).toEqual([]);
21
+ });
22
+
23
+ it("lookup: warns unless members is read or write", () => {
24
+ expect(permissionWarnings("lookup", { metadata: "read" })).toEqual([GHE_WARNINGS.lookup_members_read]);
25
+ expect(permissionWarnings("lookup", { members: "read" })).toEqual([]);
26
+ expect(permissionWarnings("lookup", { members: "write" })).toEqual([]);
27
+ });
28
+ });
29
+
30
+ describe("resolveValidation", () => {
31
+ const installer = { name: "enterprise_organization_installations", levels: ["write"] };
32
+
33
+ it("a warning never turns a valid result invalid", () => {
34
+ const r = resolveValidation("installer", installer, {
35
+ enterprise_organization_installations: "write",
36
+ });
37
+ expect(r.status).toBe("valid");
38
+ expect(r.warnings.length).toBeGreaterThan(0);
39
+ });
40
+
41
+ it("a missing required permission stays missing_permission with warnings alongside", () => {
42
+ const r = resolveValidation("installer", installer, {});
43
+ expect(r.status).toBe("missing_permission");
44
+ expect(r.error).toContain("enterprise_organization_installations");
45
+ });
46
+
47
+ it("validity is identical with and without the optional permissions", () => {
48
+ const without = resolveValidation("installer", installer, {
49
+ enterprise_organization_installations: "write",
50
+ });
51
+ const withAll = resolveValidation("installer", installer, {
52
+ enterprise_organization_installations: "write",
53
+ enterprise_organization_installation_repositories: "write",
54
+ });
55
+ expect(without.status).toBe(withAll.status);
56
+ expect(withAll.warnings).toEqual([]);
57
+ });
58
+ });
@@ -126,6 +126,7 @@ describe("getOrgToken", () => {
126
126
  token: "ghs_lookupInstallationTokenSecret",
127
127
  expiresAt: "2026-11-09T13:00:00Z",
128
128
  installationId: 7001,
129
+ repositorySelection: "all",
129
130
  });
130
131
  expect(calls.map((c) => `${c.method} ${c.path}`)).toEqual([INST, MINT]);
131
132
  for (const c of calls) {
@@ -135,6 +136,13 @@ describe("getOrgToken", () => {
135
136
  }
136
137
  });
137
138
 
139
+ it("reports repository_selection selected from the installation", async () => {
140
+ const { client } = makeClient({ [INST]: "org_installation_selected" });
141
+ expect((await client.getOrgToken("acme-eng")).repositorySelection).toBe(
142
+ "selected",
143
+ );
144
+ });
145
+
138
146
  it("caches per org until near expiry", async () => {
139
147
  const { client, calls } = makeClient({});
140
148
  await client.getOrgToken("acme-eng");
@@ -73,6 +73,12 @@ export interface LookupToken {
73
73
  token: string;
74
74
  expiresAt: string;
75
75
  installationId: number;
76
+ /**
77
+ * The lookup App's own installation scope on the org, from GET
78
+ * /orgs/{org}/installation (read with the App JWT, so it describes this
79
+ * App's installation). Absent when GitHub did not report a known value.
80
+ */
81
+ repositorySelection?: "all" | "selected";
76
82
  }
77
83
 
78
84
  export interface GithubLookupClientOptions {
@@ -119,7 +125,10 @@ export class GithubLookupClient {
119
125
  privateKey: this.privateKey,
120
126
  now: this.now(),
121
127
  });
122
- const inst = await this.request<{ id?: number }>(
128
+ const inst = await this.request<{
129
+ id?: number;
130
+ repository_selection?: unknown;
131
+ }>(
123
132
  "GET",
124
133
  `/orgs/${encodeURIComponent(org)}/installation`,
125
134
  jwt,
@@ -148,6 +157,10 @@ export class GithubLookupClient {
148
157
  expiresAt: minted.data.expires_at,
149
158
  installationId: inst.data.id,
150
159
  };
160
+ const selection = inst.data.repository_selection;
161
+ if (selection === "all" || selection === "selected") {
162
+ token.repositorySelection = selection;
163
+ }
151
164
  this.cached.set(key, token);
152
165
  return token;
153
166
  }
@@ -28,8 +28,9 @@ const { privateKey } = generateKeyPairSync("rsa", {
28
28
  });
29
29
 
30
30
  const NOW = new Date("2026-11-09T12:00:00Z");
31
+ const INST = "GET /orgs/acme-eng/installation";
31
32
  const BASE: Record<string, string> = {
32
- "GET /orgs/acme-eng/installation": "org_installation_success",
33
+ [INST]: "org_installation_success",
33
34
  "POST /app/installations/7001/access_tokens": "lookup_token_success",
34
35
  "GET /installation/repositories": "repos_success",
35
36
  "GET /users/octocat": "user_success",
@@ -98,6 +99,20 @@ describe("UserRepoAccessResolver against GHE-2.2 cassettes", () => {
98
99
  ]);
99
100
  });
100
101
 
102
+ it("selected installation: partial with a reason naming the selection", async () => {
103
+ const { resolver } = setup({
104
+ [INST]: "org_installation_selected",
105
+ [API]: "permission_maintain",
106
+ [WEB]: "permission_triage",
107
+ });
108
+ const res = await resolver.resolve("octocat");
109
+ expect(res.complete).toBe(false);
110
+ expect(res.orgs[0].status).toBe("partial");
111
+ expect(res.orgs[0].reason).toContain("selected repositories");
112
+ expect(res.orgs[0].repos).toHaveLength(2);
113
+ expect(res.orgs[0].unresolved).toBe(0);
114
+ });
115
+
101
116
  it("partial run: 429 mid-org keeps resolved and stops further calls", async () => {
102
117
  const { resolver, calls } = setup({
103
118
  [API]: "permission_write",
@@ -58,8 +58,14 @@ export interface OrgAccessResult {
58
58
  repos: ResolvedRepoAccess[];
59
59
  /** Repos that could not be checked. Never reported as "none". */
60
60
  unresolved: number;
61
+ /** Why the org is not "ok" when the cause is the lookup install scope. */
62
+ reason?: string;
61
63
  }
62
64
 
65
+ /** Shown when the lookup App is installed on selected repositories only. */
66
+ export const SELECTED_REPOS_REASON =
67
+ "lookup app is installed on selected repositories only; install it on all repositories";
68
+
63
69
  export interface UserRepoAccessResult {
64
70
  username: string;
65
71
  outcome: "ok" | "user_not_found";
@@ -173,8 +179,10 @@ export class UserRepoAccessResolver {
173
179
  username: string,
174
180
  ): Promise<OrgAccessResult> {
175
181
  let repos: LookupRepository[];
182
+ let selectedOnly = false;
176
183
  try {
177
- await this.lookup.getOrgToken(org);
184
+ const token = await this.lookup.getOrgToken(org);
185
+ selectedOnly = token.repositorySelection === "selected";
178
186
  repos = await this.lookup.listInstallationRepositories(org);
179
187
  } catch (e) {
180
188
  return orgLevelFailure(org, e);
@@ -221,6 +229,16 @@ export class UserRepoAccessResolver {
221
229
  else if (list.length > 0) status = "partial";
222
230
  else if (stop === "rate_limit") status = "rate_limited";
223
231
  else status = "error";
232
+ // A selected-only install lists a subset that looks complete: never "ok".
233
+ if (selectedOnly && status === "ok") {
234
+ return {
235
+ org,
236
+ status: "partial",
237
+ repos: list,
238
+ unresolved,
239
+ reason: SELECTED_REPOS_REASON,
240
+ };
241
+ }
224
242
  return { org, status, repos: list, unresolved };
225
243
  }
226
244
 
@@ -31,6 +31,7 @@ interface FakeOpts {
31
31
  perm?: (owner: string, repo: string) => RepoRole | Error | Promise<RepoRole>;
32
32
  token?: Record<string, Error>;
33
33
  user?: Error;
34
+ selection?: Record<string, "all" | "selected">;
34
35
  }
35
36
 
36
37
  function fake(o: FakeOpts = {}) {
@@ -40,7 +41,14 @@ function fake(o: FakeOpts = {}) {
40
41
  async getOrgToken(org) {
41
42
  const e = o.token?.[org];
42
43
  if (e) throw e;
43
- return { token: "ghs_secret", expiresAt: "x", installationId: 1 };
44
+ return {
45
+ token: "ghs_secret",
46
+ expiresAt: "x",
47
+ installationId: 1,
48
+ ...(o.selection?.[org]
49
+ ? { repositorySelection: o.selection[org] }
50
+ : {}),
51
+ };
44
52
  },
45
53
  async getUser(_org, login) {
46
54
  if (o.user) throw o.user;
@@ -70,6 +78,31 @@ function fake(o: FakeOpts = {}) {
70
78
  return { resolver, calls };
71
79
  }
72
80
 
81
+ describe("selected-repositories installation", () => {
82
+ it("marks the org partial with a reason and keeps resolved repos", async () => {
83
+ const { resolver } = fake({
84
+ repos: { acme: ["a"], beta: ["b"] },
85
+ selection: { acme: "selected", beta: "all" },
86
+ });
87
+ const res = await resolver.resolve("octocat");
88
+ const [acme, beta] = res.orgs;
89
+ expect(acme.status).toBe("partial");
90
+ expect(acme.reason).toContain("selected repositories");
91
+ expect(acme.repos).toHaveLength(1);
92
+ expect(beta.status).toBe("ok");
93
+ expect(beta.reason).toBeUndefined();
94
+ expect(res.complete).toBe(false);
95
+ });
96
+
97
+ it("an all-repositories or unreported selection is unchanged", async () => {
98
+ const { resolver } = fake({ selection: { acme: "all" } });
99
+ const res = await resolver.resolve("octocat");
100
+ expect(res.orgs[0].status).toBe("ok");
101
+ expect(res.orgs[0].reason).toBeUndefined();
102
+ expect(res.complete).toBe(true);
103
+ });
104
+ });
105
+
73
106
  describe("canPushForRole", () => {
74
107
  const cases: Array<[RepoRole, boolean]> = [
75
108
  ["admin", true],