@app-vitals/agent-admin 1.102.0 → 1.104.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.102.0",
3
+ "version": "1.104.0",
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.102.0",
47
+ "@app-vitals/agent-lib": "1.104.0",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
@@ -40,3 +40,19 @@ export function isAccountCreateErrorCode(
40
40
  ): code is keyof typeof ACCOUNT_CREATE_ERROR_MESSAGES {
41
41
  return code in ACCOUNT_CREATE_ERROR_MESSAGES;
42
42
  }
43
+
44
+ /**
45
+ * Who may create agents (ACM-7.3): platform admins, and account owners (with
46
+ * an account). Members are denied. When the resolver could not determine a
47
+ * role (no membership dep), an account user keeps the legacy behavior.
48
+ */
49
+ export function canCreateAgent(scope: CallerScope): boolean {
50
+ if (scope.kind === "all") return true;
51
+ if (scope.accountId === null) return false;
52
+ return scope.role === undefined || scope.role === "owner";
53
+ }
54
+
55
+ /** Account to stamp on a new agent, or null when the caller may not create. */
56
+ export function createAccountIdFromScope(scope: CallerScope): string | null {
57
+ return canCreateAgent(scope) ? accountIdFromScope(scope) : null;
58
+ }
@@ -4,7 +4,12 @@
4
4
  */
5
5
 
6
6
  import { describe, expect, it } from "bun:test";
7
- import { getSelfServeSpecialty } from "./account-agent-create.ts";
7
+ import {
8
+ canCreateAgent,
9
+ createAccountIdFromScope,
10
+ getSelfServeSpecialty,
11
+ } from "./account-agent-create.ts";
12
+ import type { CallerScope } from "./caller-scope.ts";
8
13
 
9
14
  describe("getSelfServeSpecialty", () => {
10
15
  it("defaults to specialist", () => {
@@ -26,3 +31,26 @@ describe("getSelfServeSpecialty", () => {
26
31
  ).toBe("base");
27
32
  });
28
33
  });
34
+
35
+ describe("canCreateAgent / createAccountIdFromScope", () => {
36
+ const scoped = (
37
+ accountId: string | null,
38
+ role?: "owner" | "member" | null,
39
+ ): CallerScope => ({ kind: "scoped", accountId, agentIds: [], role });
40
+
41
+ it("allows platform admins", () => {
42
+ expect(canCreateAgent({ kind: "all" })).toBe(true);
43
+ expect(createAccountIdFromScope({ kind: "all" })).toBeNull();
44
+ });
45
+
46
+ it("allows owners and stamps their account", () => {
47
+ expect(canCreateAgent(scoped("a", "owner"))).toBe(true);
48
+ expect(createAccountIdFromScope(scoped("a", "owner"))).toBe("a");
49
+ });
50
+
51
+ it("denies members and callers without an account", () => {
52
+ expect(canCreateAgent(scoped("a", "member"))).toBe(false);
53
+ expect(createAccountIdFromScope(scoped("a", "member"))).toBeNull();
54
+ expect(canCreateAgent(scoped(null, "owner"))).toBe(false);
55
+ });
56
+ });
@@ -211,6 +211,8 @@ export interface SettingsNavContribution {
211
211
  label: string;
212
212
  path: string;
213
213
  adminOnly?: boolean;
214
+ /** Hidden from account members; admins and owners see it. */
215
+ ownerOnly?: boolean;
214
216
  }
215
217
 
216
218
  export interface AdminExtension {
@@ -105,6 +105,7 @@ export function renderAccountPage(opts: AccountPageOpts): string {
105
105
  active: ACCOUNT_PATH,
106
106
  toolbarPath: "/admin/settings",
107
107
  isAdmin: opts.isAdmin ?? false,
108
+ isOwner: true,
108
109
  body: `${errorHtml}
109
110
  <div class="card">
110
111
  <div class="card-title">Account</div>
@@ -4,17 +4,17 @@
4
4
  */
5
5
 
6
6
  import { describe, expect, it } from "bun:test";
7
- import { Hono } from "hono";
8
7
  import type { MiddlewareHandler } from "hono";
9
- import {
10
- type AccountRouteDeps,
11
- registerAccountRoutes,
12
- } from "./admin-ui-account.ts";
13
- import type { AdminUIEnv } from "./admin-ui.ts";
8
+ import { Hono } from "hono";
14
9
  import {
15
10
  AccountMemberNotFoundError,
16
11
  LastOwnerError,
17
12
  } from "./account-members.ts";
13
+ import type { AdminUIEnv } from "./admin-ui.ts";
14
+ import {
15
+ type AccountRouteDeps,
16
+ registerAccountRoutes,
17
+ } from "./admin-ui-account.ts";
18
18
 
19
19
  const d = new Date("2026-01-01T00:00:00Z");
20
20
 
@@ -58,7 +58,7 @@ function setup(
58
58
  enabled: opts.enabled ?? true,
59
59
  requireAuth: (async (c, next) => {
60
60
  c.set("userEmail", c.req.header("x-test-user-email") ?? "owner@x.com");
61
- c.set("isAdmin", false);
61
+ c.set("isAdmin", c.req.header("x-test-admin") === "1");
62
62
  await next();
63
63
  }) as MiddlewareHandler<AdminUIEnv>,
64
64
  html: (content, o) =>
@@ -169,10 +169,10 @@ describe("/admin/account", () => {
169
169
  expect(res.status).toBe(404);
170
170
  });
171
171
 
172
- it("GET renders the account for a member", async () => {
172
+ it("GET renders the account for an owner", async () => {
173
173
  const { app } = setup();
174
174
  const res = await app.request("/admin/account", {
175
- headers: { "x-test-user-email": "member@x.com" },
175
+ headers: { "x-test-user-email": "owner@x.com" },
176
176
  });
177
177
  expect(res.status).toBe(200);
178
178
  const body = await res.text();
@@ -184,6 +184,22 @@ describe("/admin/account", () => {
184
184
  expect(body).not.toContain('class="vos-nav-link" href="/admin/account"');
185
185
  });
186
186
 
187
+ it("GET renders the account for an admin who belongs to it", async () => {
188
+ const { app } = setup();
189
+ const res = await app.request("/admin/account", {
190
+ headers: { "x-test-user-email": "member@x.com", "x-test-admin": "1" },
191
+ });
192
+ expect(res.status).toBe(200);
193
+ });
194
+
195
+ it("GET 404s for a plain member (ACM-7.2)", async () => {
196
+ const { app } = setup();
197
+ const res = await app.request("/admin/account", {
198
+ headers: { "x-test-user-email": "member@x.com" },
199
+ });
200
+ expect(res.status).toBe(404);
201
+ });
202
+
187
203
  it("owner can invite, see it pending, and revoke it", async () => {
188
204
  const { app } = setup();
189
205
  const res = await post(app, "/admin/account/invite", {
@@ -212,7 +228,7 @@ describe("/admin/account", () => {
212
228
  ).toBe(400);
213
229
  });
214
230
 
215
- it("member gets 403 on every mutation", async () => {
231
+ it("member gets 404 on every mutation (ACM-7.2)", async () => {
216
232
  const { app } = setup();
217
233
  for (const [path, fields] of [
218
234
  ["/admin/account/invite", { email: "a@b.co" }],
@@ -223,7 +239,7 @@ describe("/admin/account", () => {
223
239
  ["/admin/account/rename", { name: "X" }],
224
240
  ] as const) {
225
241
  const res = await post(app, path, { ...fields }, "member@x.com");
226
- expect(res.status).toBe(403);
242
+ expect(res.status).toBe(404);
227
243
  }
228
244
  });
229
245
 
@@ -88,6 +88,8 @@ export function registerAccountRoutes(
88
88
  const account = await deps.accounts.getByMemberEmail(c.var.userEmail);
89
89
  if (!account) return notFound();
90
90
  const me = await deps.members.getByEmail(c.var.userEmail);
91
+ // Plain members never see the Account page; admins with an account may.
92
+ if (me?.role !== "owner" && c.var.isAdmin !== true) return notFound();
91
93
  return { account, isOwner: me?.role === "owner" };
92
94
  }
93
95
 
@@ -7,11 +7,15 @@
7
7
 
8
8
  import type { SettingsNavContribution } from "./admin-extension.ts";
9
9
  import { escapeHtml, renderAdminToolbar } from "./admin-ui-styles.ts";
10
+ import type { ViewerRole } from "./caller-scope.ts";
10
11
 
11
12
  export interface SettingsNavItem {
12
13
  label: string;
13
14
  path: string;
15
+ /** Visible to platform admins only. */
14
16
  adminOnly?: boolean;
17
+ /** Visible to platform admins and account owners, hidden from members. */
18
+ ownerOnly?: boolean;
15
19
  }
16
20
 
17
21
  export interface SettingsNavSection {
@@ -36,16 +40,33 @@ export interface RenderSettingsLayoutOptions {
36
40
  toolbarPath?: string;
37
41
  /** Show adminOnly items. Default false. */
38
42
  isAdmin?: boolean;
43
+ /** Show ownerOnly items (admins always see them). Default false. */
44
+ isOwner?: boolean;
45
+ }
46
+
47
+ /** Whether an item is visible to a viewer with the given role. */
48
+ export function isSettingsItemVisible(
49
+ item: SettingsNavItem,
50
+ role: ViewerRole | null,
51
+ ): boolean {
52
+ if (role === "admin") return true;
53
+ if (item.adminOnly) return false;
54
+ if (item.ownerOnly) return role === "owner";
55
+ return true;
39
56
  }
40
57
 
41
58
  export function renderSettingsLayout(
42
59
  opts: RenderSettingsLayoutOptions,
43
60
  ): string {
44
- const isAdmin = opts.isAdmin ?? false;
61
+ const role: ViewerRole = opts.isAdmin
62
+ ? "admin"
63
+ : opts.isOwner
64
+ ? "owner"
65
+ : "member";
45
66
  const sections = opts.nav.sections
46
67
  .map((s) => ({
47
68
  label: s.label,
48
- items: s.items.filter((i) => isAdmin || !i.adminOnly),
69
+ items: s.items.filter((i) => isSettingsItemVisible(i, role)),
49
70
  }))
50
71
  .filter((s) => s.items.length > 0);
51
72
 
@@ -137,14 +158,19 @@ export function buildSettingsNav(
137
158
  });
138
159
  }
139
160
  if (opts.slackConfigToken) {
140
- // Not adminOnly, like Templates: account owners manage their own row.
161
+ // ownerOnly, like Templates: account owners manage their own row.
141
162
  platform.push({
142
163
  label: "Slack config token",
143
164
  path: SETTINGS_SLACK_CONFIG_TOKEN_PATH,
165
+ ownerOnly: true,
144
166
  });
145
167
  }
146
168
  if (opts.templates) {
147
- platform.push({ label: "Templates", path: SETTINGS_TEMPLATES_PATH });
169
+ platform.push({
170
+ label: "Templates",
171
+ path: SETTINGS_TEMPLATES_PATH,
172
+ ownerOnly: true,
173
+ });
148
174
  }
149
175
  if (opts.accounts) {
150
176
  platform.push({
@@ -176,6 +202,30 @@ export function withoutAccountItem(nav: SettingsNav): SettingsNav {
176
202
  };
177
203
  }
178
204
 
205
+ /**
206
+ * The nav as the viewer's role sees it: items the role may not see are
207
+ * dropped (adminOnly / ownerOnly), the Account item is hidden from members,
208
+ * and sections left empty are removed. A null role (no account) sees only
209
+ * unflagged items.
210
+ */
211
+ export function filterSettingsNavForRole(
212
+ nav: SettingsNav,
213
+ role: ViewerRole | null,
214
+ ): SettingsNav {
215
+ return {
216
+ sections: nav.sections
217
+ .map((sec) => ({
218
+ ...sec,
219
+ items: sec.items.filter(
220
+ (i) =>
221
+ isSettingsItemVisible(i, role) &&
222
+ !(role === "member" && i.path === SETTINGS_ACCOUNT_PATH),
223
+ ),
224
+ }))
225
+ .filter((sec) => sec.items.length > 0),
226
+ };
227
+ }
228
+
179
229
  /** Request-context key under which the viewer-resolved nav is stored. */
180
230
  export const SETTINGS_NAV_CONTEXT_KEY = "settingsNav";
181
231
 
@@ -195,9 +245,9 @@ export function getSettingsNav(c: {
195
245
  /** First nav item visible to the viewer, or undefined. */
196
246
  export function firstVisibleSettingsItem(
197
247
  nav: SettingsNav,
198
- isAdmin: boolean,
248
+ role: ViewerRole | null,
199
249
  ): SettingsNavItem | undefined {
200
250
  return nav.sections
201
251
  .flatMap((s) => s.items)
202
- .find((i) => isAdmin || !i.adminOnly);
252
+ .find((i) => isSettingsItemVisible(i, role));
203
253
  }
@@ -6,6 +6,7 @@
6
6
  import { describe, expect, test } from "bun:test";
7
7
  import {
8
8
  buildSettingsNav,
9
+ filterSettingsNavForRole,
9
10
  firstVisibleSettingsItem,
10
11
  renderSettingsLayout,
11
12
  type SettingsNav,
@@ -121,7 +122,11 @@ describe("buildSettingsNav / firstVisibleSettingsItem (SGL-2.2)", () => {
121
122
  path: "/admin/settings/github-enterprise",
122
123
  adminOnly: true,
123
124
  },
124
- { label: "Templates", path: "/admin/settings/templates" },
125
+ {
126
+ label: "Templates",
127
+ path: "/admin/settings/templates",
128
+ ownerOnly: true,
129
+ },
125
130
  ],
126
131
  },
127
132
  ],
@@ -150,17 +155,107 @@ describe("buildSettingsNav / firstVisibleSettingsItem (SGL-2.2)", () => {
150
155
  "A",
151
156
  ]);
152
157
  });
153
- test("first visible item respects adminOnly", () => {
158
+ test("first visible item respects the viewer role", () => {
154
159
  const nav = buildSettingsNav(both);
155
- expect(firstVisibleSettingsItem(nav, true)?.label).toBe(
160
+ expect(firstVisibleSettingsItem(nav, "admin")?.label).toBe(
156
161
  "GitHub Enterprise",
157
162
  );
158
- expect(firstVisibleSettingsItem(nav, false)?.label).toBe("Templates");
163
+ expect(firstVisibleSettingsItem(nav, "owner")?.label).toBe("Templates");
164
+ expect(firstVisibleSettingsItem(nav, "member")).toBeUndefined();
159
165
  expect(
160
166
  firstVisibleSettingsItem(
161
167
  buildSettingsNav({ githubEnterprise: true }),
162
- false,
168
+ "owner",
163
169
  ),
164
170
  ).toBeUndefined();
165
171
  });
172
+ test("a member lands on the unflagged Notifications item", () => {
173
+ const nav = buildSettingsNav({
174
+ ...both,
175
+ accounts: true,
176
+ extraItems: [
177
+ { section: "Account", label: "Notifications", path: "/n" },
178
+ {
179
+ section: "Platform",
180
+ label: "System crons",
181
+ path: "/c",
182
+ adminOnly: true,
183
+ },
184
+ ],
185
+ });
186
+ expect(firstVisibleSettingsItem(nav, "member")).toBeDefined();
187
+ expect(
188
+ firstVisibleSettingsItem(
189
+ filterSettingsNavForRole(nav, "member"),
190
+ "member",
191
+ )?.label,
192
+ ).toBe("Notifications");
193
+ });
194
+ });
195
+
196
+ describe("filterSettingsNavForRole (ACM-7.2)", () => {
197
+ const nav = buildSettingsNav({
198
+ githubEnterprise: true,
199
+ templates: true,
200
+ slackConfigToken: true,
201
+ accounts: true,
202
+ extraItems: [
203
+ { section: "Account", label: "Notifications", path: "/n" },
204
+ {
205
+ section: "Platform",
206
+ label: "System crons",
207
+ path: "/c",
208
+ adminOnly: true,
209
+ },
210
+ ],
211
+ });
212
+ const labels = (role: Parameters<typeof filterSettingsNavForRole>[1]) =>
213
+ filterSettingsNavForRole(nav, role).sections.flatMap((s) =>
214
+ s.items.map((i) => i.label),
215
+ );
216
+
217
+ test("flags Templates and Slack config token ownerOnly", () => {
218
+ const items = nav.sections.flatMap((s) => s.items);
219
+ const flag = (l: string) => items.find((i) => i.label === l);
220
+ expect(flag("Templates")?.ownerOnly).toBe(true);
221
+ expect(flag("Slack config token")?.ownerOnly).toBe(true);
222
+ expect(flag("GitHub Enterprise")?.adminOnly).toBe(true);
223
+ expect(flag("Notifications")?.ownerOnly).toBeUndefined();
224
+ });
225
+ test("admin sees every item", () => {
226
+ expect(labels("admin")).toEqual([
227
+ "Account",
228
+ "Notifications",
229
+ "GitHub Enterprise",
230
+ "Slack config token",
231
+ "Templates",
232
+ "Accounts",
233
+ "System crons",
234
+ ]);
235
+ });
236
+ test("owner sees all non-adminOnly items", () => {
237
+ expect(labels("owner")).toEqual([
238
+ "Account",
239
+ "Notifications",
240
+ "Slack config token",
241
+ "Templates",
242
+ ]);
243
+ });
244
+ test("member sees only unflagged items and not Account", () => {
245
+ expect(labels("member")).toEqual(["Notifications"]);
246
+ });
247
+ test("no role behaves like a member except Account is left to the caller", () => {
248
+ expect(labels(null)).toContain("Notifications");
249
+ expect(labels(null)).not.toContain("Templates");
250
+ });
251
+ test("renderSettingsLayout hides ownerOnly unless isOwner or isAdmin", () => {
252
+ const base = { userName: "u", title: "T", nav, active: "/n", body: "" };
253
+ expect(renderSettingsLayout(base)).not.toContain("Templates");
254
+ expect(renderSettingsLayout({ ...base, isOwner: true })).toContain(
255
+ "Templates",
256
+ );
257
+ expect(renderSettingsLayout({ ...base, isAdmin: true })).toContain(
258
+ "Templates",
259
+ );
260
+ });
166
261
  });
@@ -30,7 +30,10 @@ const adminCookie = async () => `admin_session=${await makeSessionCookie()}`;
30
30
  const userCookie = async (email = "m@acme.com") =>
31
31
  `admin_session=${await makeSessionCookie(undefined, "u2", email, false)}`;
32
32
 
33
- const memberAccounts = (member: string | null) =>
33
+ const memberAccounts = (
34
+ member: string | null,
35
+ role: "owner" | "member" = "owner",
36
+ ) =>
34
37
  ({
35
38
  accounts: {
36
39
  getByMemberEmail: async (e: string) =>
@@ -38,7 +41,10 @@ const memberAccounts = (member: string | null) =>
38
41
  listWithCounts: async () => [{ id: "acct-1", name: "Acme" }],
39
42
  getWithCounts: async (id: string) => ({ id, name: "Acme" }),
40
43
  },
41
- members: {},
44
+ members: {
45
+ getByEmail: async (e: string) =>
46
+ e === member ? { accountId: "acct-1", email: e, role } : null,
47
+ },
42
48
  }) as never;
43
49
 
44
50
  describe("GET /admin/settings", () => {
@@ -63,7 +69,7 @@ describe("GET /admin/settings", () => {
63
69
  expect(res.headers.get("location")).toBe("/admin/settings/templates");
64
70
  });
65
71
 
66
- it("redirects a non-admin member past the adminOnly item", async () => {
72
+ it("redirects an account owner past the adminOnly item", async () => {
67
73
  const app = createAdminUIApp(
68
74
  makeMockDeps({
69
75
  githubEnterpriseApi: ghe,
@@ -78,6 +84,28 @@ describe("GET /admin/settings", () => {
78
84
  expect(res.headers.get("location")).toBe("/admin/settings/templates");
79
85
  });
80
86
 
87
+ it("lands an account member on Notifications (ACM-7.2)", async () => {
88
+ const app = createAdminUIApp(
89
+ makeMockDeps({
90
+ githubEnterpriseApi: ghe,
91
+ templateService,
92
+ settingsNavItems: [
93
+ {
94
+ section: "Account",
95
+ label: "Notifications",
96
+ path: "/admin/notifications",
97
+ },
98
+ ],
99
+ accountServices: memberAccounts("m@acme.com", "member"),
100
+ }),
101
+ );
102
+ const res = await app.request("/admin/settings", {
103
+ headers: { cookie: await userCookie() },
104
+ });
105
+ expect(res.status).toBe(302);
106
+ expect(res.headers.get("location")).toBe("/admin/notifications");
107
+ });
108
+
81
109
  it("404s a non-admin when only admin-only items exist", async () => {
82
110
  const app = createAdminUIApp(makeMockDeps({ githubEnterpriseApi: ghe }));
83
111
  const res = await app.request("/admin/settings", {
@@ -126,7 +154,7 @@ describe("settings shell pages", () => {
126
154
  );
127
155
  });
128
156
 
129
- it("renders Templates in the shell and hides the GHE item from members", async () => {
157
+ it("renders Templates in the shell and hides the GHE item from owners", async () => {
130
158
  const app = createAdminUIApp(
131
159
  makeMockDeps({
132
160
  githubEnterpriseApi: ghe,
@@ -203,7 +231,7 @@ describe("GET /admin/settings with accounts (SGL-2.3)", () => {
203
231
  } as never),
204
232
  );
205
233
 
206
- it("lands an account member on Account", async () => {
234
+ it("lands an account owner on Account", async () => {
207
235
  const res = await build("m@acme.com").request("/admin/settings", {
208
236
  headers: { cookie: await userCookie("m@acme.com") },
209
237
  });
@@ -211,6 +239,28 @@ describe("GET /admin/settings with accounts (SGL-2.3)", () => {
211
239
  expect(res.headers.get("location")).toBe("/admin/account");
212
240
  });
213
241
 
242
+ it("lands an account member on Notifications, not Account (ACM-7.2)", async () => {
243
+ const app = createAdminUIApp(
244
+ makeMockDeps({
245
+ templateService,
246
+ selfServe,
247
+ settingsNavItems: [
248
+ {
249
+ section: "Account",
250
+ label: "Notifications",
251
+ path: "/admin/notifications",
252
+ },
253
+ ],
254
+ accountServices: memberAccounts("m@acme.com", "member"),
255
+ } as never),
256
+ );
257
+ const res = await app.request("/admin/settings", {
258
+ headers: { cookie: await userCookie("m@acme.com") },
259
+ });
260
+ expect(res.status).toBe(302);
261
+ expect(res.headers.get("location")).toBe("/admin/notifications");
262
+ });
263
+
214
264
  it("skips Account for an admin without an account", async () => {
215
265
  const res = await build(null).request("/admin/settings", {
216
266
  headers: { cookie: await adminCookie() },
@@ -113,6 +113,7 @@ export function renderSlackConfigTokenPage(
113
113
  buildSettingsNav({ githubEnterprise: true, slackConfigToken: true }),
114
114
  active: BASE,
115
115
  isAdmin: o.isAdmin ?? false,
116
+ isOwner: true,
116
117
  body: `${error}${notice}${encryptionWarning}
117
118
  <div class="card">
118
119
  <p class="help-text">The Slack App Configuration token used to create and update agent Slack apps. A deployment-wide token is the default; an account's own token overrides it. Tokens are stored encrypted and never shown.</p>
@@ -178,6 +178,7 @@ export function renderTemplatesPage(o: TemplatesPageOpts): string {
178
178
  o.nav ?? buildSettingsNav({ githubEnterprise: true, templates: true }),
179
179
  active: BASE,
180
180
  isAdmin: o.isAdmin ?? false,
181
+ isOwner: true,
181
182
  body: `${error}${notice}
182
183
  <div class="card">
183
184
  <p class="help-text">Default env vars, tools, plugins, crons and plugin marketplaces for new agents in a scope. Secret values are masked after saving; leave <code>***</code> to keep the stored value.</p>
@@ -94,7 +94,12 @@ function fakeService() {
94
94
  }
95
95
 
96
96
  function setup(
97
- opts: { isAdmin?: boolean; scope?: CallerScope } = {},
97
+ opts: {
98
+ isAdmin?: boolean;
99
+ scope?: CallerScope;
100
+ /** Role of u@x.com in acct-1; default "owner" (a non-admin is an owner). */
101
+ role?: "owner" | "member";
102
+ } = {},
98
103
  ): { app: Hono<AdminUIEnv> } & ReturnType<typeof fakeService> {
99
104
  const svc = fakeService();
100
105
  const app = new Hono<AdminUIEnv>();
@@ -108,6 +113,16 @@ function setup(
108
113
  templateService: svc.service,
109
114
  callerScopeResolver: async () =>
110
115
  opts.scope ?? { kind: "scoped", accountId: null, agentIds: [] },
116
+ members: {
117
+ getByEmail: async () =>
118
+ ({
119
+ id: "m1",
120
+ accountId: "acct-1",
121
+ email: "u@x.com",
122
+ role: opts.role ?? "owner",
123
+ createdAt: now,
124
+ }) as never,
125
+ },
111
126
  accounts: {
112
127
  listWithCounts: async () =>
113
128
  [
@@ -136,7 +151,7 @@ const form = (fields: Record<string, string>) => ({
136
151
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
137
152
  body: new URLSearchParams(fields).toString(),
138
153
  });
139
- const member: CallerScope = {
154
+ const ownerScope: CallerScope = {
140
155
  kind: "scoped",
141
156
  accountId: "acct-1",
142
157
  agentIds: [],
@@ -257,16 +272,16 @@ describe("/admin/settings/templates smoke", () => {
257
272
  expect(await res.text()).toContain("unknown specialty ghost");
258
273
  });
259
274
 
260
- it("offers an account member only their own account", async () => {
261
- const { app } = setup({ isAdmin: false, scope: member });
275
+ it("offers an account owner only their own account", async () => {
276
+ const { app } = setup({ isAdmin: false, scope: ownerScope });
262
277
  const html = await (await app.request(BASE)).text();
263
278
  expect(html).toContain("Acme");
264
279
  expect(html).not.toContain("Globex");
265
280
  expect(html).not.toContain("Deployment-wide");
266
281
  });
267
282
 
268
- it("pins member writes to their account and rejects other accounts", async () => {
269
- const { app, rows } = setup({ isAdmin: false, scope: member });
283
+ it("pins owner writes to their account and rejects other accounts", async () => {
284
+ const { app, rows } = setup({ isAdmin: false, scope: ownerScope });
270
285
  const ok = await app.request(
271
286
  `${BASE}/items`,
272
287
  form({ accountId: "", specialty: "", kind: "tool", key: "Bash" }),
@@ -319,6 +334,28 @@ describe("/admin/settings/templates smoke", () => {
319
334
  expect(seeded).toContain("Remove");
320
335
  });
321
336
 
337
+ it("403s a plain account member on GET and every mutating route (ACM-7.2)", async () => {
338
+ const { app, rows } = setup({
339
+ isAdmin: false,
340
+ scope: ownerScope,
341
+ role: "member",
342
+ });
343
+ expect((await app.request(BASE)).status).toBe(403);
344
+ for (const path of ["items", "items/delete", "delete"]) {
345
+ const res = await app.request(
346
+ `${BASE}/${path}`,
347
+ form({ accountId: "", specialty: "", kind: "tool", key: "Bash" }),
348
+ );
349
+ expect(res.status).toBe(403);
350
+ }
351
+ expect(rows).toHaveLength(0);
352
+ });
353
+
354
+ it("lets an account owner in, scoped to their own account (ACM-7.2)", async () => {
355
+ const { app } = setup({ isAdmin: false, scope: ownerScope });
356
+ expect((await app.request(BASE)).status).toBe(200);
357
+ });
358
+
322
359
  it("403s a non-admin without an account", async () => {
323
360
  const { app } = setup({ isAdmin: false });
324
361
  expect((await app.request(BASE)).status).toBe(403);
@@ -8,11 +8,12 @@
8
8
  * errors (denylisted env key, unknown specialty, bad payload) are shown inline.
9
9
  */
10
10
 
11
- import type { SettingsNav } from "./admin-ui-settings-layout.ts";
12
11
  import type { Context, Hono, MiddlewareHandler } from "hono";
13
12
  import { accountIdFromScope } from "./account-agent-create.ts";
13
+ import type { AccountMemberService } from "./account-members.ts";
14
14
  import type { AccountService } from "./accounts.ts";
15
15
  import type { AdminUIEnv } from "./admin-ui.ts";
16
+ import type { SettingsNav } from "./admin-ui-settings-layout.ts";
16
17
  import {
17
18
  ADMIN_TEMPLATES_PATH as BASE,
18
19
  renderTemplatesPage,
@@ -40,6 +41,8 @@ export interface AdminTemplatesRouteDeps {
40
41
  "list" | "replace" | "putItem" | "deleteItem" | "delete"
41
42
  >;
42
43
  callerScopeResolver: CallerScopeResolver;
44
+ /** Needed to tell account owners from plain members; absent = admins only. */
45
+ members?: Pick<AccountMemberService, "getByEmail">;
43
46
  /** Settings sidebar nav (SGL-2.2). */
44
47
  settingsNav?: SettingsNav;
45
48
  /** Optional: without it admins can only pick deployment-wide. */
@@ -73,8 +76,12 @@ export function registerAdminTemplatesRoutes(
73
76
  const accountId = accountIdFromScope(
74
77
  await deps.callerScopeResolver(c.var.userEmail, false),
75
78
  );
76
- if (accountId === null) {
77
- throw new ForbiddenError("Admin or account access required");
79
+ if (accountId === null || !deps.members) {
80
+ throw new ForbiddenError("Admin or account owner access required");
81
+ }
82
+ const me = await deps.members.getByEmail(c.var.userEmail);
83
+ if (!me || me.role !== "owner" || me.accountId !== accountId) {
84
+ throw new ForbiddenError("Admin or account owner access required");
78
85
  }
79
86
  return { kind: "account", accountId };
80
87
  }
@@ -7941,3 +7941,54 @@ describe("admin UI — Anthropic federation credential guards (WIF-2.1)", () =>
7941
7941
  expect(html).not.toContain('name="claudeCodeOauthToken"');
7942
7942
  });
7943
7943
  });
7944
+
7945
+ describe("agent create requires owner or admin (ACM-7.3)", () => {
7946
+ const scoped = (role: "owner" | "member") => async () => ({
7947
+ kind: "scoped" as const,
7948
+ accountId: "acct-a",
7949
+ agentIds: [],
7950
+ role,
7951
+ });
7952
+ const userCookie = () =>
7953
+ makeSessionCookie(SESSION_SECRET, "google-sub-u", "u@example.com", false);
7954
+
7955
+ it("member gets 403 on the create form and POST; no agent is created", async () => {
7956
+ const created: unknown[] = [];
7957
+ const plain = makeMockDeps();
7958
+ const app = createAdminUIApp(
7959
+ makeMockDeps({
7960
+ callerScopeResolver: scoped("member"),
7961
+ agentService: {
7962
+ ...plain.agentService,
7963
+ create: async (
7964
+ ...a: Parameters<typeof plain.agentService.create>
7965
+ ) => {
7966
+ created.push(a[0]);
7967
+ return plain.agentService.create(...a);
7968
+ },
7969
+ },
7970
+ }),
7971
+ );
7972
+ const Cookie = `admin_session=${await userCookie()}`;
7973
+ expect(
7974
+ (await app.request("/admin/agents/new", { headers: { Cookie } })).status,
7975
+ ).toBe(403);
7976
+ const res = await app.request("/admin/agents", {
7977
+ method: "POST",
7978
+ body: new URLSearchParams({ name: "X", accountId: "acct-b" }).toString(),
7979
+ headers: { Cookie, "Content-Type": "application/x-www-form-urlencoded" },
7980
+ });
7981
+ expect(res.status).toBe(403);
7982
+ expect(created).toHaveLength(0);
7983
+ });
7984
+
7985
+ it("owner can open the create form", async () => {
7986
+ const app = createAdminUIApp(
7987
+ makeMockDeps({ callerScopeResolver: scoped("owner") }),
7988
+ );
7989
+ const res = await app.request("/admin/agents/new", {
7990
+ headers: { Cookie: `admin_session=${await userCookie()}` },
7991
+ });
7992
+ expect(res.status).toBe(200);
7993
+ });
7994
+ });
package/src/admin-ui.ts CHANGED
@@ -31,6 +31,7 @@ import { deleteCookie, getCookie, setCookie } from "hono/cookie";
31
31
  import { sign, verify } from "hono/jwt";
32
32
  import {
33
33
  accountIdFromScope,
34
+ createAccountIdFromScope,
34
35
  getSelfServeSpecialty,
35
36
  } from "./account-agent-create.ts";
36
37
  import type { AccountCreatedNotifier } from "./account-created-notifier.ts";
@@ -100,6 +101,7 @@ import {
100
101
  } from "./admin-ui-pages.ts";
101
102
  import {
102
103
  buildSettingsNav,
104
+ filterSettingsNavForRole,
103
105
  firstVisibleSettingsItem,
104
106
  SETTINGS_NAV_CONTEXT_KEY,
105
107
  type SettingsNav,
@@ -134,6 +136,7 @@ import {
134
136
  type CallerScopeResolver,
135
137
  memberOnlyCallerScopeResolver,
136
138
  scopeIncludesAgent,
139
+ type ViewerRole,
137
140
  } from "./caller-scope.ts";
138
141
  import { ForbiddenError, UnprocessableEntityError } from "./errors.ts";
139
142
  import type { GithubAppsState } from "./github-apps-state.ts";
@@ -1023,16 +1026,31 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1023
1026
 
1024
1027
  // Expose the viewer-resolved nav to every /admin/* handler registered after
1025
1028
  // this point, including extension adminUiRoutes (mounted after this app).
1029
+ // Viewer role for the nav: admin, else the AccountMember.role, else null.
1030
+ const resolveNavRole = async (
1031
+ email: string,
1032
+ isAdmin: boolean,
1033
+ ): Promise<ViewerRole | null> => {
1034
+ if (isAdmin) return "admin";
1035
+ if (!accountServices) return null;
1036
+ const me = await accountServices.members
1037
+ .getByEmail(email)
1038
+ .catch(() => null);
1039
+ return me?.role === "owner" || me?.role === "member" ? me.role : null;
1040
+ };
1041
+
1026
1042
  app.use("/admin/*", async (c, next) => {
1027
1043
  let nav = settingsNav;
1028
- if (accountNavEnabled && accountServices) {
1029
- const token = getCookie(c, SESSION_COOKIE);
1030
- const user = token ? await getSessionUser(token, sessionSecret) : null;
1031
- if (user) {
1044
+ const token = getCookie(c, SESSION_COOKIE);
1045
+ const user = token ? await getSessionUser(token, sessionSecret) : null;
1046
+ if (user) {
1047
+ const role = await resolveNavRole(user.email, user.isAdmin === true);
1048
+ nav = filterSettingsNavForRole(settingsNav, role);
1049
+ if (accountNavEnabled && accountServices) {
1032
1050
  const account = await accountServices.accounts
1033
1051
  .getByMemberEmail(user.email)
1034
1052
  .catch(() => null);
1035
- if (!account) nav = withoutAccountItem(settingsNav);
1053
+ if (!account) nav = withoutAccountItem(nav);
1036
1054
  }
1037
1055
  }
1038
1056
  c.set(SETTINGS_NAV_CONTEXT_KEY, nav);
@@ -1627,7 +1645,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1627
1645
  isAdmin: boolean,
1628
1646
  ): Promise<string | null> {
1629
1647
  if (isAdmin) return null;
1630
- return accountIdFromScope(await callerScopeResolver(userEmail, false));
1648
+ return createAccountIdFromScope(
1649
+ await callerScopeResolver(userEmail, false),
1650
+ );
1631
1651
  }
1632
1652
 
1633
1653
  // ATP-2.4: the template items a new agent in this scope would inherit,
@@ -4493,6 +4513,10 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4493
4513
  ) {
4494
4514
  app.get("/admin/settings", requireAuth, async (c) => {
4495
4515
  // Admins without an account would 404 on the Account item; skip it.
4516
+ const role = await resolveNavRole(
4517
+ c.var.userEmail,
4518
+ c.var.isAdmin === true,
4519
+ );
4496
4520
  let nav = settingsNav;
4497
4521
  if (accountNavEnabled && accountServices) {
4498
4522
  const account = await accountServices.accounts
@@ -4500,7 +4524,10 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4500
4524
  .catch(() => null);
4501
4525
  if (!account) nav = withoutAccountItem(settingsNav);
4502
4526
  }
4503
- const first = firstVisibleSettingsItem(nav, c.var.isAdmin === true);
4527
+ const first = firstVisibleSettingsItem(
4528
+ filterSettingsNavForRole(nav, role),
4529
+ role,
4530
+ );
4504
4531
  if (!first) {
4505
4532
  return new Response("No settings are available for your account.", {
4506
4533
  status: 404,
@@ -4528,7 +4555,12 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4528
4555
  templateService,
4529
4556
  settingsNav,
4530
4557
  callerScopeResolver,
4531
- ...(accountServices ? { accounts: accountServices.accounts } : {}),
4558
+ ...(accountServices
4559
+ ? {
4560
+ accounts: accountServices.accounts,
4561
+ members: accountServices.members,
4562
+ }
4563
+ : {}),
4532
4564
  specialtyRegistry,
4533
4565
  html,
4534
4566
  });
@@ -5350,7 +5350,10 @@ describe("admin API — account users create and delete agents (SSP-4.2)", () =>
5350
5350
  );
5351
5351
  }
5352
5352
 
5353
- function makeAccountDeps(accountId: string | null): {
5353
+ function makeAccountDeps(
5354
+ accountId: string | null,
5355
+ role: "owner" | "member" = "owner",
5356
+ ): {
5354
5357
  deps: AdminDeps;
5355
5358
  created: Array<Record<string, unknown>>;
5356
5359
  } {
@@ -5362,6 +5365,7 @@ describe("admin API — account users create and delete agents (SSP-4.2)", () =>
5362
5365
  kind: "scoped",
5363
5366
  accountId,
5364
5367
  agentIds: accountId ? [ACCOUNT_AGENT_ID] : [],
5368
+ role,
5365
5369
  }),
5366
5370
  agentService: {
5367
5371
  ...base.agentService,
@@ -5417,6 +5421,17 @@ describe("admin API — account users create and delete agents (SSP-4.2)", () =>
5417
5421
  });
5418
5422
  });
5419
5423
 
5424
+ it("an account member (not owner) gets 403 on create", async () => {
5425
+ const { deps, created } = makeAccountDeps("acct-a", "member");
5426
+ const res = await post(
5427
+ createAdminApp(deps),
5428
+ { name: "Nope", specialty: "coding", accountId: "acct-a" },
5429
+ await accountCookie(),
5430
+ );
5431
+ expect(res.status).toBe(403);
5432
+ expect(created).toHaveLength(0);
5433
+ });
5434
+
5420
5435
  it("non-admin without an account (flag off / no membership) gets 403 on create", async () => {
5421
5436
  const { deps, created } = makeAccountDeps(null);
5422
5437
  const res = await post(
package/src/agents-api.ts CHANGED
@@ -36,6 +36,7 @@ import type { PrismaClient } from "../prisma/client/client.ts";
36
36
  import {
37
37
  ACCOUNT_CREATE_ERROR_MESSAGES,
38
38
  accountIdFromScope,
39
+ createAccountIdFromScope,
39
40
  getSelfServeSpecialty,
40
41
  isAccountCreateErrorCode,
41
42
  } from "./account-agent-create.ts";
@@ -2724,9 +2725,11 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2724
2725
  const callerAccountId =
2725
2726
  email === undefined
2726
2727
  ? null
2727
- : accountIdFromScope(await callerScopeResolver(email, false));
2728
+ : createAccountIdFromScope(await callerScopeResolver(email, false));
2728
2729
  if (callerAccountId === null) {
2729
- throw new ForbiddenError("Admin access required to create agent");
2730
+ throw new ForbiddenError(
2731
+ "Owner or admin access required to create agent",
2732
+ );
2730
2733
  }
2731
2734
  accountId = callerAccountId;
2732
2735
  }
@@ -84,6 +84,7 @@ describeOrSkip("caller scope role resolver (integration)", () => {
84
84
  kind: "scoped",
85
85
  accountId,
86
86
  agentIds: [sideAgentId],
87
+ role: "member",
87
88
  });
88
89
  expect(await scope("owner@acme.com", false)).toEqual({
89
90
  kind: "scoped",
@@ -17,7 +17,13 @@ import type { AgentMemberService } from "./agent-members.ts";
17
17
 
18
18
  export type CallerScope =
19
19
  | { kind: "all" }
20
- | { kind: "scoped"; accountId: string | null; agentIds: string[] };
20
+ | {
21
+ kind: "scoped";
22
+ accountId: string | null;
23
+ agentIds: string[];
24
+ /** AccountMember.role when known (resolver has the membership dep). */
25
+ role?: ViewerRole | null;
26
+ };
21
27
 
22
28
  interface CallerScopeInput {
23
29
  email: string;
@@ -93,6 +99,7 @@ export async function resolveCallerScope(
93
99
  kind: "scoped",
94
100
  accountId,
95
101
  agentIds: [...new Set([...accountAgentIds, ...memberAgentIds])],
102
+ ...(role ? { role } : {}),
96
103
  };
97
104
  }
98
105
 
@@ -60,6 +60,7 @@ describe("resolveCallerScope", () => {
60
60
  kind: "scoped",
61
61
  accountId: "acct-a",
62
62
  agentIds: ["ag-1", "ag-2"],
63
+ role: "owner",
63
64
  });
64
65
  });
65
66
 
@@ -68,11 +69,13 @@ describe("resolveCallerScope", () => {
68
69
  kind: "scoped",
69
70
  accountId: "acct-a",
70
71
  agentIds: [],
72
+ role: "member",
71
73
  });
72
74
  expect(await run("memboth@x.com")).toEqual({
73
75
  kind: "scoped",
74
76
  accountId: "acct-a",
75
77
  agentIds: ["ag-9"],
78
+ role: "member",
76
79
  });
77
80
  });
78
81
 
@@ -212,7 +215,7 @@ describe("resolveCallerScope matrix: role x flag", () => {
212
215
  ];
213
216
  for (const [email, flag, agentIds, accountId] of cases) {
214
217
  it(`${email} flag=${flag}`, async () => {
215
- expect(await run(email, false, flag)).toEqual({
218
+ expect(await run(email, false, flag)).toMatchObject({
216
219
  kind: "scoped",
217
220
  accountId,
218
221
  agentIds,