@terreno/admin-backend 57.20.0 → 57.22.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
@@ -5,8 +5,8 @@
5
5
  },
6
6
  "dependencies": {
7
7
  "@google-cloud/storage": "^7.15.0",
8
- "@terreno/api": "57.20.0",
9
- "@terreno/jobs": "57.20.0",
8
+ "@terreno/api": "57.22.0",
9
+ "@terreno/jobs": "57.22.0",
10
10
  "express": "^5.2.1",
11
11
  "luxon": "^3.7.2",
12
12
  "multer": "2.2.0"
@@ -14,12 +14,13 @@
14
14
  "description": "Admin panel backend plugin for @terreno/api — part of Terreno, the batteries-included TypeScript framework for universal apps.",
15
15
  "devDependencies": {
16
16
  "@biomejs/biome": "^2.3.6",
17
- "@terreno/test": "57.20.0",
17
+ "@terreno/test": "57.22.0",
18
18
  "@types/bun": "^1.4.0",
19
19
  "@types/express": "^5.0.6",
20
20
  "@types/luxon": "^3.7.1",
21
21
  "@types/multer": "^1.4.12",
22
22
  "@types/supertest": "^7.2.0",
23
+ "passport-local-mongoose": "^9.0.1",
23
24
  "supertest": "^7.2.2",
24
25
  "typescript": "~6.0.3"
25
26
  },
@@ -47,13 +48,15 @@
47
48
  "compile": "node ../.github/scripts/compile-workspace-deps.js && bun tsc",
48
49
  "compile:watch": "bun tsc -w",
49
50
  "dev": "bun tsc -w",
50
- "lint": "biome check ./src",
51
- "lint:fix": "biome check --write ./src",
51
+ "lint": "biome check ./src ./e2e",
52
+ "lint:fix": "biome check --write ./src ./e2e",
53
+ "smoke": "bun e2e/smoke.ts",
52
54
  "test": "bun test --timeout=120000",
53
55
  "test:agent": "AGENT=1 bun test --only-failures --timeout=120000",
54
56
  "test:ci": "bun test --timeout=120000",
55
- "test:coverage": "bun run ../scripts/check-coverage.ts"
57
+ "test:coverage": "bun run ../scripts/check-coverage.ts",
58
+ "typecheck": "tsc -p tsconfig.typecheck.json"
56
59
  },
57
60
  "types": "dist/index.d.ts",
58
- "version": "57.20.0"
61
+ "version": "57.22.0"
59
62
  }
@@ -11,6 +11,7 @@ import {
11
11
  createAccess,
12
12
  MIGRATION_LOCK_ID,
13
13
  MIGRATIONS_COLLECTION,
14
+ type MigrationStoreDoc,
14
15
  setupAuth,
15
16
  terrenoStatements,
16
17
  type UserModel as UserModelType,
@@ -22,7 +23,7 @@ import type TestAgent from "supertest/lib/agent";
22
23
 
23
24
  import {AdminApp} from "./adminApp";
24
25
 
25
- const fixturesDir = join(import.meta.dir, "../../api/src/migrations/fixtures/valid");
26
+ const fixturesDir = join(__dirname, "../../api/src/migrations/fixtures/valid");
26
27
 
27
28
  const buildApp = ({
28
29
  accessControl,
@@ -52,7 +53,7 @@ const waitForTask = (): Promise<void> => {
52
53
 
53
54
  const appliedIds = async (): Promise<string[]> => {
54
55
  const docs = await mongoose.connection
55
- .collection(MIGRATIONS_COLLECTION)
56
+ .collection<MigrationStoreDoc>(MIGRATIONS_COLLECTION)
56
57
  .find({_id: {$ne: MIGRATION_LOCK_ID}})
57
58
  .project({id: 1})
58
59
  .toArray();
@@ -34,13 +34,16 @@ import {
34
34
  } from "@terreno/api/testing";
35
35
  import {assert} from "chai";
36
36
  import type express from "express";
37
- import mongoose from "mongoose";
37
+ import mongoose, {type Model} from "mongoose";
38
38
  import supertest from "supertest";
39
39
  import type TestAgent from "supertest/lib/agent";
40
40
 
41
41
  import type {AdminAuditEvent, AdminModelConfig, AdminOptions} from "./adminApp";
42
42
  import {AdminApp, getArrayEmbeddedSchemaType} from "./adminApp";
43
43
 
44
+ /** Plugin contributions take `Model<unknown>`; the shared Food fixture keys `_id` as a string. */
45
+ const contributedFoodModel = FoodModel as unknown as Model<unknown>;
46
+
44
47
  const buildApp = (
45
48
  models: AdminModelConfig[] = [],
46
49
  adminOverrides?: Partial<AdminOptions>
@@ -175,7 +178,7 @@ describe("AdminApp /admin/config", () => {
175
178
  models: [
176
179
  {
177
180
  admin: {displayName: "Flags", listFields: ["key"]},
178
- model: FoodModel,
181
+ model: contributedFoodModel,
179
182
  routePath: "/feature-flags",
180
183
  },
181
184
  ],
@@ -2219,7 +2222,7 @@ describe("AdminApp adminPermissions methods", () => {
2219
2222
  listFields: ["name", "calories"],
2220
2223
  searchFields: ["name"],
2221
2224
  },
2222
- model: FoodModel,
2225
+ model: contributedFoodModel,
2223
2226
  routePath: "/locked-foods",
2224
2227
  },
2225
2228
  ],
@@ -18,7 +18,7 @@ import mongoose from "mongoose";
18
18
  import supertest from "supertest";
19
19
  import type TestAgent from "supertest/lib/agent";
20
20
 
21
- import {AdminApp} from "./adminApp";
21
+ import {AdminApp, type AdminScriptConfig} from "./adminApp";
22
22
 
23
23
  const createTestScript = (overrides?: {
24
24
  runner?: ScriptRunner;
@@ -53,7 +53,7 @@ const createFailingScript = () => ({
53
53
  });
54
54
 
55
55
  const buildApp = (
56
- scripts = [createTestScript()],
56
+ scripts: AdminScriptConfig[] = [createTestScript()],
57
57
  accessControl?: AnyTerrenoAccess
58
58
  ): express.Application => {
59
59
  const app = getBaseServer();
package/src/adminApp.ts CHANGED
@@ -123,6 +123,8 @@ export interface AdminModelConfig {
123
123
  fieldOrder?: string[];
124
124
  /** Fields to hide from admin forms/responses (e.g., password hash fields). */
125
125
  hiddenFields?: string[];
126
+ /** Fields stripped from admin create and update bodies. */
127
+ excludeFields?: string[];
126
128
  /** Optional sidebar / nav grouping label for schema v2 shells */
127
129
  group?: string;
128
130
  /** Changelist columns (defaults to listFields) */
@@ -4,12 +4,19 @@ import {
4
4
  apiErrorMiddleware,
5
5
  apiUnauthorizedMiddleware,
6
6
  BackgroundTask,
7
+ createScopedLogger,
7
8
  createScriptArgs,
8
9
  setupAuth,
9
10
  type UserModel as UserModelType,
10
11
  } from "@terreno/api";
11
12
  import {getBaseServer, setupDb, UserModel} from "@terreno/api/testing";
12
- import {Job, type JobDefinition, JobsApp, unregisterJobsService} from "@terreno/jobs";
13
+ import {
14
+ Job,
15
+ type JobDefinition,
16
+ type JobHandlerContext,
17
+ JobsApp,
18
+ unregisterJobsService,
19
+ } from "@terreno/jobs";
13
20
 
14
21
  import {
15
22
  ADMIN_SCRIPT_JOB_NAME,
@@ -38,9 +45,9 @@ const getAdminScriptHandler = (
38
45
  return handler;
39
46
  };
40
47
 
41
- const mockJobContext = {
42
- attempt: 1,
48
+ const mockJobContext: JobHandlerContext = {
43
49
  jobId: "job-test",
50
+ log: createScopedLogger({prefix: "job-test"}),
44
51
  signal: new AbortController().signal,
45
52
  };
46
53
 
@@ -16,6 +16,7 @@ import {
16
16
  Membership,
17
17
  Organization,
18
18
  orgScopedPlugin,
19
+ type PermissionSet,
19
20
  Permissions,
20
21
  registerSync,
21
22
  SyncApp,
@@ -116,7 +117,7 @@ const buildHarness = ({
116
117
  if (productHookTracker) {
117
118
  productHookTracker.preCreateCalls++;
118
119
  }
119
- return productSyncOptions.preCreate(body, req);
120
+ return productSyncOptions.preCreate(body as Record<string, unknown>, req);
120
121
  },
121
122
  preUpdate: (body, _req) => {
122
123
  if (productHookTracker) {
@@ -522,7 +523,7 @@ const buildOrgWindowHarness = (): express.Application => {
522
523
  const accessControl = createAccess({
523
524
  connection: mongoose.connection,
524
525
  organizations: true,
525
- resolvePermissions: async ({user}) => {
526
+ resolvePermissions: async ({user}): Promise<PermissionSet> => {
526
527
  if (user?.admin) {
527
528
  return {admin: ["access"], adminWindowOrgTodo: ["read", "write"]};
528
529
  }
@@ -1,8 +1,9 @@
1
1
  import {describe, expect, it} from "bun:test";
2
- import type {AdminConfig, AdminContribution, TerrenoPlugin} from "@terreno/api";
2
+ import type {AdminConfig, AdminContribution, ScriptResult, TerrenoPlugin} from "@terreno/api";
3
3
  import {modelRouter, Permissions} from "@terreno/api";
4
4
  import {FoodModel} from "@terreno/api/testing";
5
5
  import {assert} from "chai";
6
+ import type {Model} from "mongoose";
6
7
 
7
8
  import type {AdminModelConfig} from "./adminApp";
8
9
  import {
@@ -14,6 +15,9 @@ import {
14
15
  import {resetLegacyDeprecationWarningsForTests} from "./legacy";
15
16
  import {normalizeAdminRoutePath} from "./routePath";
16
17
 
18
+ /** Plugin contributions take `Model<unknown>`; the shared Food fixture keys `_id` as a string. */
19
+ const contributedFoodModel = FoodModel as unknown as Model<unknown>;
20
+
17
21
  const foodAdmin: AdminConfig = {
18
22
  displayName: "Foods",
19
23
  listFields: ["name"],
@@ -42,7 +46,7 @@ describe("aggregateAdminContributions", () => {
42
46
  models: [
43
47
  {
44
48
  admin: {displayName: "Plugin Users", listFields: ["email"]},
45
- model: FoodModel,
49
+ model: contributedFoodModel,
46
50
  routePath: "/users",
47
51
  },
48
52
  ],
@@ -98,7 +102,7 @@ describe("aggregateAdminContributions", () => {
98
102
  });
99
103
 
100
104
  it("merges unique scripts, screens, and widget ids and skips duplicates", () => {
101
- const runner = async (): Promise<void> => {};
105
+ const runner = async (): Promise<ScriptResult> => ({results: [], success: true});
102
106
  const aggregated = aggregateAdminContributions({
103
107
  pluginContributions: [
104
108
  {
@@ -134,7 +138,7 @@ describe("aggregateAdminContributions", () => {
134
138
  models: [
135
139
  {
136
140
  admin: {displayName: "Foods", listFields: ["name"]},
137
- model: FoodModel,
141
+ model: contributedFoodModel,
138
142
  populatePaths: [{fields: ["email"], path: "ownerId"}],
139
143
  routePath: "/foods",
140
144
  },
@@ -239,7 +243,7 @@ describe("aggregateFromTerrenoApp", () => {
239
243
  models: [
240
244
  {
241
245
  admin: {displayName: "Flags", listFields: ["key"]},
242
- model: FoodModel,
246
+ model: contributedFoodModel,
243
247
  routePath: "/feature-flags",
244
248
  },
245
249
  ],
@@ -26,7 +26,7 @@ describe("enrichAdminListFilters", () => {
26
26
  },
27
27
  ];
28
28
  const enriched = enrichAdminListFilters(filters, PriorityModel);
29
- expect(enriched?.[0]).toEqual({...filters[0], allowEmpty: true});
29
+ expect<unknown>(enriched?.[0]).toEqual({...filters[0], allowEmpty: true});
30
30
  expect(enriched?.[1]).toEqual(filters[1]);
31
31
  });
32
32
 
package/src/index.ts CHANGED
@@ -48,6 +48,14 @@ export {DocumentStorageApp} from "./documentStorageApp";
48
48
  export type {ParseAdminListFiltersResult} from "./filterParser";
49
49
  export {parseAdminListFilters} from "./filterParser";
50
50
  export {convertLegacyModelConfig, resetLegacyDeprecationWarningsForTests} from "./legacy";
51
+ export {
52
+ MCP_ADMIN_GROUP,
53
+ type McpAdminModelsOptions,
54
+ mcpAdminModels,
55
+ mcpAdminScripts,
56
+ mcpAdminStatements,
57
+ mcpSignOutEverywhere,
58
+ } from "./mcpAdmin";
51
59
  export type {AdminModelSource, ResolvedAdminModel} from "./resolvedAdminModel";
52
60
  export {resolvedModelFromAdminConfig} from "./resolvedAdminModel";
53
61
  export {normalizeAdminRoutePath} from "./routePath";
@@ -0,0 +1,176 @@
1
+ import {beforeEach, describe, expect, it} from "bun:test";
2
+ import {
3
+ addAuthRoutes,
4
+ apiErrorMiddleware,
5
+ apiUnauthorizedMiddleware,
6
+ createScriptArgs,
7
+ McpOAuthRevokedFamily,
8
+ McpOAuthToken,
9
+ McpServiceToken,
10
+ McpToolSetting,
11
+ type ScriptContext,
12
+ setupAuth,
13
+ type UserModel as UserModelType,
14
+ } from "@terreno/api";
15
+ import {authAsUser, getBaseServer, setupDb, UserModel} from "@terreno/api/testing";
16
+ import type express from "express";
17
+ import type mongoose from "mongoose";
18
+ import type TestAgent from "supertest/lib/agent";
19
+
20
+ import {AdminApp} from "./adminApp";
21
+ import {mcpAdminModels, mcpAdminScripts, mcpSignOutEverywhere} from "./mcpAdmin";
22
+
23
+ const buildApp = (): express.Application => {
24
+ const app = getBaseServer();
25
+ setupAuth(app, UserModel as unknown as UserModelType);
26
+ addAuthRoutes(app, UserModel as unknown as UserModelType);
27
+ new AdminApp({
28
+ basePath: "/admin",
29
+ models: mcpAdminModels({requestLog: true, toolSettings: true}),
30
+ scripts: mcpAdminScripts(),
31
+ }).register(app);
32
+ app.use(apiUnauthorizedMiddleware);
33
+ app.use(apiErrorMiddleware);
34
+ return app;
35
+ };
36
+
37
+ const scriptContext = (user: string): ScriptContext => ({
38
+ addLog: async (): Promise<void> => {},
39
+ args: createScriptArgs({values: {user}}).args,
40
+ checkCancellation: async (): Promise<void> => {},
41
+ updateProgress: async (): Promise<void> => {},
42
+ });
43
+
44
+ const issueOAuth = (userId: mongoose.Types.ObjectId) =>
45
+ McpOAuthToken.issue({
46
+ accessTokenTtlSeconds: 60,
47
+ clientId: "claude",
48
+ refreshTokenTtlSeconds: 3600,
49
+ userId,
50
+ });
51
+
52
+ describe("mcpAdminModels", () => {
53
+ it("returns every MCP screen in one group, without hash fields in any list", () => {
54
+ const models = mcpAdminModels({requestLog: true, toolSettings: true});
55
+
56
+ expect(models.map((model) => model.routePath)).toEqual([
57
+ "/mcp-service-tokens",
58
+ "/mcp-oauth-clients",
59
+ "/mcp-oauth-connections",
60
+ "/mcp-request-log",
61
+ "/mcp-tools",
62
+ ]);
63
+ for (const model of models) {
64
+ expect(model.group).toBe("MCP");
65
+ expect(model.listFields.some((field) => field.toLowerCase().includes("hash"))).toBe(false);
66
+ expect(model.permissions?.create).toBe(false);
67
+ }
68
+ });
69
+
70
+ it("leaves out the request log and tool screens unless their server options are on", () => {
71
+ expect(mcpAdminModels()).toHaveLength(3);
72
+ const models = mcpAdminModels({group: "Platform", requestLog: false, toolSettings: false});
73
+
74
+ expect(models).toHaveLength(3);
75
+ expect(models.every((model) => model.group === "Platform")).toBe(true);
76
+ });
77
+ });
78
+
79
+ describe("MCP admin routes", () => {
80
+ let adminAgent: TestAgent;
81
+ let notAdminAgent: TestAgent;
82
+ let notAdminId: mongoose.Types.ObjectId;
83
+
84
+ beforeEach(async () => {
85
+ const users = await setupDb();
86
+ notAdminId = users[1]._id as mongoose.Types.ObjectId;
87
+ await McpOAuthToken.deleteMany({});
88
+ await McpOAuthRevokedFamily.deleteMany({});
89
+ await McpServiceToken.deleteMany({});
90
+ await McpToolSetting.deleteMany({});
91
+ const app = buildApp();
92
+ adminAgent = await authAsUser(app, "admin");
93
+ notAdminAgent = await authAsUser(app, "notAdmin");
94
+ });
95
+
96
+ it("lists OAuth connections without token hashes and refuses non-admins", async () => {
97
+ await issueOAuth(notAdminId);
98
+
99
+ const res = await adminAgent.get("/admin/mcp-oauth-connections");
100
+ const denied = await notAdminAgent.get("/admin/mcp-oauth-connections");
101
+
102
+ expect(res.status).toBe(200);
103
+ expect(res.body.data).toHaveLength(1);
104
+ expect(JSON.stringify(res.body)).not.toContain("TokenHash");
105
+ expect([401, 403, 405]).toContain(denied.status);
106
+ });
107
+
108
+ it("revokes the whole connection when an admin deletes a row", async () => {
109
+ const {mcpOAuthToken} = await issueOAuth(notAdminId);
110
+
111
+ const res = await adminAgent.delete(`/admin/mcp-oauth-connections/${mcpOAuthToken._id}`);
112
+
113
+ expect(res.status).toBeLessThan(300);
114
+ const stored = await McpOAuthToken.findExactlyOne({_id: mcpOAuthToken._id});
115
+ expect(stored.revokedAt).toBeDefined();
116
+ });
117
+
118
+ it("lets an admin switch a tool off but not rename it", async () => {
119
+ const setting = await McpToolSetting.create({name: "todos_list", source: "model"});
120
+
121
+ const res = await adminAgent
122
+ .patch(`/admin/mcp-tools/${setting._id}`)
123
+ .send({enabled: false, name: "renamed"});
124
+
125
+ expect(res.status).toBe(200);
126
+ const stored = await McpToolSetting.findExactlyOne({_id: setting._id});
127
+ expect(stored.enabled).toBe(false);
128
+ expect(stored.name).toBe("todos_list");
129
+ });
130
+ });
131
+
132
+ describe("mcpSignOutEverywhere", () => {
133
+ let notAdminId: mongoose.Types.ObjectId;
134
+
135
+ beforeEach(async () => {
136
+ const users = await setupDb();
137
+ notAdminId = users[1]._id as mongoose.Types.ObjectId;
138
+ await McpOAuthToken.deleteMany({});
139
+ await McpOAuthRevokedFamily.deleteMany({});
140
+ await McpServiceToken.deleteMany({});
141
+ });
142
+
143
+ it("counts on a dry run and revokes on a wet run, by email", async () => {
144
+ await issueOAuth(notAdminId);
145
+ await McpServiceToken.issueFor({_id: notAdminId}, {name: "Laptop"});
146
+ const user = await UserModel.findById(notAdminId);
147
+ const email = String((user as unknown as {email: string}).email);
148
+
149
+ const dry = await mcpSignOutEverywhere(false, scriptContext(email));
150
+ expect(dry.success).toBe(true);
151
+ expect(dry.results[0]).toContain("Would revoke 1 OAuth connection(s) and 1 service token(s)");
152
+ expect(await McpServiceToken.countDocuments({revokedAt: {$exists: false}})).toBe(1);
153
+
154
+ const wet = await mcpSignOutEverywhere(true, scriptContext(String(notAdminId)));
155
+ expect(wet.success).toBe(true);
156
+ expect(await McpServiceToken.countDocuments({revokedAt: {$exists: false}})).toBe(0);
157
+ expect(await McpOAuthToken.countDocuments({revokedAt: {$exists: false}})).toBe(0);
158
+ });
159
+
160
+ it("looks up a 12-character email by email, not as an id", async () => {
161
+ await UserModel.updateOne({_id: notAdminId}, {$set: {email: "ab@gmail.com"}});
162
+ await McpServiceToken.issueFor({_id: notAdminId}, {name: "Laptop"});
163
+
164
+ const wet = await mcpSignOutEverywhere(true, scriptContext("ab@gmail.com"));
165
+
166
+ expect(wet.success).toBe(true);
167
+ expect(await McpServiceToken.countDocuments({revokedAt: {$exists: false}})).toBe(0);
168
+ });
169
+
170
+ it("fails without a user or with an unknown email", async () => {
171
+ expect((await mcpSignOutEverywhere(true, scriptContext(""))).success).toBe(false);
172
+ expect((await mcpSignOutEverywhere(true, scriptContext("nobody@example.com"))).success).toBe(
173
+ false
174
+ );
175
+ });
176
+ });