@terreno/admin-backend 57.1.0 → 57.3.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,
@@ -9,10 +11,11 @@ import {
9
11
  checkPermissions,
10
12
  createOpenApiBuilder,
11
13
  createScriptArgs,
12
- getOpenApiSpecForModel,
14
+ describeModel,
13
15
  type JSONValue,
14
16
  logger,
15
17
  type ModelRouterOptions,
18
+ modelDescriptionToAdminFields,
16
19
  modelRouter,
17
20
  type OpenApiMiddleware,
18
21
  type PermissionMethod,
@@ -65,6 +68,18 @@ export interface AdminFieldOverride {
65
68
  widget?: string;
66
69
  }
67
70
 
71
+ /**
72
+ * Builds an ownership check for writeOwned admin access. The field may contain an id
73
+ * directly or a populated document with `_id`.
74
+ */
75
+ export const adminOwnedBy = (field: string): NonNullable<AdminAccessConfig["isOwned"]> => {
76
+ return ({instance, user}): boolean => {
77
+ const value = (instance as Record<string, unknown> | undefined)?.[field];
78
+ const ownerId = (value as {_id?: unknown} | undefined)?._id ?? value;
79
+ return ownerId != null && String(ownerId) === String(user.id);
80
+ };
81
+ };
82
+
68
83
  export interface AdminModelConfig {
69
84
  /** The Mongoose model to expose in the admin panel */
70
85
  // noExplicitAny: Model<T> is invariant; the admin panel must accept any document shape.
@@ -110,6 +125,8 @@ export interface AdminModelConfig {
110
125
  populatePaths?: PopulatePath[];
111
126
  /** UI-only hint that live updates may be available */
112
127
  realtime?: boolean;
128
+ /** Fine-grained admin RBAC and optional ownership/custom authorization. */
129
+ adminAccess?: AdminAccessConfig;
113
130
  /**
114
131
  * Field key used for the edit screen title (browser tab / stack header). When omitted, the
115
132
  * admin UI derives a label from common keys (`name`, `title`, …) then the first scalar
@@ -170,6 +187,8 @@ export interface AdminCustomScreenConfig {
170
187
  name: string;
171
188
  /** Optional subtitle or help text shown with the screen card in the admin UI */
172
189
  description?: string;
190
+ /** RBAC or custom authorization for exposing this screen in admin metadata/navigation. */
191
+ adminAccess?: Pick<AdminAccessConfig, "authorize" | "resource"> & {action?: string};
173
192
  }
174
193
 
175
194
  /**
@@ -256,6 +275,14 @@ interface AdminConfigResponse {
256
275
  customScreens?: AdminCustomScreenConfig[];
257
276
  home: ReturnType<typeof normalizeAdminHome>;
258
277
  models: AdminModelMeta[];
278
+ platformTools: {
279
+ configuration: boolean;
280
+ roles: boolean;
281
+ runScripts: boolean;
282
+ scripts: boolean;
283
+ version: boolean;
284
+ viewScripts: boolean;
285
+ };
259
286
  schemaVersion: number;
260
287
  scripts: AdminScriptMeta[];
261
288
  widgetIds: string[];
@@ -434,23 +461,6 @@ const auditActorId = (request: express.Request): string | undefined => {
434
461
  return String(user._id);
435
462
  };
436
463
 
437
- interface OpenApiProperty {
438
- default?: unknown;
439
- description?: string;
440
- enum?: string[];
441
- $ref?: string;
442
- type?: string;
443
- format?: string;
444
- items?: {
445
- properties?: Record<string, OpenApiProperty>;
446
- required?: string[];
447
- type?: string;
448
- enum?: string[];
449
- format?: string;
450
- $ref?: string;
451
- };
452
- }
453
-
454
464
  interface ArraySchemaTypeCompatibility {
455
465
  caster?: mongoose.SchemaType;
456
466
  getEmbeddedSchemaType?: () => mongoose.SchemaType | undefined;
@@ -466,49 +476,14 @@ export const getArrayEmbeddedSchemaType = (
466
476
  return compatiblePath.caster;
467
477
  };
468
478
 
469
- const extractFieldMeta = (
470
- properties: Record<string, OpenApiProperty>,
471
- required: string[]
479
+ const extractFieldMetaFromDescription = (
480
+ model: Model<unknown>,
481
+ hiddenFields: string[]
472
482
  ): Record<string, AdminFieldMeta> => {
473
- const fields: Record<string, AdminFieldMeta> = {};
474
- for (const [key, prop] of Object.entries(properties)) {
475
- const fieldType = prop.type ?? "string";
476
- fields[key] = {
477
- default: prop.default,
478
- description: prop.description,
479
- enum: prop.enum,
480
- ref: prop.$ref ? prop.$ref.replace("#/components/schemas/", "") : undefined,
481
- required: required.includes(key),
482
- searchable: fieldType === "string" && !prop.enum,
483
- type: fieldType,
484
- };
485
-
486
- // For array fields, extract item sub-field metadata
487
- if (prop.type === "array" && prop.items?.properties) {
488
- const itemRequired: string[] = prop.items.required ?? [];
489
- fields[key].items = extractFieldMeta(
490
- prop.items.properties as Record<string, OpenApiProperty>,
491
- itemRequired
492
- );
493
- }
494
-
495
- // For array fields of primitives, capture the item type and enum
496
- if (prop.type === "array" && prop.items && !prop.items.properties) {
497
- const itemProp = prop.items as OpenApiProperty;
498
- if (itemProp.type) {
499
- fields[key].itemType = itemProp.type;
500
- }
501
- if (itemProp.enum) {
502
- fields[key].itemEnum = itemProp.enum;
503
- }
504
- }
505
-
506
- // Check for ObjectId references in the raw property
507
- if (!fields[key].ref && prop.type === "string" && prop.format === "objectid") {
508
- // mongoose-to-swagger may not preserve ref directly; we'll handle this in register()
509
- }
510
- }
511
- return fields;
483
+ const hiddenFieldSet = new Set(hiddenFields);
484
+ const description = describeModel(model);
485
+ const fields = modelDescriptionToAdminFields(description);
486
+ return Object.fromEntries(Object.entries(fields).filter(([key]) => !hiddenFieldSet.has(key)));
512
487
  };
513
488
 
514
489
  const asMiddlewareList = (
@@ -579,7 +554,7 @@ export class AdminApp {
579
554
 
580
555
  private adminAccessPermissions(): PermissionMethod<unknown>[] {
581
556
  if (this.options.accessControl) {
582
- return [this.options.accessControl.permission({admin: ["access"]})];
557
+ return [this.options.accessControl.permission({admin: [ADMIN_PAGE_ACTION]})];
583
558
  }
584
559
  return [Permissions.IsAdmin];
585
560
  }
@@ -612,8 +587,57 @@ export class AdminApp {
612
587
  return result.allowed;
613
588
  }
614
589
 
590
+ private async canAnyResourceAction(
591
+ user: User | undefined,
592
+ resource: string,
593
+ actions: string[],
594
+ instance?: unknown
595
+ ): Promise<boolean> {
596
+ const accessControl = this.options.accessControl;
597
+ if (!accessControl || !user) {
598
+ return Boolean(user?.admin);
599
+ }
600
+ for (const action of actions) {
601
+ const result = await accessControl.can({
602
+ doc: instance,
603
+ permissions: {[resource]: [action]},
604
+ user,
605
+ });
606
+ if (result.allowed) {
607
+ return true;
608
+ }
609
+ }
610
+ return false;
611
+ }
612
+
613
+ private adminResource(config: Pick<AdminModelConfig, "adminAccess" | "model">): string {
614
+ const accessControl = this.options.accessControl;
615
+ const explicit = config.adminAccess?.resource;
616
+ if (explicit) {
617
+ return explicit;
618
+ }
619
+ const standard = `admin${config.model.modelName}`;
620
+ if (accessControl?.statements[standard]) {
621
+ return standard;
622
+ }
623
+ return `${config.model.modelName.charAt(0).toLowerCase()}${config.model.modelName.slice(1)}`;
624
+ }
625
+
626
+ private async isAdminModelOwned(
627
+ config: Pick<AdminModelConfig, "adminAccess">,
628
+ user: User,
629
+ instance: unknown
630
+ ): Promise<boolean> {
631
+ if (config.adminAccess?.isOwned) {
632
+ return config.adminAccess.isOwned({instance, user});
633
+ }
634
+ const owner = (instance as {ownerId?: {_id?: unknown} | unknown} | undefined)?.ownerId;
635
+ const ownerId = (owner as {_id?: unknown} | undefined)?._id ?? owner;
636
+ return ownerId != null && String(ownerId) === String(user.id);
637
+ }
638
+
615
639
  private resourceActionPermissions(
616
- modelName: string,
640
+ config: Pick<AdminModelConfig, "adminAccess" | "model">,
617
641
  action: "list" | "read" | "create" | "update" | "delete"
618
642
  ): PermissionMethod<unknown>[] {
619
643
  const shell = this.adminAccessPermissions();
@@ -621,11 +645,43 @@ export class AdminApp {
621
645
  if (!accessControl) {
622
646
  return shell;
623
647
  }
624
- const resource = `${modelName.charAt(0).toLowerCase()}${modelName.slice(1)}`;
648
+ if (config.adminAccess?.authorize) {
649
+ return [
650
+ ...shell,
651
+ async (_method, user, instance) =>
652
+ config.adminAccess?.authorize?.({action, instance, user}) ?? false,
653
+ ];
654
+ }
655
+ const resource = this.adminResource(config);
625
656
  const knownActions = accessControl.statements[resource];
626
657
  if (!knownActions) {
627
658
  return [];
628
659
  }
660
+ const hasStandardAccess = knownActions.includes("write") || knownActions.includes("writeOwned");
661
+ if (hasStandardAccess) {
662
+ return [
663
+ ...shell,
664
+ async (_method, user, instance) => {
665
+ if (!user) {
666
+ return false;
667
+ }
668
+ if (action === "list" || action === "read") {
669
+ return this.canAnyResourceAction(user, resource, ["read"], instance);
670
+ }
671
+ if (await this.canAnyResourceAction(user, resource, ["write"], instance)) {
672
+ return true;
673
+ }
674
+ if (!(await this.canAnyResourceAction(user, resource, ["writeOwned"], instance))) {
675
+ return false;
676
+ }
677
+ // writeOwned always allows create. Ownership applies to update/delete.
678
+ if (action === "create" || instance === undefined) {
679
+ return true;
680
+ }
681
+ return this.isAdminModelOwned(config, user, instance);
682
+ },
683
+ ];
684
+ }
629
685
  return [...shell, accessControl.permission({[resource]: [action]})];
630
686
  }
631
687
 
@@ -681,55 +737,8 @@ export class AdminApp {
681
737
  }))
682
738
  );
683
739
  const configModels: AdminModelMeta[] = modelConfigs.map((config, configIndex) => {
684
- const {properties, required} = getOpenApiSpecForModel(config.model) as {
685
- properties: Record<string, OpenApiProperty>;
686
- required: string[];
687
- };
688
740
  const hiddenFieldSet = new Set(config.hiddenFields ?? []);
689
- const filteredProperties = Object.fromEntries(
690
- Object.entries(properties).filter(([key]) => !hiddenFieldSet.has(key))
691
- );
692
- const filteredRequired = required.filter((key) => !hiddenFieldSet.has(key));
693
-
694
- // Extract ref information directly from the Mongoose schema
695
- const fields = extractFieldMeta(filteredProperties, filteredRequired);
696
- for (const [key, field] of Object.entries(fields)) {
697
- const schemaPath = config.model.schema.path(key);
698
- if (schemaPath) {
699
- const pathOptions = schemaPath.options;
700
- if (pathOptions?.ref) {
701
- field.ref = pathOptions.ref;
702
- }
703
- // Handle array of refs (legacy: also set ref for back-compat)
704
- if (Array.isArray(pathOptions?.type) && pathOptions.type[0]?.ref) {
705
- field.ref = pathOptions.type[0].ref;
706
- }
707
- // For arrays, use the public embedded schema type to infer the primitive item type/ref.
708
- if (schemaPath.instance === "Array") {
709
- const embeddedSchemaType = getArrayEmbeddedSchemaType(schemaPath);
710
- if (embeddedSchemaType?.instance && !field.items) {
711
- const instanceToType: Record<string, string> = {
712
- Boolean: "boolean",
713
- Number: "number",
714
- ObjectID: "objectid",
715
- ObjectId: "objectid",
716
- SchemaObjectId: "objectid",
717
- String: "string",
718
- };
719
- const mapped = instanceToType[embeddedSchemaType.instance];
720
- if (mapped) {
721
- field.itemType = mapped;
722
- }
723
- if (embeddedSchemaType.options?.ref) {
724
- field.itemRef = embeddedSchemaType.options.ref;
725
- }
726
- if (Array.isArray(embeddedSchemaType.options?.enum)) {
727
- field.itemEnum = embeddedSchemaType.options.enum;
728
- }
729
- }
730
- }
731
- }
732
- }
741
+ const fields = extractFieldMetaFromDescription(config.model, [...hiddenFieldSet]);
733
742
 
734
743
  // Apply field overrides (e.g., widget: "markdown")
735
744
  if (config.fieldOverrides) {
@@ -798,14 +807,12 @@ export class AdminApp {
798
807
  name: script.name,
799
808
  }));
800
809
 
801
- const defaultScreens = [{displayName: "Version Config", name: "version-config"}];
802
- const mergedScreens = [
803
- ...defaultScreens,
810
+ const mergedScreens: AdminCustomScreenConfig[] = [
804
811
  ...aggregated.customScreens,
805
812
  ...(this.options.customScreens ?? []),
806
813
  ];
807
814
 
808
- const configResponse: AdminConfigResponse = {
815
+ const baseConfigResponse: AdminConfigResponse = {
809
816
  capabilities: {
810
817
  actions: true,
811
818
  fieldsets: true,
@@ -815,11 +822,109 @@ export class AdminApp {
815
822
  customScreens: mergedScreens,
816
823
  home: normalizeAdminHome(this.options.home),
817
824
  models: configModels,
825
+ platformTools: {
826
+ configuration: true,
827
+ roles: true,
828
+ runScripts: true,
829
+ scripts: true,
830
+ version: true,
831
+ viewScripts: true,
832
+ },
818
833
  schemaVersion: ADMIN_SCHEMA_VERSION,
819
834
  scripts: configScripts,
820
835
  widgetIds: aggregated.widgetIds,
821
836
  };
822
837
 
838
+ const buildAuthorizedConfig = async (user: User | undefined): Promise<AdminConfigResponse> => {
839
+ const authorizedModels = (
840
+ await Promise.all(
841
+ configModels.map(async (modelMeta, index): Promise<AdminModelMeta | null> => {
842
+ const config = modelConfigs[index];
843
+ if (!config) {
844
+ return null;
845
+ }
846
+ const canRead = await checkPermissions(
847
+ "list",
848
+ this.resourceActionPermissions(config, "list"),
849
+ user
850
+ );
851
+ if (!canRead) {
852
+ return null;
853
+ }
854
+ const canCreate =
855
+ modelMeta.permissions.create &&
856
+ (await checkPermissions(
857
+ "create",
858
+ this.resourceActionPermissions(config, "create"),
859
+ user
860
+ ));
861
+ const canDelete =
862
+ modelMeta.permissions.delete &&
863
+ (await checkPermissions(
864
+ "delete",
865
+ this.resourceActionPermissions(config, "delete"),
866
+ user
867
+ ));
868
+ const canUpdate =
869
+ modelMeta.permissions.update &&
870
+ (await checkPermissions(
871
+ "update",
872
+ this.resourceActionPermissions(config, "update"),
873
+ user
874
+ ));
875
+ return {
876
+ ...modelMeta,
877
+ permissions: {create: canCreate, delete: canDelete, update: canUpdate},
878
+ };
879
+ })
880
+ )
881
+ ).filter((model): model is AdminModelMeta => model !== null);
882
+
883
+ const authorizedScreens = (
884
+ await Promise.all(
885
+ mergedScreens.map(async (screen): Promise<AdminCustomScreenConfig | null> => {
886
+ if (!screen.adminAccess) {
887
+ return screen;
888
+ }
889
+ if (screen.adminAccess.authorize) {
890
+ const allowed = await screen.adminAccess.authorize({
891
+ action: screen.adminAccess.action ?? "read",
892
+ user,
893
+ });
894
+ return allowed ? screen : null;
895
+ }
896
+ if (!screen.adminAccess.resource) {
897
+ return screen;
898
+ }
899
+ const allowed = await this.canAnyResourceAction(user, screen.adminAccess.resource, [
900
+ screen.adminAccess.action ?? "read",
901
+ ]);
902
+ return allowed ? screen : null;
903
+ })
904
+ )
905
+ ).filter((screen): screen is AdminCustomScreenConfig => screen !== null);
906
+
907
+ const canReadConfiguration = await this.hasConfigurationPermission(user, "read");
908
+ const canReadRoles = await this.canAnyResourceAction(user, "rbac", ["read"]);
909
+ const canRunScripts = await this.hasScriptPermission(user, "runScripts");
910
+ const canViewScripts = await this.hasScriptPermission(user, "viewBackgroundTasks");
911
+ const canUseScripts = canRunScripts || canViewScripts;
912
+ return {
913
+ ...baseConfigResponse,
914
+ customScreens: authorizedScreens.map(({adminAccess: _adminAccess, ...screen}) => screen),
915
+ models: authorizedModels,
916
+ platformTools: {
917
+ configuration: canReadConfiguration,
918
+ roles: canReadRoles,
919
+ runScripts: canRunScripts,
920
+ scripts: canUseScripts,
921
+ version: canReadConfiguration,
922
+ viewScripts: canViewScripts,
923
+ },
924
+ scripts: canUseScripts ? configScripts : [],
925
+ };
926
+ };
927
+
823
928
  const adminConfigOpenApi = openApiMw
824
929
  ? createOpenApiBuilder({openApi: openApiMw})
825
930
  .withTags(["admin"])
@@ -847,6 +952,17 @@ export class AdminApp {
847
952
  },
848
953
  home: {type: "object"},
849
954
  models: {type: "array"},
955
+ platformTools: {
956
+ properties: {
957
+ configuration: {type: "boolean"},
958
+ roles: {type: "boolean"},
959
+ runScripts: {type: "boolean"},
960
+ scripts: {type: "boolean"},
961
+ version: {type: "boolean"},
962
+ viewScripts: {type: "boolean"},
963
+ },
964
+ type: "object",
965
+ },
850
966
  schemaVersion: {type: "number"},
851
967
  scripts: {
852
968
  items: {
@@ -879,7 +995,7 @@ export class AdminApp {
879
995
  ) {
880
996
  throw new APIError({status: 403, title: "Admin access required"});
881
997
  }
882
- return res.json(configResponse);
998
+ return res.json(await buildAuthorizedConfig(req.user as User | undefined));
883
999
  })
884
1000
  );
885
1001
 
@@ -1064,7 +1180,7 @@ export class AdminApp {
1064
1180
  if (
1065
1181
  !(await checkPermissions(
1066
1182
  "list",
1067
- this.resourceActionPermissions(config.model.modelName, "list"),
1183
+ this.resourceActionPermissions(config, "list"),
1068
1184
  req.user as User | undefined
1069
1185
  ))
1070
1186
  ) {
@@ -1148,10 +1264,10 @@ export class AdminApp {
1148
1264
  if (allowed === false) {
1149
1265
  return [];
1150
1266
  }
1151
- return this.resourceActionPermissions(config.model.modelName, action);
1267
+ return this.resourceActionPermissions(config, action);
1152
1268
  };
1153
1269
 
1154
- const updatePermissions = this.resourceActionPermissions(config.model.modelName, "update");
1270
+ const updatePermissions = this.resourceActionPermissions(config, "update");
1155
1271
 
1156
1272
  const stripProtectedFromBody = (body: unknown): Record<string, unknown> => {
1157
1273
  if (!body || typeof body !== "object" || Array.isArray(body)) {
@@ -1431,6 +1547,44 @@ export class AdminApp {
1431
1547
  ).terrenoAllowUserAdminWrite = true;
1432
1548
  };
1433
1549
 
1550
+ const addRecordCapabilities = async (
1551
+ value: unknown,
1552
+ request: express.Request
1553
+ ): Promise<JSONValue> => {
1554
+ const scrubbed = scrubAdminResponse(value, config, allModelAdmins);
1555
+ const sourceItems = Array.isArray(value) ? value : [value];
1556
+ const scrubbedItems = Array.isArray(scrubbed) ? scrubbed : [scrubbed];
1557
+ const withCapabilities = await Promise.all(
1558
+ scrubbedItems.map(async (item, index) => {
1559
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
1560
+ return item;
1561
+ }
1562
+ const instance = sourceItems[index];
1563
+ const canUpdate =
1564
+ config.permissions?.update !== false &&
1565
+ (await checkPermissions(
1566
+ "update",
1567
+ this.resourceActionPermissions(config, "update"),
1568
+ request.user as User | undefined,
1569
+ instance
1570
+ ));
1571
+ const canDelete =
1572
+ config.permissions?.delete !== false &&
1573
+ (await checkPermissions(
1574
+ "delete",
1575
+ this.resourceActionPermissions(config, "delete"),
1576
+ request.user as User | undefined,
1577
+ instance
1578
+ ));
1579
+ return {
1580
+ ...(item as Record<string, unknown>),
1581
+ _adminCapabilities: {delete: canDelete, update: canUpdate},
1582
+ };
1583
+ })
1584
+ );
1585
+ return (Array.isArray(scrubbed) ? withCapabilities : withCapabilities[0]) as JSONValue;
1586
+ };
1587
+
1434
1588
  // noExplicitAny: matches the Model<any> from AdminModelConfig above.
1435
1589
  // biome-ignore lint/suspicious/noExplicitAny: matches the Model<any> from AdminModelConfig above.
1436
1590
  const routerOptions: ModelRouterOptions<any> = {
@@ -1463,6 +1617,16 @@ export class AdminApp {
1463
1617
  return body;
1464
1618
  }
1465
1619
  const record = body as Record<string, unknown>;
1620
+ if (
1621
+ !(await checkPermissions(
1622
+ "create",
1623
+ this.resourceActionPermissions(config, "create"),
1624
+ req.user as User | undefined,
1625
+ record
1626
+ ))
1627
+ ) {
1628
+ throw new APIError({status: 403, title: "Admin create access denied"});
1629
+ }
1466
1630
  takePendingUserRoles(record, req);
1467
1631
  await assertCanWriteUserAdminFlag(record, req);
1468
1632
  markAuthorizedUserAdminWrite(record, req);
@@ -1485,8 +1649,8 @@ export class AdminApp {
1485
1649
  searchFields: modelMeta?.searchFields ?? config.searchFields,
1486
1650
  }),
1487
1651
  queryFilter: buildAdminListQueryFilter(config, modelMeta?.searchFields),
1488
- responseHandler: async (value, _method, _request, _options): Promise<JSONValue> =>
1489
- scrubAdminResponse(value, config, allModelAdmins) as JSONValue,
1652
+ responseHandler: async (value, _method, request): Promise<JSONValue> =>
1653
+ addRecordCapabilities(value, request),
1490
1654
  sort: config.defaultSort ?? "-created",
1491
1655
  ...(config.populatePaths ? {populatePaths: config.populatePaths} : {}),
1492
1656
  ...(auditHooks.postDelete ? {postDelete: auditHooks.postDelete} : {}),
@@ -1,6 +1,12 @@
1
1
  import {describe, expect, it} from "bun:test";
2
2
 
3
- import {buildAdminModelQueryFields} from "./adminUiV2";
3
+ import {
4
+ buildAdminModelQueryFields,
5
+ defaultBulkPatchAllowlistFrom,
6
+ normalizeAdminHome,
7
+ normalizeSidebarRecentLast,
8
+ SYSTEM_ADMIN_FIELDS,
9
+ } from "./adminUiV2";
4
10
 
5
11
  describe("buildAdminModelQueryFields", () => {
6
12
  it("includes _id, list fields, listDisplay, searchFields, and filter fields", () => {
@@ -27,3 +33,67 @@ describe("buildAdminModelQueryFields", () => {
27
33
  expect(new Set(fields).size).toBe(fields.length);
28
34
  });
29
35
  });
36
+
37
+ describe("normalizeSidebarRecentLast", () => {
38
+ it("returns empty and missing sidebars unchanged", () => {
39
+ expect(normalizeSidebarRecentLast(undefined)).toBeUndefined();
40
+ expect(normalizeSidebarRecentLast([])).toEqual([]);
41
+ });
42
+
43
+ it("leaves a sidebar without recentActivity as-is", () => {
44
+ expect(normalizeSidebarRecentLast(["modelsGrid"])).toEqual(["modelsGrid"]);
45
+ });
46
+
47
+ it("moves recentActivity to the end", () => {
48
+ expect(normalizeSidebarRecentLast(["recentActivity", "modelsGrid"])).toEqual([
49
+ "modelsGrid",
50
+ "recentActivity",
51
+ ]);
52
+ });
53
+ });
54
+
55
+ describe("normalizeAdminHome", () => {
56
+ it("defaults to modelsGrid when home is omitted", () => {
57
+ expect(normalizeAdminHome()).toEqual({
58
+ slots: {main: ["modelsGrid"]},
59
+ title: "Administration",
60
+ });
61
+ });
62
+
63
+ it("uses provided slots and normalizes the sidebar", () => {
64
+ expect(
65
+ normalizeAdminHome({
66
+ slots: {sidebar: ["recentActivity", "nav"]},
67
+ title: "Ops",
68
+ })
69
+ ).toEqual({
70
+ slots: {sidebar: ["nav", "recentActivity"]},
71
+ title: "Ops",
72
+ });
73
+ });
74
+
75
+ it("promotes legacy widgets into main and prepends modelsGrid when missing", () => {
76
+ expect(normalizeAdminHome({widgets: ["recentActivity"]})).toEqual({
77
+ slots: {main: ["modelsGrid", "recentActivity"]},
78
+ title: "Administration",
79
+ });
80
+ expect(normalizeAdminHome({widgets: ["modelsGrid", "recentActivity"]})).toEqual({
81
+ slots: {main: ["modelsGrid", "recentActivity"]},
82
+ title: "Administration",
83
+ });
84
+ });
85
+ });
86
+
87
+ describe("defaultBulkPatchAllowlistFrom", () => {
88
+ it("keeps writable schema fields from the list", () => {
89
+ expect(
90
+ defaultBulkPatchAllowlistFrom({
91
+ hiddenFieldSet: new Set(["secret"]),
92
+ listFields: ["_id", "title", "secret", "created", "notes"],
93
+ readonlyFields: ["notes"],
94
+ schemaPaths: new Set(["title", "secret", "notes"]),
95
+ })
96
+ ).toEqual(["title"]);
97
+ expect(SYSTEM_ADMIN_FIELDS.has("_id")).toBe(true);
98
+ });
99
+ });
@@ -7,7 +7,7 @@ import type {
7
7
  TerrenoApp,
8
8
  TerrenoPlugin,
9
9
  } from "@terreno/api";
10
- import {logger} from "@terreno/api";
10
+ import {APIError, logger} from "@terreno/api";
11
11
 
12
12
  import type {AdminCustomScreenConfig, AdminModelConfig, AdminScriptConfig} from "./adminApp";
13
13
  import {convertLegacyModelConfig} from "./legacy";
@@ -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
  });
@@ -132,9 +133,10 @@ export const aggregateAdminContributions = ({
132
133
  const path = registered.routePath;
133
134
  const existingRegistered = registeredByPath.get(path);
134
135
  if (existingRegistered) {
135
- throw new Error(
136
- `Duplicate admin modelRouter routePath "${path}" (${existingRegistered.sourceLabel} and ${registered.sourceLabel})`
137
- );
136
+ throw new APIError({
137
+ status: 500,
138
+ title: `Duplicate admin modelRouter routePath "${path}" (${existingRegistered.sourceLabel} and ${registered.sourceLabel})`,
139
+ });
138
140
  }
139
141
  registeredByPath.set(path, registered);
140
142
  const existing = modelsByPath.get(path);
@@ -192,9 +192,7 @@ export class DocumentStorageApp implements TerrenoPlugin {
192
192
  app.post(
193
193
  `${basePath}/`,
194
194
  ...adminGuard,
195
- // noExplicitAny: multer's RequestHandler type is incompatible with Express 5's middleware signature.
196
- // biome-ignore lint/suspicious/noExplicitAny: multer's RequestHandler type is incompatible with Express 5's middleware signature.
197
- upload.single("file") as any,
195
+ upload.single("file") as unknown as express.RequestHandler,
198
196
  asyncHandler(async (req: express.Request, res: express.Response) => {
199
197
  const file = (req as unknown as {file?: Express.Multer.File}).file;
200
198
  if (!file) {