@app-vitals/agent-admin 1.73.0 → 1.75.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/openapi.platform.json +199 -0
  2. package/package.json +2 -2
  3. package/prisma/client/internal/class.ts +4 -4
  4. package/prisma/client/internal/prismaNamespace.ts +4 -0
  5. package/prisma/client/internal/prismaNamespaceBrowser.ts +4 -0
  6. package/prisma/client/models/AgentMember.ts +36 -1
  7. package/prisma/client/models/ChatThreadWatch.ts +29 -1
  8. package/prisma/client/models/PushSubscription.ts +29 -1
  9. package/prisma/client/models/UserNotificationPrefs.ts +29 -1
  10. package/prisma/migrations/20261118000000_add_member_id_columns/migration.sql +14 -0
  11. package/prisma/schema/schema.prisma +5 -0
  12. package/scripts/backfill-member-id.ts +41 -0
  13. package/src/admin-boot.ts +13 -0
  14. package/src/admin-dev-login.smoke.test.ts +1 -0
  15. package/src/admin-local-agent.smoke.test.ts +9 -1
  16. package/src/admin-spec.ts +17 -0
  17. package/src/admin-ui.fixtures.ts +1 -0
  18. package/src/admin-ui.smoke.test.ts +57 -8
  19. package/src/agent-cron-run-stats.smoke.test.ts +1 -0
  20. package/src/agent-members.unit.test.ts +6 -1
  21. package/src/agents-api.smoke.test.ts +5 -0
  22. package/src/api.smoke.test.ts +1 -0
  23. package/src/chat.smoke.test.ts +2 -0
  24. package/src/member-id-backfill.integration.test.ts +167 -0
  25. package/src/member-id-backfill.ts +180 -0
  26. package/src/member-id-backfill.unit.test.ts +12 -0
  27. package/src/openapi-schemas.ts +31 -0
  28. package/src/principal-lookup.ts +67 -0
  29. package/src/principal-lookup.unit.test.ts +104 -0
  30. package/src/principals-api.integration.test.ts +115 -0
  31. package/src/principals-api.ts +142 -0
  32. package/src/principals-api.unit.test.ts +83 -0
  33. package/src/slack-provisioning.integration.test.ts +1 -0
@@ -0,0 +1,67 @@
1
+ /**
2
+ * admin/src/principal-lookup.ts
3
+ * PrincipalLookupService (ACM-1.1): a principal is an AccountMember.id (type
4
+ * "user") or an Agent.id (type "agent"). Resolves principal ids to
5
+ * {type,email} in batch and a (case-insensitive) email to its principal.
6
+ *
7
+ * Agents have no email of their own, so they resolve with email: null, and an
8
+ * email only ever resolves to a user principal.
9
+ */
10
+
11
+ import type { PrismaClient } from "../prisma/client/client.ts";
12
+ import { normalizeEmail } from "./account-email.ts";
13
+
14
+ export interface Principal {
15
+ id: string;
16
+ type: "user" | "agent";
17
+ email: string | null;
18
+ }
19
+
20
+ export interface PrincipalLookupResult {
21
+ principals: Principal[];
22
+ notFound: string[];
23
+ }
24
+
25
+ export class PrincipalLookupService {
26
+ constructor(private prisma: PrismaClient) {}
27
+
28
+ /** Unknown ids land in `notFound`; results follow first-seen request order. */
29
+ async resolveMany(ids: string[]): Promise<PrincipalLookupResult> {
30
+ const unique = [...new Set(ids)];
31
+ if (unique.length === 0) return { principals: [], notFound: [] };
32
+
33
+ const [members, agents] = await Promise.all([
34
+ this.prisma.accountMember.findMany({
35
+ where: { id: { in: unique } },
36
+ select: { id: true, email: true },
37
+ }),
38
+ this.prisma.agent.findMany({
39
+ where: { id: { in: unique } },
40
+ select: { id: true },
41
+ }),
42
+ ]);
43
+ const byId = new Map<string, Principal>();
44
+ for (const a of agents)
45
+ byId.set(a.id, { id: a.id, type: "agent", email: null });
46
+ // Ids are cuids so collisions are not expected; a member wins if one occurs.
47
+ for (const m of members)
48
+ byId.set(m.id, { id: m.id, type: "user", email: m.email });
49
+
50
+ const principals: Principal[] = [];
51
+ const notFound: string[] = [];
52
+ for (const id of unique) {
53
+ const p = byId.get(id);
54
+ if (p) principals.push(p);
55
+ else notFound.push(id);
56
+ }
57
+ return { principals, notFound };
58
+ }
59
+
60
+ async findIdByEmail(email: string): Promise<Principal | null> {
61
+ const member = await this.prisma.accountMember.findUnique({
62
+ where: { email: normalizeEmail(email) },
63
+ select: { id: true, email: true },
64
+ });
65
+ return member ? { id: member.id, type: "user", email: member.email } : null;
66
+ }
67
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * admin/src/principal-lookup.unit.test.ts
3
+ * PrincipalLookupService (ACM-1.1): id -> {type,email} (batch) and email -> id.
4
+ */
5
+
6
+ import { describe, expect, it } from "bun:test";
7
+ import { PrincipalLookupService } from "./principal-lookup.ts";
8
+
9
+ function fakePrisma(
10
+ members: { id: string; email: string }[],
11
+ agents: { id: string }[],
12
+ ) {
13
+ const calls = { member: 0, agent: 0 };
14
+ const prisma = {
15
+ accountMember: {
16
+ findMany: async ({ where }: { where: { id: { in: string[] } } }) => {
17
+ calls.member++;
18
+ return members.filter((m) => where.id.in.includes(m.id));
19
+ },
20
+ findUnique: async ({ where }: { where: { email: string } }) =>
21
+ members.find((m) => m.email === where.email) ?? null,
22
+ },
23
+ agent: {
24
+ findMany: async ({ where }: { where: { id: { in: string[] } } }) => {
25
+ calls.agent++;
26
+ return agents.filter((a) => where.id.in.includes(a.id));
27
+ },
28
+ },
29
+ };
30
+ return { prisma: prisma as never, calls };
31
+ }
32
+
33
+ describe("PrincipalLookupService.resolveMany", () => {
34
+ it("resolves a mixed list of member and agent ids", async () => {
35
+ const { prisma } = fakePrisma(
36
+ [{ id: "m1", email: "a@x.com" }],
37
+ [{ id: "a1" }],
38
+ );
39
+ const res = await new PrincipalLookupService(prisma).resolveMany([
40
+ "m1",
41
+ "a1",
42
+ ]);
43
+ expect(res.principals).toEqual([
44
+ { id: "m1", type: "user", email: "a@x.com" },
45
+ { id: "a1", type: "agent", email: null },
46
+ ]);
47
+ expect(res.notFound).toEqual([]);
48
+ });
49
+
50
+ it("returns unknown ids as notFound, not an error", async () => {
51
+ const { prisma } = fakePrisma([{ id: "m1", email: "a@x.com" }], []);
52
+ const res = await new PrincipalLookupService(prisma).resolveMany([
53
+ "m1",
54
+ "nope",
55
+ ]);
56
+ expect(res.principals.map((p) => p.id)).toEqual(["m1"]);
57
+ expect(res.notFound).toEqual(["nope"]);
58
+ });
59
+
60
+ it("dedupes ids and preserves request order", async () => {
61
+ const { prisma } = fakePrisma(
62
+ [
63
+ { id: "m1", email: "a@x.com" },
64
+ { id: "m2", email: "b@x.com" },
65
+ ],
66
+ [],
67
+ );
68
+ const res = await new PrincipalLookupService(prisma).resolveMany([
69
+ "m2",
70
+ "m1",
71
+ "m2",
72
+ "z",
73
+ "z",
74
+ ]);
75
+ expect(res.principals.map((p) => p.id)).toEqual(["m2", "m1"]);
76
+ expect(res.notFound).toEqual(["z"]);
77
+ });
78
+
79
+ it("makes no queries for an empty list", async () => {
80
+ const { prisma, calls } = fakePrisma([], []);
81
+ const res = await new PrincipalLookupService(prisma).resolveMany([]);
82
+ expect(res).toEqual({ principals: [], notFound: [] });
83
+ expect(calls).toEqual({ member: 0, agent: 0 });
84
+ });
85
+ });
86
+
87
+ describe("PrincipalLookupService.findIdByEmail", () => {
88
+ it("normalizes case and whitespace before matching", async () => {
89
+ const { prisma } = fakePrisma([{ id: "m1", email: "a@x.com" }], []);
90
+ const svc = new PrincipalLookupService(prisma);
91
+ expect(await svc.findIdByEmail(" A@X.com ")).toEqual({
92
+ id: "m1",
93
+ type: "user",
94
+ email: "a@x.com",
95
+ });
96
+ });
97
+
98
+ it("returns null for an unknown email", async () => {
99
+ const { prisma } = fakePrisma([], []);
100
+ expect(
101
+ await new PrincipalLookupService(prisma).findIdByEmail("q@x.com"),
102
+ ).toBeNull();
103
+ });
104
+ });
@@ -0,0 +1,115 @@
1
+ /**
2
+ * admin/src/principals-api.integration.test.ts
3
+ * /principals lookups against real Postgres (ACM-1.1), plus the additive
4
+ * nullable memberId columns from 20261118000000_add_member_id_columns.
5
+ *
6
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
7
+ */
8
+
9
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
10
+ import type { PrismaClient } from "../prisma/client/client.ts";
11
+ import { PrincipalLookupService } from "./principal-lookup.ts";
12
+ import { createPrincipalsApp } from "./principals-api.ts";
13
+ import { createAdminPrismaClient } from "./prisma-client.ts";
14
+
15
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
16
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
17
+
18
+ describeOrSkip("/principals API (integration)", () => {
19
+ let prisma: PrismaClient;
20
+ let app: ReturnType<typeof createPrincipalsApp>;
21
+ const headers = {
22
+ Authorization: "Bearer k",
23
+ "Content-Type": "application/json",
24
+ };
25
+
26
+ beforeEach(async () => {
27
+ prisma = createAdminPrismaClient(TEST_DB as string);
28
+ await prisma.agentMember.deleteMany();
29
+ await prisma.accountMember.deleteMany();
30
+ await prisma.agent.deleteMany();
31
+ await prisma.account.deleteMany();
32
+ app = createPrincipalsApp({
33
+ lookup: new PrincipalLookupService(prisma),
34
+ sessionSecret: "s".repeat(32),
35
+ adminApiKeys: new Map([["k", { name: "t", scope: "*" }]]),
36
+ agentTokenService: { validate: async () => null } as never,
37
+ });
38
+ });
39
+
40
+ afterEach(async () => {
41
+ await prisma.$disconnect();
42
+ });
43
+
44
+ it("batch resolves mixed member/agent ids and reports unknown ids as notFound", async () => {
45
+ const account = await prisma.account.create({ data: { name: "Acme" } });
46
+ const member = await prisma.accountMember.create({
47
+ data: { accountId: account.id, email: "owner@acme.com", role: "owner" },
48
+ });
49
+ const agent = await prisma.agent.create({ data: { name: "bot" } });
50
+
51
+ const res = await app.request("/principals/lookup", {
52
+ method: "POST",
53
+ headers,
54
+ body: JSON.stringify({ ids: [member.id, agent.id, "missing"] }),
55
+ });
56
+ expect(res.status).toBe(200);
57
+ expect(await res.json()).toEqual({
58
+ principals: [
59
+ { id: member.id, type: "user", email: "owner@acme.com" },
60
+ { id: agent.id, type: "agent", email: null },
61
+ ],
62
+ notFound: ["missing"],
63
+ });
64
+ });
65
+
66
+ it("email -> id is case-insensitive", async () => {
67
+ const account = await prisma.account.create({ data: { name: "Acme" } });
68
+ const member = await prisma.accountMember.create({
69
+ data: { accountId: account.id, email: "owner@acme.com", role: "owner" },
70
+ });
71
+ const res = await app.request("/principals/by-email?email=Owner@ACME.com", {
72
+ headers,
73
+ });
74
+ expect(res.status).toBe(200);
75
+ expect(await res.json()).toEqual({
76
+ id: member.id,
77
+ type: "user",
78
+ email: "owner@acme.com",
79
+ });
80
+ const miss = await app.request(
81
+ "/principals/by-email?email=nobody@acme.com",
82
+ { headers },
83
+ );
84
+ expect(miss.status).toBe(404);
85
+ });
86
+
87
+ it("memberId columns exist, are nullable and default to NULL", async () => {
88
+ const cols = await prisma.$queryRaw<
89
+ {
90
+ table_name: string;
91
+ is_nullable: string;
92
+ column_default: string | null;
93
+ }[]
94
+ >`SELECT table_name, is_nullable, column_default FROM information_schema.columns
95
+ WHERE column_name = 'memberId'
96
+ AND table_name IN ('UserNotificationPrefs','ChatThreadWatch','PushSubscription','AgentMember')
97
+ ORDER BY table_name`;
98
+ expect(cols.map((c) => c.table_name)).toEqual([
99
+ "AgentMember",
100
+ "ChatThreadWatch",
101
+ "PushSubscription",
102
+ "UserNotificationPrefs",
103
+ ]);
104
+ for (const c of cols) {
105
+ expect(c.is_nullable).toBe("YES");
106
+ expect(c.column_default).toBeNull();
107
+ }
108
+ const fks = await prisma.$queryRaw<{ n: bigint }[]>`SELECT count(*) AS n
109
+ FROM information_schema.table_constraints tc
110
+ JOIN information_schema.constraint_column_usage ccu USING (constraint_name)
111
+ WHERE ccu.column_name = 'memberId'
112
+ AND tc.table_name IN ('UserNotificationPrefs','ChatThreadWatch','PushSubscription','AgentMember')`;
113
+ expect(Number(fks[0]?.n)).toBe(0);
114
+ });
115
+ });
@@ -0,0 +1,142 @@
1
+ /**
2
+ * admin/src/principals-api.ts
3
+ * Admin-only /principals lookup API (ACM-1.1):
4
+ * POST /principals/lookup {ids} -> {principals:[{id,type,email}], notFound:[id]}
5
+ * GET /principals/by-email ?email= -> {id,type,email} (404 when unknown)
6
+ * Auth: admin cookie or scope "*" key; every other caller class gets 403.
7
+ */
8
+
9
+ import { createRoute, OpenAPIHono } from "@hono/zod-openapi";
10
+ import { HTTPException } from "hono/http-exception";
11
+ import type { AgentTokenService } from "./agent-tokens.ts";
12
+ import {
13
+ type AdminApiKey,
14
+ type AdminAuthEnv,
15
+ createAdminAuthMiddleware,
16
+ } from "./api-auth.ts";
17
+ import { ApiError, ForbiddenError, NotFoundError } from "./errors.ts";
18
+ import {
19
+ ErrorSchema,
20
+ PrincipalByEmailQuerySchema,
21
+ PrincipalLookupBodySchema,
22
+ PrincipalLookupResponseSchema,
23
+ PrincipalSchema,
24
+ } from "./openapi-schemas.ts";
25
+ import type { PrincipalLookupService } from "./principal-lookup.ts";
26
+
27
+ interface PrincipalsApiDeps {
28
+ lookup: Pick<PrincipalLookupService, "resolveMany" | "findIdByEmail">;
29
+ sessionSecret: string;
30
+ adminApiKeys?: Map<string, AdminApiKey>;
31
+ agentTokenService: Pick<AgentTokenService, "validate">;
32
+ }
33
+
34
+ const jsonError = { content: { "application/json": { schema: ErrorSchema } } };
35
+
36
+ const errorResponses = {
37
+ 401: { description: "Unauthorized", ...jsonError },
38
+ 403: { description: "Forbidden (non-admin caller)", ...jsonError },
39
+ };
40
+
41
+ const lookupRoute = createRoute({
42
+ method: "post",
43
+ path: "/principals/lookup",
44
+ tags: ["principals"],
45
+ summary: "Batch-resolve principal ids",
46
+ description:
47
+ "Admin-only. Resolves AccountMember ids (type user) and Agent ids (type agent) to type and email. Agents have no email (null). Unknown ids are listed in notFound; they are not an error.",
48
+ request: {
49
+ body: {
50
+ content: { "application/json": { schema: PrincipalLookupBodySchema } },
51
+ },
52
+ },
53
+ responses: {
54
+ 200: {
55
+ description: "Resolved principals and unknown ids",
56
+ content: {
57
+ "application/json": { schema: PrincipalLookupResponseSchema },
58
+ },
59
+ },
60
+ 400: { description: "Bad request", ...jsonError },
61
+ ...errorResponses,
62
+ },
63
+ });
64
+
65
+ const byEmailRoute = createRoute({
66
+ method: "get",
67
+ path: "/principals/by-email",
68
+ tags: ["principals"],
69
+ summary: "Resolve an email to its principal id",
70
+ description:
71
+ "Admin-only. Case-insensitive (emails are stored lowercased). 404 when no member has the email.",
72
+ request: { query: PrincipalByEmailQuerySchema },
73
+ responses: {
74
+ 200: {
75
+ description: "Principal",
76
+ content: { "application/json": { schema: PrincipalSchema } },
77
+ },
78
+ 400: { description: "Bad request", ...jsonError },
79
+ 404: { description: "No principal with that email", ...jsonError },
80
+ ...errorResponses,
81
+ },
82
+ });
83
+
84
+ export function createPrincipalsApp(
85
+ deps: PrincipalsApiDeps,
86
+ ): OpenAPIHono<AdminAuthEnv> {
87
+ const app = new OpenAPIHono<AdminAuthEnv>({
88
+ defaultHook: (result, c) => {
89
+ if (!result.success) {
90
+ const message = result.error.issues
91
+ .map((i) => `${i.path.join(".")}: ${i.message}`)
92
+ .join(", ");
93
+ return c.json({ error: message }, 400);
94
+ }
95
+ },
96
+ });
97
+
98
+ app.onError((err, c) => {
99
+ if (err instanceof ApiError && err.statusCode < 500) {
100
+ return c.json(
101
+ { error: err.message },
102
+ err.statusCode as 400 | 401 | 403 | 404 | 409 | 422,
103
+ );
104
+ }
105
+ if (err instanceof HTTPException && err.status < 500) {
106
+ return c.json({ error: err.message }, err.status as 400 | 415);
107
+ }
108
+ console.error("[principals-api] unhandled error:", err);
109
+ return c.json({ error: "Internal server error" }, 500);
110
+ });
111
+
112
+ app.use(
113
+ "/principals/*",
114
+ createAdminAuthMiddleware({
115
+ sessionSecret: deps.sessionSecret,
116
+ agentTokenService: deps.agentTokenService,
117
+ adminApiKeys: deps.adminApiKeys,
118
+ }),
119
+ );
120
+
121
+ const requireAdmin = (c: { get: (k: "isAdmin") => unknown }) => {
122
+ if (c.get("isAdmin") !== true) {
123
+ throw new ForbiddenError("Admin access required");
124
+ }
125
+ };
126
+
127
+ app.openapi(lookupRoute, async (c) => {
128
+ requireAdmin(c);
129
+ const { ids } = c.req.valid("json");
130
+ return c.json(await deps.lookup.resolveMany(ids), 200);
131
+ });
132
+
133
+ app.openapi(byEmailRoute, async (c) => {
134
+ requireAdmin(c);
135
+ const { email } = c.req.valid("query");
136
+ const principal = await deps.lookup.findIdByEmail(email);
137
+ if (!principal) throw new NotFoundError("no principal with that email");
138
+ return c.json(principal, 200);
139
+ });
140
+
141
+ return app;
142
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * admin/src/principals-api.unit.test.ts
3
+ * /principals lookup routes (ACM-1.1): auth, validation, shapes.
4
+ */
5
+
6
+ import { describe, expect, it } from "bun:test";
7
+ import { createPrincipalsApp } from "./principals-api.ts";
8
+
9
+ function build() {
10
+ return createPrincipalsApp({
11
+ lookup: {
12
+ resolveMany: async (ids: string[]) => ({
13
+ principals: ids.includes("m1")
14
+ ? [{ id: "m1", type: "user" as const, email: "a@x.com" }]
15
+ : [],
16
+ notFound: ids.filter((i) => i !== "m1"),
17
+ }),
18
+ findIdByEmail: async (email: string) =>
19
+ email.toLowerCase() === "a@x.com"
20
+ ? { id: "m1", type: "user" as const, email: "a@x.com" }
21
+ : null,
22
+ },
23
+ sessionSecret: "s".repeat(32),
24
+ adminApiKeys: new Map([["k", { name: "t", scope: "*" }]]),
25
+ agentTokenService: { validate: async () => null } as never,
26
+ });
27
+ }
28
+ const headers = {
29
+ Authorization: "Bearer k",
30
+ "Content-Type": "application/json",
31
+ };
32
+
33
+ describe("principals API", () => {
34
+ it("401s without credentials", async () => {
35
+ const res = await build().request("/principals/lookup", {
36
+ method: "POST",
37
+ headers: { "Content-Type": "application/json" },
38
+ body: JSON.stringify({ ids: ["m1"] }),
39
+ });
40
+ expect(res.status).toBe(401);
41
+ });
42
+
43
+ it("POST /principals/lookup returns principals and notFound with 200", async () => {
44
+ const res = await build().request("/principals/lookup", {
45
+ method: "POST",
46
+ headers,
47
+ body: JSON.stringify({ ids: ["m1", "x"] }),
48
+ });
49
+ expect(res.status).toBe(200);
50
+ expect(await res.json()).toEqual({
51
+ principals: [{ id: "m1", type: "user", email: "a@x.com" }],
52
+ notFound: ["x"],
53
+ });
54
+ });
55
+
56
+ it("POST /principals/lookup 400s on a non-array body", async () => {
57
+ const res = await build().request("/principals/lookup", {
58
+ method: "POST",
59
+ headers,
60
+ body: JSON.stringify({ ids: "m1" }),
61
+ });
62
+ expect(res.status).toBe(400);
63
+ });
64
+
65
+ it("GET /principals/by-email resolves case-insensitively", async () => {
66
+ const res = await build().request("/principals/by-email?email=A@X.com", {
67
+ headers,
68
+ });
69
+ expect(res.status).toBe(200);
70
+ expect(await res.json()).toEqual({
71
+ id: "m1",
72
+ type: "user",
73
+ email: "a@x.com",
74
+ });
75
+ });
76
+
77
+ it("GET /principals/by-email 404s for an unknown email", async () => {
78
+ const res = await build().request("/principals/by-email?email=q@x.com", {
79
+ headers,
80
+ });
81
+ expect(res.status).toBe(404);
82
+ });
83
+ });
@@ -220,6 +220,7 @@ function makeMockDeps(
220
220
  id: "m1",
221
221
  agentId,
222
222
  email,
223
+ memberId: null,
223
224
  createdAt: new Date(),
224
225
  }),
225
226
  remove: async () => {},