@terreno/admin-backend 57.3.0 → 57.6.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 (51) hide show
  1. package/README.md +3 -3
  2. package/bunfig.toml +9 -1
  3. package/dist/adminApp.d.ts +20 -2
  4. package/dist/adminApp.js +1261 -1873
  5. package/dist/adminConfigIdentity.d.ts +1 -0
  6. package/dist/adminConfigIdentity.js +27 -50
  7. package/dist/adminMigrations.d.ts +10 -0
  8. package/dist/adminMigrations.js +120 -0
  9. package/dist/adminScriptJob.d.ts +32 -0
  10. package/dist/adminScriptJob.js +202 -0
  11. package/dist/adminTextSearch.d.ts +1 -0
  12. package/dist/adminTextSearch.js +22 -78
  13. package/dist/adminUiV2.d.ts +2 -0
  14. package/dist/adminUiV2.js +49 -146
  15. package/dist/aggregateAdmin.js +104 -227
  16. package/dist/documentStorageApp.js +184 -325
  17. package/dist/enrichAdminListFilters.d.ts +7 -0
  18. package/dist/enrichAdminListFilters.js +26 -0
  19. package/dist/filterParser.js +230 -183
  20. package/dist/index.d.ts +2 -0
  21. package/dist/index.js +4 -1
  22. package/dist/legacy.js +21 -23
  23. package/dist/resolvedAdminModel.js +23 -78
  24. package/dist/routePath.js +3 -3
  25. package/dist/scriptCli.js +161 -307
  26. package/dist/tests/bunSetup.js +1 -1
  27. package/package.json +10 -10
  28. package/src/adminApp.migrations.test.ts +232 -0
  29. package/src/adminApp.models.test.ts +731 -1
  30. package/src/adminApp.syncMeta.test.ts +237 -0
  31. package/src/adminApp.test.ts +92 -0
  32. package/src/adminApp.ts +373 -130
  33. package/src/adminConfigIdentity.ts +1 -0
  34. package/src/adminHttpGoldens.test.ts +337 -0
  35. package/src/adminMigrations.ts +157 -0
  36. package/src/adminScriptJob.test.ts +297 -0
  37. package/src/adminScriptJob.ts +271 -0
  38. package/src/adminSyncMutationAuthMismatch.test.ts +650 -0
  39. package/src/adminTextSearch.test.ts +28 -0
  40. package/src/adminTextSearch.ts +1 -0
  41. package/src/adminUiV2.ts +2 -0
  42. package/src/aggregateAdmin.test.ts +125 -0
  43. package/src/aggregateAdmin.ts +2 -0
  44. package/src/enrichAdminListFilters.test.ts +44 -0
  45. package/src/enrichAdminListFilters.ts +29 -0
  46. package/src/filterParser.test.ts +95 -0
  47. package/src/filterParser.ts +156 -10
  48. package/src/index.ts +2 -0
  49. package/src/legacy.ts +5 -1
  50. package/src/resolvedAdminModel.ts +2 -1
  51. package/tsconfig.json +6 -21
@@ -1,14 +1,20 @@
1
- import {afterEach, beforeEach, describe, expect, it} from "bun:test";
1
+ import {afterEach, beforeEach, describe, expect, it, spyOn} from "bun:test";
2
2
  import {
3
3
  ADMIN_MODEL_ACCESS,
4
+ AuditApp,
4
5
  addAuthRoutes,
5
6
  apiErrorMiddleware,
6
7
  apiUnauthorizedMiddleware,
7
8
  BackgroundTask,
8
9
  createAccess,
9
10
  findOneOrNoneFor,
11
+ flushAuditRecorderForTests,
12
+ Membership,
10
13
  modelRouter,
14
+ Organization,
15
+ orgScopedPlugin,
11
16
  Permissions,
17
+ resetAuditRecorderForTests,
12
18
  setupAuth,
13
19
  type TerrenoApp,
14
20
  type TerrenoPlugin,
@@ -70,6 +76,40 @@ const enumArraySchema = new mongoose.Schema({
70
76
  const EnumArrayModel =
71
77
  mongoose.models.AdminEnumArray ?? mongoose.model("AdminEnumArray", enumArraySchema);
72
78
 
79
+ const orgScopedFoodSchema = new mongoose.Schema(
80
+ {
81
+ calories: {description: "Calories", type: Number},
82
+ name: {description: "Food name", type: String},
83
+ },
84
+ {strict: "throw"}
85
+ );
86
+ orgScopedFoodSchema.plugin(orgScopedPlugin);
87
+ const OrgScopedFoodModel =
88
+ mongoose.models.AdminOrgScopedFood ?? mongoose.model("AdminOrgScopedFood", orgScopedFoodSchema);
89
+
90
+ const priorityTodoSchema = new mongoose.Schema({
91
+ priority: {enum: ["low", "high"], type: String},
92
+ title: {required: true, type: String},
93
+ });
94
+ const PriorityTodoModel =
95
+ mongoose.models.AdminPriorityTodo ?? mongoose.model("AdminPriorityTodo", priorityTodoSchema);
96
+
97
+ const frameworkRefHolderSchema = new mongoose.Schema({
98
+ organizationId: {
99
+ ref: "TerrenoOrganization",
100
+ type: mongoose.Schema.Types.ObjectId,
101
+ },
102
+ organizationIds: [
103
+ {
104
+ ref: "TerrenoOrganization",
105
+ type: mongoose.Schema.Types.ObjectId,
106
+ },
107
+ ],
108
+ });
109
+ const FrameworkRefHolderModel =
110
+ mongoose.models.AdminFrameworkRefHolder ??
111
+ mongoose.model("AdminFrameworkRefHolder", frameworkRefHolderSchema);
112
+
73
113
  describe("getArrayEmbeddedSchemaType", () => {
74
114
  it("supports the legacy Mongoose 8 caster property", () => {
75
115
  const embeddedSchemaType = new mongoose.Schema({value: String}).path("value");
@@ -282,6 +322,23 @@ describe("AdminApp /admin/config", () => {
282
322
  expect(res.body.models[0].fields.values.itemEnum).toEqual(["alpha", "beta"]);
283
323
  });
284
324
 
325
+ it("accepts enum array values on admin create", async () => {
326
+ const enumApp = buildApp([
327
+ {
328
+ displayName: "Enum arrays",
329
+ listFields: ["values"],
330
+ model: EnumArrayModel,
331
+ routePath: "/enum-arrays",
332
+ },
333
+ ]);
334
+ const enumAgent = await authAsUser(enumApp, "admin");
335
+ const res = await enumAgent
336
+ .post("/admin/enum-arrays")
337
+ .send({values: ["alpha", "beta"]})
338
+ .expect(201);
339
+ expect(res.body.data.values).toEqual(["alpha", "beta"]);
340
+ });
341
+
285
342
  it("extracts itemType and itemRef for arrays of ObjectId references", async () => {
286
343
  const res = await adminAgent.get("/admin/config").expect(200);
287
344
  const [foodMeta] = res.body.models;
@@ -291,6 +348,36 @@ describe("AdminApp /admin/config", () => {
291
348
  expect(foodMeta.fields.eatenBy.itemRef).toBe("User");
292
349
  });
293
350
 
351
+ it("keeps framework model refs aligned with public admin config names", async () => {
352
+ const refApp = buildApp([
353
+ {
354
+ displayName: "Organizations",
355
+ listFields: ["name"],
356
+ model: Organization,
357
+ routePath: "/organizations",
358
+ },
359
+ {
360
+ displayName: "Framework ref holders",
361
+ listFields: ["organizationId", "organizationIds"],
362
+ model: FrameworkRefHolderModel,
363
+ routePath: "/framework-ref-holders",
364
+ },
365
+ ]);
366
+ const refAgent = await authAsUser(refApp, "admin");
367
+ const res = await refAgent.get("/admin/config").expect(200);
368
+ const organizationMeta = res.body.models.find(
369
+ (model: {routePath: string}) => model.routePath === "/admin/organizations"
370
+ );
371
+ const holderMeta = res.body.models.find(
372
+ (model: {routePath: string}) => model.routePath === "/admin/framework-ref-holders"
373
+ );
374
+
375
+ assert.equal(organizationMeta?.name, "Organization");
376
+ assert.equal(holderMeta?.fields.organizationId.ref, "Organization");
377
+ assert.equal(holderMeta?.fields.organizationIds.ref, "Organization");
378
+ assert.equal(holderMeta?.fields.organizationIds.itemRef, "Organization");
379
+ });
380
+
294
381
  it("returns 403 for non-admin users", async () => {
295
382
  const res = await notAdminAgent.get("/admin/config").expect(403);
296
383
  expect(res.body.title).toInclude("Admin access required");
@@ -777,6 +864,7 @@ describe("AdminApp model CRUD routes", () => {
777
864
 
778
865
  afterEach(async () => {
779
866
  await FoodModel.deleteMany({});
867
+ await PriorityTodoModel.deleteMany({});
780
868
  });
781
869
 
782
870
  it("creates documents via POST and strips hidden fields from response", async () => {
@@ -801,6 +889,249 @@ describe("AdminApp model CRUD routes", () => {
801
889
  }
802
890
  });
803
891
 
892
+ it("applies declared multi-choice filters through the admin list route", async () => {
893
+ app = buildApp([
894
+ {
895
+ ...foodModelConfig,
896
+ filters: [
897
+ {
898
+ choices: [
899
+ {label: "Apple", value: "Apple"},
900
+ {label: "Banana", value: "Banana"},
901
+ {label: "Carrot", value: "Carrot"},
902
+ ],
903
+ field: "name",
904
+ kind: "choice",
905
+ },
906
+ ],
907
+ },
908
+ ]);
909
+ const agent = await authAsUser(app, "admin");
910
+ await FoodModel.create({calories: 120, name: "Apple"});
911
+ await FoodModel.create({calories: 95, name: "Banana"});
912
+ await FoodModel.create({calories: 40, name: "Carrot"});
913
+
914
+ const query = new URLSearchParams([
915
+ ["name[$in][0]", "Apple"],
916
+ ["name[$in][1]", "Banana"],
917
+ ]).toString();
918
+ const res = await agent.get(`/admin/foods?${query}`).expect(200);
919
+
920
+ expect(res.body.data.map((item: {name: string}) => item.name).sort()).toEqual([
921
+ "Apple",
922
+ "Banana",
923
+ ]);
924
+ });
925
+
926
+ it("filters optional priority to high only and excludes unset priority", async () => {
927
+ app = buildApp([
928
+ {
929
+ displayName: "Priority todos",
930
+ filters: [
931
+ {
932
+ choices: [
933
+ {label: "High", value: "high"},
934
+ {label: "Low", value: "low"},
935
+ ],
936
+ field: "priority",
937
+ kind: "choice",
938
+ label: "Priority",
939
+ },
940
+ ],
941
+ listFields: ["title", "priority"],
942
+ model: PriorityTodoModel,
943
+ routePath: "/priority-todos",
944
+ },
945
+ ]);
946
+ const agent = await authAsUser(app, "admin");
947
+ await PriorityTodoModel.create({priority: "high", title: "high one"});
948
+ await PriorityTodoModel.create({priority: "low", title: "low one"});
949
+ await PriorityTodoModel.create({title: "unset"});
950
+
951
+ const scalarRes = await agent.get("/admin/priority-todos?priority=high").expect(200);
952
+ expect(scalarRes.body.data.map((item: {title: string}) => item.title)).toEqual(["high one"]);
953
+
954
+ const inRes = await agent
955
+ .get(
956
+ `/admin/priority-todos?${new URLSearchParams([["priority[$in][0]", "high"]]).toString()}`
957
+ )
958
+ .expect(200);
959
+ expect(inRes.body.data.map((item: {title: string}) => item.title)).toEqual(["high one"]);
960
+ });
961
+
962
+ it("filters optional priority empty sentinel to missing or null values", async () => {
963
+ app = buildApp([
964
+ {
965
+ displayName: "Priority todos",
966
+ filters: [
967
+ {
968
+ choices: [
969
+ {label: "High", value: "high"},
970
+ {label: "Low", value: "low"},
971
+ ],
972
+ field: "priority",
973
+ kind: "choice",
974
+ label: "Priority",
975
+ },
976
+ ],
977
+ listFields: ["title", "priority"],
978
+ model: PriorityTodoModel,
979
+ routePath: "/priority-todos",
980
+ },
981
+ ]);
982
+ const agent = await authAsUser(app, "admin");
983
+ await PriorityTodoModel.create({priority: "high", title: "high one"});
984
+ await PriorityTodoModel.create({priority: "low", title: "low one"});
985
+ await PriorityTodoModel.create({title: "unset"});
986
+ await PriorityTodoModel.create({priority: null, title: "null priority"});
987
+
988
+ const query = new URLSearchParams([["priority[$in][0]", "__empty__"]]).toString();
989
+ const res = await agent.get(`/admin/priority-todos?${query}`).expect(200);
990
+ expect(res.body.data.map((item: {title: string}) => item.title).sort()).toEqual([
991
+ "null priority",
992
+ "unset",
993
+ ]);
994
+ });
995
+
996
+ it("combines empty sentinel with concrete priority values", async () => {
997
+ app = buildApp([
998
+ {
999
+ displayName: "Priority todos",
1000
+ filters: [
1001
+ {
1002
+ choices: [
1003
+ {label: "High", value: "high"},
1004
+ {label: "Low", value: "low"},
1005
+ ],
1006
+ field: "priority",
1007
+ kind: "choice",
1008
+ label: "Priority",
1009
+ },
1010
+ ],
1011
+ listFields: ["title", "priority"],
1012
+ model: PriorityTodoModel,
1013
+ routePath: "/priority-todos",
1014
+ },
1015
+ ]);
1016
+ const agent = await authAsUser(app, "admin");
1017
+ await PriorityTodoModel.create({priority: "high", title: "high one"});
1018
+ await PriorityTodoModel.create({priority: "low", title: "low one"});
1019
+ await PriorityTodoModel.create({title: "unset"});
1020
+
1021
+ const query = new URLSearchParams([
1022
+ ["priority[$in][0]", "high"],
1023
+ ["priority[$in][1]", "__empty__"],
1024
+ ]).toString();
1025
+ const res = await agent.get(`/admin/priority-todos?${query}`).expect(200);
1026
+ expect(res.body.data.map((item: {title: string}) => item.title).sort()).toEqual([
1027
+ "high one",
1028
+ "unset",
1029
+ ]);
1030
+ });
1031
+
1032
+ it("filters empty priority with search without leaving the wire sentinel on the query", async () => {
1033
+ app = buildApp([
1034
+ {
1035
+ displayName: "Priority todos",
1036
+ filters: [
1037
+ {
1038
+ choices: [
1039
+ {label: "High", value: "high"},
1040
+ {label: "Low", value: "low"},
1041
+ ],
1042
+ field: "priority",
1043
+ kind: "choice",
1044
+ label: "Priority",
1045
+ },
1046
+ ],
1047
+ listFields: ["title", "priority"],
1048
+ model: PriorityTodoModel,
1049
+ routePath: "/priority-todos",
1050
+ searchFields: ["title"],
1051
+ },
1052
+ ]);
1053
+ const agent = await authAsUser(app, "admin");
1054
+ await PriorityTodoModel.create({priority: "high", title: "alpha task"});
1055
+ await PriorityTodoModel.create({priority: "low", title: "beta task"});
1056
+ await PriorityTodoModel.create({title: "gamma task"});
1057
+ await PriorityTodoModel.create({title: "delta task"});
1058
+ await PriorityTodoModel.create({priority: null, title: "epsilon task"});
1059
+
1060
+ const query = new URLSearchParams([
1061
+ ["priority[$in][0]", "__empty__"],
1062
+ ["q", "task"],
1063
+ ]).toString();
1064
+ const res = await agent.get(`/admin/priority-todos?${query}`).expect(200);
1065
+ expect(res.body.data.map((item: {title: string}) => item.title).sort()).toEqual([
1066
+ "delta task",
1067
+ "epsilon task",
1068
+ "gamma task",
1069
+ ]);
1070
+ });
1071
+
1072
+ it("combines empty and concrete priority filters with search", async () => {
1073
+ app = buildApp([
1074
+ {
1075
+ displayName: "Priority todos",
1076
+ filters: [
1077
+ {
1078
+ choices: [
1079
+ {label: "High", value: "high"},
1080
+ {label: "Low", value: "low"},
1081
+ ],
1082
+ field: "priority",
1083
+ kind: "choice",
1084
+ label: "Priority",
1085
+ },
1086
+ ],
1087
+ listFields: ["title", "priority"],
1088
+ model: PriorityTodoModel,
1089
+ routePath: "/priority-todos",
1090
+ searchFields: ["title"],
1091
+ },
1092
+ ]);
1093
+ const agent = await authAsUser(app, "admin");
1094
+ await PriorityTodoModel.create({priority: "high", title: "alpha task"});
1095
+ await PriorityTodoModel.create({priority: "low", title: "beta task"});
1096
+ await PriorityTodoModel.create({title: "gamma task"});
1097
+ await PriorityTodoModel.create({priority: "high", title: "high hidden"});
1098
+
1099
+ const query = new URLSearchParams([
1100
+ ["priority[$in][0]", "high"],
1101
+ ["priority[$in][1]", "__empty__"],
1102
+ ["q", "task"],
1103
+ ]).toString();
1104
+ const res = await agent.get(`/admin/priority-todos?${query}`).expect(200);
1105
+ expect(res.body.data.map((item: {title: string}) => item.title).sort()).toEqual([
1106
+ "alpha task",
1107
+ "gamma task",
1108
+ ]);
1109
+ });
1110
+
1111
+ it("exposes allowEmpty on optional choice filters in admin config", async () => {
1112
+ app = buildApp([
1113
+ {
1114
+ displayName: "Priority todos",
1115
+ filters: [
1116
+ {
1117
+ choices: [{label: "High", value: "high"}],
1118
+ field: "priority",
1119
+ kind: "choice",
1120
+ },
1121
+ ],
1122
+ listFields: ["title", "priority"],
1123
+ model: PriorityTodoModel,
1124
+ routePath: "/priority-todos",
1125
+ },
1126
+ ]);
1127
+ const agent = await authAsUser(app, "admin");
1128
+ const res = await agent.get("/admin/config").expect(200);
1129
+ const model = res.body.models.find((entry: {routePath: string}) =>
1130
+ entry.routePath.endsWith("/priority-todos")
1131
+ );
1132
+ expect(model.filters[0].allowEmpty).toBe(true);
1133
+ });
1134
+
804
1135
  it("reads a document via GET /:id", async () => {
805
1136
  const food = await FoodModel.create({calories: 120, name: "Apple"});
806
1137
  const res = await adminAgent.get(`/admin/foods/${food._id}`).expect(200);
@@ -1350,6 +1681,220 @@ describe("AdminApp onAdminAudit is best-effort", () => {
1350
1681
  });
1351
1682
  });
1352
1683
 
1684
+ const deleteAuditEventModel = (): void => {
1685
+ if (mongoose.connection.models.TerrenoAuditEvent) {
1686
+ mongoose.connection.deleteModel("TerrenoAuditEvent");
1687
+ }
1688
+ };
1689
+
1690
+ const buildAppWithAuditPlugin = (adminOverrides?: Partial<AdminOptions>): express.Application => {
1691
+ const app = getBaseServer();
1692
+ setupAuth(app, UserModel as unknown as UserModelType);
1693
+ addAuthRoutes(app, UserModel as unknown as UserModelType);
1694
+ new AuditApp().register(app);
1695
+ const admin = new AdminApp({
1696
+ basePath: "/admin",
1697
+ models: [foodModelConfig],
1698
+ ...adminOverrides,
1699
+ });
1700
+ admin.register(app);
1701
+ app.use(apiUnauthorizedMiddleware);
1702
+ app.use(apiErrorMiddleware);
1703
+ return app;
1704
+ };
1705
+
1706
+ describe("AdminApp AuditEvent auto-write", () => {
1707
+ beforeEach(async () => {
1708
+ deleteAuditEventModel();
1709
+ resetAuditRecorderForTests();
1710
+ await setupDb();
1711
+ await mongoose.connection.collection("auditevents").deleteMany({});
1712
+ });
1713
+
1714
+ afterEach(async () => {
1715
+ await FoodModel.deleteMany({});
1716
+ await mongoose.connection.collection("auditevents").deleteMany({});
1717
+ resetAuditRecorderForTests();
1718
+ deleteAuditEventModel();
1719
+ });
1720
+
1721
+ it("persists source admin AuditEvent on POST without onAdminAudit", async () => {
1722
+ const localApp = buildAppWithAuditPlugin();
1723
+ const agent = await authAsUser(localApp, "admin");
1724
+ await agent.post("/admin/foods").send({calories: 5, name: "AuditedFood"}).expect(201);
1725
+ await flushAuditRecorderForTests();
1726
+ const events = await mongoose.connection.collection("auditevents").find({}).toArray();
1727
+ assert.equal(events.length, 1);
1728
+ assert.equal(events[0]?.source, "admin");
1729
+ assert.equal(events[0]?.verb, "created");
1730
+ assert.equal(events[0]?.modelName, "Food");
1731
+ assert.equal(events[0]?.recordLabel, "AuditedFood");
1732
+ });
1733
+
1734
+ it("omits hiddenFields from admin AuditEvent diffs", async () => {
1735
+ const hiddenApp = getBaseServer();
1736
+ setupAuth(hiddenApp, UserModel as unknown as UserModelType);
1737
+ addAuthRoutes(hiddenApp, UserModel as unknown as UserModelType);
1738
+ new AuditApp().register(hiddenApp);
1739
+ new AdminApp({
1740
+ basePath: "/admin",
1741
+ models: [{...foodModelConfig, hiddenFields: ["calories"]}],
1742
+ }).register(hiddenApp);
1743
+ hiddenApp.use(apiUnauthorizedMiddleware);
1744
+ hiddenApp.use(apiErrorMiddleware);
1745
+ const agent = await authAsUser(hiddenApp, "admin");
1746
+ const food = await FoodModel.create({calories: 42, name: "HiddenCals"});
1747
+ await agent.delete(`/admin/foods/${food._id}`).expect(204);
1748
+ await flushAuditRecorderForTests();
1749
+ const events = await mongoose.connection.collection("auditevents").find({}).toArray();
1750
+ assert.equal(events.length, 1);
1751
+ const before = events[0]?.before as Record<string, unknown> | undefined;
1752
+ assert.equal(before?.name, "HiddenCals");
1753
+ assert.isUndefined(before?.calories);
1754
+ });
1755
+
1756
+ it("runs onAdminAudit and persists AuditEvent when both are configured", async () => {
1757
+ const extra: AdminAuditEvent[] = [];
1758
+ const localApp = buildAppWithAuditPlugin({
1759
+ onAdminAudit: async (event): Promise<void> => {
1760
+ extra.push(event);
1761
+ },
1762
+ });
1763
+ const agent = await authAsUser(localApp, "admin");
1764
+ await agent.post("/admin/foods").send({calories: 8, name: "BothSinks"}).expect(201);
1765
+ await flushAuditRecorderForTests();
1766
+ assert.equal(extra.length, 1);
1767
+ assert.equal(extra[0]?.verb, "created");
1768
+ const events = await mongoose.connection.collection("auditevents").find({}).toArray();
1769
+ assert.equal(events.length, 1);
1770
+ assert.equal(events[0]?.source, "admin");
1771
+ });
1772
+
1773
+ it("returns 201 on POST when AuditEvent persistence throws", async () => {
1774
+ const localApp = buildAppWithAuditPlugin();
1775
+ const AuditEvent = mongoose.connection.models.TerrenoAuditEvent;
1776
+ const createSpy = spyOn(AuditEvent, "create").mockImplementation(() => {
1777
+ throw new Error("recorder boom");
1778
+ });
1779
+ const agent = await authAsUser(localApp, "admin");
1780
+ const res = await agent
1781
+ .post("/admin/foods")
1782
+ .send({calories: 5, name: "StillCreated"})
1783
+ .expect(201);
1784
+ await flushAuditRecorderForTests();
1785
+ createSpy.mockRestore();
1786
+ const stored = await FoodModel.findById(res.body.data._id).lean();
1787
+ assert.equal(stored?.name, "StillCreated");
1788
+ });
1789
+
1790
+ it("returns 405 for admin create on AuditEvent when AuditApp is a plugin", async () => {
1791
+ const auditPlugin = new AuditApp();
1792
+ const terrenoApp = {
1793
+ getPlugins: () => [auditPlugin],
1794
+ getRegistrations: () => [],
1795
+ } as unknown as TerrenoApp;
1796
+ const app = getBaseServer();
1797
+ setupAuth(app, UserModel as unknown as UserModelType);
1798
+ addAuthRoutes(app, UserModel as unknown as UserModelType);
1799
+ auditPlugin.register(app);
1800
+ new AdminApp({basePath: "/admin", models: [foodModelConfig]}).register(
1801
+ app,
1802
+ undefined,
1803
+ terrenoApp
1804
+ );
1805
+ app.use(apiUnauthorizedMiddleware);
1806
+ app.use(apiErrorMiddleware);
1807
+ const agent = await authAsUser(app, "admin");
1808
+ const config = await agent.get("/admin/config").expect(200);
1809
+ const auditMeta = (
1810
+ config.body.models as Array<{name: string; permissions: object; routePath: string}>
1811
+ ).find((model) => model.name === "AuditEvent" || model.routePath.includes("audit-events"));
1812
+ assert.ok(
1813
+ auditMeta,
1814
+ JSON.stringify(config.body.models.map((model: {name: string}) => model.name))
1815
+ );
1816
+ assert.equal(auditMeta?.name, "AuditEvent");
1817
+ assert.deepEqual(auditMeta.permissions, {create: false, delete: false, update: false});
1818
+ const create = await agent.post("/admin/audit-events").send({
1819
+ modelName: "Todo",
1820
+ operation: "create",
1821
+ source: "admin",
1822
+ verb: "created",
1823
+ });
1824
+ assert.equal(create.status, 405, JSON.stringify(create.body));
1825
+ });
1826
+
1827
+ it("keeps AuditEvent admin name and adminAuditEvent RBAC after Mongoose rename", async () => {
1828
+ const auditPlugin = new AuditApp();
1829
+ const terrenoApp = {
1830
+ getPlugins: () => [auditPlugin],
1831
+ getRegistrations: () => [],
1832
+ } as unknown as TerrenoApp;
1833
+ const accessControl = createAccess({
1834
+ connection: mongoose.connection,
1835
+ resolvePermissions: async () => ({
1836
+ admin: ["access"],
1837
+ adminAuditEvent: ["list", "read"],
1838
+ }),
1839
+ statements: {
1840
+ ...terrenoStatements,
1841
+ adminAuditEvent: ["list", "read"],
1842
+ },
1843
+ });
1844
+ const app = getBaseServer();
1845
+ setupAuth(app, UserModel as unknown as UserModelType);
1846
+ addAuthRoutes(app, UserModel as unknown as UserModelType);
1847
+ auditPlugin.register(app);
1848
+ new AdminApp({
1849
+ accessControl,
1850
+ basePath: "/admin",
1851
+ models: [foodModelConfig],
1852
+ }).register(app, undefined, terrenoApp);
1853
+ app.use(apiUnauthorizedMiddleware);
1854
+ app.use(apiErrorMiddleware);
1855
+ const agent = await authAsUser(app, "admin");
1856
+ const config = await agent.get("/admin/config").expect(200);
1857
+ const auditMeta = (config.body.models as Array<{name: string; routePath: string}>).find(
1858
+ (model) => model.routePath.includes("audit-events")
1859
+ );
1860
+ assert.equal(auditMeta?.name, "AuditEvent");
1861
+ const list = await agent.get("/admin/audit-events").expect(200);
1862
+ assert.isArray(list.body.data);
1863
+ });
1864
+
1865
+ it("lists AuditEvent without an organization even when organizations is enabled", async () => {
1866
+ const auditPlugin = new AuditApp();
1867
+ const terrenoApp = {
1868
+ getPlugins: () => [auditPlugin],
1869
+ getRegistrations: () => [],
1870
+ } as unknown as TerrenoApp;
1871
+ const app = getBaseServer();
1872
+ setupAuth(app, UserModel as unknown as UserModelType);
1873
+ addAuthRoutes(app, UserModel as unknown as UserModelType);
1874
+ auditPlugin.register(app);
1875
+ new AdminApp({
1876
+ basePath: "/admin",
1877
+ models: [foodModelConfig],
1878
+ organizations: true,
1879
+ }).register(app, undefined, terrenoApp);
1880
+ app.use(apiUnauthorizedMiddleware);
1881
+ app.use(apiErrorMiddleware);
1882
+ const agent = await authAsUser(app, "admin");
1883
+ const config = await agent.get("/admin/config").expect(200);
1884
+ const auditMeta = (
1885
+ config.body.models as Array<{name: string; organizationScoped?: boolean; routePath: string}>
1886
+ ).find((model) => model.name === "AuditEvent" || model.routePath.includes("audit-events"));
1887
+ assert.ok(
1888
+ auditMeta,
1889
+ JSON.stringify(config.body.models.map((model: {name: string}) => model.name))
1890
+ );
1891
+ assert.equal(auditMeta?.name, "AuditEvent");
1892
+ assert.strictEqual(auditMeta?.organizationScoped, false);
1893
+ const list = await agent.get("/admin/audit-events").expect(200);
1894
+ assert.isArray(list.body.data);
1895
+ });
1896
+ });
1897
+
1353
1898
  describe("AdminApp per-model queryFilter", () => {
1354
1899
  beforeEach(async () => {
1355
1900
  await setupDb();
@@ -1514,6 +2059,191 @@ describe("AdminApp per-model queryFilter", () => {
1514
2059
  });
1515
2060
  });
1516
2061
 
2062
+ describe("AdminApp organization scoping", () => {
2063
+ beforeEach(async () => {
2064
+ const [admin] = await setupDb();
2065
+ admin.roles = ["operator"];
2066
+ await admin.save();
2067
+ await Promise.all([
2068
+ Membership.deleteMany({}),
2069
+ Organization.deleteMany({}),
2070
+ OrgScopedFoodModel.deleteMany({}),
2071
+ ]);
2072
+ });
2073
+
2074
+ it("requires org context and scopes list/create when organizations is enabled", async () => {
2075
+ const accessControl = createAccess({
2076
+ connection: mongoose.connection,
2077
+ organizations: true,
2078
+ sources: [
2079
+ {
2080
+ getGrants: async () => ({
2081
+ permissions: {
2082
+ admin: ["access"],
2083
+ adminOrgScopedFood: ["read", "write"],
2084
+ },
2085
+ }),
2086
+ name: "org-scoped-food-admin",
2087
+ },
2088
+ ],
2089
+ statements: {
2090
+ ...terrenoStatements,
2091
+ adminOrgScopedFood: ADMIN_MODEL_ACCESS,
2092
+ },
2093
+ userModel: UserModel as unknown as UserModelType,
2094
+ });
2095
+ await accessControl.roles.seedDefaults();
2096
+ const localApp = buildApp(
2097
+ [
2098
+ {
2099
+ displayName: "Org foods",
2100
+ listFields: ["name", "calories"],
2101
+ model: OrgScopedFoodModel,
2102
+ routePath: "/org-foods",
2103
+ },
2104
+ ],
2105
+ {accessControl, organizations: true}
2106
+ );
2107
+ const agent = await authAsUser(localApp, "admin");
2108
+ const admin = await UserModel.findOne({email: "admin@example.com"}).orFail();
2109
+ const [firstOrg, secondOrg] = await Organization.create([
2110
+ {name: "First Org", ownerId: admin._id},
2111
+ {name: "Second Org", ownerId: admin._id},
2112
+ ]);
2113
+ await OrgScopedFoodModel.create([
2114
+ {calories: 1, name: "First", organizationId: firstOrg._id},
2115
+ {calories: 2, name: "Second", organizationId: secondOrg._id},
2116
+ ]);
2117
+
2118
+ await agent.get("/admin/org-foods").expect(400);
2119
+ const list = await agent
2120
+ .get("/admin/org-foods")
2121
+ .set("X-Organization-Id", String(firstOrg._id))
2122
+ .expect(200);
2123
+ expect(list.body.data).toHaveLength(1);
2124
+ expect(list.body.data[0].name).toBe("First");
2125
+ await agent.get("/admin/org-foods/search?q=Second").expect(400);
2126
+ const search = await agent
2127
+ .get("/admin/org-foods/search?q=Second")
2128
+ .set("X-Organization-Id", String(firstOrg._id))
2129
+ .expect(200);
2130
+ expect(search.body.data).toHaveLength(0);
2131
+ const second = await OrgScopedFoodModel.findOne({name: "Second"}).orFail();
2132
+ await agent
2133
+ .get(`/admin/org-foods/${second._id}`)
2134
+ .set("X-Organization-Id", String(firstOrg._id))
2135
+ .expect(403);
2136
+ await agent
2137
+ .patch(`/admin/org-foods/${second._id}`)
2138
+ .set("X-Organization-Id", String(firstOrg._id))
2139
+ .send({calories: 99})
2140
+ .expect(403);
2141
+ await agent
2142
+ .delete(`/admin/org-foods/${second._id}`)
2143
+ .set("X-Organization-Id", String(firstOrg._id))
2144
+ .expect(403);
2145
+ await agent
2146
+ .post("/admin/org-foods/bulk-patch")
2147
+ .send({ids: [second._id], patch: {calories: 99}})
2148
+ .expect(400);
2149
+ const bulk = await agent
2150
+ .post("/admin/org-foods/bulk-patch")
2151
+ .set("X-Organization-Id", String(firstOrg._id))
2152
+ .send({ids: [second._id], patch: {calories: 99}})
2153
+ .expect(200);
2154
+ expect(bulk.body.updated).toBe(0);
2155
+ expect(bulk.body.failures).toHaveLength(1);
2156
+
2157
+ const created = await agent
2158
+ .post("/admin/org-foods")
2159
+ .set("X-Organization-Id", String(firstOrg._id))
2160
+ .send({calories: 3, name: "Created", organizationId: secondOrg._id})
2161
+ .expect(201);
2162
+ expect(String(created.body.data.organizationId)).toBe(String(firstOrg._id));
2163
+ const stored = await OrgScopedFoodModel.findById(created.body.data._id).lean();
2164
+ expect(String(stored?.organizationId)).toBe(String(firstOrg._id));
2165
+ });
2166
+
2167
+ it("infers a single org-admin membership and denies another organization", async () => {
2168
+ const admin = await UserModel.findOne({email: "admin@example.com"}).orFail();
2169
+ admin.roles = [];
2170
+ await admin.save();
2171
+ const accessControl = createAccess({
2172
+ connection: mongoose.connection,
2173
+ organizations: true,
2174
+ sources: [
2175
+ {
2176
+ getGrants: async () => ({
2177
+ permissions: {
2178
+ admin: ["access"],
2179
+ adminOrgScopedFood: ["read", "write"],
2180
+ },
2181
+ }),
2182
+ name: "org-scoped-food-admin",
2183
+ },
2184
+ ],
2185
+ statements: {
2186
+ ...terrenoStatements,
2187
+ adminOrgScopedFood: ADMIN_MODEL_ACCESS,
2188
+ },
2189
+ userModel: UserModel as unknown as UserModelType,
2190
+ });
2191
+ await accessControl.roles.seedDefaults();
2192
+ const localApp = buildApp(
2193
+ [
2194
+ {
2195
+ displayName: "Org foods",
2196
+ listFields: ["name", "calories"],
2197
+ model: OrgScopedFoodModel,
2198
+ routePath: "/org-foods",
2199
+ },
2200
+ ],
2201
+ {accessControl, organizations: true}
2202
+ );
2203
+ const [firstOrg, secondOrg] = await Organization.create([
2204
+ {name: "Admin Org", ownerId: admin._id},
2205
+ {name: "Other Org", ownerId: admin._id},
2206
+ ]);
2207
+ await Membership.create({
2208
+ organizationId: firstOrg._id,
2209
+ roleName: "org-admin",
2210
+ userId: admin._id,
2211
+ });
2212
+ await OrgScopedFoodModel.create([
2213
+ {calories: 1, name: "Admin row", organizationId: firstOrg._id},
2214
+ {calories: 2, name: "Other row", organizationId: secondOrg._id},
2215
+ ]);
2216
+ const agent = await authAsUser(localApp, "admin");
2217
+
2218
+ const inferred = await agent.get("/admin/org-foods").expect(200);
2219
+ expect(inferred.body.data).toHaveLength(1);
2220
+ expect(inferred.body.data[0].name).toBe("Admin row");
2221
+ await agent.get("/admin/org-foods").set("X-Organization-Id", String(secondOrg._id)).expect(403);
2222
+ });
2223
+
2224
+ it("leaves org-scoped models unscoped when organizations is omitted", async () => {
2225
+ const localApp = buildApp([
2226
+ {
2227
+ displayName: "Org foods",
2228
+ listFields: ["name", "calories"],
2229
+ model: OrgScopedFoodModel,
2230
+ routePath: "/org-foods",
2231
+ },
2232
+ ]);
2233
+ const agent = await authAsUser(localApp, "admin");
2234
+ const admin = await UserModel.findOne({email: "admin@example.com"}).orFail();
2235
+ const organization = await Organization.create({name: "Optional", ownerId: admin._id});
2236
+ await OrgScopedFoodModel.create({
2237
+ calories: 1,
2238
+ name: "Visible",
2239
+ organizationId: organization._id,
2240
+ });
2241
+
2242
+ const list = await agent.get("/admin/org-foods").expect(200);
2243
+ expect(list.body.data).toHaveLength(1);
2244
+ });
2245
+ });
2246
+
1517
2247
  describe("AdminApp user elevation and scoped bulk-patch", () => {
1518
2248
  beforeEach(async () => {
1519
2249
  await setupDb();