@app-vitals/agent-admin 1.107.2 → 1.107.3

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 (50) hide show
  1. package/e2e/real/seed.ts +0 -1
  2. package/package.json +2 -2
  3. package/prisma/client/internal/class.ts +4 -4
  4. package/prisma/client/internal/prismaNamespace.ts +1 -5
  5. package/prisma/client/internal/prismaNamespaceBrowser.ts +1 -5
  6. package/prisma/client/models/AgentMember.ts +26 -61
  7. package/prisma/client/models/ChatThreadWatch.ts +19 -47
  8. package/prisma/client/models/PushSubscription.ts +15 -43
  9. package/prisma/client/models/UserNotificationPrefs.ts +38 -66
  10. package/prisma/migrations/20261130000000_drop_email_key_columns/migration.sql +49 -0
  11. package/prisma/schema/schema.prisma +11 -15
  12. package/src/account-member-removal.integration.test.ts +31 -44
  13. package/src/account-members.ts +4 -6
  14. package/src/account-onboarding.ts +2 -5
  15. package/src/account-onboarding.unit.test.ts +71 -0
  16. package/src/accounts.ts +1 -3
  17. package/src/admin-dev-login.smoke.test.ts +1 -1
  18. package/src/admin-local-agent.smoke.test.ts +3 -3
  19. package/src/admin-ui-agent-members.smoke.test.ts +29 -1
  20. package/src/admin-ui.fixtures.ts +1 -1
  21. package/src/admin-ui.smoke.test.ts +18 -18
  22. package/src/admin-ui.ts +20 -12
  23. package/src/agent-cron-run-stats.smoke.test.ts +1 -1
  24. package/src/agent-deletion.integration.test.ts +1 -1
  25. package/src/agent-members.integration.test.ts +14 -10
  26. package/src/agent-members.ts +28 -18
  27. package/src/agents-api.integration.test.ts +2 -2
  28. package/src/agents-api.smoke.test.ts +5 -5
  29. package/src/agents.integration.test.ts +1 -2
  30. package/src/api.smoke.test.ts +1 -1
  31. package/src/chat.smoke.test.ts +68 -14
  32. package/src/drop-email-key-columns-migration.integration.test.ts +141 -0
  33. package/src/ensure-account-member.integration.test.ts +17 -232
  34. package/src/ensure-account-member.ts +0 -5
  35. package/src/github-enterprise-client.unit.test.ts +62 -2
  36. package/src/member-rows.ts +24 -0
  37. package/src/member-rows.unit.test.ts +48 -0
  38. package/src/principals-api.integration.test.ts +3 -2
  39. package/src/push-service.integration.test.ts +7 -12
  40. package/src/push-service.ts +28 -39
  41. package/src/push-service.unit.test.ts +8 -8
  42. package/src/slack-provisioning.integration.test.ts +1 -1
  43. package/src/user-notification-prefs.integration.test.ts +5 -16
  44. package/src/user-notification-prefs.ts +12 -18
  45. package/scripts/backfill-member-id.ts +0 -50
  46. package/src/member-id-backfill.integration.test.ts +0 -167
  47. package/src/member-id-backfill.ts +0 -253
  48. package/src/member-id-backfill.unit.test.ts +0 -12
  49. package/src/member-id-stamp.ts +0 -68
  50. package/src/member-id-stamp.unit.test.ts +0 -81
@@ -0,0 +1,141 @@
1
+ /**
2
+ * admin/src/drop-email-key-columns-migration.integration.test.ts
3
+ * Migration test for 20261130000000_drop_email_key_columns (ACM-5.1): the
4
+ * email key columns on AgentMember, ChatThreadWatch, PushSubscription and
5
+ * UserNotificationPrefs are dropped and uniques re-keyed on memberId.
6
+ *
7
+ * Replays the real migration files inside a throwaway Postgres schema:
8
+ * - guard: any NULL memberId row aborts the migration, changing nothing.
9
+ * - seeded: fully-stamped rows survive; email columns are gone; the new
10
+ * uniques / primary key are enforced.
11
+ *
12
+ * Requires DATABASE_URL_ADMIN_TEST; skips otherwise.
13
+ */
14
+
15
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
16
+ import { readdirSync, readFileSync } from "node:fs";
17
+ import { Client } from "pg";
18
+
19
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
20
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
21
+
22
+ const MIGRATIONS_DIR = new URL("../prisma/migrations/", import.meta.url);
23
+ const DROP = "20261130000000_drop_email_key_columns";
24
+
25
+ const ALL_MIGRATIONS = readdirSync(MIGRATIONS_DIR, { withFileTypes: true })
26
+ .filter((d) => d.isDirectory())
27
+ .map((d) => d.name)
28
+ .sort();
29
+
30
+ function migrationSql(dir: string): string {
31
+ return readFileSync(new URL(`${dir}/migration.sql`, MIGRATIONS_DIR), "utf8");
32
+ }
33
+
34
+ describeOrSkip("drop_email_key_columns migration (ACM-5.1)", () => {
35
+ const schema = `drop_email_keys_${process.pid}_${Date.now()}`;
36
+ let client: Client;
37
+
38
+ const columns = async (table: string): Promise<string[]> =>
39
+ (
40
+ await client.query<{ column_name: string }>(
41
+ `SELECT column_name FROM information_schema.columns
42
+ WHERE table_schema = $1 AND table_name = $2`,
43
+ [schema, table],
44
+ )
45
+ ).rows.map((r) => r.column_name);
46
+
47
+ const seed = async (memberId: string | null): Promise<void> => {
48
+ await client.query(
49
+ `INSERT INTO "Agent" ("id","name","updatedAt") VALUES ('a1','a1',now())`,
50
+ );
51
+ await client.query(
52
+ `INSERT INTO "AgentMember" ("id","agentId","email","memberId")
53
+ VALUES ('am1','a1','x@acme.com',$1)`,
54
+ [memberId],
55
+ );
56
+ await client.query(
57
+ `INSERT INTO "ChatThreadWatch" ("id","userEmail","threadId","agentId","memberId","updatedAt")
58
+ VALUES ('w1','x@acme.com','t1','a1',$1,now())`,
59
+ [memberId],
60
+ );
61
+ await client.query(
62
+ `INSERT INTO "PushSubscription" ("id","userEmail","endpoint","p256dh","auth","memberId","updatedAt")
63
+ VALUES ('p1','x@acme.com','https://push/1','k','a',$1,now())`,
64
+ [memberId],
65
+ );
66
+ await client.query(
67
+ `INSERT INTO "UserNotificationPrefs" ("userEmail","memberId","updatedAt")
68
+ VALUES ('x@acme.com',$1,now())`,
69
+ [memberId],
70
+ );
71
+ };
72
+
73
+ beforeEach(async () => {
74
+ client = new Client({ connectionString: TEST_DB as string });
75
+ await client.connect();
76
+ await client.query(`CREATE SCHEMA "${schema}"`);
77
+ await client.query(`SET search_path TO "${schema}"`);
78
+ for (const dir of ALL_MIGRATIONS.slice(0, ALL_MIGRATIONS.indexOf(DROP))) {
79
+ await client.query(migrationSql(dir));
80
+ }
81
+ });
82
+
83
+ afterEach(async () => {
84
+ await client.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`);
85
+ await client.end();
86
+ });
87
+
88
+ it("is the last migration in apply order", () => {
89
+ expect(ALL_MIGRATIONS.at(-1)).toBe(DROP);
90
+ });
91
+
92
+ it("aborts, changing nothing, while any row has a NULL memberId", async () => {
93
+ await seed(null);
94
+ await expect(client.query(migrationSql(DROP))).rejects.toThrow(
95
+ /ACM-5\.1 aborted.*Stamp each listed row with its AccountMember id, or delete it/,
96
+ );
97
+ expect(await columns("AgentMember")).toContain("email");
98
+ expect(await columns("UserNotificationPrefs")).toContain("userEmail");
99
+ });
100
+
101
+ it("drops the email columns, keeps rows, and re-keys uniques on memberId", async () => {
102
+ await seed("m1");
103
+ await client.query(migrationSql(DROP));
104
+
105
+ for (const [table, col] of [
106
+ ["AgentMember", "email"],
107
+ ["ChatThreadWatch", "userEmail"],
108
+ ["PushSubscription", "userEmail"],
109
+ ["UserNotificationPrefs", "userEmail"],
110
+ ] as const) {
111
+ expect(await columns(table)).not.toContain(col);
112
+ expect(await columns(table)).toContain("memberId");
113
+ const { rows } = await client.query(
114
+ `SELECT count(*)::int AS n FROM "${table}"`,
115
+ );
116
+ expect(rows[0].n).toBe(1);
117
+ }
118
+
119
+ await expect(
120
+ client.query(
121
+ `INSERT INTO "AgentMember" ("id","agentId","memberId") VALUES ('am2','a1','m1')`,
122
+ ),
123
+ ).rejects.toThrow(/AgentMember_agentId_memberId_key/);
124
+ await expect(
125
+ client.query(
126
+ `INSERT INTO "ChatThreadWatch" ("id","threadId","agentId","memberId","updatedAt")
127
+ VALUES ('w2','t1','a1','m1',now())`,
128
+ ),
129
+ ).rejects.toThrow(/ChatThreadWatch_memberId_threadId_key/);
130
+ await expect(
131
+ client.query(
132
+ `INSERT INTO "UserNotificationPrefs" ("memberId","updatedAt") VALUES ('m1',now())`,
133
+ ),
134
+ ).rejects.toThrow(/UserNotificationPrefs_pkey/);
135
+ await expect(
136
+ client.query(
137
+ `INSERT INTO "AgentMember" ("id","agentId") VALUES ('am3','a1')`,
138
+ ),
139
+ ).rejects.toThrow(/null value/);
140
+ });
141
+ });
@@ -1,19 +1,15 @@
1
1
  /**
2
2
  * admin/src/ensure-account-member.integration.test.ts
3
- * ensureAccountMember, stamping on every AccountMember creation path, re-add
4
- * repair of a hidden agent member, and the --verify report. Real Postgres.
3
+ * ensureAccountMember and its interplay with AgentMemberService.add. Real
4
+ * Postgres.
5
5
  *
6
6
  * Requires DATABASE_URL_ADMIN_TEST; skips otherwise.
7
7
  */
8
8
 
9
9
  import { afterEach, beforeEach, describe, expect, it } from "bun:test";
10
10
  import type { PrismaClient } from "../prisma/client/client.ts";
11
- import { AccountMemberService } from "./account-members.ts";
12
- import { AccountOnboardingService } from "./account-onboarding.ts";
13
- import { AccountService } from "./accounts.ts";
14
- import { AgentMemberService } from "./agent-members.ts";
11
+ import { AgentMemberService, NoAccountMemberError } from "./agent-members.ts";
15
12
  import { ensureAccountMember } from "./ensure-account-member.ts";
16
- import { verifyMemberIds } from "./member-id-backfill.ts";
17
13
  import { createAdminPrismaClient } from "./prisma-client.ts";
18
14
 
19
15
  const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
@@ -27,32 +23,6 @@ describeOrSkip("ensureAccountMember (integration)", () => {
27
23
  let other: string;
28
24
  let agentId: string;
29
25
 
30
- async function seedNullRows(email: string) {
31
- await prisma.agentMember.create({ data: { agentId, email } });
32
- await prisma.chatThreadWatch.create({
33
- data: { userEmail: email, threadId: `t-${email}`, agentId },
34
- });
35
- await prisma.pushSubscription.create({
36
- data: {
37
- userEmail: email,
38
- endpoint: `ep-${email}`,
39
- p256dh: "p",
40
- auth: "a",
41
- },
42
- });
43
- await prisma.userNotificationPrefs.create({ data: { userEmail: email } });
44
- }
45
-
46
- async function memberIdsFor(email: string) {
47
- const [a, b, c, d] = await Promise.all([
48
- prisma.agentMember.findMany({ where: { email } }),
49
- prisma.chatThreadWatch.findMany({ where: { userEmail: email } }),
50
- prisma.pushSubscription.findMany({ where: { userEmail: email } }),
51
- prisma.userNotificationPrefs.findMany({ where: { userEmail: email } }),
52
- ]);
53
- return [a, b, c, d].map((rows) => rows.map((r) => r.memberId));
54
- }
55
-
56
26
  beforeEach(async () => {
57
27
  prisma = createAdminPrismaClient(TEST_DB as string);
58
28
  await prisma.userNotificationPrefs.deleteMany();
@@ -172,212 +142,27 @@ describeOrSkip("ensureAccountMember (integration)", () => {
172
142
  expect(result.ok).toBe(true);
173
143
  });
174
144
 
175
- it("stamps null rows in all four tables when it creates the record", async () => {
176
- await seedNullRows("late@acme.com");
177
- const ensured = await ensureAccountMember(prisma, {
178
- email: "late@acme.com",
179
- agentAccountId: acme,
180
- creator: ADMIN,
181
- });
182
- if (!ensured.ok) throw new Error(ensured.message);
183
- expect(await memberIdsFor("late@acme.com")).toEqual([
184
- [ensured.member.id],
185
- [ensured.member.id],
186
- [ensured.member.id],
187
- [ensured.member.id],
188
- ]);
189
- });
190
-
191
- it("re-adding a hidden agent member repairs its null memberId", async () => {
192
- await seedNullRows("hidden@acme.com");
145
+ it("AgentMemberService.add fails without writing when the email has no AccountMember", async () => {
193
146
  const service = new AgentMemberService(prisma);
194
- expect(await service.listByAgentId(agentId)).toEqual([]);
147
+ await expect(service.add(agentId, "ghost@acme.com")).rejects.toThrow(
148
+ NoAccountMemberError,
149
+ );
150
+ expect(await prisma.agentMember.count()).toBe(0);
151
+ });
195
152
 
153
+ it("ensureAccountMember then AgentMemberService.add keys the row on the member id", async () => {
196
154
  const ensured = await ensureAccountMember(prisma, {
197
- email: "hidden@acme.com",
155
+ email: "later@acme.com",
198
156
  agentAccountId: acme,
199
157
  creator: ADMIN,
200
158
  });
201
- expect(ensured.ok).toBe(true);
202
- await service.add(agentId, "hidden@acme.com").catch(() => {});
159
+ if (!ensured.ok) throw new Error(ensured.message);
160
+ const service = new AgentMemberService(prisma);
161
+ await service.add(agentId, "later@acme.com");
162
+ const rows = await prisma.agentMember.findMany();
163
+ expect(rows.map((r) => r.memberId)).toEqual([ensured.member.id]);
203
164
  expect((await service.listByAgentId(agentId)).map((m) => m.email)).toEqual([
204
- "hidden@acme.com",
165
+ "later@acme.com",
205
166
  ]);
206
- expect(await prisma.agentMember.count()).toBe(1);
207
- });
208
-
209
- it("repairs when the record already exists but the rows were left null", async () => {
210
- const rec = await prisma.accountMember.create({
211
- data: { accountId: other, email: "ex@x.com", role: "member" },
212
- });
213
- await seedNullRows("ex@x.com");
214
- await ensureAccountMember(prisma, {
215
- email: "ex@x.com",
216
- agentAccountId: acme,
217
- });
218
- expect(await memberIdsFor("ex@x.com")).toEqual([
219
- [rec.id],
220
- [rec.id],
221
- [rec.id],
222
- [rec.id],
223
- ]);
224
- });
225
-
226
- describe("stamping on every AccountMember creation path", () => {
227
- it("AccountMemberService.add", async () => {
228
- await seedNullRows("svc@x.com");
229
- const m = await new AccountMemberService(prisma).add(acme, "SVC@x.com");
230
- expect(await memberIdsFor("svc@x.com")).toEqual([
231
- [m.id],
232
- [m.id],
233
- [m.id],
234
- [m.id],
235
- ]);
236
- });
237
-
238
- it("AccountMemberService.add inside a caller transaction rolls the stamping back with it", async () => {
239
- await seedNullRows("rb@x.com");
240
- await prisma
241
- .$transaction(async (tx) => {
242
- await new AccountMemberService(prisma).add(
243
- acme,
244
- "rb@x.com",
245
- "member",
246
- tx,
247
- );
248
- throw new Error("abort");
249
- })
250
- .catch(() => {});
251
- expect(await memberIdsFor("rb@x.com")).toEqual([
252
- [null],
253
- [null],
254
- [null],
255
- [null],
256
- ]);
257
- });
258
-
259
- it("AccountService.create", async () => {
260
- await seedNullRows("boss@x.com");
261
- const account = await new AccountService(prisma).create(
262
- "New",
263
- "boss@x.com",
264
- );
265
- const owner = await prisma.accountMember.findFirstOrThrow({
266
- where: { accountId: account.id },
267
- });
268
- expect(await memberIdsFor("boss@x.com")).toEqual([
269
- [owner.id],
270
- [owner.id],
271
- [owner.id],
272
- [owner.id],
273
- ]);
274
- });
275
-
276
- it("AccountOnboardingService (new account and invite)", async () => {
277
- const onboarding = new AccountOnboardingService(prisma, 3);
278
- await seedNullRows("first@x.com");
279
- await onboarding.provisionForEmail("first@x.com");
280
- const first = await prisma.accountMember.findUniqueOrThrow({
281
- where: { email: "first@x.com" },
282
- });
283
- expect(await memberIdsFor("first@x.com")).toEqual([
284
- [first.id],
285
- [first.id],
286
- [first.id],
287
- [first.id],
288
- ]);
289
-
290
- await prisma.accountInvite.create({
291
- data: { accountId: acme, email: "inv@x.com", invitedBy: "o@x.com" },
292
- });
293
- await seedNullRows("inv@x.com");
294
- await onboarding.provisionForEmail("inv@x.com");
295
- const invited = await prisma.accountMember.findUniqueOrThrow({
296
- where: { email: "inv@x.com" },
297
- });
298
- expect(invited.accountId).toBe(acme);
299
- expect(await memberIdsFor("inv@x.com")).toEqual([
300
- [invited.id],
301
- [invited.id],
302
- [invited.id],
303
- [invited.id],
304
- ]);
305
- });
306
- });
307
-
308
- describe("verifyMemberIds", () => {
309
- it("reports nothing wrong on a clean database", async () => {
310
- const report = await verifyMemberIds(prisma);
311
- expect(report.hasProblems).toBe(false);
312
- });
313
-
314
- async function runScript() {
315
- const proc = Bun.spawn(
316
- [
317
- "bun",
318
- `${import.meta.dir}/../scripts/backfill-member-id.ts`,
319
- "--verify",
320
- ],
321
- {
322
- env: {
323
- ...process.env,
324
- DATABASE_URL_SHIPWRIGHT_ADMIN: TEST_DB as string,
325
- },
326
- stdout: "pipe",
327
- stderr: "pipe",
328
- },
329
- );
330
- const [out, code] = await Promise.all([
331
- new Response(proc.stdout).text(),
332
- proc.exited,
333
- ]);
334
- return { out, code };
335
- }
336
-
337
- it("the --verify script exits 0 when clean and non-zero with a report otherwise, writing nothing", async () => {
338
- expect((await runScript()).code).toBe(0);
339
- await seedNullRows("nul@x.com");
340
- const { out, code } = await runScript();
341
- expect(code).toBe(1);
342
- expect(JSON.parse(out).tables.AgentMember.null.emails).toEqual([
343
- "nul@x.com",
344
- ]);
345
- expect((await prisma.agentMember.findFirstOrThrow()).memberId).toBeNull();
346
- });
347
-
348
- it("reports null and dangling memberId per table, and writes nothing", async () => {
349
- await seedNullRows("nul@x.com");
350
- const good = await prisma.accountMember.create({
351
- data: { accountId: acme, email: "ok@x.com", role: "member" },
352
- });
353
- await prisma.agentMember.create({
354
- data: { agentId, email: "ok@x.com", memberId: good.id },
355
- });
356
- // Dangling: a memberId naming no AccountMember (there is no FK).
357
- await prisma.userNotificationPrefs.create({
358
- data: { userEmail: "dang@x.com", memberId: "gone-id" },
359
- });
360
- const before = await prisma.agentMember.findMany({
361
- orderBy: { id: "asc" },
362
- });
363
-
364
- const report = await verifyMemberIds(prisma);
365
- expect(report.hasProblems).toBe(true);
366
- expect(report.tables.AgentMember.null).toEqual({
367
- count: 1,
368
- emails: ["nul@x.com"],
369
- });
370
- expect(report.tables.ChatThreadWatch.null.count).toBe(1);
371
- expect(report.tables.PushSubscription.null.emails).toEqual(["nul@x.com"]);
372
- expect(report.tables.UserNotificationPrefs.null.count).toBe(1);
373
- expect(report.tables.AgentMember.dangling.count).toBe(0);
374
- expect(report.tables.UserNotificationPrefs.dangling).toEqual({
375
- count: 1,
376
- emails: ["dang@x.com"],
377
- });
378
- expect(
379
- await prisma.agentMember.findMany({ orderBy: { id: "asc" } }),
380
- ).toEqual(before);
381
- });
382
167
  });
383
168
  });
@@ -8,14 +8,11 @@
8
8
  * only Account when the agent has none and exactly one exists. No other case
9
9
  * picks an account: the operation fails with a clear message and writes nothing.
10
10
  * - Creating a record needs a platform admin or the owner of the target account.
11
- * - Null memberId rows for the email are stamped either way, so a hidden agent
12
- * member becomes visible again on re-add.
13
11
  */
14
12
 
15
13
  import type { AccountMember } from "../prisma/client/client.ts";
16
14
  import { normalizeEmail } from "./account-email.ts";
17
15
  import type { CallerScope } from "./caller-scope.ts";
18
- import { stampMemberId } from "./member-id-stamp.ts";
19
16
  import type { PrismaTransactionClient } from "./prisma-tx.ts";
20
17
 
21
18
  /** Who is asking, as far as creating account members is concerned. */
@@ -92,7 +89,6 @@ export async function ensureAccountMember(
92
89
  const email = normalizeEmail(input.email);
93
90
  const existing = await client.accountMember.findUnique({ where: { email } });
94
91
  if (existing) {
95
- await stampMemberId(client, email, existing.id);
96
92
  return { ok: true, member: existing, created: false };
97
93
  }
98
94
 
@@ -124,6 +120,5 @@ export async function ensureAccountMember(
124
120
  create: { accountId: choice.accountId, email, role: "member" },
125
121
  update: {},
126
122
  });
127
- await stampMemberId(client, email, member.id);
128
123
  return { ok: true, member, created: true };
129
124
  }
@@ -131,7 +131,9 @@ describe("repository client validation", () => {
131
131
  });
132
132
 
133
133
  it("rejects a non-integer installation id before any network call", async () => {
134
- const err = await client.listInstallationRepositories("o", Number.NaN).catch((e) => e);
134
+ const err = await client
135
+ .listInstallationRepositories("o", Number.NaN)
136
+ .catch((e) => e);
135
137
  expect(err.kind).toBe("validation");
136
138
  });
137
139
 
@@ -145,7 +147,10 @@ describe("repository client validation", () => {
145
147
  it("rejects selected with more than 50 repositories", async () => {
146
148
  const repositories = Array.from({ length: 51 }, (_, i) => `r${i}`);
147
149
  const err = await client
148
- .setRepositorySelection("o", 1, { repositorySelection: "selected", repositories })
150
+ .setRepositorySelection("o", 1, {
151
+ repositorySelection: "selected",
152
+ repositories,
153
+ })
149
154
  .catch((e) => e);
150
155
  expect(err.kind).toBe("validation");
151
156
  });
@@ -215,3 +220,58 @@ describe("GithubEnterpriseClient.uninstallFromOrg", () => {
215
220
  expect(calls).toHaveLength(0);
216
221
  });
217
222
  });
223
+
224
+ describe("GithubEnterpriseClient malformed responses", () => {
225
+ const { privateKey } = require("node:crypto").generateKeyPairSync("rsa", {
226
+ modulusLength: 2048,
227
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
228
+ publicKeyEncoding: { type: "spki", format: "pem" },
229
+ });
230
+ const make = (bodies: { installation?: unknown; token?: unknown }) => {
231
+ const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
232
+ const u = new URL(input.toString());
233
+ if (u.pathname === "/enterprises/acme/installation")
234
+ return Response.json(bodies.installation ?? { id: 4242 });
235
+ if (u.pathname === "/app/installations/4242/access_tokens")
236
+ return Response.json(
237
+ bodies.token ?? {
238
+ token: "ghs_t",
239
+ expires_at: "2099-01-01T00:00:00Z",
240
+ },
241
+ { status: 201 },
242
+ );
243
+ if (init?.method === "POST") return Response.json({}, { status: 201 });
244
+ throw new Error(`unexpected ${init?.method} ${u.pathname}`);
245
+ }) as typeof fetch;
246
+ return new GithubEnterpriseClient({
247
+ appId: "1",
248
+ enterprise: "acme",
249
+ privateKey,
250
+ fetchFn,
251
+ });
252
+ };
253
+
254
+ it("rejects an installation lookup without an id", async () => {
255
+ const err = await make({ installation: {} })
256
+ .getInstallationToken()
257
+ .catch((e) => e);
258
+ expect(err.kind).toBe("unexpected");
259
+ expect(err.message).toContain("response missing id");
260
+ });
261
+
262
+ it("rejects an access token response without token or expires_at", async () => {
263
+ const err = await make({ token: { token: "ghs_t" } })
264
+ .getInstallationToken()
265
+ .catch((e) => e);
266
+ expect(err.kind).toBe("unexpected");
267
+ expect(err.message).toContain("missing token or expires_at");
268
+ });
269
+
270
+ it("rejects an install-on-org response without an id", async () => {
271
+ const err = await make({})
272
+ .installOnOrg("org-1", { clientId: "c", repositorySelection: "all" })
273
+ .catch((e) => e);
274
+ expect(err.kind).toBe("unexpected");
275
+ expect(err.message).toContain("install App on org: response missing id");
276
+ });
277
+ });
@@ -0,0 +1,24 @@
1
+ /**
2
+ * admin/src/member-rows.ts
3
+ * Cleanup of the per-user rows keyed on AccountMember.id (AgentMember,
4
+ * ChatThreadWatch, PushSubscription, UserNotificationPrefs). Callers that
5
+ * delete an AccountMember run this with their own transaction client so the
6
+ * record and its rows go together.
7
+ */
8
+
9
+ import type { PrismaTransactionClient } from "./prisma-tx.ts";
10
+
11
+ /** Deletes the member's rows in all four tables; returns the rows deleted. */
12
+ export async function deleteMemberRows(
13
+ client: PrismaTransactionClient,
14
+ memberId: string,
15
+ ): Promise<number> {
16
+ const where = { memberId };
17
+ const results = await Promise.all([
18
+ client.agentMember.deleteMany({ where }),
19
+ client.chatThreadWatch.deleteMany({ where }),
20
+ client.pushSubscription.deleteMany({ where }),
21
+ client.userNotificationPrefs.deleteMany({ where }),
22
+ ]);
23
+ return results.reduce((n, r) => n + r.count, 0);
24
+ }
@@ -0,0 +1,48 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import { deleteMemberRows } from "./member-rows.ts";
3
+ import type { PrismaTransactionClient } from "./prisma-tx.ts";
4
+
5
+ const TABLES = [
6
+ "agentMember",
7
+ "chatThreadWatch",
8
+ "pushSubscription",
9
+ "userNotificationPrefs",
10
+ ] as const;
11
+
12
+ type Call = { table: string; where: unknown };
13
+
14
+ function fakeClient(
15
+ counts: Partial<Record<(typeof TABLES)[number], number>> = {},
16
+ ) {
17
+ const calls: Call[] = [];
18
+ const client = Object.fromEntries(
19
+ TABLES.map((table) => [
20
+ table,
21
+ {
22
+ deleteMany: async ({ where }: { where: unknown }) => {
23
+ calls.push({ table, where });
24
+ return { count: counts[table] ?? 0 };
25
+ },
26
+ },
27
+ ]),
28
+ );
29
+ return { client: client as unknown as PrismaTransactionClient, calls };
30
+ }
31
+
32
+ describe("deleteMemberRows", () => {
33
+ it("deletes only the member's rows, by memberId, in all four tables", async () => {
34
+ const { client, calls } = fakeClient();
35
+ await deleteMemberRows(client, "m1");
36
+ expect(calls.map((c) => c.table).sort()).toEqual([...TABLES].sort());
37
+ for (const c of calls) expect(c.where).toEqual({ memberId: "m1" });
38
+ });
39
+
40
+ it("returns the summed count of deleted rows", async () => {
41
+ const { client } = fakeClient({
42
+ agentMember: 1,
43
+ chatThreadWatch: 1,
44
+ userNotificationPrefs: 4,
45
+ });
46
+ expect(await deleteMemberRows(client, "m1")).toBe(6);
47
+ });
48
+ });
@@ -84,7 +84,7 @@ describeOrSkip("/principals API (integration)", () => {
84
84
  expect(miss.status).toBe(404);
85
85
  });
86
86
 
87
- it("memberId columns exist, are nullable and default to NULL", async () => {
87
+ it("memberId columns exist, are NOT NULL and have no default", async () => {
88
88
  const cols = await prisma.$queryRaw<
89
89
  {
90
90
  table_name: string;
@@ -102,13 +102,14 @@ describeOrSkip("/principals API (integration)", () => {
102
102
  "UserNotificationPrefs",
103
103
  ]);
104
104
  for (const c of cols) {
105
- expect(c.is_nullable).toBe("YES");
105
+ expect(c.is_nullable).toBe("NO");
106
106
  expect(c.column_default).toBeNull();
107
107
  }
108
108
  const fks = await prisma.$queryRaw<{ n: bigint }[]>`SELECT count(*) AS n
109
109
  FROM information_schema.table_constraints tc
110
110
  JOIN information_schema.constraint_column_usage ccu USING (constraint_name)
111
111
  WHERE ccu.column_name = 'memberId'
112
+ AND tc.constraint_type = 'FOREIGN KEY'
112
113
  AND tc.table_name IN ('UserNotificationPrefs','ChatThreadWatch','PushSubscription','AgentMember')`;
113
114
  expect(Number(fks[0]?.n)).toBe(0);
114
115
  });