@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.
@@ -111,8 +111,23 @@ const OrgParamSchema = z.object({
111
111
  .openapi({ param: { name: "org", in: "path" }, example: "example-org" }),
112
112
  });
113
113
 
114
+ const AccountQuerySchema = z.object({
115
+ accountId: z
116
+ .string()
117
+ .min(1)
118
+ .optional()
119
+ .openapi({
120
+ param: { name: "accountId", in: "query" },
121
+ description:
122
+ "Account whose App pair to read/write. Omit for the deployment-wide pair.",
123
+ }),
124
+ });
125
+
114
126
  const AppMetadataSchema = z
115
127
  .object({
128
+ accountId: z.string().nullable().optional().openapi({
129
+ description: "Null for the deployment-wide App.",
130
+ }),
116
131
  role: z.string().openapi({ example: "installer" }),
117
132
  appId: z.string().openapi({ example: "12345" }),
118
133
  slug: z.string().openapi({ example: "example-installer" }),
@@ -168,7 +183,7 @@ const ValidateResultSchema = z
168
183
  })
169
184
  .openapi("GithubEnterpriseValidateResult");
170
185
 
171
- const OrgsQuerySchema = z.object({
186
+ const OrgsQuerySchema = AccountQuerySchema.extend({
172
187
  agentId: z
173
188
  .string()
174
189
  .min(1)
@@ -253,6 +268,7 @@ const statusRoute = createRoute({
253
268
  summary: "GitHub Enterprise App status",
254
269
  description:
255
270
  "Admin-only. Metadata and key-set flag per role; never the key. Returns configured=false with null roles when nothing is set.",
271
+ request: { query: AccountQuerySchema },
256
272
  responses: {
257
273
  200: {
258
274
  description: "Status",
@@ -271,6 +287,7 @@ const putRoute = createRoute({
271
287
  "Admin-only. Stores the App id, slug, enterprise slug (installer) and the encrypted private key, and resets validation state. 422 when SHIPWRIGHT_ENCRYPTION_KEY is not configured.",
272
288
  request: {
273
289
  params: RoleParamSchema,
290
+ query: AccountQuerySchema,
274
291
  body: { content: { "application/json": { schema: PutAppBodySchema } } },
275
292
  },
276
293
  responses: {
@@ -293,7 +310,7 @@ const deleteRoute = createRoute({
293
310
  tags,
294
311
  summary: "Remove the App for a role",
295
312
  description: "Admin-only. No-op when the role is not configured.",
296
- request: { params: RoleParamSchema },
313
+ request: { params: RoleParamSchema, query: AccountQuerySchema },
297
314
  responses: {
298
315
  204: { description: "Removed" },
299
316
  ...errorResponses,
@@ -307,7 +324,7 @@ const validateRoute = createRoute({
307
324
  summary: "Validate the App for a role",
308
325
  description:
309
326
  "Admin-only. Authenticates as the App and checks the required permission (installer: enterprise_organization_installations write; lookup: metadata read). The outcome is persisted and returned; GitHub failures are reported as status=error with a generic message.",
310
- request: { params: RoleParamSchema },
327
+ request: { params: RoleParamSchema, query: AccountQuerySchema },
311
328
  responses: {
312
329
  200: {
313
330
  description: "Validation outcome",
@@ -345,6 +362,7 @@ const installRoute = createRoute({
345
362
  "Admin-only. Uses the agent's stored GH_APP_CLIENT_ID when set; otherwise resolves the stored GH_APP_SLUG and looks the App up through the public GET /apps/{slug} to get its client id. Installs it on the org with the installer App. 422 for an agent with neither a stored client id nor a slug, and for a private App (not visible to the public lookup) with no stored client id; 409 when the installer App is not configured.",
346
363
  request: {
347
364
  params: OrgParamSchema,
365
+ query: AccountQuerySchema,
348
366
  body: { content: { "application/json": { schema: InstallBodySchema } } },
349
367
  },
350
368
  responses: {
@@ -417,6 +435,7 @@ export function mapEnterpriseFailure(kind: GithubEnterpriseErrorKind): Mapped {
417
435
 
418
436
  function serializeApp(m: GitHubEnterpriseAppMetadata) {
419
437
  return {
438
+ accountId: m.accountId ?? null,
420
439
  role: m.role,
421
440
  appId: m.appId,
422
441
  slug: m.slug,
@@ -444,17 +463,17 @@ export function createGithubAccessPreview(
444
463
  "appService" | "fetchFn" | "apiBase" | "now"
445
464
  >,
446
465
  ): GithubAccessPreviewFn {
447
- return async (username) => {
466
+ return async (username, accountId) => {
448
467
  const [installer, lookup] = await Promise.all([
449
- deps.appService.get("installer"),
450
- deps.appService.get("lookup"),
468
+ deps.appService.get("installer", accountId),
469
+ deps.appService.get("lookup", accountId),
451
470
  ]);
452
471
  if (!installer || !lookup || !installer.enterpriseSlug) {
453
472
  return { status: "unconfigured" };
454
473
  }
455
474
  const [installerKey, lookupKey] = await Promise.all([
456
- deps.appService.getPrivateKey("installer"),
457
- deps.appService.getPrivateKey("lookup"),
475
+ deps.appService.getPrivateKey("installer", accountId),
476
+ deps.appService.getPrivateKey("lookup", accountId),
458
477
  ]);
459
478
  if (!installerKey || !lookupKey) return { status: "unconfigured" };
460
479
 
@@ -498,40 +517,48 @@ export function createGithubLookupService(
498
517
  > & {
499
518
  /** Test seam: replaces the clients built from the stored Apps. */
500
519
  clients?: {
501
- installer: LookupInstallerPort;
520
+ installer?: LookupInstallerPort;
502
521
  lookup: LookupRepositoriesPort;
503
522
  };
504
523
  },
505
524
  ): GithubLookupService {
506
525
  return {
507
- async listRepositories() {
526
+ async listRepositories(accountId) {
508
527
  let clients = deps.clients;
509
528
  if (!clients) {
510
529
  const [installer, lookup] = await Promise.all([
511
- deps.appService.get("installer"),
512
- deps.appService.get("lookup"),
513
- ]);
514
- if (!installer || !lookup || !installer.enterpriseSlug) {
515
- return { configured: false, repos: [] };
516
- }
517
- const [installerKey, lookupKey] = await Promise.all([
518
- deps.appService.getPrivateKey("installer"),
519
- deps.appService.getPrivateKey("lookup"),
530
+ deps.appService.get("installer", accountId),
531
+ deps.appService.get("lookup", accountId),
520
532
  ]);
521
- if (!installerKey || !lookupKey)
522
- return { configured: false, repos: [] };
533
+ if (!lookup) return { configured: false, repos: [] };
534
+ const lookupKey = await deps.appService.getPrivateKey(
535
+ "lookup",
536
+ accountId,
537
+ );
538
+ if (!lookupKey) return { configured: false, repos: [] };
523
539
  const common = {
524
540
  apiBase: deps.apiBase,
525
541
  fetchFn: deps.fetchFn,
526
542
  now: deps.now,
527
543
  };
544
+ // An installer with an enterprise slug supplies the org list; without
545
+ // one the lookup App lists the orgs it is installed on.
546
+ const installerKey = installer?.enterpriseSlug
547
+ ? await deps.appService.getPrivateKey("installer", accountId)
548
+ : null;
549
+ if (installer?.enterpriseSlug && !installerKey) {
550
+ return { configured: false, repos: [] };
551
+ }
528
552
  clients = {
529
- installer: new GithubEnterpriseClient({
530
- appId: installer.appId,
531
- enterprise: installer.enterpriseSlug,
532
- privateKey: installerKey,
533
- ...common,
534
- }),
553
+ installer:
554
+ installer?.enterpriseSlug && installerKey
555
+ ? new GithubEnterpriseClient({
556
+ appId: installer.appId,
557
+ enterprise: installer.enterpriseSlug,
558
+ privateKey: installerKey,
559
+ ...common,
560
+ })
561
+ : undefined,
535
562
  lookup: new GithubLookupClient({
536
563
  appId: lookup.appId,
537
564
  privateKey: lookupKey,
@@ -608,9 +635,11 @@ export function createGithubEnterpriseApp(
608
635
 
609
636
  const clientFor = async (
610
637
  meta: GitHubEnterpriseAppMetadata,
638
+ accountId: string | undefined,
611
639
  ): Promise<GithubEnterpriseClient> => {
612
640
  const privateKey = await appService.getPrivateKey(
613
641
  meta.role as GitHubEnterpriseAppRole,
642
+ accountId,
614
643
  );
615
644
  if (!privateKey || !meta.enterpriseSlug) {
616
645
  throw new UnprocessableEntityError(
@@ -677,7 +706,8 @@ export function createGithubEnterpriseApp(
677
706
 
678
707
  app.openapi(statusRoute, async (c) => {
679
708
  requireAdmin(c);
680
- const rows = await appService.list();
709
+ const { accountId } = c.req.valid("query");
710
+ const rows = await appService.list(accountId);
681
711
  const byRole = (role: string) => {
682
712
  const r = rows.find((x) => x.role === role);
683
713
  return r ? serializeApp(r) : null;
@@ -695,6 +725,7 @@ export function createGithubEnterpriseApp(
695
725
  app.openapi(putRoute, async (c) => {
696
726
  requireAdmin(c);
697
727
  const { role } = c.req.valid("param");
728
+ const { accountId } = c.req.valid("query");
698
729
  const body = c.req.valid("json");
699
730
  if (role === "installer" && !body.enterpriseSlug) {
700
731
  throw new UnprocessableEntityError(
@@ -710,6 +741,7 @@ export function createGithubEnterpriseApp(
710
741
  );
711
742
  }
712
743
  const saved = await appService.save({
744
+ accountId,
713
745
  role,
714
746
  appId: body.appId,
715
747
  slug: body.slug,
@@ -721,16 +753,20 @@ export function createGithubEnterpriseApp(
721
753
 
722
754
  app.openapi(deleteRoute, async (c) => {
723
755
  requireAdmin(c);
724
- await appService.delete(c.req.valid("param").role);
756
+ await appService.delete(
757
+ c.req.valid("param").role,
758
+ c.req.valid("query").accountId,
759
+ );
725
760
  return c.body(null, 204);
726
761
  });
727
762
 
728
763
  app.openapi(validateRoute, async (c) => {
729
764
  requireAdmin(c);
730
765
  const { role } = c.req.valid("param");
731
- const meta = await appService.get(role);
766
+ const { accountId } = c.req.valid("query");
767
+ const meta = await appService.get(role, accountId);
732
768
  if (!meta) throw new NotFoundError(`no '${role}' App is configured`);
733
- const privateKey = await appService.getPrivateKey(role);
769
+ const privateKey = await appService.getPrivateKey(role, accountId);
734
770
  if (!privateKey) throw new NotFoundError(`no '${role}' App is configured`);
735
771
 
736
772
  const required = REQUIRED_PERMISSION[role];
@@ -787,8 +823,14 @@ export function createGithubEnterpriseApp(
787
823
  }
788
824
  }
789
825
 
790
- await appService.recordValidation(role, { status, error });
791
- const updated = await appService.get(role);
826
+ // Record against the row that was validated (the deployment-wide row when
827
+ // the account has none of its own).
828
+ await appService.recordValidation(
829
+ role,
830
+ { status, error },
831
+ meta.accountId ?? null,
832
+ );
833
+ const updated = await appService.get(role, accountId);
792
834
  return c.json(
793
835
  {
794
836
  role,
@@ -806,8 +848,8 @@ export function createGithubEnterpriseApp(
806
848
 
807
849
  app.openapi(orgsRoute, async (c) => {
808
850
  requireAdmin(c);
809
- const { agentId } = c.req.valid("query");
810
- const installer = await appService.get("installer");
851
+ const { agentId, accountId } = c.req.valid("query");
852
+ const installer = await appService.get("installer", accountId);
811
853
  if (!installer) return c.json({ configured: false, orgs: [] }, 200);
812
854
 
813
855
  let agentAppSlug: string | null = null;
@@ -830,9 +872,9 @@ export function createGithubEnterpriseApp(
830
872
  }
831
873
  }
832
874
  }
833
- const lookup = await appService.get("lookup");
875
+ const lookup = await appService.get("lookup", accountId);
834
876
 
835
- const client = await clientFor(installer);
877
+ const client = await clientFor(installer, accountId);
836
878
  const orgs = await client.listInstallableOrganizations();
837
879
  const same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();
838
880
  const needInstallations = lookup !== null || agentAppSlug !== null;
@@ -867,8 +909,9 @@ export function createGithubEnterpriseApp(
867
909
  requireAdmin(c);
868
910
  const { org } = c.req.valid("param");
869
911
  const body = c.req.valid("json");
912
+ const { accountId } = c.req.valid("query");
870
913
 
871
- const installer = await appService.get("installer");
914
+ const installer = await appService.get("installer", accountId);
872
915
  if (!installer) {
873
916
  throw new ConflictError("the installer App is not configured");
874
917
  }
@@ -897,7 +940,7 @@ export function createGithubEnterpriseApp(
897
940
  }
898
941
  }
899
942
 
900
- const client = await clientFor(installer);
943
+ const client = await clientFor(installer, accountId);
901
944
  const res = await client.installOnOrg(org, {
902
945
  clientId,
903
946
  repositorySelection: body.repositorySelection,
@@ -46,10 +46,12 @@ function lazyInstallerClient(
46
46
  "appService" | "fetchFn" | "apiBase" | "now"
47
47
  >,
48
48
  ): InstallationRepoClient & InstalledOrgsClient {
49
- const client = async (): Promise<GithubEnterpriseClient> => {
49
+ const client = async (
50
+ accountId?: string | null,
51
+ ): Promise<GithubEnterpriseClient> => {
50
52
  const [installer, privateKey] = await Promise.all([
51
- deps.appService.get("installer"),
52
- deps.appService.getPrivateKey("installer"),
53
+ deps.appService.get("installer", accountId),
54
+ deps.appService.getPrivateKey("installer", accountId),
53
55
  ]);
54
56
  if (!installer?.enterpriseSlug || !privateKey) {
55
57
  throw new Error("installer App is not configured");
@@ -64,16 +66,16 @@ function lazyInstallerClient(
64
66
  });
65
67
  };
66
68
  return {
67
- listInstallableOrganizations: async () =>
68
- (await client()).listInstallableOrganizations(),
69
- listOrgInstallations: async (org) =>
70
- (await client()).listOrgInstallations(org),
71
- listInstallationRepositories: async (org, id) =>
72
- (await client()).listInstallationRepositories(org, id),
73
- addRepositories: async (org, id, names) =>
74
- (await client()).addRepositories(org, id, names),
75
- removeRepositories: async (org, id, names) =>
76
- (await client()).removeRepositories(org, id, names),
69
+ listInstallableOrganizations: async (accountId) =>
70
+ (await client(accountId)).listInstallableOrganizations(),
71
+ listOrgInstallations: async (org, accountId) =>
72
+ (await client(accountId)).listOrgInstallations(org),
73
+ listInstallationRepositories: async (org, id, accountId) =>
74
+ (await client(accountId)).listInstallationRepositories(org, id),
75
+ addRepositories: async (org, id, names, accountId) =>
76
+ (await client(accountId)).addRepositories(org, id, names),
77
+ removeRepositories: async (org, id, names, accountId) =>
78
+ (await client(accountId)).removeRepositories(org, id, names),
77
79
  };
78
80
  }
79
81
 
@@ -81,6 +81,12 @@ export interface LookupToken {
81
81
  repositorySelection?: "all" | "selected";
82
82
  }
83
83
 
84
+ export interface LookupInstallation {
85
+ id: number;
86
+ /** The account (organization) login the App is installed on. */
87
+ login: string;
88
+ }
89
+
84
90
  export interface GithubLookupClientOptions {
85
91
  appId: string;
86
92
  privateKey: string;
@@ -165,6 +171,49 @@ export class GithubLookupClient {
165
171
  return token;
166
172
  }
167
173
 
174
+ /**
175
+ * List the organizations the lookup App is installed on (GET
176
+ * /app/installations, App JWT, paginated). User-account installations are
177
+ * dropped: the per-org read path only works for organizations.
178
+ */
179
+ async listInstallations(): Promise<LookupInstallation[]> {
180
+ const jwt = signGithubAppJwt({
181
+ appId: this.appId,
182
+ privateKey: this.privateKey,
183
+ now: this.now(),
184
+ });
185
+ const all: LookupInstallation[] = [];
186
+ for (let page = 1; page <= MAX_PAGES; page++) {
187
+ const res = await this.request<RawInstallation[]>(
188
+ "GET",
189
+ `/app/installations?per_page=${PER_PAGE}&page=${page}`,
190
+ jwt,
191
+ "GitHub App installations",
192
+ );
193
+ const rows = res.data;
194
+ if (!Array.isArray(rows)) {
195
+ throw new GithubEnterpriseError(
196
+ "unexpected",
197
+ "GitHub App installations: response is not an installation list",
198
+ );
199
+ }
200
+ for (const r of rows) {
201
+ if (
202
+ typeof r.id === "number" &&
203
+ r.account?.type === "Organization" &&
204
+ typeof r.account.login === "string"
205
+ ) {
206
+ all.push({ id: r.id, login: r.account.login });
207
+ }
208
+ }
209
+ const link = res.headers.get("link");
210
+ const hasNext =
211
+ link !== null ? /rel="next"/.test(link) : rows.length >= PER_PAGE;
212
+ if (!hasNext) break;
213
+ }
214
+ return all;
215
+ }
216
+
168
217
  /** List every repository the lookup App can see on `org` (paginated). */
169
218
  async listInstallationRepositories(org: string): Promise<LookupRepository[]> {
170
219
  const { token } = await this.getOrgToken(org);
@@ -302,6 +351,11 @@ export class GithubLookupClient {
302
351
  }
303
352
  }
304
353
 
354
+ interface RawInstallation {
355
+ id?: number;
356
+ account?: { login?: string; type?: string } | null;
357
+ }
358
+
305
359
  interface RawRepository {
306
360
  id: number;
307
361
  name: string;
@@ -91,3 +91,62 @@ describe("GithubLookupClient errors", () => {
91
91
  throw new Error("expected rejection");
92
92
  });
93
93
  });
94
+
95
+ describe("GithubLookupClient.listInstallations", () => {
96
+ const { privateKey } = generateKeyPairSync("rsa", {
97
+ modulusLength: 2048,
98
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
99
+ publicKeyEncoding: { type: "spki", format: "pem" },
100
+ });
101
+ const inst = (id: number, login: string, type = "Organization") => ({
102
+ id,
103
+ account: { login, type },
104
+ });
105
+
106
+ it("paginates with the App JWT and keeps only organization installs", async () => {
107
+ const page1 = Array.from({ length: 100 }, (_, i) => inst(i, `org${i}`));
108
+ const seen: string[] = [];
109
+ const client = new GithubLookupClient({
110
+ appId: "555",
111
+ privateKey,
112
+ fetchFn: (async (input: RequestInfo | URL, init?: RequestInit) => {
113
+ const u = new URL(input.toString());
114
+ expect(u.pathname).toBe("/app/installations");
115
+ expect(
116
+ String(new Headers(init?.headers).get("authorization")),
117
+ ).toStartWith("Bearer ey");
118
+ seen.push(u.searchParams.get("page") ?? "");
119
+ return u.searchParams.get("page") === "1"
120
+ ? Response.json(page1, {
121
+ headers: { link: '<https://x/?page=2>; rel="next"' },
122
+ })
123
+ : Response.json([inst(900, "last"), inst(901, "someone", "User")]);
124
+ }) as unknown as typeof fetch,
125
+ });
126
+ const out = await client.listInstallations();
127
+ expect(seen).toEqual(["1", "2"]);
128
+ expect(out).toHaveLength(101);
129
+ expect(out.at(-1)).toEqual({ id: 900, login: "last" });
130
+ });
131
+
132
+ it("rejects on a GitHub error", async () => {
133
+ const client = new GithubLookupClient({
134
+ appId: "555",
135
+ privateKey,
136
+ fetchFn: (async () =>
137
+ Response.json({ message: "boom" }, { status: 500 })) as unknown as typeof fetch,
138
+ });
139
+ await expect(client.listInstallations()).rejects.toBeInstanceOf(
140
+ GithubEnterpriseError,
141
+ );
142
+ });
143
+
144
+ it("rejects a non-list response", async () => {
145
+ const client = new GithubLookupClient({
146
+ appId: "555",
147
+ privateKey,
148
+ fetchFn: (async () => Response.json({})) as unknown as typeof fetch,
149
+ });
150
+ await expect(client.listInstallations()).rejects.toThrow("not an installation list");
151
+ });
152
+ });