@app-vitals/agent-admin 1.22.0 → 1.24.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.22.0",
3
+ "version": "1.24.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.22.0",
45
+ "@app-vitals/agent-lib": "1.24.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,7 +7,10 @@
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
+ import {
11
+ GHE_WARNINGS,
12
+ type GheWarningCode,
13
+ } from "./github-enterprise-warnings.ts";
11
14
  import { renderAdminPage } from "./admin-ui-layout.ts";
12
15
  import { escapeHtml, renderAdminToolbar } from "./admin-ui-styles.ts";
13
16
 
@@ -79,14 +82,39 @@ function validationBadge(status: string | null): string {
79
82
  const ROLE_COPY = {
80
83
  installer: {
81
84
  title: "Installer app",
82
- help: "Installs agents' GitHub Apps on the enterprise's organizations. Needs the enterprise_organization_installations (write) permission.",
85
+ descriptor:
86
+ "Auto-installs agents' GitHub Apps on your enterprise's organizations.",
87
+ steps: [
88
+ "In GitHub, open your enterprise's Settings → GitHub Apps → New GitHub App (an enterprise-owned App).",
89
+ "Under Enterprise permissions, grant both <code>enterprise_organization_installations</code> and <code>enterprise_organization_installation_repositories</code> at <strong>Read and write</strong>.",
90
+ "Create the App. The App ID is on the App's settings page; the App slug is the last part of its public URL (<code>github.com/apps/&lt;slug&gt;</code>).",
91
+ "The enterprise slug is the last part of your enterprise's URL (<code>github.com/enterprises/&lt;slug&gt;</code>).",
92
+ "Under Private keys, choose Generate a private key and paste the downloaded PEM below.",
93
+ ],
83
94
  },
84
95
  lookup: {
85
96
  title: "Lookup app",
86
- help: "Read-only App used to see which organizations the platform can look up. Needs the metadata (read) permission.",
97
+ descriptor:
98
+ "Read-only App that gives the platform repository access lookups. Optional.",
99
+ steps: [
100
+ "In GitHub, open your organization's Settings &rarr; Developer settings &rarr; GitHub Apps &rarr; New GitHub App.",
101
+ "Grant Repository <code>Metadata</code> at <strong>Read</strong> and Organization <code>Members</code> at <strong>Read</strong>.",
102
+ "Create the App. The App ID is on the App's settings page; the App slug is the last part of its public URL (<code>github.com/apps/&lt;slug&gt;</code>).",
103
+ "It must be installed on all repositories of each organization, not selected repositories only.",
104
+ "Under Private keys, choose Generate a private key and paste the downloaded PEM below.",
105
+ ],
87
106
  },
88
107
  } as const;
89
108
 
109
+ const IGNORED_OPTIONS =
110
+ "Ignore these options: callback URL, request user authorization, expire user authorization tokens, device flow, and webhook (uncheck Active).";
111
+
112
+ function guidance(role: "installer" | "lookup"): string {
113
+ const copy = ROLE_COPY[role];
114
+ return `<ol class="help-text gh-ent-steps" style="font-size:12px;margin:8px 0;padding-left:20px">${copy.steps.map((x) => `<li>${x}</li>`).join("")}</ol>
115
+ <p class="help-text gh-ent-ignore" style="font-size:12px;margin:8px 0">${IGNORED_OPTIONS}</p>`;
116
+ }
117
+
90
118
  function statusLine(app: GheApp): string {
91
119
  const validated = app.lastValidatedAt
92
120
  ? ` &middot; ${escapeHtml(formatTime(app.lastValidatedAt))}`
@@ -110,9 +138,14 @@ function postButton(
110
138
  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>`;
111
139
  }
112
140
 
113
- function warningsBlock(role: "installer" | "lookup", codes: string[] | undefined): string {
141
+ function warningsBlock(
142
+ role: "installer" | "lookup",
143
+ codes: string[] | undefined,
144
+ ): string {
114
145
  return (codes ?? [])
115
- .filter((c): c is GheWarningCode => c in GHE_WARNINGS && c.startsWith(`${role}_`))
146
+ .filter(
147
+ (c): c is GheWarningCode => c in GHE_WARNINGS && c.startsWith(`${role}_`),
148
+ )
116
149
  .map(
117
150
  (c) =>
118
151
  `<div class="help-text gh-ent-warning" style="font-size:12px;margin-top:4px">Warning: ${escapeHtml(GHE_WARNINGS[c])}</div>`,
@@ -138,13 +171,15 @@ function appCard(
138
171
  : "";
139
172
  return `<div class="card">
140
173
  <div class="card-title">${copy.title}</div>
141
- <p class="help-text" style="font-size:12px">${copy.help}</p>
174
+ <p class="help-text" style="font-size:12px">${copy.descriptor}</p>
175
+ ${guidance(role)}
142
176
  ${summary}
143
- <form method="POST" action="${action}" style="display:grid;gap:8px;max-width:480px">
177
+ <form method="POST" action="${action}" enctype="multipart/form-data" style="display:grid;gap:8px;max-width:480px">
144
178
  <label>App ID <input name="appId" class="form-input" required inputmode="numeric" pattern="[0-9]+" /></label>
145
179
  <label>App slug <input name="slug" class="form-input" required /></label>
146
180
  ${enterprise}
147
- <label>Private key (PEM) <textarea name="privateKey" class="form-input" rows="4" required autocomplete="off" spellcheck="false" placeholder="Paste the private key. It is stored encrypted and never shown again."></textarea></label>
181
+ <label>Private key (PEM) <textarea name="privateKey" class="form-input" rows="4" autocomplete="off" spellcheck="false" placeholder="Paste the private key. It is stored encrypted and never shown again."></textarea></label>
182
+ <label>Or upload the .pem file <input type="file" name="privateKeyFile" accept=".pem,application/x-pem-file" class="form-input" /></label>
148
183
  <div><button type="submit" class="btn btn-primary">${app ? "Replace credentials" : "Save credentials"}</button></div>
149
184
  </form>
150
185
  </div>`;
@@ -221,10 +256,9 @@ export function renderGithubEnterpriseSettingsPage(
221
256
  const notice = opts.notice
222
257
  ? `<div class="alert alert-success">${escapeHtml(opts.notice)}</div>`
223
258
  : "";
224
- const emptyState = status.configured
225
- ? ""
226
- : `<div class="card"><div class="card-title">Not configured</div>
227
- <p>This feature is optional. Without it, agents are provisioned exactly as before. Configure an installer app to install agents' GitHub Apps on your enterprise's organizations from here, and a lookup app to see which organizations are reachable. Paste the credentials of Apps you created in GitHub below.</p>
259
+ const intro = `<div class="card">
260
+ <p>Configure an installer app to auto-install agent apps on your enterprise's organizations, and a lookup app for repository access. Both are optional.</p>
261
+ <p class="help-text gh-ent-required" style="margin-top:8px"><strong>A GitHub Enterprise Cloud enterprise is required.</strong> These Apps are created in and scoped to an enterprise.</p>
228
262
  </div>`;
229
263
 
230
264
  return renderAdminPage({
@@ -232,7 +266,7 @@ export function renderGithubEnterpriseSettingsPage(
232
266
  body: `${renderAdminToolbar(opts.userEmail, BASE)}
233
267
  <div class="vos-page">
234
268
  <div class="page-header"><h1 class="page-title">GitHub Enterprise apps</h1></div>
235
- ${error}${notice}${emptyState}
269
+ ${error}${notice}${intro}
236
270
  ${appCard("installer", status.installer, opts.warnings)}
237
271
  ${appCard("lookup", status.lookup, opts.warnings)}
238
272
  ${orgsCard(opts)}
@@ -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
  );
@@ -47,10 +48,45 @@ describe("renderGithubEnterpriseSettingsPage", () => {
47
48
  );
48
49
  expect(html).toContain('name="enterpriseSlug"');
49
50
  expect(html).toContain('name="privateKey"');
51
+ expect(html).toContain('name="privateKeyFile"');
52
+ expect(html).toContain('enctype="multipart/form-data"');
50
53
  expect(html).not.toContain("/validate");
51
54
  expect(html).not.toContain("Organizations</div>");
52
55
  });
53
56
 
57
+ test("intro and enterprise-required notice render; old wording is gone", () => {
58
+ for (const status of [
59
+ empty,
60
+ { configured: true, installer: app(), lookup: null },
61
+ ]) {
62
+ const html = renderGithubEnterpriseSettingsPage({ ...base, status });
63
+ expect(html).toContain("auto-install agent apps");
64
+ expect(html).toContain("lookup app for repository access");
65
+ expect(html).toContain("GitHub Enterprise Cloud enterprise is required");
66
+ expect(html).not.toContain("exactly as before");
67
+ }
68
+ });
69
+
70
+ test("each card lists permissions, field locations and options to ignore", () => {
71
+ const html = renderGithubEnterpriseSettingsPage({ ...base, status: empty });
72
+ expect(html.match(/gh-ent-steps/g)?.length).toBe(2);
73
+ expect(html.match(/gh-ent-ignore/g)?.length).toBe(2);
74
+ expect(html).toContain("enterprise_organization_installations");
75
+ expect(html).toContain("Read and write");
76
+ expect(html).toContain("<code>Metadata</code>");
77
+ expect(html).toContain("<code>Members</code>");
78
+ expect(html).toContain("github.com/enterprises/");
79
+ expect(html).toContain("Generate a private key");
80
+ for (const opt of [
81
+ "callback URL",
82
+ "request user authorization",
83
+ "device flow",
84
+ "webhook",
85
+ ]) {
86
+ expect(html).toContain(opt);
87
+ }
88
+ });
89
+
54
90
  test("only the installer form asks for an enterprise slug", () => {
55
91
  const html = renderGithubEnterpriseSettingsPage({ ...base, status: empty });
56
92
  expect(html.match(/name="enterpriseSlug"/g)?.length).toBe(1);
@@ -105,7 +141,11 @@ describe("renderGithubEnterpriseSettingsPage", () => {
105
141
  test("warnings render on the matching card only, as non-error notes", () => {
106
142
  const html = renderGithubEnterpriseSettingsPage({
107
143
  ...base,
108
- status: { configured: true, installer: app(), lookup: app({ role: "lookup", enterpriseSlug: null }) },
144
+ status: {
145
+ configured: true,
146
+ installer: app(),
147
+ lookup: app({ role: "lookup", enterpriseSlug: null }),
148
+ },
109
149
  warnings: ["installer_repositories_write"],
110
150
  });
111
151
  expect(html).toContain("enterprise_organization_installation_repositories");
@@ -158,6 +158,79 @@ describe("GET /admin/settings/github-enterprise", () => {
158
158
  expect(html).toContain("optional");
159
159
  expect(html).toContain("Installer app");
160
160
  });
161
+
162
+ it("renders setup guidance on both cards and the enterprise notice", async () => {
163
+ const { app } = setup();
164
+ const html = await (await app.request(BASE)).text();
165
+ expect(html).toContain("GitHub Enterprise Cloud enterprise is required");
166
+ expect(html).not.toContain("exactly as before");
167
+ expect(html.match(/gh-ent-steps/g)?.length).toBe(2);
168
+ expect(html.match(/gh-ent-ignore/g)?.length).toBe(2);
169
+ });
170
+ });
171
+
172
+ const upload = (fields: Record<string, string>, file?: File) => {
173
+ const body = new FormData();
174
+ for (const [k, v] of Object.entries(fields)) body.set(k, v);
175
+ if (file) body.set("privateKeyFile", file);
176
+ return { method: "POST", body };
177
+ };
178
+
179
+ describe("private key upload", () => {
180
+ it("stores the same key as the paste path and never renders it", async () => {
181
+ const pasted = setup();
182
+ await pasted.app.request(
183
+ `${BASE}/apps/lookup`,
184
+ form({ appId: "42", slug: "acme-lookup", privateKey: PEM }),
185
+ );
186
+ const uploaded = setup();
187
+ const res = await uploaded.app.request(
188
+ `${BASE}/apps/lookup`,
189
+ upload(
190
+ { appId: "42", slug: "acme-lookup" },
191
+ new File([PEM], "key.pem", { type: "application/x-pem-file" }),
192
+ ),
193
+ );
194
+ expect(res.status).toBe(302);
195
+ expect(await uploaded.appService.get("lookup")).toEqual(
196
+ await pasted.appService.get("lookup"),
197
+ );
198
+ expect(await uploaded.appService.getPrivateKey("lookup")).toBe(
199
+ await pasted.appService.getPrivateKey("lookup"),
200
+ );
201
+ const html = await (await uploaded.app.request(BASE)).text();
202
+ expect(html).not.toContain("PRIVATE KEY");
203
+ });
204
+
205
+ it("rejects a non-PEM file and stores nothing", async () => {
206
+ const { app, appService } = setup();
207
+ const res = await app.request(
208
+ `${BASE}/apps/lookup`,
209
+ upload(
210
+ { appId: "42", slug: "acme-lookup" },
211
+ new File(["not-a-pem-SECRET"], "key.pem"),
212
+ ),
213
+ );
214
+ expect(res.status).toBe(400);
215
+ const html = await res.text();
216
+ expect(html).toContain("not a PEM private key");
217
+ expect(html).not.toContain("not-a-pem-SECRET");
218
+ expect(await appService.get("lookup")).toBeNull();
219
+ });
220
+
221
+ it("rejects an oversized file and stores nothing", async () => {
222
+ const { app, appService } = setup();
223
+ const res = await app.request(
224
+ `${BASE}/apps/lookup`,
225
+ upload(
226
+ { appId: "42", slug: "acme-lookup" },
227
+ new File([PEM + "A".repeat(20 * 1024)], "key.pem"),
228
+ ),
229
+ );
230
+ expect(res.status).toBe(400);
231
+ expect(await res.text()).toContain("too large");
232
+ expect(await appService.get("lookup")).toBeNull();
233
+ });
161
234
  });
162
235
 
163
236
  describe("form posts", () => {
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import type { Context, Hono, MiddlewareHandler } from "hono";
11
+ import { readPrivateKeyField } from "./github-enterprise-pem-upload.ts";
11
12
  import { warningCodeFor } from "./github-enterprise-warnings.ts";
12
13
  import type { AdminUIEnv } from "./admin-ui.ts";
13
14
  import {
@@ -158,12 +159,14 @@ export function registerAdminGithubEnterpriseRoutes(
158
159
  if (!isRole(role)) return new Response("Not Found", { status: 404 });
159
160
  const form = await readForm(c);
160
161
  const enterpriseSlug = field(form, "enterpriseSlug");
162
+ const key = await readPrivateKeyField(form);
163
+ if (!key.ok) return renderPage(c, { error: key.error, status: 400 });
161
164
  const r = await call(c, "PUT", `/github-enterprise/apps/${role}`, {
162
165
  appId: field(form, "appId"),
163
166
  slug: field(form, "slug"),
164
167
  ...(enterpriseSlug ? { enterpriseSlug } : {}),
165
- // Pasted as-is; never trimmed away from or echoed back to the page.
166
- privateKey: form.get("privateKey")?.toString() ?? "",
168
+ // Pasted or uploaded; never echoed back to the page.
169
+ privateKey: key.pem,
167
170
  });
168
171
  return r.ok ? back(c, "saved") : fail(c, r);
169
172
  });
@@ -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({
@@ -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": {
@@ -17,6 +17,10 @@ import { AgentPluginService } from "./agent-plugins.ts";
17
17
  import { AgentService } from "./agents.ts";
18
18
  import { createAgentRuntimeApp } from "./api.ts";
19
19
  import { parseAdminApiKeys } from "./api-auth.ts";
20
+ import type { MiddlewareHandler } from "hono";
21
+ import { Hono } from "hono";
22
+ import { type AdminUIEnv } from "./admin-ui.ts";
23
+ import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
20
24
  import { createGithubEnterpriseApp } from "./github-enterprise-api.ts";
21
25
  import { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
22
26
  import { createAdminPrismaClient } from "./prisma-client.ts";
@@ -122,6 +126,55 @@ describeOrSkip("github-enterprise API (integration)", () => {
122
126
  expect(await prisma.gitHubEnterpriseApp.count()).toBe(0);
123
127
  });
124
128
 
129
+ it("a .pem upload through the settings UI saves the same row as pasting", async () => {
130
+ const api = build();
131
+ const ui = new Hono<AdminUIEnv>();
132
+ registerAdminGithubEnterpriseRoutes(ui, {
133
+ requireAuth: (async (c, next) => {
134
+ c.set("userEmail", "admin@x.com");
135
+ c.set("isAdmin", true);
136
+ await next();
137
+ }) as MiddlewareHandler<AdminUIEnv>,
138
+ html: (content, o) => new Response(content, { status: o?.status ?? 200 }),
139
+ api: (path, init) =>
140
+ api.request(path, {
141
+ ...init,
142
+ headers: { ...(init?.headers ?? {}), ...ADMIN },
143
+ }),
144
+ });
145
+ const base = "/admin/settings/github-enterprise/apps/lookup";
146
+ const fields = { appId: "777", slug: "example-lookup" };
147
+ const snapshot = async () => {
148
+ const row = await prisma.gitHubEnterpriseApp.findUnique({
149
+ where: { role: "lookup" },
150
+ });
151
+ return {
152
+ appId: row?.appId,
153
+ slug: row?.slug,
154
+ enterpriseSlug: row?.enterpriseSlug,
155
+ key: await appService.getPrivateKey("lookup"),
156
+ };
157
+ };
158
+
159
+ const body = new FormData();
160
+ for (const [k, v] of Object.entries(fields)) body.set(k, v);
161
+ body.set("privateKey", PEM);
162
+ expect((await ui.request(base, { method: "POST", body })).status).toBe(302);
163
+ const pasted = await snapshot();
164
+
165
+ await prisma.gitHubEnterpriseApp.deleteMany();
166
+ const upload = new FormData();
167
+ for (const [k, v] of Object.entries(fields)) upload.set(k, v);
168
+ upload.set("privateKeyFile", new File([PEM], "key.pem"));
169
+ const res = await ui.request(base, { method: "POST", body: upload });
170
+ expect(res.status).toBe(302);
171
+ expect(await snapshot()).toEqual(pasted);
172
+ const row = await prisma.gitHubEnterpriseApp.findUnique({
173
+ where: { role: "lookup" },
174
+ });
175
+ expect(row?.privateKeyEncrypted).not.toContain(PEM_BODY);
176
+ });
177
+
125
178
  it("PUT then validate persists the result; the key is encrypted and never returned", async () => {
126
179
  const app = build();
127
180
  const saved = await put(app);
@@ -81,4 +81,28 @@ describe("GitHub Enterprise key isolation", () => {
81
81
  expect(src).not.toMatch(/enterprise/i);
82
82
  }
83
83
  });
84
+
85
+ it("the upload route and parser never touch the key-bearing service", () => {
86
+ for (const rel of [
87
+ "admin/src/admin-ui-github-enterprise.ts",
88
+ "admin/src/github-enterprise-pem-upload.ts",
89
+ ]) {
90
+ const src = readFileSync(join(REPO, rel), "utf-8");
91
+ expect(src).not.toMatch(/\.getPrivateKey\(|privateKeyEncrypted/);
92
+ expect(src).not.toMatch(/github-enterprise-apps/);
93
+ // Uploaded content is never logged.
94
+ expect(src).not.toMatch(/console\.|logger\./);
95
+ }
96
+ });
97
+
98
+ it("the upload field name is only handled by the pem-upload parser", () => {
99
+ const handlers = files
100
+ .map((f) => relative(REPO, f))
101
+ .filter((rel) =>
102
+ /get\(["']privateKeyFile["']\)/.test(
103
+ readFileSync(join(REPO, rel), "utf-8"),
104
+ ),
105
+ );
106
+ expect(handlers).toEqual(["admin/src/github-enterprise-pem-upload.ts"]);
107
+ });
84
108
  });
@@ -0,0 +1,47 @@
1
+ /**
2
+ * admin/src/github-enterprise-pem-upload.ts
3
+ * Parses the private-key field of the GHE settings form (GHE-1.12): a pasted
4
+ * value or an uploaded .pem file. Pure and key-service free; errors are fixed
5
+ * strings that never include any submitted content.
6
+ */
7
+
8
+ /** A PEM private key is ~1.7 KB (RSA 2048) to ~3.3 KB (RSA 4096); 16 KB is generous. */
9
+ export const MAX_PEM_BYTES = 16 * 1024;
10
+
11
+ const PEM_PRIVATE_KEY =
12
+ /^-----BEGIN (?:RSA |EC |ENCRYPTED )?PRIVATE KEY-----[\s\S]+-----END (?:RSA |EC |ENCRYPTED )?PRIVATE KEY-----$/;
13
+
14
+ export type PemResult =
15
+ | { ok: true; pem: string }
16
+ | { ok: false; error: string };
17
+
18
+ /** Returns the key from the uploaded file when one was chosen, else the pasted text. */
19
+ export async function readPrivateKeyField(form: FormData): Promise<PemResult> {
20
+ const file = form.get("privateKeyFile");
21
+ if (file instanceof File && file.size > 0) {
22
+ if (file.size > MAX_PEM_BYTES) {
23
+ return {
24
+ ok: false,
25
+ error: `The key file is too large (limit ${MAX_PEM_BYTES / 1024} KB).`,
26
+ };
27
+ }
28
+ return checkPem(await file.text(), "The file is not a PEM private key.");
29
+ }
30
+ const pasted = form.get("privateKey")?.toString() ?? "";
31
+ if (!pasted.trim()) {
32
+ return { ok: false, error: "Paste a private key or choose a .pem file." };
33
+ }
34
+ // Multipart and browser textareas submit CRLF; the API validates the key.
35
+ return { ok: true, pem: normalizeNewlines(pasted) };
36
+ }
37
+
38
+ function checkPem(text: string, error: string): PemResult {
39
+ return PEM_PRIVATE_KEY.test(text.trim())
40
+ ? { ok: true, pem: normalizeNewlines(text) }
41
+ : { ok: false, error };
42
+ }
43
+
44
+ /** Both paths store LF so an upload and a paste save identical rows. */
45
+ function normalizeNewlines(text: string): string {
46
+ return text.replace(/\r\n/g, "\n");
47
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * admin/src/github-enterprise-pem-upload.unit.test.ts
3
+ * Unit tests for the paste-or-upload private key parsing (GHE-1.12).
4
+ */
5
+
6
+ import { describe, expect, it } from "bun:test";
7
+ import { generateKeyPairSync } from "node:crypto";
8
+ import {
9
+ MAX_PEM_BYTES,
10
+ readPrivateKeyField,
11
+ } from "./github-enterprise-pem-upload.ts";
12
+
13
+ const { privateKey: PEM } = generateKeyPairSync("rsa", {
14
+ modulusLength: 2048,
15
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
16
+ publicKeyEncoding: { type: "spki", format: "pem" },
17
+ });
18
+
19
+ const formWith = (entries: Record<string, string | File>) => {
20
+ const f = new FormData();
21
+ for (const [k, v] of Object.entries(entries)) f.set(k, v);
22
+ return f;
23
+ };
24
+ const pemFile = (body: string) =>
25
+ new File([body], "app.private-key.pem", { type: "application/x-pem-file" });
26
+
27
+ describe("readPrivateKeyField", () => {
28
+ it("returns an uploaded valid PEM unchanged", async () => {
29
+ const r = await readPrivateKeyField(
30
+ formWith({ privateKeyFile: pemFile(PEM) }),
31
+ );
32
+ expect(r).toEqual({ ok: true, pem: PEM });
33
+ });
34
+
35
+ it("accepts RSA and EC private key headers", async () => {
36
+ for (const kind of ["RSA ", "EC ", ""]) {
37
+ const body = `-----BEGIN ${kind}PRIVATE KEY-----\nQUJD\n-----END ${kind}PRIVATE KEY-----`;
38
+ const r = await readPrivateKeyField(
39
+ formWith({ privateKeyFile: pemFile(body) }),
40
+ );
41
+ expect(r.ok).toBe(true);
42
+ }
43
+ });
44
+
45
+ it("prefers the file over pasted text", async () => {
46
+ const r = await readPrivateKeyField(
47
+ formWith({ privateKeyFile: pemFile(PEM), privateKey: "pasted" }),
48
+ );
49
+ expect(r).toEqual({ ok: true, pem: PEM });
50
+ });
51
+
52
+ it("passes pasted text through unchanged when no file is chosen", async () => {
53
+ const r = await readPrivateKeyField(
54
+ formWith({ privateKey: PEM, privateKeyFile: new File([], "") }),
55
+ );
56
+ expect(r).toEqual({ ok: true, pem: PEM });
57
+ });
58
+
59
+ it("stores CRLF uploads and pastes identically (LF)", async () => {
60
+ const crlf = PEM.replace(/\n/g, "\r\n");
61
+ const up = await readPrivateKeyField(
62
+ formWith({ privateKeyFile: pemFile(crlf) }),
63
+ );
64
+ const paste = await readPrivateKeyField(formWith({ privateKey: crlf }));
65
+ expect(up).toEqual({ ok: true, pem: PEM });
66
+ expect(paste).toEqual(up);
67
+ });
68
+
69
+ it("rejects a non-PEM file without echoing its content", async () => {
70
+ const r = await readPrivateKeyField(
71
+ formWith({ privateKeyFile: pemFile("hunter2-SECRET not a key") }),
72
+ );
73
+ expect(r.ok).toBe(false);
74
+ if (!r.ok) {
75
+ expect(r.error).toContain("not a PEM private key");
76
+ expect(r.error).not.toContain("hunter2");
77
+ }
78
+ });
79
+
80
+ it("rejects a public key or certificate PEM", async () => {
81
+ for (const kind of ["PUBLIC KEY", "CERTIFICATE"]) {
82
+ const r = await readPrivateKeyField(
83
+ formWith({
84
+ privateKeyFile: pemFile(
85
+ `-----BEGIN ${kind}-----\nQUJD\n-----END ${kind}-----`,
86
+ ),
87
+ }),
88
+ );
89
+ expect(r.ok).toBe(false);
90
+ }
91
+ });
92
+
93
+ it("rejects an oversized file", async () => {
94
+ const big = `${PEM}${"A".repeat(MAX_PEM_BYTES)}`;
95
+ const r = await readPrivateKeyField(
96
+ formWith({ privateKeyFile: pemFile(big) }),
97
+ );
98
+ expect(r.ok).toBe(false);
99
+ if (!r.ok) expect(r.error).toContain("too large");
100
+ });
101
+
102
+ it("rejects when neither a file nor text is provided", async () => {
103
+ const r = await readPrivateKeyField(formWith({ privateKey: " " }));
104
+ expect(r.ok).toBe(false);
105
+ });
106
+ });
@@ -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],