@app-vitals/agent-admin 1.106.1 → 1.106.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.106.1",
3
+ "version": "1.106.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@anthropic-ai/sdk": "0.137.0",
47
- "@app-vitals/agent-lib": "1.106.1",
47
+ "@app-vitals/agent-lib": "1.106.2",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
@@ -0,0 +1,190 @@
1
+ /**
2
+ * admin/src/account-member-removal.integration.test.ts
3
+ * AccountMemberService.remove deletes the removed person's access and
4
+ * notification rows (AgentMember, ChatThreadWatch, PushSubscription,
5
+ * UserNotificationPrefs), atomically with the removal. Real Postgres.
6
+ *
7
+ * Requires DATABASE_URL_ADMIN_TEST; skips otherwise.
8
+ */
9
+
10
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
11
+ import type { PrismaClient } from "../prisma/client/client.ts";
12
+ import {
13
+ AccountMemberNotFoundError,
14
+ AccountMemberService,
15
+ LastOwnerError,
16
+ } from "./account-members.ts";
17
+ import { AgentMemberService } from "./agent-members.ts";
18
+ import { createAdminPrismaClient } from "./prisma-client.ts";
19
+
20
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
21
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
22
+
23
+ describeOrSkip("AccountMemberService.remove cleanup (integration)", () => {
24
+ let prisma: PrismaClient;
25
+ let service: AccountMemberService;
26
+ let acme: string;
27
+ let agentId: string;
28
+
29
+ async function seedRows(email: string, memberId: string | null) {
30
+ await prisma.agentMember.create({ data: { agentId, email, memberId } });
31
+ await prisma.chatThreadWatch.create({
32
+ data: { userEmail: email, threadId: `t-${email}`, agentId, memberId },
33
+ });
34
+ await prisma.pushSubscription.create({
35
+ data: {
36
+ userEmail: email,
37
+ endpoint: `ep-${email}`,
38
+ p256dh: "p",
39
+ auth: "a",
40
+ memberId,
41
+ },
42
+ });
43
+ await prisma.userNotificationPrefs.create({
44
+ data: { userEmail: email, memberId },
45
+ });
46
+ }
47
+
48
+ async function rowCounts(email: string) {
49
+ return Promise.all([
50
+ prisma.agentMember.count({ where: { email } }),
51
+ prisma.chatThreadWatch.count({ where: { userEmail: email } }),
52
+ prisma.pushSubscription.count({ where: { userEmail: email } }),
53
+ prisma.userNotificationPrefs.count({ where: { userEmail: email } }),
54
+ ]);
55
+ }
56
+
57
+ async function addMember(email: string, role: "owner" | "member") {
58
+ return prisma.accountMember.create({
59
+ data: { accountId: acme, email, role },
60
+ });
61
+ }
62
+
63
+ beforeEach(async () => {
64
+ prisma = createAdminPrismaClient(TEST_DB as string);
65
+ service = new AccountMemberService(prisma);
66
+ await prisma.userNotificationPrefs.deleteMany();
67
+ await prisma.chatThreadWatch.deleteMany();
68
+ await prisma.pushSubscription.deleteMany();
69
+ await prisma.agentMember.deleteMany();
70
+ await prisma.accountInvite.deleteMany();
71
+ await prisma.accountMember.deleteMany();
72
+ await prisma.agent.deleteMany();
73
+ await prisma.account.deleteMany();
74
+ acme = (await prisma.account.create({ data: { name: "Acme" } })).id;
75
+ agentId = (
76
+ await prisma.agent.create({
77
+ data: { id: "rm-agent", name: "rm-agent", accountId: acme },
78
+ })
79
+ ).id;
80
+ await addMember("owner@acme.com", "owner");
81
+ });
82
+
83
+ afterEach(async () => {
84
+ await prisma.$disconnect();
85
+ });
86
+
87
+ it("deletes the person's rows by memberId and by email where memberId is null, and no one else's", async () => {
88
+ const bob = await addMember("bob@acme.com", "member");
89
+ const carol = await addMember("carol@acme.com", "member");
90
+ await seedRows("bob@acme.com", bob.id);
91
+ await seedRows("carol@acme.com", carol.id);
92
+ await service.remove(acme, "bob@acme.com");
93
+
94
+ expect(await rowCounts("bob@acme.com")).toEqual([0, 0, 0, 0]);
95
+ expect(await rowCounts("carol@acme.com")).toEqual([1, 1, 1, 1]);
96
+ expect(await prisma.accountMember.count({ where: { id: bob.id } })).toBe(0);
97
+ });
98
+
99
+ it("deletes null-memberId rows matched by email (case-insensitive)", async () => {
100
+ await addMember("dee@acme.com", "member");
101
+ await seedRows("Dee@Acme.com", null);
102
+ await service.remove(acme, "dee@acme.com");
103
+ expect(await rowCounts("Dee@Acme.com")).toEqual([0, 0, 0, 0]);
104
+ });
105
+
106
+ it("deletes rows stamped with the member's id even if the stored email differs", async () => {
107
+ const eve = await addMember("eve@acme.com", "member");
108
+ await seedRows("eve-old@acme.com", eve.id);
109
+ await service.remove(acme, "eve@acme.com");
110
+ expect(await rowCounts("eve-old@acme.com")).toEqual([0, 0, 0, 0]);
111
+ });
112
+
113
+ it("deletes nothing when the last owner is refused", async () => {
114
+ const owner = await prisma.accountMember.findUniqueOrThrow({
115
+ where: { email: "owner@acme.com" },
116
+ });
117
+ await seedRows("owner@acme.com", owner.id);
118
+ await expect(service.remove(acme, "owner@acme.com")).rejects.toBeInstanceOf(
119
+ LastOwnerError,
120
+ );
121
+ expect(await rowCounts("owner@acme.com")).toEqual([1, 1, 1, 1]);
122
+ expect(await prisma.accountMember.count()).toBe(1);
123
+ });
124
+
125
+ it("deletes nothing when the member is unknown", async () => {
126
+ await seedRows("ghost@acme.com", null);
127
+ await expect(service.remove(acme, "ghost@acme.com")).rejects.toBeInstanceOf(
128
+ AccountMemberNotFoundError,
129
+ );
130
+ expect(await rowCounts("ghost@acme.com")).toEqual([1, 1, 1, 1]);
131
+ });
132
+
133
+ it("rolls back the removal and the deletes when a step fails partway", async () => {
134
+ const fay = await addMember("fay@acme.com", "member");
135
+ await seedRows("fay@acme.com", fay.id);
136
+ // Fail the final AccountMember delete after the row deletes have run.
137
+ const failing = new Proxy(prisma, {
138
+ get(target, prop, receiver) {
139
+ if (prop !== "$transaction") return Reflect.get(target, prop, receiver);
140
+ return (fn: (tx: unknown) => Promise<unknown>) =>
141
+ target.$transaction(async (tx) =>
142
+ fn(
143
+ new Proxy(tx, {
144
+ get(t, p, r) {
145
+ if (p !== "accountMember") return Reflect.get(t, p, r);
146
+ return new Proxy(t.accountMember, {
147
+ get(m, mp, mr) {
148
+ if (mp === "delete") {
149
+ return async () => {
150
+ throw new Error("boom");
151
+ };
152
+ }
153
+ return Reflect.get(m, mp, mr);
154
+ },
155
+ });
156
+ },
157
+ }),
158
+ ),
159
+ );
160
+ },
161
+ }) as PrismaClient;
162
+
163
+ await expect(
164
+ new AccountMemberService(failing).remove(acme, "fay@acme.com"),
165
+ ).rejects.toThrow("boom");
166
+ expect(await rowCounts("fay@acme.com")).toEqual([1, 1, 1, 1]);
167
+ expect(await prisma.accountMember.count({ where: { id: fay.id } })).toBe(1);
168
+ });
169
+
170
+ it("after re-adding, the person can be added to the same agent again with no earlier settings", async () => {
171
+ const gus = await addMember("gus@acme.com", "member");
172
+ await seedRows("gus@acme.com", gus.id);
173
+ await service.remove(acme, "gus@acme.com");
174
+
175
+ const readded = await service.add(acme, "gus@acme.com");
176
+ expect(readded.id).not.toBe(gus.id);
177
+
178
+ const agentMembers = new AgentMemberService(prisma);
179
+ await agentMembers.add(agentId, "gus@acme.com");
180
+ expect(await agentMembers.exists(agentId, "gus@acme.com")).toBe(true);
181
+ const rows = await prisma.agentMember.findMany({
182
+ where: { email: "gus@acme.com" },
183
+ });
184
+ expect(rows).toHaveLength(1);
185
+ expect(rows[0]?.id).not.toBe(undefined);
186
+ expect(await prisma.chatThreadWatch.count()).toBe(0);
187
+ expect(await prisma.pushSubscription.count()).toBe(0);
188
+ expect(await prisma.userNotificationPrefs.count()).toBe(0);
189
+ });
190
+ });
@@ -8,7 +8,7 @@
8
8
 
9
9
  import type { AccountMember, PrismaClient } from "../prisma/client/client.ts";
10
10
  import { normalizeEmail } from "./account-email.ts";
11
- import { stampMemberId } from "./member-id-stamp.ts";
11
+ import { deleteMemberRows, stampMemberId } from "./member-id-stamp.ts";
12
12
  import type { PrismaTransactionClient } from "./prisma-tx.ts";
13
13
 
14
14
  export type { AccountMember };
@@ -74,8 +74,14 @@ export class AccountMemberService {
74
74
  : run(client);
75
75
  }
76
76
 
77
+ /**
78
+ * Remove a member and their access and notification rows (AgentMember,
79
+ * ChatThreadWatch, PushSubscription, UserNotificationPrefs), matched by
80
+ * memberId and by email where memberId is null, in one transaction.
81
+ */
77
82
  async remove(accountId: string, email: string): Promise<void> {
78
83
  await this.guardedChange(accountId, email, async (tx, member) => {
84
+ await deleteMemberRows(tx, member.email, member.id);
79
85
  await tx.accountMember.delete({ where: { id: member.id } });
80
86
  });
81
87
  }
@@ -32,13 +32,20 @@ interface AccountPageOpts {
32
32
  isAdmin?: boolean;
33
33
  }
34
34
 
35
+ export const REMOVE_MEMBER_CONFIRM =
36
+ "Remove this member? Their agent access and notification settings are removed too.";
37
+
35
38
  function emailForm(
36
39
  action: string,
37
40
  email: string,
38
41
  label: string,
39
42
  danger = false,
43
+ confirmText?: string,
40
44
  ): string {
41
- return `<form method="POST" action="${ACCOUNT_PATH}/${action}" style="display:inline;margin:0">
45
+ const onsubmit = confirmText
46
+ ? ` onsubmit="return confirm('${confirmText}')"`
47
+ : "";
48
+ return `<form method="POST" action="${ACCOUNT_PATH}/${action}"${onsubmit} style="display:inline;margin:0">
42
49
  <input type="hidden" name="email" value="${escapeHtml(email)}" />
43
50
  <button type="submit" class="btn ${danger ? "btn-danger" : "btn-secondary"}" style="font-size:12px;padding:4px 10px">${label}</button>
44
51
  </form>`;
@@ -50,7 +57,13 @@ function renderMemberRow(m: AccountMember, isOwner: boolean): string {
50
57
  m.role === "owner"
51
58
  ? emailForm("members/demote", m.email, "Demote")
52
59
  : emailForm("members/promote", m.email, "Make owner"),
53
- emailForm("members/remove", m.email, "Remove", true),
60
+ emailForm(
61
+ "members/remove",
62
+ m.email,
63
+ "Remove",
64
+ true,
65
+ REMOVE_MEMBER_CONFIRM,
66
+ ),
54
67
  ].join(" ")
55
68
  : "";
56
69
  return `<tr>
@@ -72,6 +72,10 @@ describe("renderAccountPage", () => {
72
72
  expect(html).toContain('action="/admin/account/rename"');
73
73
  });
74
74
 
75
+ test("remove form confirms that access and notification settings are removed", () => {
76
+ expect(render(true)).toContain("notification settings are removed");
77
+ });
78
+
75
79
  test("member sees read-only page", () => {
76
80
  const html = render(false);
77
81
  expect(html).not.toContain('action="/admin/account/');
@@ -7,6 +7,7 @@
7
7
  import type { AccountInvite } from "./account-invites.ts";
8
8
  import type { AccountMember } from "./account-members.ts";
9
9
  import type { AccountWithCounts } from "./accounts.ts";
10
+ import { REMOVE_MEMBER_CONFIRM } from "./admin-ui-account-pages.ts";
10
11
  import { renderAdminPage } from "./admin-ui-layout.ts";
11
12
  import {
12
13
  buildSettingsNav,
@@ -101,14 +102,18 @@ function postForm(
101
102
  fields: Record<string, string>,
102
103
  label: string,
103
104
  danger = false,
105
+ confirmText?: string,
104
106
  ): string {
107
+ const onsubmit = confirmText
108
+ ? ` onsubmit="return confirm('${confirmText}')"`
109
+ : "";
105
110
  const hidden = Object.entries(fields)
106
111
  .map(
107
112
  ([k, v]) =>
108
113
  `<input type="hidden" name="${escapeHtml(k)}" value="${escapeHtml(v)}" />`,
109
114
  )
110
115
  .join("");
111
- return `<form method="POST" action="${ADMIN_ACCOUNTS_PATH}/${escapeHtml(accountId)}/${action}" style="display:inline;margin:0">${hidden}
116
+ return `<form method="POST" action="${ADMIN_ACCOUNTS_PATH}/${escapeHtml(accountId)}/${action}"${onsubmit} style="display:inline;margin:0">${hidden}
112
117
  <button type="submit" class="btn ${danger ? "btn-danger" : "btn-secondary"}" style="font-size:12px;padding:4px 10px">${label}</button>
113
118
  </form>`;
114
119
  }
@@ -139,7 +144,14 @@ export function renderAccountDetailPage(opts: AccountDetailPageOpts): string {
139
144
  m.role === "owner"
140
145
  ? postForm(id, "members/demote", { email: m.email }, "Demote")
141
146
  : postForm(id, "members/promote", { email: m.email }, "Make owner"),
142
- postForm(id, "members/remove", { email: m.email }, "Remove", true),
147
+ postForm(
148
+ id,
149
+ "members/remove",
150
+ { email: m.email },
151
+ "Remove",
152
+ true,
153
+ REMOVE_MEMBER_CONFIRM,
154
+ ),
143
155
  ].join(" ")}</td>
144
156
  </tr>`,
145
157
  )
@@ -85,6 +85,7 @@ describe("renderAccountDetailPage", () => {
85
85
 
86
86
  test("edit form, suspend button, agents, members, invites", () => {
87
87
  const html = renderAccountDetailPage(base);
88
+ expect(html).toContain("notification settings are removed");
88
89
  expect(html).toContain('action="/admin/accounts/a1/update"');
89
90
  expect(html).toContain('name="maxAgents"');
90
91
  expect(html).toContain('value="2026-03-05"');
@@ -7491,7 +7491,8 @@ function makeFakePushService(
7491
7491
  p256dh: string,
7492
7492
  auth: string,
7493
7493
  ) => Promise<
7494
- { ok: true } | { ok: false; reason: "unavailable" | "store_failed" }
7494
+ | { ok: true }
7495
+ | { ok: false; reason: "unavailable" | "store_failed" | "no_member" }
7495
7496
  > = async () => ({ ok: true }),
7496
7497
  unsubscribe: (
7497
7498
  userEmail: string,
@@ -7569,6 +7570,27 @@ describe("admin UI — POST /admin/chat/:agentId/push/subscribe", () => {
7569
7570
  expect(await res.json()).toEqual({ error: "bad_request" });
7570
7571
  });
7571
7572
 
7573
+ it("returns 409 no_member when the user has no account member record", async () => {
7574
+ const deps = makeMockDeps({
7575
+ pushService: makeFakePushService(undefined, async () => ({
7576
+ ok: false,
7577
+ reason: "no_member",
7578
+ })),
7579
+ vapidPublicKey: "test-vapid-public-key",
7580
+ });
7581
+ const app = createAdminUIApp(deps);
7582
+ const res = await app.request(`/admin/chat/${AGENT_ID}/push/subscribe`, {
7583
+ method: "POST",
7584
+ body: JSON.stringify(PUSH_SUBSCRIPTION_BODY),
7585
+ headers: {
7586
+ "Content-Type": "application/json",
7587
+ Cookie: `admin_session=${cookie}`,
7588
+ },
7589
+ });
7590
+ expect(res.status).toBe(409);
7591
+ expect(await res.json()).toEqual({ error: "no_member" });
7592
+ });
7593
+
7572
7594
  it("upserts the subscription and returns ok:true when push is enabled", async () => {
7573
7595
  let subscribeCalledWith: unknown;
7574
7596
  const deps = makeMockDeps({
@@ -7992,3 +8014,143 @@ describe("agent create requires owner or admin (ACM-7.3)", () => {
7992
8014
  expect(res.status).toBe(200);
7993
8015
  });
7994
8016
  });
8017
+
8018
+ // ─── Admin sign-in ensures an account member record ──────────────────────────
8019
+
8020
+ describe("admin UI — admin sign-in ensures an AccountMember", () => {
8021
+ type EnsureFn = NonNullable<
8022
+ Parameters<typeof makeMockDeps>[0]
8023
+ >["ensureAccountMember"];
8024
+
8025
+ function googleCb(nonce = "n1"): Request {
8026
+ const oauthState = encodeURIComponent(JSON.stringify({ nonce }));
8027
+ return new Request(
8028
+ `https://example.com/admin/auth/callback?state=${nonce}&code=c`,
8029
+ { headers: { Cookie: `oauth_state=${oauthState}` } },
8030
+ );
8031
+ }
8032
+ function oktaCb(nonce = "n1"): Request {
8033
+ const oauthState = encodeURIComponent(JSON.stringify({ nonce }));
8034
+ return new Request(
8035
+ `https://example.com/admin/auth/okta/callback?state=${nonce}&code=c`,
8036
+ { headers: { Cookie: `oauth_state=${oauthState}` } },
8037
+ );
8038
+ }
8039
+ const okResult = {
8040
+ ok: true,
8041
+ created: true,
8042
+ member: { id: "m1" },
8043
+ } as unknown as Awaited<ReturnType<NonNullable<EnsureFn>>>;
8044
+
8045
+ for (const [name, mk] of [
8046
+ ["Google", googleCb],
8047
+ ["Okta", oktaCb],
8048
+ ] as const) {
8049
+ it(`${name}: an allowlisted admin gets ensured with no agent, role via admin creator`, async () => {
8050
+ const calls: unknown[] = [];
8051
+ const app = createAdminUIApp(
8052
+ makeMockDeps({
8053
+ ensureAccountMember: async (input) => {
8054
+ calls.push(input);
8055
+ return okResult;
8056
+ },
8057
+ }),
8058
+ );
8059
+ const res = await app.request(mk());
8060
+ expect(res.status).toBe(302);
8061
+ expect(res.headers.get("Location")).toBe("/admin/agents");
8062
+ expect(res.headers.get("Set-Cookie") ?? "").toContain("admin_session=");
8063
+ expect(calls).toEqual([
8064
+ {
8065
+ email: "admin@example.com",
8066
+ agentAccountId: null,
8067
+ creator: { platformAdmin: true, ownerOfAccountId: null },
8068
+ },
8069
+ ]);
8070
+ });
8071
+
8072
+ it(`${name}: sign-in succeeds when no account can be chosen`, async () => {
8073
+ for (const code of ["no_account", "ambiguous_account"] as const) {
8074
+ const app = createAdminUIApp(
8075
+ makeMockDeps({
8076
+ ensureAccountMember: async () => ({
8077
+ ok: false,
8078
+ code,
8079
+ message: "nope",
8080
+ }),
8081
+ }),
8082
+ );
8083
+ const res = await app.request(mk());
8084
+ expect(res.status).toBe(302);
8085
+ expect(res.headers.get("Location")).toBe("/admin/agents");
8086
+ expect(res.headers.get("Set-Cookie") ?? "").toContain("admin_session=");
8087
+ }
8088
+ });
8089
+
8090
+ it(`${name}: sign-in succeeds when ensure throws`, async () => {
8091
+ const app = createAdminUIApp(
8092
+ makeMockDeps({
8093
+ ensureAccountMember: async () => {
8094
+ throw new Error("db down");
8095
+ },
8096
+ }),
8097
+ );
8098
+ const res = await app.request(mk());
8099
+ expect(res.status).toBe(302);
8100
+ expect(res.headers.get("Location")).toBe("/admin/agents");
8101
+ expect(res.headers.get("Set-Cookie") ?? "").toContain("admin_session=");
8102
+ });
8103
+
8104
+ it(`${name}: a non-admin sign-in does not run ensure`, async () => {
8105
+ let called = false;
8106
+ const app = createAdminUIApp(
8107
+ makeMockDeps({
8108
+ adminAllowedEmails: ["someone-else@example.com"],
8109
+ ensureAccountMember: async () => {
8110
+ called = true;
8111
+ return okResult;
8112
+ },
8113
+ }),
8114
+ );
8115
+ const res = await app.request(mk());
8116
+ expect(called).toBe(false);
8117
+ // Unchanged behavior: no AgentMember rows -> the existing outcome.
8118
+ const baseline = await createAdminUIApp(
8119
+ makeMockDeps({ adminAllowedEmails: ["someone-else@example.com"] }),
8120
+ ).request(mk());
8121
+ expect(res.status).toBe(baseline.status);
8122
+ });
8123
+ }
8124
+
8125
+ it("an existing record is passed through unchanged (created:false)", async () => {
8126
+ const app = createAdminUIApp(
8127
+ makeMockDeps({
8128
+ ensureAccountMember: async () =>
8129
+ ({
8130
+ ok: true,
8131
+ created: false,
8132
+ member: { id: "m1" },
8133
+ }) as unknown as Awaited<ReturnType<NonNullable<EnsureFn>>>,
8134
+ }),
8135
+ );
8136
+ const res = await app.request(googleCb());
8137
+ expect(res.status).toBe(302);
8138
+ });
8139
+
8140
+ it("dev-login ensures the dev admin and still signs in when ensure throws", async () => {
8141
+ const emails: string[] = [];
8142
+ const app = createAdminUIApp(
8143
+ makeMockDeps({
8144
+ devAuthEnabled: true,
8145
+ ensureAccountMember: async (input) => {
8146
+ emails.push(input.email);
8147
+ throw new Error("boom");
8148
+ },
8149
+ }),
8150
+ );
8151
+ const res = await app.request("/admin/dev-login");
8152
+ expect(res.status).toBe(302);
8153
+ expect(res.headers.get("Set-Cookie") ?? "").toContain("admin_session=");
8154
+ expect(emails).toEqual(["dev@localhost"]);
8155
+ });
8156
+ });
package/src/admin-ui.ts CHANGED
@@ -1139,6 +1139,34 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1139
1139
 
1140
1140
  // ─── Login / OAuth / Logout ───────────────────────────────────────────────
1141
1141
 
1142
+ /**
1143
+ * Best-effort: an allowlisted platform admin signs in with an AccountMember
1144
+ * record (role member; admin powers come from the allowlist), so push
1145
+ * subscriptions and other member-keyed rows attach to them. Never blocks
1146
+ * sign-in: no/ambiguous account or any error is logged and ignored (the
1147
+ * ensure operation runs in one transaction, so a failure writes nothing).
1148
+ */
1149
+ async function ensureAdminMemberRecord(email: string): Promise<void> {
1150
+ if (!ensureAccountMember) return;
1151
+ try {
1152
+ const ensured = await ensureAccountMember({
1153
+ email: email.toLowerCase(),
1154
+ agentAccountId: null,
1155
+ creator: { platformAdmin: true, ownerOfAccountId: null },
1156
+ });
1157
+ if (!ensured.ok) {
1158
+ console.warn(
1159
+ `[admin] sign-in: no account member created for admin (${ensured.code})`,
1160
+ );
1161
+ }
1162
+ } catch (err) {
1163
+ console.error(
1164
+ "[admin] sign-in: ensuring admin account member failed",
1165
+ err,
1166
+ );
1167
+ }
1168
+ }
1169
+
1142
1170
  /**
1143
1171
  * Shared post-authentication step for every OAuth provider (Google, Okta):
1144
1172
  * checks the verified-email + admin-allowlist/AgentMember-fallback rules,
@@ -1171,7 +1199,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1171
1199
  .map((e) => e.toLowerCase())
1172
1200
  .includes(userInfo.email.toLowerCase());
1173
1201
 
1174
- if (!isAdmin) {
1202
+ if (isAdmin) {
1203
+ await ensureAdminMemberRecord(userInfo.email);
1204
+ } else {
1175
1205
  const memberships = await agentMemberService.listByEmail(
1176
1206
  userInfo.email.toLowerCase(),
1177
1207
  );
@@ -1540,6 +1570,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1540
1570
  "dev@localhost",
1541
1571
  true,
1542
1572
  );
1573
+ await ensureAdminMemberRecord("dev@localhost");
1543
1574
  setCookie(c, SESSION_COOKIE, token, {
1544
1575
  httpOnly: true,
1545
1576
  secure: appBaseUrl.startsWith("https://"),
@@ -5339,6 +5370,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
5339
5370
  auth,
5340
5371
  );
5341
5372
  if (!result?.ok) {
5373
+ if (result?.reason === "no_member") {
5374
+ return c.json({ error: "no_member" }, 409);
5375
+ }
5342
5376
  if (result?.reason === "store_failed") {
5343
5377
  return c.json({ error: "store_failed" }, 500);
5344
5378
  }
@@ -40,3 +40,29 @@ export async function stampMemberId(
40
40
  ]);
41
41
  return results.reduce((n, r) => n + r.count, 0);
42
42
  }
43
+
44
+ /**
45
+ * Deletes the member's rows in all four tables: those with this memberId, plus
46
+ * those matching the email whose memberId is still null. Rows stamped with a
47
+ * different memberId are left alone. Returns the rows deleted.
48
+ */
49
+ export async function deleteMemberRows(
50
+ client: PrismaTransactionClient,
51
+ rawEmail: string,
52
+ memberId: string,
53
+ ): Promise<number> {
54
+ const email = {
55
+ equals: normalizeEmail(rawEmail),
56
+ mode: "insensitive",
57
+ } as const;
58
+ const match = (emailField: "email" | "userEmail") => ({
59
+ OR: [{ memberId }, { [emailField]: email, memberId: null }],
60
+ });
61
+ const results = await Promise.all([
62
+ client.agentMember.deleteMany({ where: match("email") }),
63
+ client.chatThreadWatch.deleteMany({ where: match("userEmail") }),
64
+ client.pushSubscription.deleteMany({ where: match("userEmail") }),
65
+ client.userNotificationPrefs.deleteMany({ where: match("userEmail") }),
66
+ ]);
67
+ return results.reduce((n, r) => n + r.count, 0);
68
+ }
@@ -120,6 +120,18 @@ describeOrSkip("PushService by memberId (integration)", () => {
120
120
  expect(row.memberId).toBe(bobId);
121
121
  });
122
122
 
123
+ it("subscribe for an email with no member record stores nothing", async () => {
124
+ expect(
125
+ await service.subscribe(
126
+ "ghost@nowhere.com",
127
+ "https://p/g",
128
+ P256DH,
129
+ AUTH,
130
+ ),
131
+ ).toEqual({ ok: false, reason: "no_member" });
132
+ expect(await prisma.pushSubscription.count()).toBe(0);
133
+ });
134
+
123
135
  it("sendToUsers resolves emails to members and skips null-memberId subscriptions", async () => {
124
136
  await service.subscribe(
125
137
  "alice@acme.com",
@@ -84,12 +84,12 @@ interface PushPrismaLike {
84
84
  };
85
85
  }
86
86
 
87
- /** Outcome of PushService.subscribe — distinguishes the three response shapes
88
- * the route handler maps to HTTP status (503 unavailable / 500 store_failed /
89
- * 200 ok). */
87
+ /** Outcome of PushService.subscribe — distinguishes the response shapes the
88
+ * route handler maps to HTTP status (503 unavailable / 409 no_member /
89
+ * 500 store_failed / 200 ok). */
90
90
  type PushSubscribeResult =
91
91
  | { ok: true }
92
- | { ok: false; reason: "unavailable" | "store_failed" };
92
+ | { ok: false; reason: "unavailable" | "store_failed" | "no_member" };
93
93
 
94
94
  /** Outcome of PushService.unsubscribe — delete failures are swallowed/logged
95
95
  * inside the service (best-effort), so only "unavailable" (model missing) is
@@ -344,6 +344,9 @@ export class PushService {
344
344
  return { ok: false, reason: "unavailable" };
345
345
  try {
346
346
  const memberId = await this.memberIdForEmail(userEmail);
347
+ // No account member record: nothing to attach the subscription to, so
348
+ // store nothing and let the caller say why.
349
+ if (!memberId) return { ok: false, reason: "no_member" };
347
350
  await this.prisma.pushSubscription.upsert({
348
351
  where: { endpoint },
349
352
  create: { userEmail, memberId, endpoint, p256dh, auth },
@@ -597,6 +597,30 @@ describe("PushService.subscribe", () => {
597
597
  ]);
598
598
  });
599
599
 
600
+ it("returns reason:no_member and stores nothing when the email has no member record", async () => {
601
+ const calls: unknown[] = [];
602
+ const prisma = {
603
+ chatThreadWatch: { findMany: async () => [] },
604
+ pushSubscription: {
605
+ findMany: async () => [],
606
+ deleteMany: async () => ({ count: 0 }),
607
+ upsert: async (args: unknown) => {
608
+ calls.push(args);
609
+ return { id: "sub_1" };
610
+ },
611
+ },
612
+ };
613
+ const service = makeService(prisma as never, vapid, unusedFetch, "title");
614
+ const result = await service.subscribe(
615
+ "nobody@x.com",
616
+ "https://push/ok",
617
+ P256DH,
618
+ AUTH,
619
+ );
620
+ expect(result).toEqual({ ok: false, reason: "no_member" });
621
+ expect(calls).toEqual([]);
622
+ });
623
+
600
624
  it("returns reason:unavailable when the pushSubscription model is absent", async () => {
601
625
  const prisma = {
602
626
  chatThreadWatch: { findMany: async () => [] },
@@ -126,6 +126,16 @@ export function renderPushToggle(args: PushToggleArgs): string {
126
126
  window.location.href = '/admin/login?returnTo=' + encodeURIComponent(location.pathname + location.search);
127
127
  return;
128
128
  }
129
+ if (res && res.status === 409) {
130
+ btn.disabled = false;
131
+ setStatus("Notifications can't be enabled: your account has no member record. Ask an owner or admin to add you.");
132
+ return;
133
+ }
134
+ if (res && !res.ok) {
135
+ btn.disabled = false;
136
+ setStatus("Notifications couldn't be enabled. Please try again.");
137
+ return;
138
+ }
129
139
  setStatus('Notifications enabled.');
130
140
  btn.textContent = 'Notifications on';
131
141
  });