@app-vitals/agent-admin 1.109.0 → 1.111.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.
Files changed (53) hide show
  1. package/openapi.json +0 -193
  2. package/openapi.platform.json +1 -238
  3. package/package.json +2 -2
  4. package/src/admin-boot.ts +6 -5
  5. package/src/admin-ui-github-enterprise-pages.ts +13 -2
  6. package/src/admin-ui-github-enterprise.smoke.test.ts +20 -1
  7. package/src/admin-ui-github-enterprise.ts +16 -1
  8. package/src/admin-ui-github-identity-pages.ts +35 -139
  9. package/src/admin-ui-github-identity-pages.unit.test.ts +50 -173
  10. package/src/admin-ui-github-identity.smoke.test.ts +103 -63
  11. package/src/admin-ui-installation-repos-pages.ts +2 -23
  12. package/src/admin-ui-installation-repos-pages.unit.test.ts +41 -36
  13. package/src/admin-ui-installation-repos.smoke.test.ts +9 -8
  14. package/src/admin-ui-pages.ts +4 -5
  15. package/src/admin-ui-slack-config-token-pages.ts +11 -2
  16. package/src/admin-ui-slack-config-token.smoke.test.ts +39 -3
  17. package/src/admin-ui-slack-config-token.ts +51 -9
  18. package/src/admin-ui-templates-pages.ts +7 -1
  19. package/src/admin-ui-templates.smoke.test.ts +31 -5
  20. package/src/admin-ui-templates.ts +43 -8
  21. package/src/admin-ui.ts +51 -36
  22. package/src/agent-templates-api.integration.test.ts +29 -7
  23. package/src/agent-templates.ts +7 -1
  24. package/src/agents-api.smoke.test.ts +26 -315
  25. package/src/agents-api.ts +1 -107
  26. package/src/deployment-wide-settings.integration.test.ts +309 -0
  27. package/src/deployment-wide-settings.ts +42 -0
  28. package/src/github-access-preview.ts +2 -2
  29. package/src/github-agent-installation-crawler.ts +18 -1
  30. package/src/github-enterprise-api.integration.test.ts +7 -0
  31. package/src/github-enterprise-api.smoke.test.ts +26 -0
  32. package/src/github-enterprise-api.ts +24 -4
  33. package/src/github-enterprise-apps.integration.test.ts +33 -8
  34. package/src/github-enterprise-apps.ts +4 -0
  35. package/src/github-enterprise-client.integration.test.ts +0 -41
  36. package/src/github-enterprise-client.ts +0 -25
  37. package/src/github-enterprise-client.unit.test.ts +0 -18
  38. package/src/github-installation-wiring.ts +48 -13
  39. package/src/github-installation-wiring.unit.test.ts +38 -1
  40. package/src/github-sync-all-repos.unit.test.ts +116 -0
  41. package/src/github-sync-cache.integration.test.ts +9 -2
  42. package/src/github-sync-snapshot-refresh.integration.test.ts +168 -0
  43. package/src/github-sync-snapshot-refresh.unit.test.ts +144 -0
  44. package/src/github-sync.ts +103 -137
  45. package/src/github-sync.unit.test.ts +82 -1
  46. package/src/installation-ports.ts +1 -40
  47. package/src/installation-repos-service.ts +7 -4
  48. package/src/reconcile-open-work.integration.test.ts +0 -1
  49. package/src/slack-config-token.integration.test.ts +19 -2
  50. package/src/slack-config-token.ts +6 -1
  51. package/src/github-access-preview.integration.test.ts +0 -399
  52. package/src/github-sync-switch.integration.test.ts +0 -297
  53. package/src/github-sync-switch.unit.test.ts +0 -467
@@ -0,0 +1,309 @@
1
+ /**
2
+ * Integration: deployment-wide (accountId null) settings against real Postgres.
3
+ * With more than one account the Slack config token, the enterprise GitHub
4
+ * Apps and agent templates cannot be created or updated without an account;
5
+ * existing deployment-wide rows stay readable and removable. With one account
6
+ * or none nothing changes.
7
+ *
8
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
9
+ */
10
+
11
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
12
+ import type { PrismaClient } from "../prisma/client/client.ts";
13
+ import { AgentTemplateService } from "./agent-templates.ts";
14
+ import { createAgentTemplatesApp } from "./agent-templates-api.ts";
15
+ import { parseAdminApiKeys } from "./api-auth.ts";
16
+ import { DeploymentWideSettingBlockedError } from "./deployment-wide-settings.ts";
17
+ import { createGithubLookupService } from "./github-enterprise-api.ts";
18
+ import { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
19
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
20
+ import { createAdminPrismaClient } from "./prisma-client.ts";
21
+ import {
22
+ hasStoredSlackConfigToken,
23
+ SlackConfigTokenService,
24
+ } from "./slack-config-token.ts";
25
+ import { SpecialtyTypes } from "./specialty-types.ts";
26
+ import { makeStrictTokenCrypto } from "./token-crypto.ts";
27
+
28
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
29
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
30
+
31
+ const KEY = "ab".repeat(32);
32
+ const PEM =
33
+ "-----BEGIN RSA PRIVATE KEY-----\nMADEUPPEMBODY0123456789\n-----END RSA PRIVATE KEY-----";
34
+ const NOW = new Date("2026-11-20T12:00:00Z");
35
+
36
+ describeOrSkip("deployment-wide settings (integration)", () => {
37
+ let prisma: PrismaClient;
38
+ const crypto = makeStrictTokenCrypto(KEY);
39
+ if (!crypto) throw new Error("test crypto");
40
+
41
+ const addAccount = async (name: string) =>
42
+ (await prisma.account.create({ data: { name } })).id;
43
+
44
+ const slack = () => new SlackConfigTokenService(prisma, crypto);
45
+ const apps = () => new GitHubEnterpriseAppService(prisma, crypto);
46
+ const templates = () =>
47
+ new AgentTemplateService(
48
+ prisma,
49
+ crypto,
50
+ new SpecialtyTypes({ defaultTypeName: "specialist" }),
51
+ );
52
+ const lookupApp = (accountId?: string | null) => ({
53
+ accountId,
54
+ role: "lookup" as const,
55
+ appId: "555",
56
+ slug: "example-lookup",
57
+ privateKey: PEM,
58
+ });
59
+ const envItem = {
60
+ kind: "env" as const,
61
+ key: "EXAMPLE_VAR",
62
+ payload: { value: "made-up" },
63
+ };
64
+ const admin = { kind: "admin" as const };
65
+
66
+ beforeEach(async () => {
67
+ prisma = createAdminPrismaClient(TEST_DB as string);
68
+ await prisma.slackConfigToken.deleteMany();
69
+ await prisma.gitHubEnterpriseApp.deleteMany();
70
+ await prisma.gitHubCachedRepo.deleteMany();
71
+ await prisma.gitHubRepoSnapshot.deleteMany();
72
+ await prisma.agentTemplateItem.deleteMany();
73
+ await prisma.agentTemplate.deleteMany();
74
+ await prisma.agent.deleteMany();
75
+ await prisma.accountInvite.deleteMany();
76
+ await prisma.accountMember.deleteMany();
77
+ await prisma.account.deleteMany();
78
+ });
79
+
80
+ afterEach(async () => {
81
+ await prisma.gitHubCachedRepo.deleteMany();
82
+ await prisma.gitHubRepoSnapshot.deleteMany();
83
+ await prisma.slackConfigToken.deleteMany();
84
+ await prisma.gitHubEnterpriseApp.deleteMany();
85
+ await prisma.agentTemplate.deleteMany();
86
+ await prisma.account.deleteMany();
87
+ await prisma.$disconnect();
88
+ });
89
+
90
+ describe("Slack config token", () => {
91
+ it("saves a deployment-wide token with no account or one account", async () => {
92
+ await slack().save(null, { refreshToken: "made-up-refresh-1" });
93
+ await addAccount("A");
94
+ await slack().save(null, { refreshToken: "made-up-refresh-2" });
95
+ expect(await slack().get(null)).not.toBeNull();
96
+ });
97
+
98
+ it("rejects creating and updating a deployment-wide token with several accounts", async () => {
99
+ const a = await addAccount("A");
100
+ await addAccount("B");
101
+ await expect(
102
+ slack().save(null, { refreshToken: "made-up-refresh" }),
103
+ ).rejects.toBeInstanceOf(DeploymentWideSettingBlockedError);
104
+ expect(await slack().get(null)).toBeNull();
105
+ // An account's own token is still fine.
106
+ await slack().save(a, { refreshToken: "made-up-refresh" });
107
+ expect(await slack().get(a)).not.toBeNull();
108
+ });
109
+
110
+ it("keeps an existing deployment-wide token readable and removable, not updatable", async () => {
111
+ const a = await addAccount("A");
112
+ await slack().save(null, { refreshToken: "made-up-refresh" });
113
+ await addAccount("B");
114
+ expect(await slack().get(null)).not.toBeNull();
115
+ // The shared row still backs an account with no token of its own.
116
+ expect((await slack().resolveForAccount(a))?.accountId).toBeNull();
117
+ await expect(
118
+ slack().save(null, { refreshToken: "made-up-refresh-new" }),
119
+ ).rejects.toBeInstanceOf(DeploymentWideSettingBlockedError);
120
+ await slack().clear(null);
121
+ expect(await slack().get(null)).toBeNull();
122
+ });
123
+
124
+ it("gives an account without its own token none once no deployment-wide row exists", async () => {
125
+ const a = await addAccount("A");
126
+ await addAccount("B");
127
+ expect(await slack().resolveForAccount(a)).toBeNull();
128
+ expect(await hasStoredSlackConfigToken(slack(), a)).toBe(false);
129
+ // An agent with no account only sees the deployment-wide row.
130
+ expect(await hasStoredSlackConfigToken(slack(), null)).toBe(false);
131
+ });
132
+ });
133
+
134
+ describe("GitHub Apps", () => {
135
+ it("saves a deployment-wide App with no account or one account", async () => {
136
+ await apps().save(lookupApp());
137
+ await addAccount("A");
138
+ await apps().save(lookupApp(null));
139
+ expect((await apps().get("lookup"))?.accountId).toBeNull();
140
+ });
141
+
142
+ it("rejects creating and updating a deployment-wide App with several accounts", async () => {
143
+ const a = await addAccount("A");
144
+ await addAccount("B");
145
+ await expect(apps().save(lookupApp())).rejects.toBeInstanceOf(
146
+ DeploymentWideSettingBlockedError,
147
+ );
148
+ await expect(apps().save(lookupApp(null))).rejects.toBeInstanceOf(
149
+ DeploymentWideSettingBlockedError,
150
+ );
151
+ expect(await apps().list()).toEqual([]);
152
+ await apps().save(lookupApp(a));
153
+ expect((await apps().get("lookup", a))?.accountId).toBe(a);
154
+ });
155
+
156
+ it("keeps an existing deployment-wide App readable and removable, not updatable", async () => {
157
+ const a = await addAccount("A");
158
+ await apps().save(lookupApp());
159
+ await addAccount("B");
160
+ expect((await apps().get("lookup", a))?.accountId).toBeNull();
161
+ expect(await apps().list()).toHaveLength(1);
162
+ await expect(apps().save(lookupApp())).rejects.toBeInstanceOf(
163
+ DeploymentWideSettingBlockedError,
164
+ );
165
+ await apps().delete("lookup");
166
+ expect(await apps().get("lookup", a)).toBeNull();
167
+ });
168
+
169
+ describe("repo listings and caches", () => {
170
+ let cache: GitHubRepoCacheService;
171
+ const listing = () =>
172
+ createGithubLookupService({
173
+ appService: apps(),
174
+ cache,
175
+ now: () => NOW,
176
+ });
177
+
178
+ async function seedSnapshot(accountId: string, appRef: string) {
179
+ const key = {
180
+ accountId,
181
+ appKind: "lookup" as const,
182
+ appRef,
183
+ org: "example-org",
184
+ };
185
+ const snap = await cache.upsertSnapshot(key, {
186
+ crawlPage: 1,
187
+ crawlStartedAt: NOW,
188
+ totalCount: 1,
189
+ });
190
+ await cache.upsertRepos(snap.id, [
191
+ { githubId: 1, fullName: "example-org/repo-one" },
192
+ ]);
193
+ await cache.upsertSnapshot(key, { completedAt: NOW });
194
+ }
195
+
196
+ beforeEach(() => {
197
+ cache = new GitHubRepoCacheService(prisma, { now: () => NOW });
198
+ });
199
+
200
+ it("lists nothing for an account or an agent with no account when no deployment-wide App exists", async () => {
201
+ const a = await addAccount("A");
202
+ await addAccount("B");
203
+ // A snapshot left behind by a removed deployment-wide App.
204
+ await seedSnapshot("deployment", "555");
205
+ expect(await listing().listRepositories(a)).toEqual({
206
+ configured: false,
207
+ repos: [],
208
+ });
209
+ expect(await listing().listRepositories(null)).toEqual({
210
+ configured: false,
211
+ repos: [],
212
+ });
213
+ });
214
+
215
+ it("serves the deployment-wide listing as the fallback while the row exists", async () => {
216
+ const a = await addAccount("A");
217
+ await apps().save(lookupApp());
218
+ await addAccount("B");
219
+ await seedSnapshot("deployment", "555");
220
+ const r = await listing().listRepositories(a);
221
+ expect(r.configured).toBe(true);
222
+ expect(r.repos).toEqual([
223
+ { fullName: "example-org/repo-one", archived: false },
224
+ ]);
225
+ expect((await listing().listRepositories(null)).configured).toBe(true);
226
+ });
227
+
228
+ it("does not mix the deployment-wide cache into an account with its own App", async () => {
229
+ const a = await addAccount("A");
230
+ await addAccount("B");
231
+ await apps().save(lookupApp(a));
232
+ await seedSnapshot("deployment", "555");
233
+ const r = await listing().listRepositories(a);
234
+ expect(r.configured).toBe(true);
235
+ expect(r.repos).toEqual([]);
236
+ });
237
+ });
238
+ });
239
+
240
+ describe("agent templates", () => {
241
+ it("saves a deployment-wide template with no account or one account", async () => {
242
+ expect((await templates().replace(admin, {}, [envItem])).created).toBe(
243
+ true,
244
+ );
245
+ await addAccount("A");
246
+ const again = await templates().replace(admin, {}, [envItem]);
247
+ expect(again.created).toBe(false);
248
+ expect(again.template.accountId).toBeNull();
249
+ });
250
+
251
+ it("rejects creating and updating a deployment-wide template with several accounts", async () => {
252
+ const a = await addAccount("A");
253
+ await addAccount("B");
254
+ await expect(
255
+ templates().replace(admin, {}, [envItem]),
256
+ ).rejects.toBeInstanceOf(DeploymentWideSettingBlockedError);
257
+ await expect(
258
+ templates().replace(admin, { accountId: null, specialty: null }, []),
259
+ ).rejects.toBeInstanceOf(DeploymentWideSettingBlockedError);
260
+ expect(await prisma.agentTemplate.count()).toBe(0);
261
+ const own = await templates().replace(admin, { accountId: a }, [envItem]);
262
+ expect(own.template.accountId).toBe(a);
263
+ });
264
+
265
+ it("keeps an existing deployment-wide template readable and removable, not updatable", async () => {
266
+ const { template } = await templates().replace(admin, {}, [envItem]);
267
+ await addAccount("A");
268
+ await addAccount("B");
269
+ expect(await templates().list(admin, {})).toHaveLength(1);
270
+ await expect(
271
+ templates().replace(admin, {}, [envItem]),
272
+ ).rejects.toBeInstanceOf(DeploymentWideSettingBlockedError);
273
+ await expect(
274
+ templates().putItem(admin, template.id, {
275
+ kind: "env",
276
+ key: "OTHER_VAR",
277
+ payload: { value: "x" },
278
+ }),
279
+ ).rejects.toBeInstanceOf(DeploymentWideSettingBlockedError);
280
+ await templates().deleteItem(admin, template.id, "env", "EXAMPLE_VAR");
281
+ await templates().delete(admin, template.id);
282
+ expect(await prisma.agentTemplate.count()).toBe(0);
283
+ });
284
+
285
+ it("answers PUT /templates for a deployment-wide scope with 422 once there are several accounts", async () => {
286
+ const app = createAgentTemplatesApp({
287
+ templateService: templates(),
288
+ callerScopeResolver: async () => ({ kind: "all" }),
289
+ sessionSecret: "test-session-secret-32-chars-long!!",
290
+ adminApiKeys: parseAdminApiKeys("root:tok-admin:*"),
291
+ agentTokenService: { validate: async () => null },
292
+ });
293
+ const put = (body: unknown) =>
294
+ app.request("/templates", {
295
+ method: "PUT",
296
+ headers: {
297
+ Authorization: "Bearer tok-admin",
298
+ "Content-Type": "application/json",
299
+ },
300
+ body: JSON.stringify(body),
301
+ });
302
+ const a = await addAccount("A");
303
+ expect((await put({ items: [] })).status).toBe(201);
304
+ await addAccount("B");
305
+ expect((await put({ items: [] })).status).toBe(422);
306
+ expect((await put({ accountId: a, items: [] })).status).toBe(201);
307
+ });
308
+ });
309
+ });
@@ -0,0 +1,42 @@
1
+ /**
2
+ * admin/src/deployment-wide-settings.ts
3
+ * Guard for settings that can be stored with no account (accountId null): the
4
+ * Slack config token, the enterprise GitHub Apps and agent templates. A row
5
+ * with no account is a fallback for every account, so once there is more than
6
+ * one account nobody may create or update one: the admin picks an account.
7
+ * Existing deployment-wide rows stay readable and removable. With one account
8
+ * or none, shared settings work as before.
9
+ */
10
+
11
+ import type { PrismaClient } from "../prisma/client/client.ts";
12
+ import { UnprocessableEntityError } from "./errors.ts";
13
+
14
+ export class DeploymentWideSettingBlockedError extends UnprocessableEntityError {
15
+ constructor(what: string) {
16
+ super(
17
+ `There is more than one account, so ${what} cannot be created or changed deployment-wide. Choose an account. An existing deployment-wide setting can still be removed.`,
18
+ );
19
+ this.name = "DeploymentWideSettingBlockedError";
20
+ }
21
+ }
22
+
23
+ /** True when more than one account exists. */
24
+ export async function hasMultipleAccounts(
25
+ prisma: Pick<PrismaClient, "account">,
26
+ ): Promise<boolean> {
27
+ const rows = await prisma.account.findMany({
28
+ select: { id: true },
29
+ take: 2,
30
+ });
31
+ return rows.length > 1;
32
+ }
33
+
34
+ /** Throws DeploymentWideSettingBlockedError when several accounts exist. */
35
+ export async function assertDeploymentWideAllowed(
36
+ prisma: Pick<PrismaClient, "account">,
37
+ what: string,
38
+ ): Promise<void> {
39
+ if (await hasMultipleAccounts(prisma)) {
40
+ throw new DeploymentWideSettingBlockedError(what);
41
+ }
42
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * admin/src/github-access-preview.ts
3
- * Result type and port for GET /agents/:id/github-access (GHE-2.4): a
4
- * read-only preview of the repos an agent's bound GitHub user can reach.
3
+ * Result type and port (GHE-2.4) for the live resolver of the repos an agent's
4
+ * bound GitHub user can reach, consumed by the installation-repos service and Sync.
5
5
  * The implementation lives in github-enterprise-api.ts (the only module that
6
6
  * may read the App keys); agents-api.ts only sees this port.
7
7
  */
@@ -45,6 +45,22 @@ export function lookupAccountKeys(accountId?: string | null): string[] {
45
45
  : [DEPLOYMENT_WIDE_ACCOUNT_KEY];
46
46
  }
47
47
 
48
+ /**
49
+ * lookupAccountKeys for an agent whose lookup App resolved to `app`. The
50
+ * deployment key holds snapshots of the deployment-wide App only, so it is
51
+ * left out when the agent uses its own account's App and no deployment-wide
52
+ * lookup App exists any more (a removed App's cache must not leak to accounts).
53
+ * `hasDeploymentApp` is asked only in that case.
54
+ */
55
+ export async function lookupKeysForApp(
56
+ app: { accountId?: string | null },
57
+ accountId: string | null | undefined,
58
+ hasDeploymentApp: () => Promise<boolean>,
59
+ ): Promise<string[]> {
60
+ if (app.accountId && !(await hasDeploymentApp())) return [app.accountId];
61
+ return lookupAccountKeys(accountId);
62
+ }
63
+
48
64
  /**
49
65
  * Reads per-user access rows under every key in lookupAccountKeys(accountId)
50
66
  * and merges them. The writer files rows under the resolved lookup App's scope
@@ -213,7 +229,8 @@ export async function crawlAgentInstallation(
213
229
  let selection: "all" | "selected" | null;
214
230
  try {
215
231
  selection = (await source.resolveRepositorySelection?.()) ?? null;
216
- if (!source.resolveRepositorySelection) await source.resolveInstallationId();
232
+ if (!source.resolveRepositorySelection)
233
+ await source.resolveInstallationId();
217
234
  } catch (err) {
218
235
  if (!(err instanceof AppNotInstalledError)) {
219
236
  // Let the engine record GitHub failures and rate limits on the snapshot.
@@ -107,6 +107,10 @@ describeOrSkip("github-enterprise API (integration)", () => {
107
107
  await prisma.agentCronJob.deleteMany();
108
108
  await prisma.agentTool.deleteMany();
109
109
  await prisma.agent.deleteMany();
110
+ // Deployment-wide Apps cannot be saved while there are several accounts.
111
+ await prisma.accountInvite.deleteMany();
112
+ await prisma.accountMember.deleteMany();
113
+ await prisma.account.deleteMany();
110
114
  appService = new GitHubEnterpriseAppService(
111
115
  prisma,
112
116
  makeStrictTokenCrypto(ENC_KEY),
@@ -371,6 +375,9 @@ describeOrSkip("DELETE /orgs/{org}/install (integration)", () => {
371
375
  await prisma.agentCronJob.deleteMany();
372
376
  await prisma.agentTool.deleteMany();
373
377
  await prisma.agent.deleteMany();
378
+ await prisma.accountInvite.deleteMany();
379
+ await prisma.accountMember.deleteMany();
380
+ await prisma.account.deleteMany();
374
381
  });
375
382
 
376
383
  afterEach(async () => {
@@ -722,6 +722,32 @@ describe("POST install", () => {
722
722
  expect(h.calls).toContain(INSTALL);
723
723
  });
724
724
 
725
+ it("rejects selected with no repositories and over 50 with a clear 400", async () => {
726
+ const h = build({
727
+ routes: { "GET /apps/example-agent-app": "public_app_success" },
728
+ });
729
+ await seed(h);
730
+ const empty = await post(h, {
731
+ agentId: "agent-1",
732
+ repositorySelection: "selected",
733
+ repositories: [],
734
+ });
735
+ expect(empty.status).toBe(400);
736
+ expect(((await empty.json()) as { error: string }).error).toMatch(
737
+ /at least one repository/,
738
+ );
739
+ const many = await post(h, {
740
+ agentId: "agent-1",
741
+ repositorySelection: "selected",
742
+ repositories: Array.from({ length: 51 }, (_, i) => `r${i}`),
743
+ });
744
+ expect(many.status).toBe(400);
745
+ expect(((await many.json()) as { error: string }).error).toMatch(
746
+ /at most 50/,
747
+ );
748
+ expect(h.calls).not.toContain(INSTALL);
749
+ });
750
+
725
751
  it("refuses a private App (public lookup 404) with a clear 422", async () => {
726
752
  const h = build({
727
753
  routes: { "GET /apps/example-agent-app": "public_app_private_404" },
@@ -36,7 +36,7 @@ import {
36
36
  UnprocessableEntityError,
37
37
  } from "./errors.ts";
38
38
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
39
- import { lookupAccountKeys } from "./github-agent-installation-crawler.ts";
39
+ import { lookupKeysForApp } from "./github-agent-installation-crawler.ts";
40
40
  import { fetchAuthenticatedApp, fetchPublicApp } from "./github-app-api.ts";
41
41
  import {
42
42
  GITHUB_ENTERPRISE_APP_ROLES,
@@ -251,7 +251,10 @@ const InstallBodySchema = z
251
251
  .object({
252
252
  agentId: z.string().min(1).openapi({ example: "agent-id" }),
253
253
  repositorySelection: z.enum(["all", "selected", "none"]).default("all"),
254
- repositories: z.array(z.string().min(1)).max(50).optional(),
254
+ repositories: z
255
+ .array(z.string().min(1))
256
+ .max(50, "at most 50 repositories can be selected")
257
+ .optional(),
255
258
  })
256
259
  .openapi("GithubEnterpriseInstallBody");
257
260
 
@@ -572,7 +575,7 @@ function serializeApp(m: GitHubEnterpriseAppMetadata) {
572
575
  // ─── Access preview (GHE-2.4) ─────────────────────────────────────────────────
573
576
 
574
577
  /**
575
- * Backs GET /agents/:id/github-access. Unconfigured (the lookup App, or its
578
+ * Live access resolver used by the installation-repos service and Sync. Unconfigured (the lookup App, or its
576
579
  * key, missing) returns before any GitHub
577
580
  * call. A GitHub failure while listing orgs is rethrown as a 502 carrying only
578
581
  * the mapped, non-leaky message.
@@ -660,7 +663,11 @@ export function createGithubLookupService(
660
663
  return { configured: false, repos: [] };
661
664
  }
662
665
  const snapshots = await deps.cache.listLookupSnapshots(
663
- lookupAccountKeys(accountId),
666
+ await lookupKeysForApp(
667
+ lookup,
668
+ accountId,
669
+ async () => (await deps.appService.get("lookup", null)) !== null,
670
+ ),
664
671
  lookup.appId,
665
672
  );
666
673
  return summarizeLookupSnapshots(
@@ -1031,6 +1038,19 @@ export function createGithubEnterpriseApp(
1031
1038
  const body = c.req.valid("json");
1032
1039
  const { accountId } = c.req.valid("query");
1033
1040
 
1041
+ if (
1042
+ body.repositorySelection === "selected" &&
1043
+ (body.repositories ?? []).length === 0
1044
+ ) {
1045
+ return c.json(
1046
+ {
1047
+ error:
1048
+ "repositories: select at least one repository when repositorySelection is selected",
1049
+ },
1050
+ 400,
1051
+ );
1052
+ }
1053
+
1034
1054
  const installer = await appService.get("installer", accountId);
1035
1055
  if (!installer) {
1036
1056
  throw new ConflictError("the installer App is not configured");
@@ -155,6 +155,31 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
155
155
  let acctA: string;
156
156
  let acctB: string;
157
157
 
158
+ /** A deployment-wide row that predates the second account. */
159
+ const seedGlobal = async (input: typeof lookup) => {
160
+ const data = {
161
+ appId: input.appId,
162
+ slug: input.slug,
163
+ enterpriseSlug: null,
164
+ privateKeyEncrypted: (
165
+ makeStrictTokenCrypto(KEY_A) as { encrypt(v: string): string }
166
+ ).encrypt(input.privateKey),
167
+ };
168
+ const existing = await prisma.gitHubEnterpriseApp.findFirst({
169
+ where: { role: input.role, accountId: null },
170
+ });
171
+ if (existing) {
172
+ await prisma.gitHubEnterpriseApp.update({
173
+ where: { id: existing.id },
174
+ data,
175
+ });
176
+ } else {
177
+ await prisma.gitHubEnterpriseApp.create({
178
+ data: { role: input.role, accountId: null, ...data },
179
+ });
180
+ }
181
+ };
182
+
158
183
  beforeEach(async () => {
159
184
  await prisma.account.deleteMany({
160
185
  where: { name: { in: ["ghe-a", "ghe-b"] } },
@@ -171,7 +196,7 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
171
196
  });
172
197
 
173
198
  it("get(role, accountId) prefers the account row, else falls back to deployment-wide", async () => {
174
- await service.save(lookup);
199
+ await seedGlobal(lookup);
175
200
  expect((await service.get("lookup", acctA))?.appId).toBe("900");
176
201
  await service.save({ ...lookup, accountId: acctA, appId: "901" });
177
202
  const own = await service.get("lookup", acctA);
@@ -182,7 +207,7 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
182
207
  });
183
208
 
184
209
  it("listAccountIds returns each account with Apps of its own once, never the deployment scope", async () => {
185
- await service.save(lookup);
210
+ await seedGlobal(lookup);
186
211
  expect(await service.listAccountIds()).toEqual([]);
187
212
  await service.save({ ...lookup, accountId: acctA });
188
213
  await service.save({ ...installer, accountId: acctA });
@@ -200,7 +225,7 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
200
225
  });
201
226
 
202
227
  it("accounts are isolated: save/delete/recordValidation hit only the targeted row", async () => {
203
- await service.save(lookup);
228
+ await seedGlobal(lookup);
204
229
  await service.save({ ...lookup, accountId: acctA, appId: "A" });
205
230
  await service.save({ ...lookup, accountId: acctB, appId: "B" });
206
231
  await service.recordValidation("lookup", { status: "ok" }, acctA);
@@ -218,7 +243,7 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
218
243
  });
219
244
 
220
245
  it("getPrivateKey follows the same fallback and decrypts the right row", async () => {
221
- await service.save(lookup);
246
+ await seedGlobal(lookup);
222
247
  await service.save({
223
248
  ...lookup,
224
249
  accountId: acctA,
@@ -230,15 +255,15 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
230
255
  });
231
256
 
232
257
  it("save is idempotent per (accountId, role), including the NULL scope", async () => {
233
- await service.save(lookup);
234
- await service.save({ ...lookup, appId: "again" });
258
+ await seedGlobal(lookup);
259
+ await seedGlobal({ ...lookup, appId: "again" });
235
260
  await service.save({ ...lookup, accountId: acctA });
236
261
  await service.save({ ...lookup, accountId: acctA, appId: "again" });
237
262
  expect(await prisma.gitHubEnterpriseApp.count()).toBe(2);
238
263
  });
239
264
 
240
265
  it("the database rejects a second deployment-wide row for a role", async () => {
241
- await service.save(lookup);
266
+ await seedGlobal(lookup);
242
267
  const dup = async () =>
243
268
  prisma.gitHubEnterpriseApp.create({
244
269
  data: {
@@ -252,7 +277,7 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
252
277
  });
253
278
 
254
279
  it("deleting an account cascades to its apps only", async () => {
255
- await service.save(lookup);
280
+ await seedGlobal(lookup);
256
281
  await service.save({ ...lookup, accountId: acctA });
257
282
  await prisma.account.delete({ where: { id: acctA } });
258
283
  expect(await prisma.gitHubEnterpriseApp.count()).toBe(1);
@@ -21,6 +21,7 @@
21
21
 
22
22
  import type { PrismaClient } from "../prisma/client/client.ts";
23
23
  import { type Clock, SystemClock } from "./clock.ts";
24
+ import { assertDeploymentWideAllowed } from "./deployment-wide-settings.ts";
24
25
  import { ApiError, UnprocessableEntityError } from "./errors.ts";
25
26
  import type { TokenCrypto } from "./token-crypto.ts";
26
27
 
@@ -150,6 +151,9 @@ export class GitHubEnterpriseAppService {
150
151
  throw new UnprocessableEntityError("privateKey is required");
151
152
  }
152
153
  const accountId = input.accountId ?? null;
154
+ if (accountId === null) {
155
+ await assertDeploymentWideAllowed(this.prisma, "a GitHub App");
156
+ }
153
157
  const data = {
154
158
  appId: input.appId,
155
159
  slug: input.slug,
@@ -461,44 +461,3 @@ describe("removeRepositories", () => {
461
461
  });
462
462
  }
463
463
  });
464
-
465
- describe("setRepositorySelection", () => {
466
- it("toggles to selected with repositories", async () => {
467
- const { client, calls } = makeClient({ [SELECTION]: "install_selection_success" });
468
- const inst = await client.setRepositorySelection("acme-eng", 501, {
469
- repositorySelection: "selected",
470
- repositories: ["repo-1"],
471
- });
472
- expect(inst.repositorySelection).toBe("selected");
473
- const last = calls[calls.length - 1] as Recorded;
474
- expect(last.method).toBe("PATCH");
475
- expect(JSON.parse(last.body ?? "")).toEqual({
476
- repository_selection: "selected",
477
- repositories: ["repo-1"],
478
- });
479
- });
480
-
481
- it("toggles to all without sending repositories", async () => {
482
- const { client, calls } = makeClient({ [SELECTION]: "install_selection_all" });
483
- const inst = await client.setRepositorySelection("acme-eng", 501, {
484
- repositorySelection: "all",
485
- repositories: ["ignored"],
486
- });
487
- expect(inst.repositorySelection).toBe("all");
488
- expect(JSON.parse((calls[calls.length - 1] as Recorded).body ?? "")).toEqual({
489
- repository_selection: "all",
490
- });
491
- });
492
-
493
- for (const [suffix, kind, status] of ERRORS) {
494
- it(`${suffix} -> ${kind}`, async () => {
495
- const { client } = makeClient({ [SELECTION]: `install_selection_${suffix}` });
496
- const e = await errOf(
497
- client.setRepositorySelection("acme-eng", 501, { repositorySelection: "all" }),
498
- );
499
- expect(e.kind).toBe(kind);
500
- expect(e.status).toBe(status);
501
- expectNoSecrets(e);
502
- });
503
- }
504
- });