@app-vitals/agent-admin 1.54.0 → 1.55.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.
@@ -0,0 +1,21 @@
1
+ -- Surrogate primary key: existing rows (the deployment-wide pair) get a
2
+ -- deterministic id derived from their role; no data is otherwise touched.
3
+ ALTER TABLE "GitHubEnterpriseApp" DROP CONSTRAINT "GitHubEnterpriseApp_pkey";
4
+ ALTER TABLE "GitHubEnterpriseApp" ADD COLUMN "id" TEXT;
5
+ UPDATE "GitHubEnterpriseApp" SET "id" = 'ghe_' || "role";
6
+ ALTER TABLE "GitHubEnterpriseApp" ALTER COLUMN "id" SET NOT NULL;
7
+ ALTER TABLE "GitHubEnterpriseApp" ADD CONSTRAINT "GitHubEnterpriseApp_pkey" PRIMARY KEY ("id");
8
+
9
+ -- Nullable account scope; existing rows stay NULL (deployment-wide).
10
+ ALTER TABLE "GitHubEnterpriseApp" ADD COLUMN "accountId" TEXT;
11
+
12
+ -- CreateIndex
13
+ CREATE UNIQUE INDEX "GitHubEnterpriseApp_accountId_role_key" ON "GitHubEnterpriseApp"("accountId", "role");
14
+
15
+ -- AddForeignKey
16
+ ALTER TABLE "GitHubEnterpriseApp" ADD CONSTRAINT "GitHubEnterpriseApp_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
17
+
18
+ -- Partial unique index (not expressible in Prisma; see the GitHubEnterpriseApp
19
+ -- comment in schema.prisma). The plain (accountId, role) index above cannot
20
+ -- enforce one deployment-wide row per role because NULLs compare distinct.
21
+ CREATE UNIQUE INDEX "GitHubEnterpriseApp_role_global_key" ON "GitHubEnterpriseApp"("role") WHERE "accountId" IS NULL;
@@ -130,12 +130,23 @@ model AgentEnv {
130
130
  }
131
131
 
132
132
  // ─── GitHub Enterprise Apps ───────────────────────────────────────────────────
133
- // Optional admin-level GitHub Apps, one per role ('installer' | 'lookup'), at most
134
- // two rows per deployment; no rows means the feature is off. Deliberately NOT in
135
- // AgentEnv so the private key can never reach the agent config bundle.
133
+ // Optional admin-level GitHub Apps, one per (accountId, role) where role is
134
+ // 'installer' | 'lookup'. accountId null = the deployment-wide pair (at most two
135
+ // rows); an account row overrides it for that account. No rows means the feature
136
+ // is off. Deliberately NOT in AgentEnv so the private key can never reach the
137
+ // agent config bundle.
138
+ //
139
+ // UNIQUENESS: NULLs compare distinct in a plain unique index, so the
140
+ // deployment-wide (accountId NULL) uniqueness is a partial unique index
141
+ // hand-written in 20261116000000_github_enterprise_app_account_id/migration.sql:
142
+ // GitHubEnterpriseApp_role_global_key (accountId NULL)
143
+ // Prisma's schema diff does not see it; keep it when editing this model.
136
144
 
137
145
  model GitHubEnterpriseApp {
138
- role String @id // 'installer' | 'lookup'
146
+ id String @id @default(cuid())
147
+ accountId String?
148
+ account Account? @relation(fields: [accountId], references: [id], onDelete: Cascade)
149
+ role String // 'installer' | 'lookup'
139
150
  appId String
140
151
  slug String
141
152
  enterpriseSlug String? // installer only
@@ -145,6 +156,8 @@ model GitHubEnterpriseApp {
145
156
  lastValidationError String?
146
157
  createdAt DateTime @default(now())
147
158
  updatedAt DateTime @updatedAt
159
+
160
+ @@unique([accountId, role])
148
161
  }
149
162
 
150
163
  // ─── Agent Cron Jobs ──────────────────────────────────────────────────────────
@@ -279,6 +292,7 @@ model Account {
279
292
  members AccountMember[]
280
293
  invites AccountInvite[]
281
294
  templates AgentTemplate[]
295
+ githubEnterpriseApps GitHubEnterpriseApp[]
282
296
  }
283
297
 
284
298
  // ─── Agent Templates ──────────────────────────────────────────────────────────
@@ -67,8 +67,6 @@ export interface GithubEnterpriseSettingsPageOpts {
67
67
  orgs?: GheOrgs;
68
68
  /** Readable message when the org list could not be loaded. */
69
69
  orgsError?: string;
70
- /** Agent whose App the install actions target (carried via ?agentId=). */
71
- agentId?: string;
72
70
  error?: string;
73
71
  notice?: string;
74
72
  /** Warning codes from the last validate (carried via ?warn=); unknown codes are ignored. */
@@ -204,14 +202,8 @@ function installedCell(v: boolean | null): string {
204
202
  function orgsCard(opts: GithubEnterpriseSettingsPageOpts): string {
205
203
  const { status } = opts;
206
204
  if (!status.installer) return "";
207
- const agentId = opts.agentId ?? "";
208
205
  const lookupSlug = status.lookup?.slug;
209
206
 
210
- const filter = `<form method="GET" action="${BASE}" style="display:flex;gap:8px;margin:8px 0">
211
- <input name="agentId" class="form-input" placeholder="Agent ID (to check its App)" value="${escapeHtml(agentId)}" style="max-width:280px" />
212
- <button type="submit" class="btn btn-secondary">Check agent</button>
213
- </form>`;
214
-
215
207
  let body: string;
216
208
  if (opts.orgsError) {
217
209
  body = `<div class="alert alert-error">${escapeHtml(opts.orgsError)}</div>`;
@@ -219,38 +211,27 @@ function orgsCard(opts: GithubEnterpriseSettingsPageOpts): string {
219
211
  const orgs = opts.orgs?.orgs ?? [];
220
212
  const rows =
221
213
  orgs.length === 0
222
- ? `<tr><td colspan="4" class="empty-state">No installable organizations.</td></tr>`
214
+ ? `<tr><td colspan="3" class="empty-state">No installable organizations.</td></tr>`
223
215
  : orgs
224
216
  .map((o) => {
225
- const login = escapeHtml(o.login);
226
- const lookupAction = !lookupSlug
227
- ? ""
228
- : o.lookupAppInstalled
217
+ const lookupAction =
218
+ !lookupSlug || o.lookupAppInstalled
229
219
  ? ""
230
220
  : `<a class="btn btn-secondary" style="font-size:12px;padding:4px 10px" href="https://github.com/apps/${escapeHtml(lookupSlug)}/installations/new" target="_blank" rel="noopener noreferrer">Install lookup app</a>`;
231
- const agentAction = `<form method="POST" action="${BASE}/orgs/${encodeURIComponent(o.login)}/install" style="display:inline-flex;gap:4px;margin:0">
232
- <input name="agentId" class="form-input" required placeholder="Agent ID" value="${escapeHtml(agentId)}" style="max-width:160px;padding:4px 8px" />
233
- <button type="submit" class="btn btn-primary" style="font-size:12px;padding:4px 10px">Install agent app</button>
234
- </form>`;
235
221
  return `<tr>
236
- <td>${login}</td>
222
+ <td>${escapeHtml(o.login)}</td>
237
223
  <td>${installedCell(o.lookupAppInstalled)}</td>
238
- <td>${installedCell(o.agentAppInstalled)}</td>
239
- <td style="text-align:right">${lookupAction} ${agentAction}</td>
224
+ <td style="text-align:right">${lookupAction}</td>
240
225
  </tr>`;
241
226
  })
242
227
  .join("\n");
243
- const reason = opts.orgs?.agentAppReason
244
- ? `<div class="alert alert-error">${escapeHtml(opts.orgs.agentAppReason)}</div>`
245
- : "";
246
- body = `${reason}<table class="data-table">
247
- <thead><tr><th>Organization</th><th>Lookup app</th><th>Agent app</th><th></th></tr></thead>
228
+ body = `<table class="data-table">
229
+ <thead><tr><th>Organization</th><th>Lookup app</th><th></th></tr></thead>
248
230
  <tbody>${rows}</tbody>
249
231
  </table>`;
250
232
  }
251
233
  return `<div class="card">
252
234
  <div class="card-title">Organizations</div>
253
- ${filter}
254
235
  ${body}
255
236
  </div>`;
256
237
  }
@@ -175,10 +175,9 @@ describe("renderGithubEnterpriseSettingsPage", () => {
175
175
  expect(html).toContain("Key not set");
176
176
  });
177
177
 
178
- test("org list renders install actions and lookup state", () => {
178
+ test("org list shows only org, lookup state and the lookup install link", () => {
179
179
  const html = renderGithubEnterpriseSettingsPage({
180
180
  ...base,
181
- agentId: "agent-1",
182
181
  status: {
183
182
  configured: true,
184
183
  installer: app(),
@@ -190,7 +189,6 @@ describe("renderGithubEnterpriseSettingsPage", () => {
190
189
  },
191
190
  orgs: {
192
191
  configured: true,
193
- agentAppSlug: "agent-app",
194
192
  orgs: [
195
193
  {
196
194
  id: 1,
@@ -212,35 +210,12 @@ describe("renderGithubEnterpriseSettingsPage", () => {
212
210
  expect(html).toContain(
213
211
  "https://github.com/apps/acme-lookup/installations/new",
214
212
  );
215
- expect(html).toContain(
216
- 'action="/admin/settings/github-enterprise/orgs/org-a/install"',
217
- );
218
- expect(html).toContain('value="agent-1"');
219
- expect(html).toContain("Install agent app");
220
213
  expect(html).toContain("Installed");
221
- });
222
-
223
- test("check agent shows the private-App reason, escaped", () => {
224
- const html = renderGithubEnterpriseSettingsPage({
225
- ...base,
226
- agentId: "agent-1",
227
- status: { configured: true, installer: app(), lookup: null },
228
- orgs: {
229
- configured: true,
230
- agentAppSlug: "agent-app",
231
- agentAppReason: "the agent's App 'agent-app' is private <b>",
232
- orgs: [
233
- {
234
- id: 1,
235
- login: "org-a",
236
- lookupAppInstalled: null,
237
- agentAppInstalled: false,
238
- },
239
- ],
240
- },
241
- });
242
- expect(html).toContain("is private &lt;b&gt;");
243
- expect(html).not.toContain("private <b>");
214
+ expect(html).not.toContain('name="agentId"');
215
+ expect(html).not.toContain("Install agent app");
216
+ expect(html).not.toContain("Agent app");
217
+ expect(html).not.toContain("Check agent");
218
+ expect(html).not.toContain("/orgs/org-a/install");
244
219
  });
245
220
 
246
221
  test("org list failure and top-level error/notice are escaped messages", () => {
@@ -338,21 +338,13 @@ describe("form posts", () => {
338
338
  );
339
339
  });
340
340
 
341
- it("install without a configured installer surfaces the 409 message", async () => {
341
+ it("the per-org agent install UI route is gone", async () => {
342
342
  const { app } = setup();
343
343
  const res = await app.request(
344
344
  `${BASE}/orgs/org-a/install`,
345
345
  form({ agentId: "agent-1" }),
346
346
  );
347
- expect(res.status).toBe(409);
348
- expect(await res.text()).toContain("the installer App is not configured");
349
- });
350
-
351
- it("install with an empty agent id is a readable 400", async () => {
352
- const { app } = setup();
353
- const res = await app.request(`${BASE}/orgs/org-a/install`, form({}));
354
- expect(res.status).toBe(400);
355
- expect(await res.text()).toContain("Agent ID is required");
347
+ expect(res.status).toBe(404);
356
348
  });
357
349
 
358
350
  it("org list failure from GitHub renders a message, not a 500", async () => {
@@ -32,8 +32,6 @@ const NOTICES: Record<string, string> = {
32
32
  saved: "Credentials saved. Validate the app to check its permissions.",
33
33
  deleted: "App removed.",
34
34
  validated: "Validation finished; see the status below.",
35
- installed: "Agent app installed.",
36
- already: "The agent app was already installed on that organization.",
37
35
  };
38
36
 
39
37
  // Deliberately not imported from the enterprise credential service: that
@@ -96,7 +94,6 @@ export function registerAdminGithubEnterpriseRoutes(
96
94
  c: Context<AdminUIEnv>,
97
95
  flash: { error?: string; notice?: string; status?: number } = {},
98
96
  ): Promise<Response> {
99
- const agentId = c.req.query("agentId")?.trim() || undefined;
100
97
  const statusRes = await call<GheStatus>(
101
98
  c,
102
99
  "GET",
@@ -118,8 +115,7 @@ export function registerAdminGithubEnterpriseRoutes(
118
115
  let orgs: GheOrgs | undefined;
119
116
  let orgsError: string | undefined;
120
117
  if (status.installer) {
121
- const qs = agentId ? `?agentId=${encodeURIComponent(agentId)}` : "";
122
- const r = await call<GheOrgs>(c, "GET", `/github-enterprise/orgs${qs}`);
118
+ const r = await call<GheOrgs>(c, "GET", "/github-enterprise/orgs");
123
119
  if (r.ok) orgs = r.data;
124
120
  else orgsError = r.error;
125
121
  }
@@ -133,7 +129,6 @@ export function registerAdminGithubEnterpriseRoutes(
133
129
  status,
134
130
  orgs,
135
131
  orgsError,
136
- agentId,
137
132
  error: flash.error,
138
133
  notice,
139
134
  warnings: c.req.query("warn")?.split(",").filter(Boolean),
@@ -151,11 +146,8 @@ export function registerAdminGithubEnterpriseRoutes(
151
146
  return new FormData();
152
147
  }
153
148
  }
154
- const back = (c: Context<AdminUIEnv>, notice: string, agentId?: string) =>
155
- c.redirect(
156
- `${BASE}?notice=${notice}${agentId ? `&agentId=${encodeURIComponent(agentId)}` : ""}`,
157
- 302,
158
- );
149
+ const back = (c: Context<AdminUIEnv>, notice: string) =>
150
+ c.redirect(`${BASE}?notice=${notice}`, 302);
159
151
  const fail = (c: Context<AdminUIEnv>, r: ApiResult<unknown>) =>
160
152
  renderPage(c, { error: r.error, status: r.status >= 400 ? r.status : 400 });
161
153
 
@@ -213,29 +205,4 @@ export function registerAdminGithubEnterpriseRoutes(
213
205
  return r.ok ? back(c, "deleted") : fail(c, r);
214
206
  },
215
207
  );
216
-
217
- app.post(
218
- `${BASE}/orgs/:org/install`,
219
- deps.requireAuth,
220
- requireAdmin,
221
- async (c) => {
222
- const org = c.req.param("org");
223
- const agentId = field(await readForm(c), "agentId");
224
- if (!agentId) {
225
- return renderPage(c, { error: "Agent ID is required.", status: 400 });
226
- }
227
- const r = await call<{ created: boolean }>(
228
- c,
229
- "POST",
230
- `/github-enterprise/orgs/${encodeURIComponent(org)}/install`,
231
- { agentId },
232
- );
233
- if (!r.ok) return fail(c, r);
234
- return back(
235
- c,
236
- r.data?.created === false ? "already" : "installed",
237
- agentId,
238
- );
239
- },
240
- );
241
208
  }
@@ -145,7 +145,7 @@ describeOrSkip("github-enterprise API (integration)", () => {
145
145
  const base = "/admin/settings/github-enterprise/apps/lookup";
146
146
  const fields = { appId: "777", slug: "example-lookup" };
147
147
  const snapshot = async () => {
148
- const row = await prisma.gitHubEnterpriseApp.findUnique({
148
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
149
149
  where: { role: "lookup" },
150
150
  });
151
151
  return {
@@ -169,7 +169,7 @@ describeOrSkip("github-enterprise API (integration)", () => {
169
169
  const res = await ui.request(base, { method: "POST", body: upload });
170
170
  expect(res.status).toBe(302);
171
171
  expect(await snapshot()).toEqual(pasted);
172
- const row = await prisma.gitHubEnterpriseApp.findUnique({
172
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
173
173
  where: { role: "lookup" },
174
174
  });
175
175
  expect(row?.privateKeyEncrypted).not.toContain(PEM_BODY);
@@ -194,7 +194,7 @@ describeOrSkip("github-enterprise API (integration)", () => {
194
194
  expect(text).not.toContain("ghs_cassette");
195
195
  expect(JSON.parse(text)).toMatchObject({ ok: true, status: "valid" });
196
196
 
197
- const row = await prisma.gitHubEnterpriseApp.findUnique({
197
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
198
198
  where: { role: "installer" },
199
199
  });
200
200
  expect(row?.lastValidationStatus).toBe("valid");
@@ -223,7 +223,7 @@ describeOrSkip("github-enterprise API (integration)", () => {
223
223
  },
224
224
  );
225
225
  expect(await res.json()).toMatchObject({ ok: false, status: "error" });
226
- const row = await prisma.gitHubEnterpriseApp.findUnique({
226
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
227
227
  where: { role: "installer" },
228
228
  });
229
229
  expect(row?.lastValidationStatus).toBe("error");
@@ -304,7 +304,7 @@ describeOrSkip("github-enterprise API (integration)", () => {
304
304
  const envService = new AgentEnvService(prisma, identityCrypto);
305
305
  await envService.upsert(agent.id, { GH_APP_SLUG: "example-agent-app" });
306
306
  await put(build());
307
- const row = await prisma.gitHubEnterpriseApp.findUnique({
307
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
308
308
  where: { role: "installer" },
309
309
  });
310
310
  const needles = [
@@ -88,7 +88,7 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
88
88
 
89
89
  it("stores the key encrypted and round-trips it via getPrivateKey", async () => {
90
90
  await service.save(installer);
91
- const row = await prisma.gitHubEnterpriseApp.findUnique({
91
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
92
92
  where: { role: "installer" },
93
93
  });
94
94
  expect(row?.privateKeyEncrypted).not.toContain("SUPERSECRETPEMBODY");
@@ -134,14 +134,14 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
134
134
 
135
135
  it("strict decrypt: tampered and legacy plain-text values throw", async () => {
136
136
  await service.save(installer);
137
- const row = await prisma.gitHubEnterpriseApp.findUnique({
137
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
138
138
  where: { role: "installer" },
139
139
  });
140
140
  const [iv, ct, tag] = (row?.privateKeyEncrypted ?? "").split(":");
141
141
  const flipped = (ct[0] === "0" ? "1" : "0") + ct.slice(1);
142
142
  for (const bad of [`${iv}:${flipped}:${tag}`, PEM]) {
143
143
  await prisma.gitHubEnterpriseApp.update({
144
- where: { role: "installer" },
144
+ where: { id: row?.id },
145
145
  data: { privateKeyEncrypted: bad },
146
146
  });
147
147
  const err = await service.getPrivateKey("installer").catch((e) => e);
@@ -149,4 +149,102 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
149
149
  expect(err.message).not.toContain("SUPERSECRETPEMBODY");
150
150
  }
151
151
  });
152
+
153
+ describe("account scope", () => {
154
+ const lookup = { ...installer, role: "lookup" as const, appId: "900" };
155
+ let acctA: string;
156
+ let acctB: string;
157
+
158
+ beforeEach(async () => {
159
+ await prisma.account.deleteMany({
160
+ where: { name: { in: ["ghe-a", "ghe-b"] } },
161
+ });
162
+ acctA = (await prisma.account.create({ data: { name: "ghe-a" } })).id;
163
+ acctB = (await prisma.account.create({ data: { name: "ghe-b" } })).id;
164
+ });
165
+
166
+ afterEach(async () => {
167
+ await prisma.gitHubEnterpriseApp.deleteMany();
168
+ await prisma.account.deleteMany({
169
+ where: { id: { in: [acctA, acctB] } },
170
+ });
171
+ });
172
+
173
+ it("get(role, accountId) prefers the account row, else falls back to deployment-wide", async () => {
174
+ await service.save(lookup);
175
+ expect((await service.get("lookup", acctA))?.appId).toBe("900");
176
+ await service.save({ ...lookup, accountId: acctA, appId: "901" });
177
+ const own = await service.get("lookup", acctA);
178
+ expect(own?.appId).toBe("901");
179
+ expect(own?.accountId).toBe(acctA);
180
+ expect((await service.get("lookup", acctB))?.appId).toBe("900");
181
+ expect((await service.get("lookup"))?.appId).toBe("900");
182
+ });
183
+
184
+ it("get(role) without accountId never sees an account row", async () => {
185
+ await service.save({ ...lookup, accountId: acctA });
186
+ expect(await service.get("lookup")).toBeNull();
187
+ expect(await service.list()).toEqual([]);
188
+ expect(await service.list(acctA)).toHaveLength(1);
189
+ });
190
+
191
+ it("accounts are isolated: save/delete/recordValidation hit only the targeted row", async () => {
192
+ await service.save(lookup);
193
+ await service.save({ ...lookup, accountId: acctA, appId: "A" });
194
+ await service.save({ ...lookup, accountId: acctB, appId: "B" });
195
+ await service.recordValidation("lookup", { status: "ok" }, acctA);
196
+ expect((await service.get("lookup", acctA))?.lastValidationStatus).toBe(
197
+ "ok",
198
+ );
199
+ expect((await service.get("lookup", acctB))?.lastValidationStatus).toBe(
200
+ null,
201
+ );
202
+ expect((await service.get("lookup"))?.lastValidationStatus).toBe(null);
203
+ await service.delete("lookup", acctA);
204
+ expect((await service.get("lookup", acctA))?.appId).toBe("900");
205
+ expect((await service.get("lookup", acctB))?.appId).toBe("B");
206
+ expect(await prisma.gitHubEnterpriseApp.count()).toBe(2);
207
+ });
208
+
209
+ it("getPrivateKey follows the same fallback and decrypts the right row", async () => {
210
+ await service.save(lookup);
211
+ await service.save({
212
+ ...lookup,
213
+ accountId: acctA,
214
+ privateKey: `${PEM}-ACCT`,
215
+ });
216
+ expect(await service.getPrivateKey("lookup", acctA)).toBe(`${PEM}-ACCT`);
217
+ expect(await service.getPrivateKey("lookup", acctB)).toBe(PEM);
218
+ expect(await service.getPrivateKey("lookup")).toBe(PEM);
219
+ });
220
+
221
+ it("save is idempotent per (accountId, role), including the NULL scope", async () => {
222
+ await service.save(lookup);
223
+ await service.save({ ...lookup, appId: "again" });
224
+ await service.save({ ...lookup, accountId: acctA });
225
+ await service.save({ ...lookup, accountId: acctA, appId: "again" });
226
+ expect(await prisma.gitHubEnterpriseApp.count()).toBe(2);
227
+ });
228
+
229
+ it("the database rejects a second deployment-wide row for a role", async () => {
230
+ await service.save(lookup);
231
+ const dup = async () =>
232
+ prisma.gitHubEnterpriseApp.create({
233
+ data: {
234
+ role: "lookup",
235
+ appId: "x",
236
+ slug: "x",
237
+ privateKeyEncrypted: "x",
238
+ },
239
+ });
240
+ await expect(dup()).rejects.toThrow();
241
+ });
242
+
243
+ it("deleting an account cascades to its apps only", async () => {
244
+ await service.save(lookup);
245
+ await service.save({ ...lookup, accountId: acctA });
246
+ await prisma.account.delete({ where: { id: acctA } });
247
+ expect(await prisma.gitHubEnterpriseApp.count()).toBe(1);
248
+ });
249
+ });
152
250
  });
@@ -1,8 +1,11 @@
1
1
  /**
2
2
  * admin/src/github-enterprise-apps.ts
3
3
  * GitHubEnterpriseAppService — storage for the two optional admin-level GitHub
4
- * Apps ('installer' and 'lookup'), at most one row per role. No rows means the
5
- * feature is off.
4
+ * Apps ('installer' and 'lookup'), at most one row per (accountId, role).
5
+ * accountId null is the deployment-wide pair; an account row overrides it for
6
+ * that account (get() falls back to the deployment-wide row). Every method takes
7
+ * an optional accountId; omitting it behaves as before (deployment-wide row).
8
+ * No rows means the feature is off.
6
9
  *
7
10
  * The private key is encrypted on write (AES-256-GCM via TokenCrypto) and is
8
11
  * never returned by any read path: reads return metadata plus a `keySet` flag.
@@ -26,6 +29,8 @@ export type GitHubEnterpriseAppRole =
26
29
  (typeof GITHUB_ENTERPRISE_APP_ROLES)[number];
27
30
 
28
31
  export interface GitHubEnterpriseAppMetadata {
32
+ /** Null/absent for the deployment-wide app. */
33
+ accountId?: string | null;
29
34
  role: string;
30
35
  appId: string;
31
36
  slug: string;
@@ -40,6 +45,8 @@ export interface GitHubEnterpriseAppMetadata {
40
45
  }
41
46
 
42
47
  export interface SaveGitHubEnterpriseAppInput {
48
+ /** Omit/null for the deployment-wide app. */
49
+ accountId?: string | null;
43
50
  role: GitHubEnterpriseAppRole;
44
51
  appId: string;
45
52
  slug: string;
@@ -50,6 +57,7 @@ export interface SaveGitHubEnterpriseAppInput {
50
57
  }
51
58
 
52
59
  interface GitHubEnterpriseAppRow {
60
+ accountId?: string | null;
53
61
  role: string;
54
62
  appId: string;
55
63
  slug: string;
@@ -86,6 +94,7 @@ export function toGitHubEnterpriseAppMetadata(
86
94
  row: GitHubEnterpriseAppRow,
87
95
  ): GitHubEnterpriseAppMetadata {
88
96
  return {
97
+ accountId: row.accountId ?? null,
89
98
  role: row.role,
90
99
  appId: row.appId,
91
100
  slug: row.slug,
@@ -115,7 +124,23 @@ export class GitHubEnterpriseAppService {
115
124
  private clock: Clock = SystemClock(),
116
125
  ) {}
117
126
 
118
- /** Create or replace the app for a role. Resets validation state. */
127
+ /** Exact-scope row lookup: no fallback. */
128
+ private findExact(role: GitHubEnterpriseAppRole, accountId: string | null) {
129
+ return this.prisma.gitHubEnterpriseApp.findFirst({
130
+ where: { role, accountId },
131
+ });
132
+ }
133
+
134
+ /** Account row if present, else the deployment-wide row. */
135
+ private async resolve(
136
+ role: GitHubEnterpriseAppRole,
137
+ accountId: string | null,
138
+ ) {
139
+ const own = accountId ? await this.findExact(role, accountId) : null;
140
+ return own ?? (await this.findExact(role, null));
141
+ }
142
+
143
+ /** Create or replace the app for a (accountId, role). Resets validation state. */
119
144
  async save(
120
145
  input: SaveGitHubEnterpriseAppInput,
121
146
  ): Promise<GitHubEnterpriseAppMetadata> {
@@ -124,6 +149,7 @@ export class GitHubEnterpriseAppService {
124
149
  if (!input.privateKey) {
125
150
  throw new UnprocessableEntityError("privateKey is required");
126
151
  }
152
+ const accountId = input.accountId ?? null;
127
153
  const data = {
128
154
  appId: input.appId,
129
155
  slug: input.slug,
@@ -135,48 +161,66 @@ export class GitHubEnterpriseAppService {
135
161
  lastValidationError: null,
136
162
  updatedAt: this.clock.now(),
137
163
  };
138
- const row = await this.prisma.gitHubEnterpriseApp.upsert({
139
- where: { role: input.role },
140
- create: { role: input.role, ...data },
141
- update: data,
142
- });
164
+ // Not upsert: Prisma cannot target the NULL accountId side of the
165
+ // composite unique. The partial unique indexes still reject a racing
166
+ // duplicate insert.
167
+ const existing = await this.findExact(input.role, accountId);
168
+ const row = existing
169
+ ? await this.prisma.gitHubEnterpriseApp.update({
170
+ where: { id: existing.id },
171
+ data,
172
+ })
173
+ : await this.prisma.gitHubEnterpriseApp.create({
174
+ data: { role: input.role, accountId, ...data },
175
+ });
143
176
  return toGitHubEnterpriseAppMetadata(row);
144
177
  }
145
178
 
179
+ /** The account's row if present, otherwise the deployment-wide row. */
146
180
  async get(
147
181
  role: GitHubEnterpriseAppRole,
182
+ accountId?: string | null,
148
183
  ): Promise<GitHubEnterpriseAppMetadata | null> {
149
184
  assertRole(role);
150
- const row = await this.prisma.gitHubEnterpriseApp.findUnique({
151
- where: { role },
152
- });
185
+ const row = await this.resolve(role, accountId ?? null);
153
186
  return row ? toGitHubEnterpriseAppMetadata(row) : null;
154
187
  }
155
188
 
156
- async list(): Promise<GitHubEnterpriseAppMetadata[]> {
189
+ /** Rows at exactly this scope (deployment-wide when accountId is omitted). */
190
+ async list(
191
+ accountId?: string | null,
192
+ ): Promise<GitHubEnterpriseAppMetadata[]> {
157
193
  const rows = await this.prisma.gitHubEnterpriseApp.findMany({
194
+ where: { accountId: accountId ?? null },
158
195
  orderBy: { role: "asc" },
159
196
  });
160
197
  return rows.map(toGitHubEnterpriseAppMetadata);
161
198
  }
162
199
 
163
- /** Delete the app for a role. No-ops if absent. */
164
- async delete(role: GitHubEnterpriseAppRole): Promise<void> {
200
+ /** Delete the app at exactly this (accountId, role). No-ops if absent. */
201
+ async delete(
202
+ role: GitHubEnterpriseAppRole,
203
+ accountId?: string | null,
204
+ ): Promise<void> {
165
205
  assertRole(role);
166
- await this.prisma.gitHubEnterpriseApp.deleteMany({ where: { role } });
206
+ await this.prisma.gitHubEnterpriseApp.deleteMany({
207
+ where: { role, accountId: accountId ?? null },
208
+ });
167
209
  }
168
210
 
169
211
  /**
170
- * Server-side only: decrypt the stored PEM. Strict — any failure throws
212
+ * Server-side only: decrypt the stored PEM of the row get() would return
213
+ * (account row, else deployment-wide). Strict — any failure throws
171
214
  * PrivateKeyDecryptError (never includes the PEM or ciphertext). Returns
172
- * null when the role has no row.
215
+ * null when no row resolves.
173
216
  */
174
- async getPrivateKey(role: GitHubEnterpriseAppRole): Promise<string | null> {
217
+ async getPrivateKey(
218
+ role: GitHubEnterpriseAppRole,
219
+ accountId?: string | null,
220
+ ): Promise<string | null> {
175
221
  assertRole(role);
176
222
  if (!this.crypto) throw new PrivateKeyEncryptionUnavailableError();
177
- const row = await this.prisma.gitHubEnterpriseApp.findUnique({
178
- where: { role },
179
- });
223
+ const row = await this.resolve(role, accountId ?? null);
180
224
  if (!row) return null;
181
225
  try {
182
226
  return this.crypto.decrypt(row.privateKeyEncrypted);
@@ -185,14 +229,15 @@ export class GitHubEnterpriseAppService {
185
229
  }
186
230
  }
187
231
 
188
- /** Record the outcome of a validation attempt. The error text must not contain key material. */
232
+ /** Record the outcome of a validation attempt on exactly this (accountId, role). The error text must not contain key material. */
189
233
  async recordValidation(
190
234
  role: GitHubEnterpriseAppRole,
191
235
  result: { status: string; error?: string | null },
236
+ accountId?: string | null,
192
237
  ): Promise<void> {
193
238
  assertRole(role);
194
239
  await this.prisma.gitHubEnterpriseApp.updateMany({
195
- where: { role },
240
+ where: { role, accountId: accountId ?? null },
196
241
  data: {
197
242
  lastValidationStatus: result.status,
198
243
  lastValidatedAt: this.clock.now(),