@app-vitals/agent-admin 1.72.0 → 1.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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 () => {},