@terreno/admin-backend 57.0.0 → 57.1.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 (43) hide show
  1. package/README.md +3 -0
  2. package/dist/adminApp.d.ts +11 -4
  3. package/dist/adminApp.js +859 -263
  4. package/dist/adminConfigIdentity.d.ts +16 -0
  5. package/dist/adminConfigIdentity.js +100 -0
  6. package/dist/adminTextSearch.d.ts +17 -0
  7. package/dist/adminTextSearch.js +117 -0
  8. package/dist/adminUiV2.js +1 -1
  9. package/dist/aggregateAdmin.d.ts +20 -0
  10. package/dist/aggregateAdmin.js +275 -0
  11. package/dist/documentStorageApp.d.ts +3 -1
  12. package/dist/documentStorageApp.js +20 -42
  13. package/dist/filterParser.d.ts +11 -0
  14. package/dist/filterParser.js +260 -0
  15. package/dist/index.d.ts +9 -0
  16. package/dist/index.js +15 -1
  17. package/dist/legacy.d.ts +9 -0
  18. package/dist/legacy.js +61 -0
  19. package/dist/resolvedAdminModel.d.ts +23 -0
  20. package/dist/resolvedAdminModel.js +130 -0
  21. package/dist/routePath.d.ts +2 -0
  22. package/dist/routePath.js +18 -0
  23. package/package.json +4 -3
  24. package/src/adminApp.models.test.ts +894 -1
  25. package/src/adminApp.test.ts +35 -1
  26. package/src/adminApp.ts +599 -98
  27. package/src/adminConfigIdentity.test.ts +56 -0
  28. package/src/adminConfigIdentity.ts +87 -0
  29. package/src/adminTextSearch.test.ts +73 -0
  30. package/src/adminTextSearch.ts +74 -0
  31. package/src/adminUiV2.test.ts +1 -0
  32. package/src/adminUiV2.ts +1 -1
  33. package/src/aggregateAdmin.test.ts +220 -0
  34. package/src/aggregateAdmin.ts +206 -0
  35. package/src/documentStorageApp.test.ts +11 -0
  36. package/src/documentStorageApp.ts +20 -39
  37. package/src/filterParser.test.ts +68 -0
  38. package/src/filterParser.ts +229 -0
  39. package/src/index.ts +35 -0
  40. package/src/legacy.test.ts +34 -0
  41. package/src/legacy.ts +63 -0
  42. package/src/resolvedAdminModel.ts +114 -0
  43. package/src/routePath.ts +14 -0
package/src/adminApp.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import {
2
+ type AdminModelAdminMap,
3
+ type AnyTerrenoAccess,
2
4
  APIError,
3
5
  asyncHandler,
4
6
  authenticateMiddleware,
@@ -13,6 +15,7 @@ import {
13
15
  type ModelRouterOptions,
14
16
  modelRouter,
15
17
  type OpenApiMiddleware,
18
+ type PermissionMethod,
16
19
  Permissions,
17
20
  type PopulatePath,
18
21
  type ScriptArgDef,
@@ -20,7 +23,9 @@ import {
20
23
  type ScriptContext,
21
24
  type ScriptResult,
22
25
  type ScriptRunner,
26
+ scrubAdminFields,
23
27
  TaskCancelledError,
28
+ type TerrenoApp,
24
29
  type User,
25
30
  VersionConfig,
26
31
  } from "@terreno/api";
@@ -28,7 +33,12 @@ import express from "express";
28
33
  import {DateTime} from "luxon";
29
34
  import type {Model} from "mongoose";
30
35
  import mongoose from "mongoose";
31
-
36
+ import {assignUniqueAdminConfigNames, findAdminModelMetaByRoutePath} from "./adminConfigIdentity";
37
+ import {
38
+ ADMIN_LIST_SEARCH_PARAM,
39
+ andMongoFilters,
40
+ buildAdminPartialSearchFilter,
41
+ } from "./adminTextSearch";
32
42
  import {
33
43
  ADMIN_SCHEMA_VERSION,
34
44
  type AdminActionInput,
@@ -42,6 +52,9 @@ import {
42
52
  normalizeAdminHome,
43
53
  SYSTEM_ADMIN_FIELDS,
44
54
  } from "./adminUiV2";
55
+ import {aggregateFromTerrenoApp} from "./aggregateAdmin";
56
+ import {parseAdminListFilters} from "./filterParser";
57
+ import type {ResolvedAdminModel} from "./resolvedAdminModel";
45
58
  import {RESERVED_SCRIPT_FLAGS} from "./scriptCli";
46
59
 
47
60
  /**
@@ -163,8 +176,8 @@ export interface AdminCustomScreenConfig {
163
176
  * Configuration options for the AdminApp plugin.
164
177
  */
165
178
  export interface AdminOptions {
166
- /** Array of model configurations to expose in the admin panel */
167
- models: AdminModelConfig[];
179
+ /** Legacy model configurations (deprecated — prefer modelRouter `admin:` or plugin contributions). */
180
+ models?: AdminModelConfig[];
168
181
  /** Array of scripts that can be run from the admin panel */
169
182
  scripts?: AdminScriptConfig[];
170
183
  /** Base path for all admin routes. Defaults to "/admin". */
@@ -178,6 +191,9 @@ export interface AdminOptions {
178
191
  * Consumers typically persist to an `AdminAuditLog` collection.
179
192
  */
180
193
  onAdminAudit?: (event: AdminAuditEvent, req: express.Request) => void | Promise<void>;
194
+ /** When set, admin shell entry requires `admin:access`; model CRUD also requires
195
+ * resource/action permissions (for example `user:update`) from the same Access instance. */
196
+ accessControl?: AnyTerrenoAccess;
181
197
  }
182
198
 
183
199
  interface AdminFieldMeta {
@@ -231,42 +247,140 @@ interface AdminScriptMeta {
231
247
  }
232
248
 
233
249
  interface AdminConfigResponse {
250
+ capabilities: {
251
+ actions: boolean;
252
+ fieldsets: boolean;
253
+ filters: boolean;
254
+ realtime: boolean;
255
+ };
234
256
  customScreens?: AdminCustomScreenConfig[];
235
257
  home: ReturnType<typeof normalizeAdminHome>;
236
258
  models: AdminModelMeta[];
237
259
  schemaVersion: number;
238
260
  scripts: AdminScriptMeta[];
261
+ widgetIds: string[];
239
262
  }
240
263
 
241
- const toPlainObject = (value: unknown): Record<string, unknown> => {
242
- if (
243
- value &&
244
- typeof value === "object" &&
245
- "toObject" in value &&
246
- typeof value.toObject === "function"
247
- ) {
248
- return (value as {toObject: () => Record<string, unknown>}).toObject();
264
+ const buildAllModelAdminsMap = (models: ResolvedAdminModel[]): AdminModelAdminMap => {
265
+ const map: AdminModelAdminMap = {};
266
+ for (const config of models) {
267
+ map[config.model.modelName] = config.admin;
249
268
  }
250
- return value as Record<string, unknown>;
269
+ return map;
251
270
  };
252
271
 
253
- const removeHiddenFields = (value: unknown, hiddenFieldSet: Set<string>): unknown => {
254
- if (Array.isArray(value)) {
255
- return value.map((item) => removeHiddenFields(item, hiddenFieldSet));
256
- }
257
- if (!value || typeof value !== "object") {
258
- return value;
259
- }
260
- const plainValue = toPlainObject(value);
261
- const nextValue: Record<string, unknown> = {};
262
- for (const [key, fieldValue] of Object.entries(plainValue)) {
263
- if (!hiddenFieldSet.has(key)) {
264
- nextValue[key] = fieldValue;
272
+ const scrubAdminResponse = (
273
+ value: unknown,
274
+ config: ResolvedAdminModel,
275
+ allModelAdmins: AdminModelAdminMap
276
+ ): unknown => {
277
+ return scrubAdminFields(value, {
278
+ admin: config.admin,
279
+ allModelAdmins,
280
+ schema: config.model.schema,
281
+ });
282
+ };
283
+
284
+ const buildAdminListQueryFilter = (
285
+ config: ResolvedAdminModel,
286
+ /** Resolved (possibly derived) search fields from `/admin/config`, not just explicit config. */
287
+ resolvedSearchFields?: string[]
288
+ ): NonNullable<ModelRouterOptions<unknown>["queryFilter"]> => {
289
+ const base = config.queryFilter;
290
+ const searchFields = resolvedSearchFields ?? config.searchFields ?? [];
291
+ return async (user, query) => {
292
+ const clientQuery: Record<string, unknown> = {...(query ?? {})};
293
+ const {consumedKeys, errors, filter} = parseAdminListFilters(clientQuery, config.filters ?? []);
294
+ if (Object.keys(errors).length > 0) {
295
+ throw new APIError({
296
+ detail: JSON.stringify(errors),
297
+ status: 400,
298
+ title: "Invalid filter",
299
+ });
300
+ }
301
+ for (const key of consumedKeys) {
302
+ delete clientQuery[key];
303
+ }
304
+
305
+ const rawSearch = clientQuery[ADMIN_LIST_SEARCH_PARAM];
306
+ delete clientQuery[ADMIN_LIST_SEARCH_PARAM];
307
+ const searchClause =
308
+ typeof rawSearch === "string"
309
+ ? buildAdminPartialSearchFilter({
310
+ model: config.model,
311
+ q: rawSearch,
312
+ searchFields,
313
+ })
314
+ : undefined;
315
+
316
+ let merged: Record<string, unknown> = {...clientQuery, ...filter};
317
+ if (base) {
318
+ const baseResult = await base(user, merged);
319
+ if (baseResult === null) {
320
+ return null;
321
+ }
322
+ merged = {...merged, ...baseResult};
265
323
  }
324
+ const result = andMongoFilters(merged, searchClause);
325
+ return {...result, [ADMIN_LIST_SEARCH_PARAM]: undefined};
326
+ };
327
+ };
328
+
329
+ const ADMIN_TIMESTAMP_SORT_FIELDS = ["created", "createdAt", "updated", "updatedAt"];
330
+
331
+ const sortTokensToFields = (sort: string | string[] | undefined): string[] => {
332
+ if (!sort) {
333
+ return [];
266
334
  }
267
- return nextValue;
335
+ const raw = Array.isArray(sort) ? sort.join(" ") : sort;
336
+ return raw
337
+ .trim()
338
+ .split(/\s+/)
339
+ .map((token) => token.replace(/^-/, ""))
340
+ .filter((field) => field.length > 0);
341
+ };
342
+
343
+ const resolveAdminSortableFields = ({
344
+ defaultSort,
345
+ listDisplay,
346
+ sortableFields,
347
+ }: {
348
+ defaultSort?: string | string[];
349
+ listDisplay: string[];
350
+ sortableFields?: string[];
351
+ }): string[] => {
352
+ return [
353
+ ...new Set([
354
+ ...(sortableFields ?? listDisplay),
355
+ "_id",
356
+ ...ADMIN_TIMESTAMP_SORT_FIELDS,
357
+ ...sortTokensToFields(defaultSort),
358
+ ]),
359
+ ];
268
360
  };
269
361
 
362
+ const validateAdminSortParam =
363
+ (sortableFields: string[]): express.RequestHandler =>
364
+ (req, _res, next) => {
365
+ const sort = req.query.sort;
366
+ if (typeof sort !== "string" || !sort.trim()) {
367
+ next();
368
+ return;
369
+ }
370
+ const tokens = sort.trim().split(/\s+/);
371
+ for (const token of tokens) {
372
+ const field = token.replace(/^-/, "");
373
+ if (!sortableFields.includes(field)) {
374
+ throw new APIError({
375
+ detail: field,
376
+ status: 400,
377
+ title: "Invalid sort field",
378
+ });
379
+ }
380
+ }
381
+ next();
382
+ };
383
+
270
384
  const auditDocumentToPlain = (value: unknown): Record<string, unknown> => {
271
385
  if (
272
386
  value &&
@@ -294,6 +408,24 @@ const auditLabelFromListFields = (
294
408
  return id != null ? String(id) : undefined;
295
409
  };
296
410
 
411
+ const coerceAdminFlag = (value: unknown): boolean => {
412
+ if (value === true || value === 1 || value === "1" || value === "true" || value === "yes") {
413
+ return true;
414
+ }
415
+ if (
416
+ value === false ||
417
+ value === 0 ||
418
+ value === "0" ||
419
+ value === "false" ||
420
+ value === "no" ||
421
+ value === "" ||
422
+ value == null
423
+ ) {
424
+ return false;
425
+ }
426
+ throw new APIError({status: 400, title: "admin must be a boolean"});
427
+ };
428
+
297
429
  const auditActorId = (request: express.Request): string | undefined => {
298
430
  const user = request.user as {_id?: unknown} | undefined;
299
431
  if (!user || user._id == null) {
@@ -445,6 +577,58 @@ export class AdminApp {
445
577
  this.options = options;
446
578
  }
447
579
 
580
+ private adminAccessPermissions(): PermissionMethod<unknown>[] {
581
+ if (this.options.accessControl) {
582
+ return [this.options.accessControl.permission({admin: ["access"]})];
583
+ }
584
+ return [Permissions.IsAdmin];
585
+ }
586
+
587
+ private async hasScriptPermission(
588
+ user: User | undefined,
589
+ action: "runScripts" | "viewBackgroundTasks"
590
+ ): Promise<boolean> {
591
+ if (!this.options.accessControl) {
592
+ return Boolean(user?.admin);
593
+ }
594
+ const result = await this.options.accessControl.can({
595
+ permissions: {admin: [action]},
596
+ user,
597
+ });
598
+ return result.allowed;
599
+ }
600
+
601
+ private async hasConfigurationPermission(
602
+ user: User | undefined,
603
+ action: "read" | "update"
604
+ ): Promise<boolean> {
605
+ if (!this.options.accessControl) {
606
+ return Boolean(user?.admin);
607
+ }
608
+ const result = await this.options.accessControl.can({
609
+ permissions: {configuration: [action]},
610
+ user,
611
+ });
612
+ return result.allowed;
613
+ }
614
+
615
+ private resourceActionPermissions(
616
+ modelName: string,
617
+ action: "list" | "read" | "create" | "update" | "delete"
618
+ ): PermissionMethod<unknown>[] {
619
+ const shell = this.adminAccessPermissions();
620
+ const accessControl = this.options.accessControl;
621
+ if (!accessControl) {
622
+ return shell;
623
+ }
624
+ const resource = `${modelName.charAt(0).toLowerCase()}${modelName.slice(1)}`;
625
+ const knownActions = accessControl.statements[resource];
626
+ if (!knownActions) {
627
+ return [];
628
+ }
629
+ return [...shell, accessControl.permission({[resource]: [action]})];
630
+ }
631
+
448
632
  /**
449
633
  * Register admin routes with the Express application.
450
634
  *
@@ -461,10 +645,15 @@ export class AdminApp {
461
645
  *
462
646
  * @param app - The Express application instance to register with
463
647
  */
464
- register(app: express.Application, openApi?: unknown): void {
648
+ register(app: express.Application, openApi?: unknown, terrenoApp?: TerrenoApp): void {
465
649
  const basePath = this.options.basePath ?? "/admin";
466
650
  const openApiMw = openApi as OpenApiMiddleware | undefined;
467
- const modelConfigs = this.options.models;
651
+ const aggregated = aggregateFromTerrenoApp({
652
+ legacyModels: this.options.models ?? [],
653
+ terrenoApp,
654
+ });
655
+ const modelConfigs = aggregated.models;
656
+ const allModelAdmins = buildAllModelAdminsMap(modelConfigs);
468
657
  const onAdminAudit = this.options.onAdminAudit;
469
658
 
470
659
  /** Audit is best-effort: failures must not change HTTP outcomes after mutations succeed. */
@@ -484,7 +673,14 @@ export class AdminApp {
484
673
  };
485
674
 
486
675
  // Build config response with field metadata from Mongoose schemas
487
- const configModels: AdminModelMeta[] = modelConfigs.map((config) => {
676
+ const configNames = assignUniqueAdminConfigNames(
677
+ modelConfigs.map((config) => ({
678
+ modelName: config.model.modelName,
679
+ routePath: config.routePath,
680
+ source: config.source,
681
+ }))
682
+ );
683
+ const configModels: AdminModelMeta[] = modelConfigs.map((config, configIndex) => {
488
684
  const {properties, required} = getOpenApiSpecForModel(config.model) as {
489
685
  properties: Record<string, OpenApiProperty>;
490
686
  required: string[];
@@ -549,7 +745,11 @@ export class AdminApp {
549
745
  const listDisplay = config.listDisplay ?? listFields;
550
746
  const derivedSearchFields = listFields.filter((field) => fields[field]?.searchable);
551
747
  const searchFields = config.searchFields ?? derivedSearchFields;
552
- const sortableFields = config.sortableFields ?? [...listDisplay, "_id"];
748
+ const sortableFields = resolveAdminSortableFields({
749
+ defaultSort: config.defaultSort,
750
+ listDisplay,
751
+ sortableFields: config.sortableFields,
752
+ });
553
753
  const schemaPathKeys = new Set(Object.keys(config.model.schema.paths));
554
754
  const bulkPatchAllowlist =
555
755
  config.bulkPatchAllowlist ??
@@ -574,7 +774,7 @@ export class AdminApp {
574
774
  listDisplay,
575
775
  listDisplayLinks: config.listDisplayLinks ?? [],
576
776
  listFields,
577
- name: config.model.modelName,
777
+ name: configNames[configIndex] ?? config.model.modelName,
578
778
  pageSize: config.pageSize,
579
779
  permissions: {
580
780
  create: config.permissions?.create !== false,
@@ -591,7 +791,7 @@ export class AdminApp {
591
791
  });
592
792
 
593
793
  // Build script metadata for config response
594
- const scriptConfigs = this.options.scripts ?? [];
794
+ const scriptConfigs = [...(this.options.scripts ?? []), ...aggregated.scripts];
595
795
  const configScripts: AdminScriptMeta[] = scriptConfigs.map((script) => ({
596
796
  args: script.args ?? [],
597
797
  description: script.description,
@@ -599,14 +799,25 @@ export class AdminApp {
599
799
  }));
600
800
 
601
801
  const defaultScreens = [{displayName: "Version Config", name: "version-config"}];
602
- const mergedScreens = [...defaultScreens, ...(this.options.customScreens ?? [])];
802
+ const mergedScreens = [
803
+ ...defaultScreens,
804
+ ...aggregated.customScreens,
805
+ ...(this.options.customScreens ?? []),
806
+ ];
603
807
 
604
808
  const configResponse: AdminConfigResponse = {
809
+ capabilities: {
810
+ actions: true,
811
+ fieldsets: true,
812
+ filters: true,
813
+ realtime: modelConfigs.some((config) => config.realtime === true),
814
+ },
605
815
  customScreens: mergedScreens,
606
816
  home: normalizeAdminHome(this.options.home),
607
817
  models: configModels,
608
818
  schemaVersion: ADMIN_SCHEMA_VERSION,
609
819
  scripts: configScripts,
820
+ widgetIds: aggregated.widgetIds,
610
821
  };
611
822
 
612
823
  const adminConfigOpenApi = openApiMw
@@ -614,6 +825,15 @@ export class AdminApp {
614
825
  .withTags(["admin"])
615
826
  .withSummary("Admin panel configuration")
616
827
  .withResponse(200, {
828
+ capabilities: {
829
+ properties: {
830
+ actions: {type: "boolean"},
831
+ fieldsets: {type: "boolean"},
832
+ filters: {type: "boolean"},
833
+ realtime: {type: "boolean"},
834
+ },
835
+ type: "object",
836
+ },
617
837
  customScreens: {
618
838
  items: {
619
839
  properties: {
@@ -639,6 +859,7 @@ export class AdminApp {
639
859
  },
640
860
  type: "array",
641
861
  },
862
+ widgetIds: {items: {type: "string"}, type: "array"},
642
863
  })
643
864
  .build()
644
865
  : undefined;
@@ -650,7 +871,11 @@ export class AdminApp {
650
871
  ...asMiddlewareList(adminConfigOpenApi),
651
872
  asyncHandler(async (req, res) => {
652
873
  if (
653
- !(await checkPermissions("read", [Permissions.IsAdmin], req.user as User | undefined))
874
+ !(await checkPermissions(
875
+ "read",
876
+ this.adminAccessPermissions(),
877
+ req.user as User | undefined
878
+ ))
654
879
  ) {
655
880
  throw new APIError({status: 403, title: "Admin access required"});
656
881
  }
@@ -693,12 +918,11 @@ export class AdminApp {
693
918
  authenticateMiddleware(),
694
919
  ...asMiddlewareList(backgroundTasksOpenApi),
695
920
  asyncHandler(async (req, res) => {
696
- if (
697
- !(await checkPermissions("update", [Permissions.IsAdmin], req.user as User | undefined))
698
- ) {
921
+ const actor = req.user as User | undefined;
922
+ if (!actor || !(await this.hasScriptPermission(actor, "runScripts"))) {
699
923
  throw new APIError({status: 403, title: "Admin access required"});
700
924
  }
701
- const user = req.user as {_id: unknown} | undefined;
925
+ const user = actor as {_id: unknown};
702
926
  const raw = req.body as {
703
927
  ids?: unknown;
704
928
  kind?: unknown;
@@ -753,9 +977,7 @@ export class AdminApp {
753
977
  versionConfigPath,
754
978
  authenticateMiddleware(),
755
979
  asyncHandler(async (req, res) => {
756
- if (
757
- !(await checkPermissions("read", [Permissions.IsAdmin], req.user as User | undefined))
758
- ) {
980
+ if (!(await this.hasConfigurationPermission(req.user as User | undefined, "read"))) {
759
981
  throw new APIError({status: 403, title: "Admin access required"});
760
982
  }
761
983
  const config = await VersionConfig.findOneOrNone({_singleton: "config"});
@@ -775,9 +997,7 @@ export class AdminApp {
775
997
  versionConfigPath,
776
998
  authenticateMiddleware(),
777
999
  asyncHandler(async (req, res) => {
778
- if (
779
- !(await checkPermissions("update", [Permissions.IsAdmin], req.user as User | undefined))
780
- ) {
1000
+ if (!(await this.hasConfigurationPermission(req.user as User | undefined, "update"))) {
781
1001
  throw new APIError({status: 403, title: "Admin access required"});
782
1002
  }
783
1003
  const raw = req.body as Record<string, unknown>;
@@ -822,7 +1042,10 @@ export class AdminApp {
822
1042
  // not the OpenAPI type (which reports ObjectId as "string")
823
1043
  const searchableFields: string[] = [];
824
1044
  const objectIdFields: string[] = [];
825
- const modelMeta = configModels.find((m) => m.name === config.model.modelName);
1045
+ const modelMeta = findAdminModelMetaByRoutePath(
1046
+ configModels,
1047
+ `${basePath}${config.routePath}`
1048
+ );
826
1049
  if (modelMeta) {
827
1050
  for (const key of Object.keys(modelMeta.fields)) {
828
1051
  const schemaPath = config.model.schema.path(key);
@@ -838,8 +1061,13 @@ export class AdminApp {
838
1061
  `${basePath}${config.routePath}/search`,
839
1062
  authenticateMiddleware(),
840
1063
  asyncHandler(async (req, res) => {
841
- const user = req.user as {_id: unknown; admin?: boolean} | undefined;
842
- if (!user?.admin) {
1064
+ if (
1065
+ !(await checkPermissions(
1066
+ "list",
1067
+ this.resourceActionPermissions(config.model.modelName, "list"),
1068
+ req.user as User | undefined
1069
+ ))
1070
+ ) {
843
1071
  throw new APIError({
844
1072
  disableExternalErrorTracking: true,
845
1073
  status: 403,
@@ -851,24 +1079,19 @@ export class AdminApp {
851
1079
  return res.json({data: []});
852
1080
  }
853
1081
 
854
- const escapedQ = q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
855
- const regex = new RegExp(escapedQ, "i");
856
-
857
1082
  const fields =
858
1083
  typeof req.query.fields === "string"
859
1084
  ? req.query.fields.split(",").filter((f: string) => searchableFields.includes(f))
860
1085
  : searchableFields;
861
1086
 
862
- const orConditions = fields.map((field: string) => ({[field]: {$regex: regex}}));
863
-
864
- // If the query is a valid ObjectId, also match against ObjectId fields
865
- if (mongoose.isValidObjectId(q)) {
866
- for (const field of objectIdFields) {
867
- orConditions.push({[field]: new mongoose.Types.ObjectId(q)});
868
- }
869
- }
1087
+ const searchClause = buildAdminPartialSearchFilter({
1088
+ extraObjectIdFields: objectIdFields,
1089
+ model: config.model,
1090
+ q,
1091
+ searchFields: fields,
1092
+ });
870
1093
 
871
- if (orConditions.length === 0) {
1094
+ if (!searchClause) {
872
1095
  return res.json({data: []});
873
1096
  }
874
1097
  logger.debug("Admin search query", {
@@ -877,12 +1100,24 @@ export class AdminApp {
877
1100
  q,
878
1101
  });
879
1102
  try {
880
- const results = await config.model.find({$or: orConditions}).limit(20).lean();
1103
+ const scoped = await buildAdminListQueryFilter(config, modelMeta?.searchFields)(
1104
+ req.user as User | undefined,
1105
+ {}
1106
+ );
1107
+ if (scoped === null) {
1108
+ return res.json({data: []});
1109
+ }
1110
+ const results = await config.model
1111
+ .find({$and: [scoped, searchClause]})
1112
+ .limit(20)
1113
+ .lean();
881
1114
  logger.debug("Admin search results", {
882
1115
  count: results.length,
883
1116
  model: config.model.modelName,
884
1117
  });
885
- return res.json({data: results});
1118
+ return res.json({
1119
+ data: results.map((doc) => scrubAdminResponse(doc, config, allModelAdmins)),
1120
+ });
886
1121
  } catch (err) {
887
1122
  logger.error("Admin search failed", {
888
1123
  error: err,
@@ -899,16 +1134,25 @@ export class AdminApp {
899
1134
  for (const config of modelConfigs) {
900
1135
  const hiddenFieldSet = new Set(config.hiddenFields ?? []);
901
1136
  const readonlySet = new Set(config.readonlyFields ?? []);
902
- const modelMeta = configModels.find((m) => m.name === config.model.modelName);
1137
+ const excludeFieldSet = new Set(config.excludeFields ?? []);
1138
+ const modelMeta = findAdminModelMetaByRoutePath(
1139
+ configModels,
1140
+ `${basePath}${config.routePath}`
1141
+ );
903
1142
  const allowlist = new Set(modelMeta?.bulkPatchAllowlist ?? []);
904
1143
 
905
- const adminPermission = (allowed: boolean | undefined): (typeof Permissions.IsAdmin)[] => {
1144
+ const adminPermission = (
1145
+ allowed: boolean | undefined,
1146
+ action: "list" | "read" | "create" | "update" | "delete"
1147
+ ): PermissionMethod<unknown>[] => {
906
1148
  if (allowed === false) {
907
1149
  return [];
908
1150
  }
909
- return [Permissions.IsAdmin];
1151
+ return this.resourceActionPermissions(config.model.modelName, action);
910
1152
  };
911
1153
 
1154
+ const updatePermissions = this.resourceActionPermissions(config.model.modelName, "update");
1155
+
912
1156
  const stripProtectedFromBody = (body: unknown): Record<string, unknown> => {
913
1157
  if (!body || typeof body !== "object" || Array.isArray(body)) {
914
1158
  return {};
@@ -920,12 +1164,131 @@ export class AdminApp {
920
1164
  for (const key of hiddenFieldSet) {
921
1165
  delete next[key];
922
1166
  }
1167
+ for (const key of excludeFieldSet) {
1168
+ delete next[key];
1169
+ }
923
1170
  for (const key of SYSTEM_ADMIN_FIELDS) {
924
1171
  delete next[key];
925
1172
  }
1173
+ // Self-service never writes these fields. Admin CRUD may set `admin`.
1174
+ // When RBAC is enabled, `roles` must go through RoleManager.assign and
1175
+ // tenant membership is not a generic User document field.
1176
+ if (config.model.modelName === "User" && this.options.accessControl) {
1177
+ delete next.organizationIds;
1178
+ delete next.roles;
1179
+ }
926
1180
  return next;
927
1181
  };
928
1182
 
1183
+ const parseRoleNames = (value: unknown): string[] => {
1184
+ if (!Array.isArray(value) || value.some((roleName) => typeof roleName !== "string")) {
1185
+ throw new APIError({status: 400, title: "roles must be an array of strings"});
1186
+ }
1187
+ return value as string[];
1188
+ };
1189
+
1190
+ const takePendingUserRoles = (
1191
+ body: Record<string, unknown>,
1192
+ request: express.Request
1193
+ ): void => {
1194
+ if (config.model.modelName !== "User" || !this.options.accessControl) {
1195
+ return;
1196
+ }
1197
+ if (!("roles" in body)) {
1198
+ return;
1199
+ }
1200
+ (
1201
+ request as express.Request & {terrenoPendingUserRoles?: string[]}
1202
+ ).terrenoPendingUserRoles = parseRoleNames(body.roles);
1203
+ };
1204
+
1205
+ const applyPendingUserRoles = async (
1206
+ value: unknown,
1207
+ request: express.Request,
1208
+ rollbackOnFailure = false
1209
+ ): Promise<void> => {
1210
+ const pending = (request as express.Request & {terrenoPendingUserRoles?: string[]})
1211
+ .terrenoPendingUserRoles;
1212
+ if (!pending) {
1213
+ return;
1214
+ }
1215
+ const actor = request.user as User | undefined;
1216
+ const accessControl = this.options.accessControl;
1217
+ if (!actor || !accessControl) {
1218
+ throw new APIError({status: 401, title: "Unauthorized"});
1219
+ }
1220
+ const record = value as {
1221
+ _id?: unknown;
1222
+ id?: string;
1223
+ roles?: string[];
1224
+ set?: (path: string, value: unknown) => void;
1225
+ };
1226
+ const userId = record.id ?? (record._id != null ? String(record._id) : undefined);
1227
+ if (!userId) {
1228
+ throw new APIError({status: 500, title: "User id missing after write"});
1229
+ }
1230
+ try {
1231
+ await accessControl.roles.assign({actor, roleNames: pending, userId});
1232
+ if (typeof record.set === "function") {
1233
+ record.set("roles", [...pending]);
1234
+ } else {
1235
+ record.roles = [...pending];
1236
+ }
1237
+ } catch (error) {
1238
+ if (rollbackOnFailure) {
1239
+ try {
1240
+ await config.model.deleteOne({_id: userId});
1241
+ } catch (rollbackError) {
1242
+ logger.error("Failed to roll back user after role assignment failure", {
1243
+ error: rollbackError,
1244
+ userId,
1245
+ });
1246
+ }
1247
+ }
1248
+ throw error;
1249
+ }
1250
+ };
1251
+
1252
+ const restoreUserFieldsAfterFailedRoleAssign = async (
1253
+ value: unknown,
1254
+ prev: unknown,
1255
+ cleanedBody: unknown
1256
+ ): Promise<void> => {
1257
+ if (!prev || typeof prev !== "object" || !cleanedBody || typeof cleanedBody !== "object") {
1258
+ return;
1259
+ }
1260
+ if (Array.isArray(cleanedBody)) {
1261
+ return;
1262
+ }
1263
+ const record = value as {
1264
+ _id?: unknown;
1265
+ save?: () => Promise<unknown>;
1266
+ set?: (path: string, next: unknown) => void;
1267
+ };
1268
+ const prevRecord = prev as Record<string, unknown>;
1269
+ const body = cleanedBody as Record<string, unknown>;
1270
+ const restore: Record<string, unknown> = {};
1271
+ for (const key of Object.keys(body)) {
1272
+ if (key === "roles") {
1273
+ continue;
1274
+ }
1275
+ restore[key] = prevRecord[key];
1276
+ if (typeof record.set === "function") {
1277
+ record.set(key, prevRecord[key]);
1278
+ }
1279
+ }
1280
+ if (Object.keys(restore).length === 0) {
1281
+ return;
1282
+ }
1283
+ if (typeof record.save === "function") {
1284
+ await record.save();
1285
+ return;
1286
+ }
1287
+ if (record._id != null) {
1288
+ await config.model.updateOne({_id: record._id}, {$set: restore});
1289
+ }
1290
+ };
1291
+
929
1292
  const bulkPatchOpenApi = openApiMw
930
1293
  ? createOpenApiBuilder({openApi: openApiMw})
931
1294
  .withTags(["admin"])
@@ -994,56 +1357,150 @@ export class AdminApp {
994
1357
  }
995
1358
  : {};
996
1359
 
1360
+ const assertCanWriteUserAdminFlag = async (
1361
+ body: Record<string, unknown>,
1362
+ request: express.Request,
1363
+ currentAdmin = false,
1364
+ targetUserId?: string
1365
+ ): Promise<void> => {
1366
+ if (config.model.modelName !== "User" || !("admin" in body)) {
1367
+ return;
1368
+ }
1369
+ const accessControl = this.options.accessControl;
1370
+ if (!accessControl) {
1371
+ return;
1372
+ }
1373
+ if (coerceAdminFlag(body.admin) === Boolean(currentAdmin)) {
1374
+ return;
1375
+ }
1376
+ const actor = request.user as User | undefined;
1377
+ if (!actor) {
1378
+ throw new APIError({status: 401, title: "Unauthorized"});
1379
+ }
1380
+ const result = await accessControl.can({
1381
+ permissions: {rbac: ["assignRoles"]},
1382
+ user: actor,
1383
+ });
1384
+ if (!result.allowed) {
1385
+ throw new APIError({
1386
+ status: 403,
1387
+ title: "Missing rbac:assignRoles permission",
1388
+ });
1389
+ }
1390
+ const nextAdmin = coerceAdminFlag(body.admin);
1391
+ const isGrantingAdmin = nextAdmin === true && !currentAdmin;
1392
+ const isRevokingAdmin = nextAdmin === false && currentAdmin;
1393
+ // assignRoles and manageRoles still cannot mint or strip the legacy admin
1394
+ // plane (IsAdmin, password reset, owner bypass). Only an existing admin can.
1395
+ if ((isGrantingAdmin || isRevokingAdmin) && !actor.admin) {
1396
+ throw new APIError({
1397
+ status: 403,
1398
+ title: isGrantingAdmin
1399
+ ? "Cannot grant the legacy admin flag without the admin privilege"
1400
+ : "Cannot revoke the legacy admin flag without the admin privilege",
1401
+ });
1402
+ }
1403
+ const targetId = targetUserId ?? request.params?.id;
1404
+ if (targetId) {
1405
+ await accessControl.roles.assertCanModifyUser({actor, userId: String(targetId)});
1406
+ }
1407
+ };
1408
+
1409
+ const currentUserAdminFlag = async (request: express.Request): Promise<boolean> => {
1410
+ const id = request.params?.id;
1411
+ if (!id) {
1412
+ return false;
1413
+ }
1414
+ const existing = await config.model.findById(id).select("admin").lean();
1415
+ return Boolean((existing as {admin?: boolean} | null)?.admin);
1416
+ };
1417
+
1418
+ const markAuthorizedUserAdminWrite = (
1419
+ body: Record<string, unknown>,
1420
+ request: express.Request
1421
+ ): void => {
1422
+ if (
1423
+ config.model.modelName !== "User" ||
1424
+ !this.options.accessControl ||
1425
+ !("admin" in body)
1426
+ ) {
1427
+ return;
1428
+ }
1429
+ (
1430
+ request as express.Request & {terrenoAllowUserAdminWrite?: boolean}
1431
+ ).terrenoAllowUserAdminWrite = true;
1432
+ };
1433
+
997
1434
  // noExplicitAny: matches the Model<any> from AdminModelConfig above.
998
1435
  // biome-ignore lint/suspicious/noExplicitAny: matches the Model<any> from AdminModelConfig above.
999
1436
  const routerOptions: ModelRouterOptions<any> = {
1000
1437
  ...(openApiMw ? {openApi: openApiMw} : {}),
1438
+ ...(this.options.accessControl ? {accessControl: this.options.accessControl} : {}),
1001
1439
  defaultLimit: config.pageSize ?? 100,
1002
1440
  maxLimit: 500,
1003
1441
  permissions: {
1004
- create: adminPermission(config.permissions?.create),
1005
- delete: adminPermission(config.permissions?.delete),
1006
- list: [Permissions.IsAdmin],
1007
- read: [Permissions.IsAdmin],
1008
- update: adminPermission(config.permissions?.update),
1442
+ create: adminPermission(config.permissions?.create, "create"),
1443
+ delete: adminPermission(config.permissions?.delete, "delete"),
1444
+ list: adminPermission(true, "list"),
1445
+ read: adminPermission(true, "read"),
1446
+ update: adminPermission(config.permissions?.update, "update"),
1009
1447
  },
1010
- queryFields: buildAdminModelQueryFields({
1011
- filters: config.filters,
1012
- listDisplay: config.listDisplay,
1013
- listFields: config.listFields,
1014
- searchFields: config.searchFields,
1015
- }),
1016
- ...(config.queryFilter ? {queryFilter: config.queryFilter} : {}),
1017
- preCreate: async (body, _req) => {
1448
+ postCreate: async (value, request) => {
1449
+ await applyPendingUserRoles(value, request, true);
1450
+ await auditHooks.postCreate?.(value, request);
1451
+ },
1452
+ postUpdate: async (value, cleanedBody, request, prev) => {
1453
+ try {
1454
+ await applyPendingUserRoles(value, request);
1455
+ } catch (error) {
1456
+ await restoreUserFieldsAfterFailedRoleAssign(value, prev, cleanedBody);
1457
+ throw error;
1458
+ }
1459
+ await auditHooks.postUpdate?.(value, cleanedBody, request, prev);
1460
+ },
1461
+ preCreate: async (body, req) => {
1018
1462
  if (!body || typeof body !== "object") {
1019
1463
  return body;
1020
1464
  }
1465
+ const record = body as Record<string, unknown>;
1466
+ takePendingUserRoles(record, req);
1467
+ await assertCanWriteUserAdminFlag(record, req);
1468
+ markAuthorizedUserAdminWrite(record, req);
1021
1469
  return stripProtectedFromBody(body) as typeof body;
1022
1470
  },
1023
- preUpdate: async (body, _req) => {
1471
+ preUpdate: async (body, req) => {
1024
1472
  if (!body || typeof body !== "object") {
1025
1473
  return body;
1026
1474
  }
1475
+ const record = body as Record<string, unknown>;
1476
+ takePendingUserRoles(record, req);
1477
+ await assertCanWriteUserAdminFlag(record, req, await currentUserAdminFlag(req));
1478
+ markAuthorizedUserAdminWrite(record, req);
1027
1479
  return stripProtectedFromBody(body) as typeof body;
1028
1480
  },
1029
- responseHandler:
1030
- hiddenFieldSet.size > 0
1031
- ? async (value, _method, _request, _options): Promise<JSONValue> =>
1032
- removeHiddenFields(value, hiddenFieldSet) as JSONValue
1033
- : undefined,
1481
+ queryFields: buildAdminModelQueryFields({
1482
+ filters: config.filters,
1483
+ listDisplay: config.listDisplay,
1484
+ listFields: config.listFields,
1485
+ searchFields: modelMeta?.searchFields ?? config.searchFields,
1486
+ }),
1487
+ queryFilter: buildAdminListQueryFilter(config, modelMeta?.searchFields),
1488
+ responseHandler: async (value, _method, _request, _options): Promise<JSONValue> =>
1489
+ scrubAdminResponse(value, config, allModelAdmins) as JSONValue,
1034
1490
  sort: config.defaultSort ?? "-created",
1035
1491
  ...(config.populatePaths ? {populatePaths: config.populatePaths} : {}),
1036
- ...auditHooks,
1492
+ ...(auditHooks.postDelete ? {postDelete: auditHooks.postDelete} : {}),
1037
1493
  };
1038
1494
 
1039
1495
  const modelBase = express.Router();
1496
+ modelBase.use(validateAdminSortParam(modelMeta?.sortableFields ?? []));
1040
1497
  modelBase.post(
1041
1498
  "/bulk-patch",
1042
1499
  authenticateMiddleware(),
1043
1500
  ...asMiddlewareList(bulkPatchOpenApi),
1044
1501
  asyncHandler(async (req, res) => {
1045
1502
  if (
1046
- !(await checkPermissions("update", [Permissions.IsAdmin], req.user as User | undefined))
1503
+ !(await checkPermissions("update", updatePermissions, req.user as User | undefined))
1047
1504
  ) {
1048
1505
  throw new APIError({status: 403, title: "Admin access required"});
1049
1506
  }
@@ -1077,7 +1534,15 @@ export class AdminApp {
1077
1534
  });
1078
1535
  }
1079
1536
  const patch = stripProtectedFromBody(rawPatch);
1080
- if (Object.keys(patch).length === 0) {
1537
+ let pendingRoles: string[] | undefined;
1538
+ if (
1539
+ config.model.modelName === "User" &&
1540
+ this.options.accessControl &&
1541
+ "roles" in rawPatch
1542
+ ) {
1543
+ pendingRoles = parseRoleNames(rawPatch.roles);
1544
+ }
1545
+ if (Object.keys(patch).length === 0 && pendingRoles === undefined) {
1081
1546
  throw new APIError({
1082
1547
  status: 400,
1083
1548
  title: "Patch must include at least one writable field",
@@ -1085,18 +1550,54 @@ export class AdminApp {
1085
1550
  }
1086
1551
  let updated = 0;
1087
1552
  const failures: {id: string; title: string}[] = [];
1553
+ const actor = req.user as User | undefined;
1088
1554
  for (const id of ids) {
1089
1555
  if (!mongoose.isValidObjectId(id)) {
1090
1556
  failures.push({id, title: "Invalid id"});
1091
1557
  continue;
1092
1558
  }
1093
1559
  try {
1094
- const resUpdate = await config.model.updateOne({_id: id}, {$set: patch});
1095
- if (resUpdate.matchedCount === 0) {
1560
+ const doc = await config.model.findById(id);
1561
+ if (!doc) {
1096
1562
  failures.push({id, title: "Not found"});
1097
- } else {
1098
- updated += 1;
1563
+ continue;
1564
+ }
1565
+ if (!(await checkPermissions("update", updatePermissions, actor, doc))) {
1566
+ failures.push({id, title: "Forbidden"});
1567
+ continue;
1568
+ }
1569
+ await assertCanWriteUserAdminFlag(
1570
+ rawPatch,
1571
+ req,
1572
+ Boolean((doc as {admin?: boolean}).admin),
1573
+ id
1574
+ );
1575
+ const previousPatch: Record<string, unknown> = {};
1576
+ for (const key of Object.keys(patch)) {
1577
+ previousPatch[key] = (doc as unknown as Record<string, unknown>)[key];
1578
+ }
1579
+ if (Object.keys(patch).length > 0) {
1580
+ await doc.updateOne({$set: patch});
1581
+ }
1582
+ try {
1583
+ if (pendingRoles) {
1584
+ if (!actor) {
1585
+ failures.push({id, title: "Forbidden"});
1586
+ continue;
1587
+ }
1588
+ await this.options.accessControl?.roles.assign({
1589
+ actor,
1590
+ roleNames: pendingRoles,
1591
+ userId: id,
1592
+ });
1593
+ }
1594
+ } catch (roleError) {
1595
+ if (Object.keys(previousPatch).length > 0) {
1596
+ await config.model.updateOne({_id: id}, {$set: previousPatch});
1597
+ }
1598
+ throw roleError;
1099
1599
  }
1600
+ updated += 1;
1100
1601
  } catch (err: unknown) {
1101
1602
  const message = err instanceof Error ? err.message : String(err);
1102
1603
  failures.push({id, title: message});
@@ -1129,8 +1630,8 @@ export class AdminApp {
1129
1630
  router.get(
1130
1631
  "/runs",
1131
1632
  asyncHandler(async (req: express.Request, res: express.Response) => {
1132
- const user = req.user as {admin?: boolean} | undefined;
1133
- if (!user?.admin) {
1633
+ const user = req.user as User | undefined;
1634
+ if (!user || !(await this.hasScriptPermission(user, "viewBackgroundTasks"))) {
1134
1635
  throw new APIError({status: 403, title: "Only admins can view run history"});
1135
1636
  }
1136
1637
 
@@ -1187,8 +1688,8 @@ export class AdminApp {
1187
1688
  router.post(
1188
1689
  "/:name/run",
1189
1690
  asyncHandler(async (req: express.Request<{name: string}>, res: express.Response) => {
1190
- const user = req.user as {_id: unknown; admin?: boolean; name?: string} | undefined;
1191
- if (!user?.admin) {
1691
+ const user = req.user as (User & {_id: unknown; name?: string}) | undefined;
1692
+ if (!user || !(await this.hasScriptPermission(user, "runScripts"))) {
1192
1693
  throw new APIError({status: 403, title: "Only admins can run scripts"});
1193
1694
  }
1194
1695
 
@@ -1242,7 +1743,7 @@ export class AdminApp {
1242
1743
  let task: BackgroundTaskDocument;
1243
1744
  try {
1244
1745
  task = (await BackgroundTask.create({
1245
- createdBy: user._id as mongoose.Types.ObjectId,
1746
+ createdBy: user._id as unknown as mongoose.Types.ObjectId,
1246
1747
  isDryRun: !isWetRun,
1247
1748
  logs: [
1248
1749
  {level: "info", message: `Script started by ${user.name ?? "admin"}`, timestamp: now},
@@ -1330,8 +1831,8 @@ export class AdminApp {
1330
1831
  router.get(
1331
1832
  "/tasks/:id",
1332
1833
  asyncHandler(async (req: express.Request<{id: string}>, res: express.Response) => {
1333
- const user = req.user as {_id: unknown; admin?: boolean} | undefined;
1334
- if (!user?.admin) {
1834
+ const user = req.user as User | undefined;
1835
+ if (!user || !(await this.hasScriptPermission(user, "viewBackgroundTasks"))) {
1335
1836
  throw new APIError({status: 403, title: "Only admins can view tasks"});
1336
1837
  }
1337
1838
 
@@ -1354,8 +1855,8 @@ export class AdminApp {
1354
1855
  router.delete(
1355
1856
  "/tasks/:id",
1356
1857
  asyncHandler(async (req: express.Request<{id: string}>, res: express.Response) => {
1357
- const user = req.user as {_id: unknown; admin?: boolean; name?: string} | undefined;
1358
- if (!user?.admin) {
1858
+ const user = req.user as (User & {name?: string}) | undefined;
1859
+ if (!user || !(await this.hasScriptPermission(user, "runScripts"))) {
1359
1860
  throw new APIError({status: 403, title: "Only admins can cancel tasks"});
1360
1861
  }
1361
1862