@terreno/admin-backend 57.1.0 → 57.2.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/src/adminApp.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import {
2
+ ADMIN_PAGE_ACTION,
3
+ type AdminAccessConfig,
2
4
  type AdminModelAdminMap,
3
5
  type AnyTerrenoAccess,
4
6
  APIError,
@@ -65,6 +67,18 @@ export interface AdminFieldOverride {
65
67
  widget?: string;
66
68
  }
67
69
 
70
+ /**
71
+ * Builds an ownership check for writeOwned admin access. The field may contain an id
72
+ * directly or a populated document with `_id`.
73
+ */
74
+ export const adminOwnedBy = (field: string): NonNullable<AdminAccessConfig["isOwned"]> => {
75
+ return ({instance, user}): boolean => {
76
+ const value = (instance as Record<string, unknown> | undefined)?.[field];
77
+ const ownerId = (value as {_id?: unknown} | undefined)?._id ?? value;
78
+ return ownerId != null && String(ownerId) === String(user.id);
79
+ };
80
+ };
81
+
68
82
  export interface AdminModelConfig {
69
83
  /** The Mongoose model to expose in the admin panel */
70
84
  // noExplicitAny: Model<T> is invariant; the admin panel must accept any document shape.
@@ -110,6 +124,8 @@ export interface AdminModelConfig {
110
124
  populatePaths?: PopulatePath[];
111
125
  /** UI-only hint that live updates may be available */
112
126
  realtime?: boolean;
127
+ /** Fine-grained admin RBAC and optional ownership/custom authorization. */
128
+ adminAccess?: AdminAccessConfig;
113
129
  /**
114
130
  * Field key used for the edit screen title (browser tab / stack header). When omitted, the
115
131
  * admin UI derives a label from common keys (`name`, `title`, …) then the first scalar
@@ -170,6 +186,8 @@ export interface AdminCustomScreenConfig {
170
186
  name: string;
171
187
  /** Optional subtitle or help text shown with the screen card in the admin UI */
172
188
  description?: string;
189
+ /** RBAC or custom authorization for exposing this screen in admin metadata/navigation. */
190
+ adminAccess?: Pick<AdminAccessConfig, "authorize" | "resource"> & {action?: string};
173
191
  }
174
192
 
175
193
  /**
@@ -256,6 +274,14 @@ interface AdminConfigResponse {
256
274
  customScreens?: AdminCustomScreenConfig[];
257
275
  home: ReturnType<typeof normalizeAdminHome>;
258
276
  models: AdminModelMeta[];
277
+ platformTools: {
278
+ configuration: boolean;
279
+ roles: boolean;
280
+ runScripts: boolean;
281
+ scripts: boolean;
282
+ version: boolean;
283
+ viewScripts: boolean;
284
+ };
259
285
  schemaVersion: number;
260
286
  scripts: AdminScriptMeta[];
261
287
  widgetIds: string[];
@@ -579,7 +605,7 @@ export class AdminApp {
579
605
 
580
606
  private adminAccessPermissions(): PermissionMethod<unknown>[] {
581
607
  if (this.options.accessControl) {
582
- return [this.options.accessControl.permission({admin: ["access"]})];
608
+ return [this.options.accessControl.permission({admin: [ADMIN_PAGE_ACTION]})];
583
609
  }
584
610
  return [Permissions.IsAdmin];
585
611
  }
@@ -612,8 +638,57 @@ export class AdminApp {
612
638
  return result.allowed;
613
639
  }
614
640
 
641
+ private async canAnyResourceAction(
642
+ user: User | undefined,
643
+ resource: string,
644
+ actions: string[],
645
+ instance?: unknown
646
+ ): Promise<boolean> {
647
+ const accessControl = this.options.accessControl;
648
+ if (!accessControl || !user) {
649
+ return Boolean(user?.admin);
650
+ }
651
+ for (const action of actions) {
652
+ const result = await accessControl.can({
653
+ doc: instance,
654
+ permissions: {[resource]: [action]},
655
+ user,
656
+ });
657
+ if (result.allowed) {
658
+ return true;
659
+ }
660
+ }
661
+ return false;
662
+ }
663
+
664
+ private adminResource(config: Pick<AdminModelConfig, "adminAccess" | "model">): string {
665
+ const accessControl = this.options.accessControl;
666
+ const explicit = config.adminAccess?.resource;
667
+ if (explicit) {
668
+ return explicit;
669
+ }
670
+ const standard = `admin${config.model.modelName}`;
671
+ if (accessControl?.statements[standard]) {
672
+ return standard;
673
+ }
674
+ return `${config.model.modelName.charAt(0).toLowerCase()}${config.model.modelName.slice(1)}`;
675
+ }
676
+
677
+ private async isAdminModelOwned(
678
+ config: Pick<AdminModelConfig, "adminAccess">,
679
+ user: User,
680
+ instance: unknown
681
+ ): Promise<boolean> {
682
+ if (config.adminAccess?.isOwned) {
683
+ return config.adminAccess.isOwned({instance, user});
684
+ }
685
+ const owner = (instance as {ownerId?: {_id?: unknown} | unknown} | undefined)?.ownerId;
686
+ const ownerId = (owner as {_id?: unknown} | undefined)?._id ?? owner;
687
+ return ownerId != null && String(ownerId) === String(user.id);
688
+ }
689
+
615
690
  private resourceActionPermissions(
616
- modelName: string,
691
+ config: Pick<AdminModelConfig, "adminAccess" | "model">,
617
692
  action: "list" | "read" | "create" | "update" | "delete"
618
693
  ): PermissionMethod<unknown>[] {
619
694
  const shell = this.adminAccessPermissions();
@@ -621,11 +696,43 @@ export class AdminApp {
621
696
  if (!accessControl) {
622
697
  return shell;
623
698
  }
624
- const resource = `${modelName.charAt(0).toLowerCase()}${modelName.slice(1)}`;
699
+ if (config.adminAccess?.authorize) {
700
+ return [
701
+ ...shell,
702
+ async (_method, user, instance) =>
703
+ config.adminAccess?.authorize?.({action, instance, user}) ?? false,
704
+ ];
705
+ }
706
+ const resource = this.adminResource(config);
625
707
  const knownActions = accessControl.statements[resource];
626
708
  if (!knownActions) {
627
709
  return [];
628
710
  }
711
+ const hasStandardAccess = knownActions.includes("write") || knownActions.includes("writeOwned");
712
+ if (hasStandardAccess) {
713
+ return [
714
+ ...shell,
715
+ async (_method, user, instance) => {
716
+ if (!user) {
717
+ return false;
718
+ }
719
+ if (action === "list" || action === "read") {
720
+ return this.canAnyResourceAction(user, resource, ["read"], instance);
721
+ }
722
+ if (await this.canAnyResourceAction(user, resource, ["write"], instance)) {
723
+ return true;
724
+ }
725
+ if (!(await this.canAnyResourceAction(user, resource, ["writeOwned"], instance))) {
726
+ return false;
727
+ }
728
+ // writeOwned always allows create. Ownership applies to update/delete.
729
+ if (action === "create" || instance === undefined) {
730
+ return true;
731
+ }
732
+ return this.isAdminModelOwned(config, user, instance);
733
+ },
734
+ ];
735
+ }
629
736
  return [...shell, accessControl.permission({[resource]: [action]})];
630
737
  }
631
738
 
@@ -798,14 +905,20 @@ export class AdminApp {
798
905
  name: script.name,
799
906
  }));
800
907
 
801
- const defaultScreens = [{displayName: "Version Config", name: "version-config"}];
802
- const mergedScreens = [
908
+ const defaultScreens: AdminCustomScreenConfig[] = [
909
+ {
910
+ adminAccess: {action: "read", resource: "configuration"},
911
+ displayName: "Version Config",
912
+ name: "version-config",
913
+ },
914
+ ];
915
+ const mergedScreens: AdminCustomScreenConfig[] = [
803
916
  ...defaultScreens,
804
917
  ...aggregated.customScreens,
805
918
  ...(this.options.customScreens ?? []),
806
919
  ];
807
920
 
808
- const configResponse: AdminConfigResponse = {
921
+ const baseConfigResponse: AdminConfigResponse = {
809
922
  capabilities: {
810
923
  actions: true,
811
924
  fieldsets: true,
@@ -815,11 +928,109 @@ export class AdminApp {
815
928
  customScreens: mergedScreens,
816
929
  home: normalizeAdminHome(this.options.home),
817
930
  models: configModels,
931
+ platformTools: {
932
+ configuration: true,
933
+ roles: true,
934
+ runScripts: true,
935
+ scripts: true,
936
+ version: true,
937
+ viewScripts: true,
938
+ },
818
939
  schemaVersion: ADMIN_SCHEMA_VERSION,
819
940
  scripts: configScripts,
820
941
  widgetIds: aggregated.widgetIds,
821
942
  };
822
943
 
944
+ const buildAuthorizedConfig = async (user: User | undefined): Promise<AdminConfigResponse> => {
945
+ const authorizedModels = (
946
+ await Promise.all(
947
+ configModels.map(async (modelMeta, index): Promise<AdminModelMeta | null> => {
948
+ const config = modelConfigs[index];
949
+ if (!config) {
950
+ return null;
951
+ }
952
+ const canRead = await checkPermissions(
953
+ "list",
954
+ this.resourceActionPermissions(config, "list"),
955
+ user
956
+ );
957
+ if (!canRead) {
958
+ return null;
959
+ }
960
+ const canCreate =
961
+ modelMeta.permissions.create &&
962
+ (await checkPermissions(
963
+ "create",
964
+ this.resourceActionPermissions(config, "create"),
965
+ user
966
+ ));
967
+ const canDelete =
968
+ modelMeta.permissions.delete &&
969
+ (await checkPermissions(
970
+ "delete",
971
+ this.resourceActionPermissions(config, "delete"),
972
+ user
973
+ ));
974
+ const canUpdate =
975
+ modelMeta.permissions.update &&
976
+ (await checkPermissions(
977
+ "update",
978
+ this.resourceActionPermissions(config, "update"),
979
+ user
980
+ ));
981
+ return {
982
+ ...modelMeta,
983
+ permissions: {create: canCreate, delete: canDelete, update: canUpdate},
984
+ };
985
+ })
986
+ )
987
+ ).filter((model): model is AdminModelMeta => model !== null);
988
+
989
+ const authorizedScreens = (
990
+ await Promise.all(
991
+ mergedScreens.map(async (screen): Promise<AdminCustomScreenConfig | null> => {
992
+ if (!screen.adminAccess) {
993
+ return screen;
994
+ }
995
+ if (screen.adminAccess.authorize) {
996
+ const allowed = await screen.adminAccess.authorize({
997
+ action: screen.adminAccess.action ?? "read",
998
+ user,
999
+ });
1000
+ return allowed ? screen : null;
1001
+ }
1002
+ if (!screen.adminAccess.resource) {
1003
+ return screen;
1004
+ }
1005
+ const allowed = await this.canAnyResourceAction(user, screen.adminAccess.resource, [
1006
+ screen.adminAccess.action ?? "read",
1007
+ ]);
1008
+ return allowed ? screen : null;
1009
+ })
1010
+ )
1011
+ ).filter((screen): screen is AdminCustomScreenConfig => screen !== null);
1012
+
1013
+ const canReadConfiguration = await this.hasConfigurationPermission(user, "read");
1014
+ const canReadRoles = await this.canAnyResourceAction(user, "rbac", ["read"]);
1015
+ const canRunScripts = await this.hasScriptPermission(user, "runScripts");
1016
+ const canViewScripts = await this.hasScriptPermission(user, "viewBackgroundTasks");
1017
+ const canUseScripts = canRunScripts || canViewScripts;
1018
+ return {
1019
+ ...baseConfigResponse,
1020
+ customScreens: authorizedScreens.map(({adminAccess: _adminAccess, ...screen}) => screen),
1021
+ models: authorizedModels,
1022
+ platformTools: {
1023
+ configuration: canReadConfiguration,
1024
+ roles: canReadRoles,
1025
+ runScripts: canRunScripts,
1026
+ scripts: canUseScripts,
1027
+ version: canReadConfiguration,
1028
+ viewScripts: canViewScripts,
1029
+ },
1030
+ scripts: canUseScripts ? configScripts : [],
1031
+ };
1032
+ };
1033
+
823
1034
  const adminConfigOpenApi = openApiMw
824
1035
  ? createOpenApiBuilder({openApi: openApiMw})
825
1036
  .withTags(["admin"])
@@ -847,6 +1058,17 @@ export class AdminApp {
847
1058
  },
848
1059
  home: {type: "object"},
849
1060
  models: {type: "array"},
1061
+ platformTools: {
1062
+ properties: {
1063
+ configuration: {type: "boolean"},
1064
+ roles: {type: "boolean"},
1065
+ runScripts: {type: "boolean"},
1066
+ scripts: {type: "boolean"},
1067
+ version: {type: "boolean"},
1068
+ viewScripts: {type: "boolean"},
1069
+ },
1070
+ type: "object",
1071
+ },
850
1072
  schemaVersion: {type: "number"},
851
1073
  scripts: {
852
1074
  items: {
@@ -879,7 +1101,7 @@ export class AdminApp {
879
1101
  ) {
880
1102
  throw new APIError({status: 403, title: "Admin access required"});
881
1103
  }
882
- return res.json(configResponse);
1104
+ return res.json(await buildAuthorizedConfig(req.user as User | undefined));
883
1105
  })
884
1106
  );
885
1107
 
@@ -1064,7 +1286,7 @@ export class AdminApp {
1064
1286
  if (
1065
1287
  !(await checkPermissions(
1066
1288
  "list",
1067
- this.resourceActionPermissions(config.model.modelName, "list"),
1289
+ this.resourceActionPermissions(config, "list"),
1068
1290
  req.user as User | undefined
1069
1291
  ))
1070
1292
  ) {
@@ -1148,10 +1370,10 @@ export class AdminApp {
1148
1370
  if (allowed === false) {
1149
1371
  return [];
1150
1372
  }
1151
- return this.resourceActionPermissions(config.model.modelName, action);
1373
+ return this.resourceActionPermissions(config, action);
1152
1374
  };
1153
1375
 
1154
- const updatePermissions = this.resourceActionPermissions(config.model.modelName, "update");
1376
+ const updatePermissions = this.resourceActionPermissions(config, "update");
1155
1377
 
1156
1378
  const stripProtectedFromBody = (body: unknown): Record<string, unknown> => {
1157
1379
  if (!body || typeof body !== "object" || Array.isArray(body)) {
@@ -1431,6 +1653,44 @@ export class AdminApp {
1431
1653
  ).terrenoAllowUserAdminWrite = true;
1432
1654
  };
1433
1655
 
1656
+ const addRecordCapabilities = async (
1657
+ value: unknown,
1658
+ request: express.Request
1659
+ ): Promise<JSONValue> => {
1660
+ const scrubbed = scrubAdminResponse(value, config, allModelAdmins);
1661
+ const sourceItems = Array.isArray(value) ? value : [value];
1662
+ const scrubbedItems = Array.isArray(scrubbed) ? scrubbed : [scrubbed];
1663
+ const withCapabilities = await Promise.all(
1664
+ scrubbedItems.map(async (item, index) => {
1665
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
1666
+ return item;
1667
+ }
1668
+ const instance = sourceItems[index];
1669
+ const canUpdate =
1670
+ config.permissions?.update !== false &&
1671
+ (await checkPermissions(
1672
+ "update",
1673
+ this.resourceActionPermissions(config, "update"),
1674
+ request.user as User | undefined,
1675
+ instance
1676
+ ));
1677
+ const canDelete =
1678
+ config.permissions?.delete !== false &&
1679
+ (await checkPermissions(
1680
+ "delete",
1681
+ this.resourceActionPermissions(config, "delete"),
1682
+ request.user as User | undefined,
1683
+ instance
1684
+ ));
1685
+ return {
1686
+ ...(item as Record<string, unknown>),
1687
+ _adminCapabilities: {delete: canDelete, update: canUpdate},
1688
+ };
1689
+ })
1690
+ );
1691
+ return (Array.isArray(scrubbed) ? withCapabilities : withCapabilities[0]) as JSONValue;
1692
+ };
1693
+
1434
1694
  // noExplicitAny: matches the Model<any> from AdminModelConfig above.
1435
1695
  // biome-ignore lint/suspicious/noExplicitAny: matches the Model<any> from AdminModelConfig above.
1436
1696
  const routerOptions: ModelRouterOptions<any> = {
@@ -1463,6 +1723,16 @@ export class AdminApp {
1463
1723
  return body;
1464
1724
  }
1465
1725
  const record = body as Record<string, unknown>;
1726
+ if (
1727
+ !(await checkPermissions(
1728
+ "create",
1729
+ this.resourceActionPermissions(config, "create"),
1730
+ req.user as User | undefined,
1731
+ record
1732
+ ))
1733
+ ) {
1734
+ throw new APIError({status: 403, title: "Admin create access denied"});
1735
+ }
1466
1736
  takePendingUserRoles(record, req);
1467
1737
  await assertCanWriteUserAdminFlag(record, req);
1468
1738
  markAuthorizedUserAdminWrite(record, req);
@@ -1485,8 +1755,8 @@ export class AdminApp {
1485
1755
  searchFields: modelMeta?.searchFields ?? config.searchFields,
1486
1756
  }),
1487
1757
  queryFilter: buildAdminListQueryFilter(config, modelMeta?.searchFields),
1488
- responseHandler: async (value, _method, _request, _options): Promise<JSONValue> =>
1489
- scrubAdminResponse(value, config, allModelAdmins) as JSONValue,
1758
+ responseHandler: async (value, _method, request): Promise<JSONValue> =>
1759
+ addRecordCapabilities(value, request),
1490
1760
  sort: config.defaultSort ?? "-created",
1491
1761
  ...(config.populatePaths ? {populatePaths: config.populatePaths} : {}),
1492
1762
  ...(auditHooks.postDelete ? {postDelete: auditHooks.postDelete} : {}),
@@ -35,6 +35,7 @@ const contributionScriptToConfig = (script: AdminScriptContribution): AdminScrip
35
35
  });
36
36
 
37
37
  const contributionScreenToConfig = (screen: AdminCustomScreen): AdminCustomScreenConfig => ({
38
+ adminAccess: screen.adminAccess,
38
39
  displayName: screen.displayName,
39
40
  name: screen.name,
40
41
  });
package/src/index.ts CHANGED
@@ -28,7 +28,7 @@ export type {
28
28
  AdminOptions,
29
29
  AdminScriptConfig,
30
30
  } from "./adminApp";
31
- export {AdminApp} from "./adminApp";
31
+ export {AdminApp, adminOwnedBy} from "./adminApp";
32
32
  export * from "./adminUiV2";
33
33
  export type {AggregatedAdminContributions} from "./aggregateAdmin";
34
34
  export {
@@ -81,6 +81,7 @@ export const resolvedModelFromAdminConfig = ({
81
81
  return {
82
82
  actions: admin.actions,
83
83
  admin,
84
+ adminAccess: admin.adminAccess,
84
85
  autocompleteFields: admin.autocompleteFields,
85
86
  bulkPatchAllowlist: admin.bulkPatchAllowlist,
86
87
  defaultSort,