@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
package/dist/adminApp.js CHANGED
@@ -1,264 +1,174 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
- var __rest = (this && this.__rest) || function (s, e) {
50
- var t = {};
51
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
52
- t[p] = s[p];
53
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
54
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
55
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
56
- t[p[i]] = s[p[i]];
57
- }
58
- return t;
59
- };
60
- var __values = (this && this.__values) || function(o) {
61
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
62
- if (m) return m.call(o);
63
- if (o && typeof o.length === "number") return {
64
- next: function () {
65
- if (o && i >= o.length) o = void 0;
66
- return { value: o && o[i++], done: !o };
67
- }
68
- };
69
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
70
- };
71
- var __read = (this && this.__read) || function (o, n) {
72
- var m = typeof Symbol === "function" && o[Symbol.iterator];
73
- if (!m) return o;
74
- var i = m.call(o), r, ar = [], e;
75
- try {
76
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
77
- }
78
- catch (error) { e = { error: error }; }
79
- finally {
80
- try {
81
- if (r && !r.done && (m = i["return"])) m.call(i);
82
- }
83
- finally { if (e) throw e.error; }
84
- }
85
- return ar;
86
- };
87
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
88
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
89
- if (ar || !(i in from)) {
90
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
91
- ar[i] = from[i];
92
- }
93
- }
94
- return to.concat(ar || Array.prototype.slice.call(from));
95
- };
96
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
97
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
98
4
  };
99
5
  Object.defineProperty(exports, "__esModule", { value: true });
100
6
  exports.AdminApp = exports.getArrayEmbeddedSchemaType = exports.adminOwnedBy = void 0;
101
- var api_1 = require("@terreno/api");
102
- var express_1 = __importDefault(require("express"));
103
- var luxon_1 = require("luxon");
104
- var mongoose_1 = __importDefault(require("mongoose"));
105
- var adminConfigIdentity_1 = require("./adminConfigIdentity");
106
- var adminTextSearch_1 = require("./adminTextSearch");
107
- var adminUiV2_1 = require("./adminUiV2");
108
- var aggregateAdmin_1 = require("./aggregateAdmin");
109
- var filterParser_1 = require("./filterParser");
110
- var scriptCli_1 = require("./scriptCli");
7
+ const api_1 = require("@terreno/api");
8
+ const jobs_1 = require("@terreno/jobs");
9
+ const express_1 = __importDefault(require("express"));
10
+ const luxon_1 = require("luxon");
11
+ const mongoose_1 = __importDefault(require("mongoose"));
12
+ const adminConfigIdentity_1 = require("./adminConfigIdentity");
13
+ const adminMigrations_1 = require("./adminMigrations");
14
+ const adminScriptJob_1 = require("./adminScriptJob");
15
+ const adminTextSearch_1 = require("./adminTextSearch");
16
+ const adminUiV2_1 = require("./adminUiV2");
17
+ const aggregateAdmin_1 = require("./aggregateAdmin");
18
+ const filterParser_1 = require("./filterParser");
19
+ const scriptCli_1 = require("./scriptCli");
20
+ const AUDIT_EVENT_MODEL_NAMES = new Set(["AuditEvent", "TerrenoAuditEvent"]);
111
21
  /**
112
22
  * Builds an ownership check for writeOwned admin access. The field may contain an id
113
23
  * directly or a populated document with `_id`.
114
24
  */
115
- var adminOwnedBy = function (field) {
116
- return function (_a) {
117
- var _b;
118
- var instance = _a.instance, user = _a.user;
119
- var value = instance === null || instance === void 0 ? void 0 : instance[field];
120
- var ownerId = (_b = value === null || value === void 0 ? void 0 : value._id) !== null && _b !== void 0 ? _b : value;
25
+ const adminOwnedBy = (field) => {
26
+ return ({ instance, user }) => {
27
+ const value = instance?.[field];
28
+ const ownerId = value?._id ?? value;
121
29
  return ownerId != null && String(ownerId) === String(user.id);
122
30
  };
123
31
  };
124
32
  exports.adminOwnedBy = adminOwnedBy;
125
- var buildAllModelAdminsMap = function (models) {
126
- var e_1, _a;
127
- var map = {};
128
- try {
129
- for (var models_1 = __values(models), models_1_1 = models_1.next(); !models_1_1.done; models_1_1 = models_1.next()) {
130
- var config = models_1_1.value;
131
- map[config.model.modelName] = config.admin;
132
- }
33
+ const publicFrameworkFieldMeta = (field) => {
34
+ return {
35
+ ...field,
36
+ ...(field.ref ? { ref: (0, api_1.publicFrameworkModelName)(field.ref) } : {}),
37
+ ...(field.itemRef ? { itemRef: (0, api_1.publicFrameworkModelName)(field.itemRef) } : {}),
38
+ ...(field.items
39
+ ? {
40
+ items: Object.fromEntries(Object.entries(field.items).map(([key, item]) => [key, publicFrameworkFieldMeta(item)])),
41
+ }
42
+ : {}),
43
+ };
44
+ };
45
+ const syncMetaForAdminModel = (modelName, isOrganizationScoped = false) => {
46
+ if (isOrganizationScoped) {
47
+ return { adminBroadcast: false };
133
48
  }
134
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
135
- finally {
136
- try {
137
- if (models_1_1 && !models_1_1.done && (_a = models_1.return)) _a.call(models_1);
138
- }
139
- finally { if (e_1) throw e_1.error; }
49
+ const entry = (0, api_1.findSyncEntryByModelName)(modelName);
50
+ if (entry?.config.adminBroadcast !== true) {
51
+ return { adminBroadcast: false };
52
+ }
53
+ return { adminBroadcast: true, syncCollection: entry.collectionTag };
54
+ };
55
+ const disableOrgScopedAdminBroadcastSync = (modelName) => {
56
+ const syncEntry = (0, api_1.findSyncEntryByModelName)(modelName);
57
+ if (syncEntry?.config.adminBroadcast !== true) {
58
+ return;
59
+ }
60
+ (0, api_1.updateSyncRegistryOptions)(syncEntry.routePath, {
61
+ ...syncEntry.options,
62
+ sync: {
63
+ ...syncEntry.config,
64
+ adminBroadcast: false,
65
+ },
66
+ });
67
+ };
68
+ const buildAllModelAdminsMap = (models) => {
69
+ const map = {};
70
+ for (const config of models) {
71
+ map[config.model.modelName] = config.admin;
140
72
  }
141
73
  return map;
142
74
  };
143
- var scrubAdminResponse = function (value, config, allModelAdmins) {
75
+ const scrubAdminResponse = (value, config, allModelAdmins) => {
144
76
  return (0, api_1.scrubAdminFields)(value, {
145
77
  admin: config.admin,
146
- allModelAdmins: allModelAdmins,
78
+ allModelAdmins,
147
79
  schema: config.model.schema,
148
80
  });
149
81
  };
150
- var buildAdminListQueryFilter = function (config,
82
+ const buildAdminListQueryFilter = (config,
151
83
  /** Resolved (possibly derived) search fields from `/admin/config`, not just explicit config. */
152
- resolvedSearchFields) {
153
- var _a;
154
- var base = config.queryFilter;
155
- var searchFields = (_a = resolvedSearchFields !== null && resolvedSearchFields !== void 0 ? resolvedSearchFields : config.searchFields) !== null && _a !== void 0 ? _a : [];
156
- return function (user, query) { return __awaiter(void 0, void 0, void 0, function () {
157
- var clientQuery, _a, consumedKeys, errors, filter, consumedKeys_1, consumedKeys_1_1, key, rawSearch, searchClause, merged, baseResult, result;
158
- var e_2, _b, _c;
159
- var _d;
160
- return __generator(this, function (_e) {
161
- switch (_e.label) {
162
- case 0:
163
- clientQuery = __assign({}, (query !== null && query !== void 0 ? query : {}));
164
- _a = (0, filterParser_1.parseAdminListFilters)(clientQuery, (_d = config.filters) !== null && _d !== void 0 ? _d : []), consumedKeys = _a.consumedKeys, errors = _a.errors, filter = _a.filter;
165
- if (Object.keys(errors).length > 0) {
166
- throw new api_1.APIError({
167
- detail: JSON.stringify(errors),
168
- status: 400,
169
- title: "Invalid filter",
170
- });
171
- }
172
- try {
173
- for (consumedKeys_1 = __values(consumedKeys), consumedKeys_1_1 = consumedKeys_1.next(); !consumedKeys_1_1.done; consumedKeys_1_1 = consumedKeys_1.next()) {
174
- key = consumedKeys_1_1.value;
175
- delete clientQuery[key];
176
- }
177
- }
178
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
179
- finally {
180
- try {
181
- if (consumedKeys_1_1 && !consumedKeys_1_1.done && (_b = consumedKeys_1.return)) _b.call(consumedKeys_1);
182
- }
183
- finally { if (e_2) throw e_2.error; }
184
- }
185
- rawSearch = clientQuery[adminTextSearch_1.ADMIN_LIST_SEARCH_PARAM];
186
- delete clientQuery[adminTextSearch_1.ADMIN_LIST_SEARCH_PARAM];
187
- searchClause = typeof rawSearch === "string"
188
- ? (0, adminTextSearch_1.buildAdminPartialSearchFilter)({
189
- model: config.model,
190
- q: rawSearch,
191
- searchFields: searchFields,
192
- })
193
- : undefined;
194
- merged = __assign(__assign({}, clientQuery), filter);
195
- if (!base) return [3 /*break*/, 2];
196
- return [4 /*yield*/, base(user, merged)];
197
- case 1:
198
- baseResult = _e.sent();
199
- if (baseResult === null) {
200
- return [2 /*return*/, null];
201
- }
202
- merged = __assign(__assign({}, merged), baseResult);
203
- _e.label = 2;
204
- case 2:
205
- result = (0, adminTextSearch_1.andMongoFilters)(merged, searchClause);
206
- return [2 /*return*/, __assign(__assign({}, result), (_c = {}, _c[adminTextSearch_1.ADMIN_LIST_SEARCH_PARAM] = undefined, _c))];
84
+ resolvedSearchFields, isOrganizationScoped = false) => {
85
+ const base = config.queryFilter;
86
+ const searchFields = resolvedSearchFields ?? config.searchFields ?? [];
87
+ return async (user, query) => {
88
+ const clientQuery = { ...(query ?? {}) };
89
+ const { consumedKeys, errors, filter } = (0, filterParser_1.parseAdminListFilters)(clientQuery, config.filters ?? []);
90
+ if (Object.keys(errors).length > 0) {
91
+ throw new api_1.APIError({
92
+ detail: JSON.stringify(errors),
93
+ status: 400,
94
+ title: "Invalid filter",
95
+ });
96
+ }
97
+ for (const key of consumedKeys) {
98
+ delete clientQuery[key];
99
+ }
100
+ const rawSearch = clientQuery[adminTextSearch_1.ADMIN_LIST_SEARCH_PARAM];
101
+ delete clientQuery[adminTextSearch_1.ADMIN_LIST_SEARCH_PARAM];
102
+ const searchClause = typeof rawSearch === "string"
103
+ ? (0, adminTextSearch_1.buildAdminPartialSearchFilter)({
104
+ model: config.model,
105
+ q: rawSearch,
106
+ searchFields,
107
+ })
108
+ : undefined;
109
+ let merged = { ...clientQuery, ...filter };
110
+ if (base) {
111
+ const baseResult = await base(user, merged);
112
+ if (baseResult === null) {
113
+ return null;
207
114
  }
208
- });
209
- }); };
115
+ merged = { ...merged, ...baseResult };
116
+ }
117
+ if (isOrganizationScoped) {
118
+ merged = { ...merged, ...(0, api_1.OrgQueryFilter)(user, merged) };
119
+ }
120
+ const result = (0, adminTextSearch_1.andMongoFilters)(merged, searchClause);
121
+ const overrides = { ...filter };
122
+ for (const key of consumedKeys) {
123
+ if (!(key in overrides)) {
124
+ overrides[key] = undefined;
125
+ }
126
+ }
127
+ return { ...result, ...overrides, [adminTextSearch_1.ADMIN_LIST_SEARCH_PARAM]: undefined };
128
+ };
210
129
  };
211
- var ADMIN_TIMESTAMP_SORT_FIELDS = ["created", "createdAt", "updated", "updatedAt"];
212
- var sortTokensToFields = function (sort) {
130
+ const ADMIN_TIMESTAMP_SORT_FIELDS = ["created", "createdAt", "updated", "updatedAt"];
131
+ const sortTokensToFields = (sort) => {
213
132
  if (!sort) {
214
133
  return [];
215
134
  }
216
- var raw = Array.isArray(sort) ? sort.join(" ") : sort;
135
+ const raw = Array.isArray(sort) ? sort.join(" ") : sort;
217
136
  return raw
218
137
  .trim()
219
138
  .split(/\s+/)
220
- .map(function (token) { return token.replace(/^-/, ""); })
221
- .filter(function (field) { return field.length > 0; });
139
+ .map((token) => token.replace(/^-/, ""))
140
+ .filter((field) => field.length > 0);
222
141
  };
223
- var resolveAdminSortableFields = function (_a) {
224
- var defaultSort = _a.defaultSort, listDisplay = _a.listDisplay, sortableFields = _a.sortableFields;
225
- return __spreadArray([], __read(new Set(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read((sortableFields !== null && sortableFields !== void 0 ? sortableFields : listDisplay)), false), [
226
- "_id"
227
- ], false), __read(ADMIN_TIMESTAMP_SORT_FIELDS), false), __read(sortTokensToFields(defaultSort)), false))), false);
142
+ const resolveAdminSortableFields = ({ defaultSort, listDisplay, sortableFields, }) => {
143
+ return [
144
+ ...new Set([
145
+ ...(sortableFields ?? listDisplay),
146
+ "_id",
147
+ ...ADMIN_TIMESTAMP_SORT_FIELDS,
148
+ ...sortTokensToFields(defaultSort),
149
+ ]),
150
+ ];
228
151
  };
229
- var validateAdminSortParam = function (sortableFields) {
230
- return function (req, _res, next) {
231
- var e_3, _a;
232
- var sort = req.query.sort;
233
- if (typeof sort !== "string" || !sort.trim()) {
234
- next();
235
- return;
236
- }
237
- var tokens = sort.trim().split(/\s+/);
238
- try {
239
- for (var tokens_1 = __values(tokens), tokens_1_1 = tokens_1.next(); !tokens_1_1.done; tokens_1_1 = tokens_1.next()) {
240
- var token = tokens_1_1.value;
241
- var field = token.replace(/^-/, "");
242
- if (!sortableFields.includes(field)) {
243
- throw new api_1.APIError({
244
- detail: field,
245
- status: 400,
246
- title: "Invalid sort field",
247
- });
248
- }
249
- }
250
- }
251
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
252
- finally {
253
- try {
254
- if (tokens_1_1 && !tokens_1_1.done && (_a = tokens_1.return)) _a.call(tokens_1);
255
- }
256
- finally { if (e_3) throw e_3.error; }
257
- }
152
+ const validateAdminSortParam = (sortableFields) => (req, _res, next) => {
153
+ const sort = req.query.sort;
154
+ if (typeof sort !== "string" || !sort.trim()) {
258
155
  next();
259
- };
156
+ return;
157
+ }
158
+ const tokens = sort.trim().split(/\s+/);
159
+ for (const token of tokens) {
160
+ const field = token.replace(/^-/, "");
161
+ if (!sortableFields.includes(field)) {
162
+ throw new api_1.APIError({
163
+ detail: field,
164
+ status: 400,
165
+ title: "Invalid sort field",
166
+ });
167
+ }
168
+ }
169
+ next();
260
170
  };
261
- var auditDocumentToPlain = function (value) {
171
+ const auditDocumentToPlain = (value) => {
262
172
  if (value &&
263
173
  typeof value === "object" &&
264
174
  "toObject" in value &&
@@ -267,29 +177,18 @@ var auditDocumentToPlain = function (value) {
267
177
  }
268
178
  return value;
269
179
  };
270
- var auditLabelFromListFields = function (doc, listFields) {
271
- var e_4, _a;
272
- try {
273
- for (var listFields_1 = __values(listFields), listFields_1_1 = listFields_1.next(); !listFields_1_1.done; listFields_1_1 = listFields_1.next()) {
274
- var key = listFields_1_1.value;
275
- var fieldValue = doc[key];
276
- if (fieldValue == null || typeof fieldValue === "object") {
277
- continue;
278
- }
279
- return String(fieldValue);
280
- }
281
- }
282
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
283
- finally {
284
- try {
285
- if (listFields_1_1 && !listFields_1_1.done && (_a = listFields_1.return)) _a.call(listFields_1);
180
+ const auditLabelFromListFields = (doc, listFields) => {
181
+ for (const key of listFields) {
182
+ const fieldValue = doc[key];
183
+ if (fieldValue == null || typeof fieldValue === "object") {
184
+ continue;
286
185
  }
287
- finally { if (e_4) throw e_4.error; }
186
+ return String(fieldValue);
288
187
  }
289
- var id = doc._id;
188
+ const id = doc._id;
290
189
  return id != null ? String(id) : undefined;
291
190
  };
292
- var coerceAdminFlag = function (value) {
191
+ const coerceAdminFlag = (value) => {
293
192
  if (value === true || value === 1 || value === "1" || value === "true" || value === "yes") {
294
193
  return true;
295
194
  }
@@ -304,31 +203,25 @@ var coerceAdminFlag = function (value) {
304
203
  }
305
204
  throw new api_1.APIError({ status: 400, title: "admin must be a boolean" });
306
205
  };
307
- var auditActorId = function (request) {
308
- var user = request.user;
309
- if (!user || user._id == null) {
310
- return undefined;
311
- }
312
- return String(user._id);
313
- };
314
- var getArrayEmbeddedSchemaType = function (schemaPath) {
315
- var compatiblePath = schemaPath;
206
+ const auditActorId = api_1.auditActorIdFromRequest;
207
+ /** @internal */
208
+ const getArrayEmbeddedSchemaType = (schemaPath) => {
209
+ const compatiblePath = schemaPath;
316
210
  if (typeof compatiblePath.getEmbeddedSchemaType === "function") {
317
211
  return compatiblePath.getEmbeddedSchemaType();
318
212
  }
319
213
  return compatiblePath.caster;
320
214
  };
321
215
  exports.getArrayEmbeddedSchemaType = getArrayEmbeddedSchemaType;
322
- var extractFieldMetaFromDescription = function (model, hiddenFields) {
323
- var hiddenFieldSet = new Set(hiddenFields);
324
- var description = (0, api_1.describeModel)(model);
325
- var fields = (0, api_1.modelDescriptionToAdminFields)(description);
326
- return Object.fromEntries(Object.entries(fields).filter(function (_a) {
327
- var _b = __read(_a, 1), key = _b[0];
328
- return !hiddenFieldSet.has(key);
329
- }));
216
+ const extractFieldMetaFromDescription = (model, hiddenFields) => {
217
+ const hiddenFieldSet = new Set(hiddenFields);
218
+ const description = (0, api_1.describeModel)(model);
219
+ const fields = (0, api_1.modelDescriptionToAdminFields)(description);
220
+ return Object.fromEntries(Object.entries(fields)
221
+ .filter(([key]) => !hiddenFieldSet.has(key))
222
+ .map(([key, field]) => [key, publicFrameworkFieldMeta(field)]));
330
223
  };
331
- var asMiddlewareList = function (middleware) {
224
+ const asMiddlewareList = (middleware) => {
332
225
  if (middleware === undefined) {
333
226
  return [];
334
227
  }
@@ -379,193 +272,141 @@ var asMiddlewareList = function (middleware) {
379
272
  * @see AdminModelConfig for model configuration
380
273
  * @see TerrenoPlugin for the plugin interface
381
274
  */
382
- var AdminApp = /** @class */ (function () {
275
+ class AdminApp {
276
+ options;
383
277
  /**
384
278
  * Create a new AdminApp plugin.
385
279
  *
386
280
  * @param options - Admin panel configuration including models and base path
387
281
  */
388
- function AdminApp(options) {
282
+ constructor(options) {
389
283
  this.options = options;
390
284
  }
391
- AdminApp.prototype.adminAccessPermissions = function () {
285
+ isOrganizationScoped(config) {
286
+ if (!this.options.organizations) {
287
+ return false;
288
+ }
289
+ // Platform audit rows may omit organizationId. Requiring a selected org hides
290
+ // those events and skips Recent Activity / the AuditEvent changelist.
291
+ if (AUDIT_EVENT_MODEL_NAMES.has(config.model.modelName)) {
292
+ return false;
293
+ }
294
+ return Boolean(config.model.schema.path("organizationId"));
295
+ }
296
+ adminAccessPermissions() {
392
297
  if (this.options.accessControl) {
393
298
  return [this.options.accessControl.permission({ admin: [api_1.ADMIN_PAGE_ACTION] })];
394
299
  }
395
300
  return [api_1.Permissions.IsAdmin];
396
- };
397
- AdminApp.prototype.hasScriptPermission = function (user, action) {
398
- return __awaiter(this, void 0, void 0, function () {
399
- var result;
400
- return __generator(this, function (_a) {
401
- switch (_a.label) {
402
- case 0:
403
- if (!this.options.accessControl) {
404
- return [2 /*return*/, Boolean(user === null || user === void 0 ? void 0 : user.admin)];
405
- }
406
- return [4 /*yield*/, this.options.accessControl.can({
407
- permissions: { admin: [action] },
408
- user: user,
409
- })];
410
- case 1:
411
- result = _a.sent();
412
- return [2 /*return*/, result.allowed];
413
- }
414
- });
301
+ }
302
+ adminRunScriptsPermissions() {
303
+ if (this.options.accessControl) {
304
+ return [this.options.accessControl.permission({ admin: ["runScripts"] })];
305
+ }
306
+ return [api_1.Permissions.IsAdmin];
307
+ }
308
+ async hasScriptPermission(user, action) {
309
+ if (!this.options.accessControl) {
310
+ return Boolean(user?.admin);
311
+ }
312
+ const result = await this.options.accessControl.can({
313
+ permissions: { admin: [action] },
314
+ user,
415
315
  });
416
- };
417
- AdminApp.prototype.hasConfigurationPermission = function (user, action) {
418
- return __awaiter(this, void 0, void 0, function () {
419
- var result;
420
- return __generator(this, function (_a) {
421
- switch (_a.label) {
422
- case 0:
423
- if (!this.options.accessControl) {
424
- return [2 /*return*/, Boolean(user === null || user === void 0 ? void 0 : user.admin)];
425
- }
426
- return [4 /*yield*/, this.options.accessControl.can({
427
- permissions: { configuration: [action] },
428
- user: user,
429
- })];
430
- case 1:
431
- result = _a.sent();
432
- return [2 /*return*/, result.allowed];
433
- }
434
- });
316
+ return result.allowed;
317
+ }
318
+ async hasConfigurationPermission(user, action) {
319
+ if (!this.options.accessControl) {
320
+ return Boolean(user?.admin);
321
+ }
322
+ const result = await this.options.accessControl.can({
323
+ permissions: { configuration: [action] },
324
+ user,
435
325
  });
436
- };
437
- AdminApp.prototype.canAnyResourceAction = function (user, resource, actions, instance) {
438
- return __awaiter(this, void 0, void 0, function () {
439
- var accessControl, actions_1, actions_1_1, action, result, e_5_1;
440
- var e_5, _a, _b;
441
- return __generator(this, function (_c) {
442
- switch (_c.label) {
443
- case 0:
444
- accessControl = this.options.accessControl;
445
- if (!accessControl || !user) {
446
- return [2 /*return*/, Boolean(user === null || user === void 0 ? void 0 : user.admin)];
447
- }
448
- _c.label = 1;
449
- case 1:
450
- _c.trys.push([1, 6, 7, 8]);
451
- actions_1 = __values(actions), actions_1_1 = actions_1.next();
452
- _c.label = 2;
453
- case 2:
454
- if (!!actions_1_1.done) return [3 /*break*/, 5];
455
- action = actions_1_1.value;
456
- return [4 /*yield*/, accessControl.can({
457
- doc: instance,
458
- permissions: (_b = {}, _b[resource] = [action], _b),
459
- user: user,
460
- })];
461
- case 3:
462
- result = _c.sent();
463
- if (result.allowed) {
464
- return [2 /*return*/, true];
465
- }
466
- _c.label = 4;
467
- case 4:
468
- actions_1_1 = actions_1.next();
469
- return [3 /*break*/, 2];
470
- case 5: return [3 /*break*/, 8];
471
- case 6:
472
- e_5_1 = _c.sent();
473
- e_5 = { error: e_5_1 };
474
- return [3 /*break*/, 8];
475
- case 7:
476
- try {
477
- if (actions_1_1 && !actions_1_1.done && (_a = actions_1.return)) _a.call(actions_1);
478
- }
479
- finally { if (e_5) throw e_5.error; }
480
- return [7 /*endfinally*/];
481
- case 8: return [2 /*return*/, false];
482
- }
326
+ return result.allowed;
327
+ }
328
+ async canAnyResourceAction(user, resource, actions, instance) {
329
+ const accessControl = this.options.accessControl;
330
+ if (!accessControl || !user) {
331
+ return Boolean(user?.admin);
332
+ }
333
+ for (const action of actions) {
334
+ const result = await accessControl.can({
335
+ doc: instance,
336
+ permissions: { [resource]: [action] },
337
+ user,
483
338
  });
484
- });
485
- };
486
- AdminApp.prototype.adminResource = function (config) {
487
- var _a;
488
- var accessControl = this.options.accessControl;
489
- var explicit = (_a = config.adminAccess) === null || _a === void 0 ? void 0 : _a.resource;
339
+ if (result.allowed) {
340
+ return true;
341
+ }
342
+ }
343
+ return false;
344
+ }
345
+ adminResource(config) {
346
+ const accessControl = this.options.accessControl;
347
+ const explicit = config.adminAccess?.resource;
490
348
  if (explicit) {
491
349
  return explicit;
492
350
  }
493
- var standard = "admin".concat(config.model.modelName);
494
- if (accessControl === null || accessControl === void 0 ? void 0 : accessControl.statements[standard]) {
351
+ const publicName = (0, api_1.publicFrameworkModelName)(config.model.modelName);
352
+ const standard = `admin${publicName}`;
353
+ if (accessControl?.statements[standard]) {
495
354
  return standard;
496
355
  }
497
- return "".concat(config.model.modelName.charAt(0).toLowerCase()).concat(config.model.modelName.slice(1));
498
- };
499
- AdminApp.prototype.isAdminModelOwned = function (config, user, instance) {
500
- return __awaiter(this, void 0, void 0, function () {
501
- var owner, ownerId;
502
- var _a, _b;
503
- return __generator(this, function (_c) {
504
- if ((_a = config.adminAccess) === null || _a === void 0 ? void 0 : _a.isOwned) {
505
- return [2 /*return*/, config.adminAccess.isOwned({ instance: instance, user: user })];
506
- }
507
- owner = instance === null || instance === void 0 ? void 0 : instance.ownerId;
508
- ownerId = (_b = owner === null || owner === void 0 ? void 0 : owner._id) !== null && _b !== void 0 ? _b : owner;
509
- return [2 /*return*/, ownerId != null && String(ownerId) === String(user.id)];
510
- });
511
- });
512
- };
513
- AdminApp.prototype.resourceActionPermissions = function (config, action) {
514
- var _a;
515
- var _this = this;
516
- var _b;
517
- var shell = this.adminAccessPermissions();
518
- var accessControl = this.options.accessControl;
356
+ return `${publicName.charAt(0).toLowerCase()}${publicName.slice(1)}`;
357
+ }
358
+ async isAdminModelOwned(config, user, instance) {
359
+ if (config.adminAccess?.isOwned) {
360
+ return config.adminAccess.isOwned({ instance, user });
361
+ }
362
+ const owner = instance?.ownerId;
363
+ const ownerId = owner?._id ?? owner;
364
+ return ownerId != null && String(ownerId) === String(user.id);
365
+ }
366
+ resourceActionPermissions(config, action) {
367
+ const shell = this.adminAccessPermissions();
368
+ const accessControl = this.options.accessControl;
519
369
  if (!accessControl) {
520
370
  return shell;
521
371
  }
522
- if ((_b = config.adminAccess) === null || _b === void 0 ? void 0 : _b.authorize) {
523
- return __spreadArray(__spreadArray([], __read(shell), false), [
524
- function (_method, user, instance) { return __awaiter(_this, void 0, void 0, function () { var _a, _b, _c; return __generator(this, function (_d) {
525
- return [2 /*return*/, (_c = (_b = (_a = config.adminAccess) === null || _a === void 0 ? void 0 : _a.authorize) === null || _b === void 0 ? void 0 : _b.call(_a, { action: action, instance: instance, user: user })) !== null && _c !== void 0 ? _c : false];
526
- }); }); },
527
- ], false);
372
+ if (config.adminAccess?.authorize) {
373
+ return [
374
+ ...shell,
375
+ async (_method, user, instance) => config.adminAccess?.authorize?.({ action, instance, user }) ?? false,
376
+ ];
528
377
  }
529
- var resource = this.adminResource(config);
530
- var knownActions = accessControl.statements[resource];
378
+ const resource = this.adminResource(config);
379
+ const knownActions = accessControl.statements[resource];
531
380
  if (!knownActions) {
532
381
  return [];
533
382
  }
534
- var hasStandardAccess = knownActions.includes("write") || knownActions.includes("writeOwned");
383
+ const hasStandardAccess = knownActions.includes("write") || knownActions.includes("writeOwned");
535
384
  if (hasStandardAccess) {
536
- return __spreadArray(__spreadArray([], __read(shell), false), [
537
- function (_method, user, instance) { return __awaiter(_this, void 0, void 0, function () {
538
- return __generator(this, function (_a) {
539
- switch (_a.label) {
540
- case 0:
541
- if (!user) {
542
- return [2 /*return*/, false];
543
- }
544
- if (action === "list" || action === "read") {
545
- return [2 /*return*/, this.canAnyResourceAction(user, resource, ["read"], instance)];
546
- }
547
- return [4 /*yield*/, this.canAnyResourceAction(user, resource, ["write"], instance)];
548
- case 1:
549
- if (_a.sent()) {
550
- return [2 /*return*/, true];
551
- }
552
- return [4 /*yield*/, this.canAnyResourceAction(user, resource, ["writeOwned"], instance)];
553
- case 2:
554
- if (!(_a.sent())) {
555
- return [2 /*return*/, false];
556
- }
557
- // writeOwned always allows create. Ownership applies to update/delete.
558
- if (action === "create" || instance === undefined) {
559
- return [2 /*return*/, true];
560
- }
561
- return [2 /*return*/, this.isAdminModelOwned(config, user, instance)];
562
- }
563
- });
564
- }); },
565
- ], false);
385
+ return [
386
+ ...shell,
387
+ async (_method, user, instance) => {
388
+ if (!user) {
389
+ return false;
390
+ }
391
+ if (action === "list" || action === "read") {
392
+ return this.canAnyResourceAction(user, resource, ["read"], instance);
393
+ }
394
+ if (await this.canAnyResourceAction(user, resource, ["write"], instance)) {
395
+ return true;
396
+ }
397
+ if (!(await this.canAnyResourceAction(user, resource, ["writeOwned"], instance))) {
398
+ return false;
399
+ }
400
+ // writeOwned always allows create. Ownership applies to update/delete.
401
+ if (action === "create" || instance === undefined) {
402
+ return true;
403
+ }
404
+ return this.isAdminModelOwned(config, user, instance);
405
+ },
406
+ ];
566
407
  }
567
- return __spreadArray(__spreadArray([], __read(shell), false), [accessControl.permission((_a = {}, _a[resource] = [action], _a))], false);
568
- };
408
+ return [...shell, accessControl.permission({ [resource]: [action] })];
409
+ }
569
410
  /**
570
411
  * Register admin routes with the Express application.
571
412
  *
@@ -582,136 +423,129 @@ var AdminApp = /** @class */ (function () {
582
423
  *
583
424
  * @param app - The Express application instance to register with
584
425
  */
585
- AdminApp.prototype.register = function (app, openApi, terrenoApp) {
586
- var e_6, _a, e_7, _b;
587
- var _this = this;
588
- var _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
589
- var basePath = (_c = this.options.basePath) !== null && _c !== void 0 ? _c : "/admin";
590
- var openApiMw = openApi;
591
- var aggregated = (0, aggregateAdmin_1.aggregateFromTerrenoApp)({
592
- legacyModels: (_d = this.options.models) !== null && _d !== void 0 ? _d : [],
593
- terrenoApp: terrenoApp,
426
+ register(app, openApi, terrenoApp) {
427
+ const basePath = this.options.basePath ?? "/admin";
428
+ const openApiMw = openApi;
429
+ const aggregated = (0, aggregateAdmin_1.aggregateFromTerrenoApp)({
430
+ legacyModels: this.options.models ?? [],
431
+ terrenoApp,
594
432
  });
595
- var modelConfigs = aggregated.models;
596
- var allModelAdmins = buildAllModelAdminsMap(modelConfigs);
597
- var onAdminAudit = this.options.onAdminAudit;
433
+ const modelConfigs = aggregated.models;
434
+ const allModelAdmins = buildAllModelAdminsMap(modelConfigs);
435
+ const onAdminAudit = this.options.onAdminAudit;
598
436
  /** Audit is best-effort: failures must not change HTTP outcomes after mutations succeed. */
599
- var safeOnAdminAudit = function (request, event) { return __awaiter(_this, void 0, void 0, function () {
600
- var err_1, detail;
601
- return __generator(this, function (_a) {
602
- switch (_a.label) {
603
- case 0:
604
- if (!onAdminAudit) {
605
- return [2 /*return*/];
606
- }
607
- _a.label = 1;
608
- case 1:
609
- _a.trys.push([1, 3, , 4]);
610
- return [4 /*yield*/, onAdminAudit(event, request)];
611
- case 2:
612
- _a.sent();
613
- return [3 /*break*/, 4];
614
- case 3:
615
- err_1 = _a.sent();
616
- detail = err_1 instanceof Error ? err_1.message : String(err_1);
617
- api_1.logger.error("onAdminAudit failed after ".concat(event.verb, " on ").concat(event.modelName, ": ").concat(detail));
618
- return [3 /*break*/, 4];
619
- case 4: return [2 /*return*/];
620
- }
437
+ const safeOnAdminAudit = async (request, event) => {
438
+ if (!onAdminAudit) {
439
+ return;
440
+ }
441
+ try {
442
+ await onAdminAudit(event, request);
443
+ }
444
+ catch (err) {
445
+ const detail = err instanceof Error ? err.message : String(err);
446
+ api_1.logger.error(`onAdminAudit failed after ${event.verb} on ${event.modelName}: ${detail}`);
447
+ }
448
+ };
449
+ const safeFrameworkAdminAudit = async ({ after, before, extraRedact, modelName, recordLabel, request, verb, }) => {
450
+ if (AUDIT_EVENT_MODEL_NAMES.has(modelName)) {
451
+ return;
452
+ }
453
+ void (0, api_1.maybeRecordAdminAudit)({
454
+ after,
455
+ before,
456
+ extraRedact,
457
+ modelName,
458
+ recordLabel,
459
+ req: request,
460
+ verb,
621
461
  });
622
- }); };
462
+ };
623
463
  // Build config response with field metadata from Mongoose schemas
624
- var configNames = (0, adminConfigIdentity_1.assignUniqueAdminConfigNames)(modelConfigs.map(function (config) { return ({
625
- modelName: config.model.modelName,
464
+ const configNames = (0, adminConfigIdentity_1.assignUniqueAdminConfigNames)(modelConfigs.map((config) => ({
465
+ modelName: (0, api_1.publicFrameworkModelName)(config.model.modelName),
626
466
  routePath: config.routePath,
627
467
  source: config.source,
628
- }); }));
629
- var configModels = modelConfigs.map(function (config, configIndex) {
630
- var e_8, _a;
631
- var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
632
- var hiddenFieldSet = new Set((_b = config.hiddenFields) !== null && _b !== void 0 ? _b : []);
633
- var fields = extractFieldMetaFromDescription(config.model, __spreadArray([], __read(hiddenFieldSet), false));
468
+ })));
469
+ const configModels = modelConfigs.map((config, configIndex) => {
470
+ const hiddenFieldSet = new Set(config.hiddenFields ?? []);
471
+ const fields = extractFieldMetaFromDescription(config.model, [...hiddenFieldSet]);
634
472
  // Apply field overrides (e.g., widget: "markdown")
635
473
  if (config.fieldOverrides) {
636
- try {
637
- for (var _r = __values(Object.entries(config.fieldOverrides)), _s = _r.next(); !_s.done; _s = _r.next()) {
638
- var _t = __read(_s.value, 2), key = _t[0], override = _t[1];
639
- if (fields[key] && override.widget) {
640
- fields[key].widget = override.widget;
641
- }
474
+ for (const [key, override] of Object.entries(config.fieldOverrides)) {
475
+ if (fields[key] && override.widget) {
476
+ fields[key].widget = override.widget;
642
477
  }
643
478
  }
644
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
645
- finally {
646
- try {
647
- if (_s && !_s.done && (_a = _r.return)) _a.call(_r);
648
- }
649
- finally { if (e_8) throw e_8.error; }
650
- }
651
479
  }
652
- var readonlyFields = (_c = config.readonlyFields) !== null && _c !== void 0 ? _c : [];
653
- var listFields = config.listFields.filter(function (field) { return !hiddenFieldSet.has(field); });
654
- var listDisplay = (_d = config.listDisplay) !== null && _d !== void 0 ? _d : listFields;
655
- var derivedSearchFields = listFields.filter(function (field) { var _a; return (_a = fields[field]) === null || _a === void 0 ? void 0 : _a.searchable; });
656
- var searchFields = (_e = config.searchFields) !== null && _e !== void 0 ? _e : derivedSearchFields;
657
- var sortableFields = resolveAdminSortableFields({
480
+ const readonlyFields = config.readonlyFields ?? [];
481
+ const listFields = config.listFields.filter((field) => !hiddenFieldSet.has(field));
482
+ const listDisplay = config.listDisplay ?? listFields;
483
+ const derivedSearchFields = listFields.filter((field) => fields[field]?.searchable);
484
+ const searchFields = config.searchFields ?? derivedSearchFields;
485
+ const sortableFields = resolveAdminSortableFields({
658
486
  defaultSort: config.defaultSort,
659
- listDisplay: listDisplay,
487
+ listDisplay,
660
488
  sortableFields: config.sortableFields,
661
489
  });
662
- var schemaPathKeys = new Set(Object.keys(config.model.schema.paths));
663
- var bulkPatchAllowlist = (_f = config.bulkPatchAllowlist) !== null && _f !== void 0 ? _f : (0, adminUiV2_1.defaultBulkPatchAllowlistFrom)({
664
- hiddenFieldSet: hiddenFieldSet,
665
- listFields: listFields,
666
- readonlyFields: readonlyFields,
667
- schemaPaths: schemaPathKeys,
668
- });
490
+ const schemaPathKeys = new Set(Object.keys(config.model.schema.paths));
491
+ const bulkPatchAllowlist = config.bulkPatchAllowlist ??
492
+ (0, adminUiV2_1.defaultBulkPatchAllowlistFrom)({
493
+ hiddenFieldSet,
494
+ listFields,
495
+ readonlyFields,
496
+ schemaPaths: schemaPathKeys,
497
+ });
498
+ const isOrgScopedModel = this.isOrganizationScoped(config);
499
+ const syncMeta = syncMetaForAdminModel(config.model.modelName, isOrgScopedModel);
669
500
  return {
670
- actions: (_g = config.actions) !== null && _g !== void 0 ? _g : [],
671
- bulkPatchAllowlist: bulkPatchAllowlist,
672
- defaultSort: (_h = config.defaultSort) !== null && _h !== void 0 ? _h : "-created",
501
+ actions: config.actions ?? [],
502
+ adminBroadcast: syncMeta.adminBroadcast,
503
+ bulkPatchAllowlist,
504
+ defaultSort: config.defaultSort ?? "-created",
673
505
  displayName: config.displayName,
674
506
  fieldOrder: config.fieldOrder,
675
- fields: fields,
507
+ fields,
676
508
  fieldsets: config.fieldsets,
677
- filters: (_j = config.filters) !== null && _j !== void 0 ? _j : [],
509
+ filters: config.filters ?? [],
678
510
  group: config.group,
679
- hiddenFields: __spreadArray([], __read(hiddenFieldSet), false),
680
- listDisplay: listDisplay,
681
- listDisplayLinks: (_k = config.listDisplayLinks) !== null && _k !== void 0 ? _k : [],
682
- listFields: listFields,
683
- name: (_l = configNames[configIndex]) !== null && _l !== void 0 ? _l : config.model.modelName,
511
+ hiddenFields: [...hiddenFieldSet],
512
+ listDisplay,
513
+ listDisplayLinks: config.listDisplayLinks ?? [],
514
+ listFields,
515
+ name: configNames[configIndex] ?? (0, api_1.publicFrameworkModelName)(config.model.modelName),
516
+ organizationScoped: isOrgScopedModel,
684
517
  pageSize: config.pageSize,
685
518
  permissions: {
686
- create: ((_m = config.permissions) === null || _m === void 0 ? void 0 : _m.create) !== false,
687
- delete: ((_o = config.permissions) === null || _o === void 0 ? void 0 : _o.delete) !== false,
688
- update: ((_p = config.permissions) === null || _p === void 0 ? void 0 : _p.update) !== false,
519
+ create: config.permissions?.create !== false,
520
+ delete: config.permissions?.delete !== false,
521
+ update: config.permissions?.update !== false,
689
522
  },
690
- readonlyFields: readonlyFields,
691
- realtime: (_q = config.realtime) !== null && _q !== void 0 ? _q : false,
523
+ readonlyFields,
524
+ realtime: config.realtime ?? false,
692
525
  recordTitleField: config.recordTitleField,
693
- routePath: "".concat(basePath).concat(config.routePath),
694
- searchFields: searchFields,
695
- sortableFields: sortableFields,
526
+ routePath: `${basePath}${config.routePath}`,
527
+ searchFields,
528
+ sortableFields,
529
+ ...(syncMeta.syncCollection ? { syncCollection: syncMeta.syncCollection } : {}),
696
530
  };
697
531
  });
698
532
  // Build script metadata for config response
699
- var scriptConfigs = __spreadArray(__spreadArray([], __read(((_e = this.options.scripts) !== null && _e !== void 0 ? _e : [])), false), __read(aggregated.scripts), false);
700
- var configScripts = scriptConfigs.map(function (script) {
701
- var _a;
702
- return ({
703
- args: (_a = script.args) !== null && _a !== void 0 ? _a : [],
704
- description: script.description,
705
- name: script.name,
706
- });
707
- });
708
- var mergedScreens = __spreadArray(__spreadArray([], __read(aggregated.customScreens), false), __read(((_f = this.options.customScreens) !== null && _f !== void 0 ? _f : [])), false);
709
- var baseConfigResponse = {
533
+ const scriptConfigs = [...(this.options.scripts ?? []), ...aggregated.scripts];
534
+ const configScripts = scriptConfigs.map((script) => ({
535
+ args: script.args ?? [],
536
+ description: script.description,
537
+ name: script.name,
538
+ }));
539
+ const mergedScreens = [
540
+ ...aggregated.customScreens,
541
+ ...(this.options.customScreens ?? []),
542
+ ];
543
+ const baseConfigResponse = {
710
544
  capabilities: {
711
545
  actions: true,
712
546
  fieldsets: true,
713
547
  filters: true,
714
- realtime: modelConfigs.some(function (config) { return config.realtime === true; }),
548
+ realtime: modelConfigs.some((config) => config.realtime === true),
715
549
  },
716
550
  customScreens: mergedScreens,
717
551
  home: (0, adminUiV2_1.normalizeAdminHome)(this.options.home),
@@ -728,116 +562,68 @@ var AdminApp = /** @class */ (function () {
728
562
  scripts: configScripts,
729
563
  widgetIds: aggregated.widgetIds,
730
564
  };
731
- var buildAuthorizedConfig = function (user) { return __awaiter(_this, void 0, void 0, function () {
732
- var authorizedModels, authorizedScreens, canReadConfiguration, canReadRoles, canRunScripts, canViewScripts, canUseScripts;
733
- var _this = this;
734
- return __generator(this, function (_a) {
735
- switch (_a.label) {
736
- case 0: return [4 /*yield*/, Promise.all(configModels.map(function (modelMeta, index) { return __awaiter(_this, void 0, void 0, function () {
737
- var config, canRead, canCreate, _a, canDelete, _b, canUpdate, _c;
738
- return __generator(this, function (_d) {
739
- switch (_d.label) {
740
- case 0:
741
- config = modelConfigs[index];
742
- if (!config) {
743
- return [2 /*return*/, null];
744
- }
745
- return [4 /*yield*/, (0, api_1.checkPermissions)("list", this.resourceActionPermissions(config, "list"), user)];
746
- case 1:
747
- canRead = _d.sent();
748
- if (!canRead) {
749
- return [2 /*return*/, null];
750
- }
751
- _a = modelMeta.permissions.create;
752
- if (!_a) return [3 /*break*/, 3];
753
- return [4 /*yield*/, (0, api_1.checkPermissions)("create", this.resourceActionPermissions(config, "create"), user)];
754
- case 2:
755
- _a = (_d.sent());
756
- _d.label = 3;
757
- case 3:
758
- canCreate = _a;
759
- _b = modelMeta.permissions.delete;
760
- if (!_b) return [3 /*break*/, 5];
761
- return [4 /*yield*/, (0, api_1.checkPermissions)("delete", this.resourceActionPermissions(config, "delete"), user)];
762
- case 4:
763
- _b = (_d.sent());
764
- _d.label = 5;
765
- case 5:
766
- canDelete = _b;
767
- _c = modelMeta.permissions.update;
768
- if (!_c) return [3 /*break*/, 7];
769
- return [4 /*yield*/, (0, api_1.checkPermissions)("update", this.resourceActionPermissions(config, "update"), user)];
770
- case 6:
771
- _c = (_d.sent());
772
- _d.label = 7;
773
- case 7:
774
- canUpdate = _c;
775
- return [2 /*return*/, __assign(__assign({}, modelMeta), { permissions: { create: canCreate, delete: canDelete, update: canUpdate } })];
776
- }
777
- });
778
- }); }))];
779
- case 1:
780
- authorizedModels = (_a.sent()).filter(function (model) { return model !== null; });
781
- return [4 /*yield*/, Promise.all(mergedScreens.map(function (screen) { return __awaiter(_this, void 0, void 0, function () {
782
- var allowed_1, allowed;
783
- var _a, _b;
784
- return __generator(this, function (_c) {
785
- switch (_c.label) {
786
- case 0:
787
- if (!screen.adminAccess) {
788
- return [2 /*return*/, screen];
789
- }
790
- if (!screen.adminAccess.authorize) return [3 /*break*/, 2];
791
- return [4 /*yield*/, screen.adminAccess.authorize({
792
- action: (_a = screen.adminAccess.action) !== null && _a !== void 0 ? _a : "read",
793
- user: user,
794
- })];
795
- case 1:
796
- allowed_1 = _c.sent();
797
- return [2 /*return*/, allowed_1 ? screen : null];
798
- case 2:
799
- if (!screen.adminAccess.resource) {
800
- return [2 /*return*/, screen];
801
- }
802
- return [4 /*yield*/, this.canAnyResourceAction(user, screen.adminAccess.resource, [
803
- (_b = screen.adminAccess.action) !== null && _b !== void 0 ? _b : "read",
804
- ])];
805
- case 3:
806
- allowed = _c.sent();
807
- return [2 /*return*/, allowed ? screen : null];
808
- }
809
- });
810
- }); }))];
811
- case 2:
812
- authorizedScreens = (_a.sent()).filter(function (screen) { return screen !== null; });
813
- return [4 /*yield*/, this.hasConfigurationPermission(user, "read")];
814
- case 3:
815
- canReadConfiguration = _a.sent();
816
- return [4 /*yield*/, this.canAnyResourceAction(user, "rbac", ["read"])];
817
- case 4:
818
- canReadRoles = _a.sent();
819
- return [4 /*yield*/, this.hasScriptPermission(user, "runScripts")];
820
- case 5:
821
- canRunScripts = _a.sent();
822
- return [4 /*yield*/, this.hasScriptPermission(user, "viewBackgroundTasks")];
823
- case 6:
824
- canViewScripts = _a.sent();
825
- canUseScripts = canRunScripts || canViewScripts;
826
- return [2 /*return*/, __assign(__assign({}, baseConfigResponse), { customScreens: authorizedScreens.map(function (_a) {
827
- var _adminAccess = _a.adminAccess, screen = __rest(_a, ["adminAccess"]);
828
- return screen;
829
- }), models: authorizedModels, platformTools: {
830
- configuration: canReadConfiguration,
831
- roles: canReadRoles,
832
- runScripts: canRunScripts,
833
- scripts: canUseScripts,
834
- version: canReadConfiguration,
835
- viewScripts: canViewScripts,
836
- }, scripts: canUseScripts ? configScripts : [] })];
565
+ const buildAuthorizedConfig = async (user) => {
566
+ const authorizedModels = (await Promise.all(configModels.map(async (modelMeta, index) => {
567
+ const config = modelConfigs[index];
568
+ if (!config) {
569
+ return null;
837
570
  }
838
- });
839
- }); };
840
- var adminConfigOpenApi = openApiMw
571
+ const canRead = await (0, api_1.checkPermissions)("list", this.resourceActionPermissions(config, "list"), user);
572
+ if (!canRead) {
573
+ return null;
574
+ }
575
+ const canCreate = modelMeta.permissions.create &&
576
+ (await (0, api_1.checkPermissions)("create", this.resourceActionPermissions(config, "create"), user));
577
+ const canDelete = modelMeta.permissions.delete &&
578
+ (await (0, api_1.checkPermissions)("delete", this.resourceActionPermissions(config, "delete"), user));
579
+ const canUpdate = modelMeta.permissions.update &&
580
+ (await (0, api_1.checkPermissions)("update", this.resourceActionPermissions(config, "update"), user));
581
+ return {
582
+ ...modelMeta,
583
+ permissions: { create: canCreate, delete: canDelete, update: canUpdate },
584
+ };
585
+ }))).filter((model) => model !== null);
586
+ const authorizedScreens = (await Promise.all(mergedScreens.map(async (screen) => {
587
+ if (!screen.adminAccess) {
588
+ return screen;
589
+ }
590
+ if (screen.adminAccess.authorize) {
591
+ const allowed = await screen.adminAccess.authorize({
592
+ action: screen.adminAccess.action ?? "read",
593
+ user,
594
+ });
595
+ return allowed ? screen : null;
596
+ }
597
+ if (!screen.adminAccess.resource) {
598
+ return screen;
599
+ }
600
+ const allowed = await this.canAnyResourceAction(user, screen.adminAccess.resource, [
601
+ screen.adminAccess.action ?? "read",
602
+ ]);
603
+ return allowed ? screen : null;
604
+ }))).filter((screen) => screen !== null);
605
+ const canReadConfiguration = await this.hasConfigurationPermission(user, "read");
606
+ const canReadRoles = await this.canAnyResourceAction(user, "rbac", ["read"]);
607
+ const canRunScripts = await this.hasScriptPermission(user, "runScripts");
608
+ const canViewScripts = await this.hasScriptPermission(user, "viewBackgroundTasks");
609
+ const canUseScripts = canRunScripts || canViewScripts;
610
+ return {
611
+ ...baseConfigResponse,
612
+ customScreens: authorizedScreens.map(({ adminAccess: _adminAccess, ...screen }) => screen),
613
+ migrations: { enabled: Boolean(this.options.migrations?.dir) },
614
+ models: authorizedModels,
615
+ platformTools: {
616
+ configuration: canReadConfiguration,
617
+ roles: canReadRoles,
618
+ runScripts: canRunScripts,
619
+ scripts: canUseScripts,
620
+ version: canReadConfiguration,
621
+ viewScripts: canViewScripts,
622
+ },
623
+ scripts: canUseScripts ? configScripts : [],
624
+ };
625
+ };
626
+ const adminConfigOpenApi = openApiMw
841
627
  ? (0, api_1.createOpenApiBuilder)({ openApi: openApiMw })
842
628
  .withTags(["admin"])
843
629
  .withSummary("Admin panel configuration")
@@ -856,6 +642,8 @@ var AdminApp = /** @class */ (function () {
856
642
  properties: {
857
643
  description: { type: "string" },
858
644
  displayName: { type: "string" },
645
+ group: { type: "string" },
646
+ icon: { type: "string" },
859
647
  name: { type: "string" },
860
648
  },
861
649
  type: "object",
@@ -892,22 +680,13 @@ var AdminApp = /** @class */ (function () {
892
680
  .build()
893
681
  : undefined;
894
682
  // GET /admin/config
895
- app.get.apply(app, __spreadArray(__spreadArray(["".concat(basePath, "/config"), (0, api_1.authenticateMiddleware)()], __read(asMiddlewareList(adminConfigOpenApi)), false), [(0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
896
- var _a, _b;
897
- return __generator(this, function (_c) {
898
- switch (_c.label) {
899
- case 0: return [4 /*yield*/, (0, api_1.checkPermissions)("read", this.adminAccessPermissions(), req.user)];
900
- case 1:
901
- if (!(_c.sent())) {
902
- throw new api_1.APIError({ status: 403, title: "Admin access required" });
903
- }
904
- _b = (_a = res).json;
905
- return [4 /*yield*/, buildAuthorizedConfig(req.user)];
906
- case 2: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
907
- }
908
- });
909
- }); })], false));
910
- var backgroundTasksOpenApi = openApiMw
683
+ app.get(`${basePath}/config`, (0, api_1.authenticateMiddleware)(), ...asMiddlewareList(adminConfigOpenApi), (0, api_1.asyncHandler)(async (req, res) => {
684
+ if (!(await (0, api_1.checkPermissions)("read", this.adminAccessPermissions(), req.user))) {
685
+ throw new api_1.APIError({ status: 403, title: "Admin access required" });
686
+ }
687
+ return res.json(await buildAuthorizedConfig(req.user));
688
+ }));
689
+ const backgroundTasksOpenApi = openApiMw
911
690
  ? (0, api_1.createOpenApiBuilder)({ openApi: openApiMw })
912
691
  .withTags(["admin"])
913
692
  .withSummary("Enqueue a generic admin background task")
@@ -931,355 +710,238 @@ var AdminApp = /** @class */ (function () {
931
710
  .withResponse(201, { taskId: { type: "string" } })
932
711
  .build()
933
712
  : undefined;
934
- app.post.apply(app, __spreadArray(__spreadArray(["".concat(basePath, "/background-tasks"), (0, api_1.authenticateMiddleware)()], __read(asMiddlewareList(backgroundTasksOpenApi)), false), [(0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
935
- var actor, _a, user, raw, now, summary, task, err_2, detail;
936
- return __generator(this, function (_b) {
937
- switch (_b.label) {
938
- case 0:
939
- actor = req.user;
940
- _a = !actor;
941
- if (_a) return [3 /*break*/, 2];
942
- return [4 /*yield*/, this.hasScriptPermission(actor, "runScripts")];
943
- case 1:
944
- _a = !(_b.sent());
945
- _b.label = 2;
946
- case 2:
947
- if (_a) {
948
- throw new api_1.APIError({ status: 403, title: "Admin access required" });
949
- }
950
- user = actor;
951
- raw = req.body;
952
- if (typeof raw.kind !== "string" || !raw.kind.trim()) {
953
- throw new api_1.APIError({ status: 400, title: "kind is required" });
954
- }
955
- now = luxon_1.DateTime.now().toJSDate();
956
- summary = {
957
- ids: Array.isArray(raw.ids) ? raw.ids : [],
958
- metadata: raw.metadata && typeof raw.metadata === "object" && !Array.isArray(raw.metadata)
959
- ? raw.metadata
960
- : {},
961
- resourceRoute: typeof raw.resourceRoute === "string" ? raw.resourceRoute : undefined,
962
- };
963
- _b.label = 3;
964
- case 3:
965
- _b.trys.push([3, 5, , 6]);
966
- return [4 /*yield*/, api_1.BackgroundTask.create({
967
- createdBy: user === null || user === void 0 ? void 0 : user._id,
968
- isDryRun: false,
969
- logs: [
970
- {
971
- level: "info",
972
- message: "Queued background task ".concat(raw.kind, ": ").concat(JSON.stringify(summary)),
973
- timestamp: now,
974
- },
975
- ],
976
- progress: { message: "Queued", percentage: 0, stage: "Queued" },
977
- startedAt: now,
978
- status: "pending",
979
- taskType: raw.kind,
980
- })];
981
- case 4:
982
- task = (_b.sent());
983
- return [3 /*break*/, 6];
984
- case 5:
985
- err_2 = _b.sent();
986
- detail = err_2 instanceof Error ? err_2.message : String(err_2);
987
- api_1.logger.error("Failed to create admin background task: ".concat(detail));
988
- throw new api_1.APIError({
989
- detail: detail,
990
- status: 500,
991
- title: "Failed to enqueue background task",
992
- });
993
- case 6: return [2 /*return*/, res.status(201).json({ taskId: task._id.toString() })];
994
- }
713
+ app.post(`${basePath}/background-tasks`, (0, api_1.authenticateMiddleware)(), ...asMiddlewareList(backgroundTasksOpenApi), (0, api_1.asyncHandler)(async (req, res) => {
714
+ const actor = req.user;
715
+ if (!actor || !(await this.hasScriptPermission(actor, "runScripts"))) {
716
+ throw new api_1.APIError({ status: 403, title: "Admin access required" });
717
+ }
718
+ const user = actor;
719
+ const raw = req.body;
720
+ if (typeof raw.kind !== "string" || !raw.kind.trim()) {
721
+ throw new api_1.APIError({ status: 400, title: "kind is required" });
722
+ }
723
+ const now = luxon_1.DateTime.now().toJSDate();
724
+ const summary = {
725
+ ids: Array.isArray(raw.ids) ? raw.ids : [],
726
+ metadata: raw.metadata && typeof raw.metadata === "object" && !Array.isArray(raw.metadata)
727
+ ? raw.metadata
728
+ : {},
729
+ resourceRoute: typeof raw.resourceRoute === "string" ? raw.resourceRoute : undefined,
730
+ };
731
+ let task;
732
+ try {
733
+ task = (await api_1.BackgroundTask.create({
734
+ createdBy: user?._id,
735
+ isDryRun: false,
736
+ logs: [
737
+ {
738
+ level: "info",
739
+ message: `Queued background task ${raw.kind}: ${JSON.stringify(summary)}`,
740
+ timestamp: now,
741
+ },
742
+ ],
743
+ progress: { message: "Queued", percentage: 0, stage: "Queued" },
744
+ startedAt: now,
745
+ status: "pending",
746
+ taskType: raw.kind,
747
+ }));
748
+ }
749
+ catch (err) {
750
+ const detail = err instanceof Error ? err.message : String(err);
751
+ api_1.logger.error(`Failed to create admin background task: ${detail}`);
752
+ throw new api_1.APIError({
753
+ detail,
754
+ status: 500,
755
+ title: "Failed to enqueue background task",
995
756
  });
996
- }); })], false));
757
+ }
758
+ return res.status(201).json({ taskId: task._id.toString() });
759
+ }));
997
760
  // Version config singleton routes (GET/PUT /admin/version-config)
998
- var versionConfigPath = "".concat(basePath, "/version-config");
999
- app.get(versionConfigPath, (0, api_1.authenticateMiddleware)(), (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1000
- var config, defaults;
1001
- return __generator(this, function (_a) {
1002
- switch (_a.label) {
1003
- case 0: return [4 /*yield*/, this.hasConfigurationPermission(req.user, "read")];
1004
- case 1:
1005
- if (!(_a.sent())) {
1006
- throw new api_1.APIError({ status: 403, title: "Admin access required" });
1007
- }
1008
- return [4 /*yield*/, api_1.VersionConfig.findOneOrNone({ _singleton: "config" })];
1009
- case 2:
1010
- config = _a.sent();
1011
- defaults = {
1012
- mobileRequiredVersion: 0,
1013
- mobileWarningVersion: 0,
1014
- requiredMessage: "This version is no longer supported. Please update to continue.",
1015
- updateUrl: undefined,
1016
- warningMessage: "A new version is available. Please update for the best experience.",
1017
- webRequiredVersion: 0,
1018
- webWarningVersion: 0,
1019
- };
1020
- return [2 /*return*/, res.json(config !== null && config !== void 0 ? config : defaults)];
761
+ const versionConfigPath = `${basePath}/version-config`;
762
+ app.get(versionConfigPath, (0, api_1.authenticateMiddleware)(), (0, api_1.asyncHandler)(async (req, res) => {
763
+ if (!(await this.hasConfigurationPermission(req.user, "read"))) {
764
+ throw new api_1.APIError({ status: 403, title: "Admin access required" });
765
+ }
766
+ const config = await api_1.VersionConfig.findOneOrNone({ _singleton: "config" });
767
+ const defaults = {
768
+ mobileRequiredVersion: 0,
769
+ mobileWarningVersion: 0,
770
+ requiredMessage: "This version is no longer supported. Please update to continue.",
771
+ updateUrl: undefined,
772
+ warningMessage: "A new version is available. Please update for the best experience.",
773
+ webRequiredVersion: 0,
774
+ webWarningVersion: 0,
775
+ };
776
+ return res.json(config ?? defaults);
777
+ }));
778
+ app.put(versionConfigPath, (0, api_1.authenticateMiddleware)(), (0, api_1.asyncHandler)(async (req, res) => {
779
+ if (!(await this.hasConfigurationPermission(req.user, "update"))) {
780
+ throw new api_1.APIError({ status: 403, title: "Admin access required" });
781
+ }
782
+ const raw = req.body;
783
+ const allowedFields = [
784
+ "mobileRequiredVersion",
785
+ "mobileWarningVersion",
786
+ "requiredMessage",
787
+ "updateUrl",
788
+ "webRequiredVersion",
789
+ "webWarningVersion",
790
+ "warningMessage",
791
+ ];
792
+ const setFields = {};
793
+ const unsetFields = {};
794
+ for (const field of allowedFields) {
795
+ if (raw[field] === null) {
796
+ unsetFields[field] = 1;
1021
797
  }
1022
- });
1023
- }); }));
1024
- app.put(versionConfigPath, (0, api_1.authenticateMiddleware)(), (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1025
- var raw, allowedFields, setFields, unsetFields, allowedFields_1, allowedFields_1_1, field, updateOp, doc;
1026
- var e_9, _a;
1027
- return __generator(this, function (_b) {
1028
- switch (_b.label) {
1029
- case 0: return [4 /*yield*/, this.hasConfigurationPermission(req.user, "update")];
1030
- case 1:
1031
- if (!(_b.sent())) {
1032
- throw new api_1.APIError({ status: 403, title: "Admin access required" });
1033
- }
1034
- raw = req.body;
1035
- allowedFields = [
1036
- "mobileRequiredVersion",
1037
- "mobileWarningVersion",
1038
- "requiredMessage",
1039
- "updateUrl",
1040
- "webRequiredVersion",
1041
- "webWarningVersion",
1042
- "warningMessage",
1043
- ];
1044
- setFields = {};
1045
- unsetFields = {};
1046
- try {
1047
- for (allowedFields_1 = __values(allowedFields), allowedFields_1_1 = allowedFields_1.next(); !allowedFields_1_1.done; allowedFields_1_1 = allowedFields_1.next()) {
1048
- field = allowedFields_1_1.value;
1049
- if (raw[field] === null) {
1050
- unsetFields[field] = 1;
1051
- }
1052
- else if (raw[field] !== undefined) {
1053
- setFields[field] = raw[field];
1054
- }
1055
- }
1056
- }
1057
- catch (e_9_1) { e_9 = { error: e_9_1 }; }
1058
- finally {
1059
- try {
1060
- if (allowedFields_1_1 && !allowedFields_1_1.done && (_a = allowedFields_1.return)) _a.call(allowedFields_1);
1061
- }
1062
- finally { if (e_9) throw e_9.error; }
1063
- }
1064
- updateOp = {};
1065
- if (Object.keys(setFields).length > 0) {
1066
- updateOp.$set = setFields;
1067
- }
1068
- if (Object.keys(unsetFields).length > 0) {
1069
- updateOp.$unset = unsetFields;
1070
- }
1071
- return [4 /*yield*/, api_1.VersionConfig.findOneAndUpdate({ _singleton: "config" }, updateOp, {
1072
- returnDocument: "after",
1073
- runValidators: true,
1074
- setDefaultsOnInsert: true,
1075
- upsert: true,
1076
- }).lean()];
1077
- case 2:
1078
- doc = _b.sent();
1079
- return [2 /*return*/, res.json(doc)];
798
+ else if (raw[field] !== undefined) {
799
+ setFields[field] = raw[field];
1080
800
  }
1081
- });
1082
- }); }));
1083
- var _loop_1 = function (config) {
1084
- var e_10, _t;
801
+ }
802
+ const updateOp = {};
803
+ if (Object.keys(setFields).length > 0) {
804
+ updateOp.$set = setFields;
805
+ }
806
+ if (Object.keys(unsetFields).length > 0) {
807
+ updateOp.$unset = unsetFields;
808
+ }
809
+ const doc = await api_1.VersionConfig.findOneAndUpdate({ _singleton: "config" }, updateOp, {
810
+ returnDocument: "after",
811
+ runValidators: true,
812
+ setDefaultsOnInsert: true,
813
+ upsert: true,
814
+ }).lean();
815
+ return res.json(doc);
816
+ }));
817
+ // Mount search endpoint for each model
818
+ for (const config of modelConfigs) {
819
+ const isOrganizationScoped = this.isOrganizationScoped(config);
1085
820
  // Determine searchable fields from the actual Mongoose schema type,
1086
821
  // not the OpenAPI type (which reports ObjectId as "string")
1087
- var searchableFields = [];
1088
- var objectIdFields = [];
1089
- var modelMeta = (0, adminConfigIdentity_1.findAdminModelMetaByRoutePath)(configModels, "".concat(basePath).concat(config.routePath));
822
+ const searchableFields = [];
823
+ const objectIdFields = [];
824
+ const modelMeta = (0, adminConfigIdentity_1.findAdminModelMetaByRoutePath)(configModels, `${basePath}${config.routePath}`);
1090
825
  if (modelMeta) {
1091
- try {
1092
- for (var _u = (e_10 = void 0, __values(Object.keys(modelMeta.fields))), _v = _u.next(); !_v.done; _v = _u.next()) {
1093
- var key = _v.value;
1094
- var schemaPath = config.model.schema.path(key);
1095
- if (schemaPath && schemaPath.instance === "String" && !modelMeta.fields[key].enum) {
1096
- searchableFields.push(key);
1097
- }
1098
- else if (schemaPath && schemaPath.instance === "ObjectID") {
1099
- objectIdFields.push(key);
1100
- }
826
+ for (const key of Object.keys(modelMeta.fields)) {
827
+ const schemaPath = config.model.schema.path(key);
828
+ if (schemaPath && schemaPath.instance === "String" && !modelMeta.fields[key].enum) {
829
+ searchableFields.push(key);
1101
830
  }
1102
- }
1103
- catch (e_10_1) { e_10 = { error: e_10_1 }; }
1104
- finally {
1105
- try {
1106
- if (_v && !_v.done && (_t = _u.return)) _t.call(_u);
831
+ else if (schemaPath && schemaPath.instance === "ObjectID") {
832
+ objectIdFields.push(key);
1107
833
  }
1108
- finally { if (e_10) throw e_10.error; }
1109
834
  }
1110
835
  }
1111
- app.get("".concat(basePath).concat(config.routePath, "/search"), (0, api_1.authenticateMiddleware)(), (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1112
- var q, fields, searchClause, scoped, results, err_3;
1113
- var _a;
1114
- return __generator(this, function (_b) {
1115
- switch (_b.label) {
1116
- case 0: return [4 /*yield*/, (0, api_1.checkPermissions)("list", this.resourceActionPermissions(config, "list"), req.user)];
1117
- case 1:
1118
- if (!(_b.sent())) {
1119
- throw new api_1.APIError({
1120
- disableExternalErrorTracking: true,
1121
- status: 403,
1122
- title: "Forbidden",
1123
- });
1124
- }
1125
- q = String((_a = req.query.q) !== null && _a !== void 0 ? _a : "");
1126
- if (!q) {
1127
- return [2 /*return*/, res.json({ data: [] })];
1128
- }
1129
- fields = typeof req.query.fields === "string"
1130
- ? req.query.fields.split(",").filter(function (f) { return searchableFields.includes(f); })
1131
- : searchableFields;
1132
- searchClause = (0, adminTextSearch_1.buildAdminPartialSearchFilter)({
1133
- extraObjectIdFields: objectIdFields,
1134
- model: config.model,
1135
- q: q,
1136
- searchFields: fields,
1137
- });
1138
- if (!searchClause) {
1139
- return [2 /*return*/, res.json({ data: [] })];
1140
- }
1141
- api_1.logger.debug("Admin search query", {
1142
- fields: fields,
1143
- model: config.model.modelName,
1144
- q: q,
1145
- });
1146
- _b.label = 2;
1147
- case 2:
1148
- _b.trys.push([2, 5, , 6]);
1149
- return [4 /*yield*/, buildAdminListQueryFilter(config, modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.searchFields)(req.user, {})];
1150
- case 3:
1151
- scoped = _b.sent();
1152
- if (scoped === null) {
1153
- return [2 /*return*/, res.json({ data: [] })];
1154
- }
1155
- return [4 /*yield*/, config.model
1156
- .find({ $and: [scoped, searchClause] })
1157
- .limit(20)
1158
- .lean()];
1159
- case 4:
1160
- results = _b.sent();
1161
- api_1.logger.debug("Admin search results", {
1162
- count: results.length,
1163
- model: config.model.modelName,
1164
- });
1165
- return [2 /*return*/, res.json({
1166
- data: results.map(function (doc) { return scrubAdminResponse(doc, config, allModelAdmins); }),
1167
- })];
1168
- case 5:
1169
- err_3 = _b.sent();
1170
- api_1.logger.error("Admin search failed", {
1171
- error: err_3,
1172
- fields: fields,
1173
- model: config.model.modelName,
1174
- });
1175
- throw err_3;
1176
- case 6: return [2 /*return*/];
1177
- }
836
+ app.get(`${basePath}${config.routePath}/search`, (0, api_1.authenticateMiddleware)(), ...(isOrganizationScoped ? [(0, api_1.orgContextMiddleware)({ required: true })] : []), (0, api_1.asyncHandler)(async (req, res) => {
837
+ if (!(await (0, api_1.checkPermissions)("list", this.resourceActionPermissions(config, "list"), req.user))) {
838
+ throw new api_1.APIError({
839
+ disableExternalErrorTracking: true,
840
+ status: 403,
841
+ title: "Forbidden",
842
+ });
843
+ }
844
+ const q = String(req.query.q ?? "");
845
+ if (!q) {
846
+ return res.json({ data: [] });
847
+ }
848
+ const fields = typeof req.query.fields === "string"
849
+ ? req.query.fields.split(",").filter((f) => searchableFields.includes(f))
850
+ : searchableFields;
851
+ const searchClause = (0, adminTextSearch_1.buildAdminPartialSearchFilter)({
852
+ extraObjectIdFields: objectIdFields,
853
+ model: config.model,
854
+ q,
855
+ searchFields: fields,
1178
856
  });
1179
- }); }));
1180
- };
1181
- try {
1182
- // Mount search endpoint for each model
1183
- for (var modelConfigs_1 = __values(modelConfigs), modelConfigs_1_1 = modelConfigs_1.next(); !modelConfigs_1_1.done; modelConfigs_1_1 = modelConfigs_1.next()) {
1184
- var config = modelConfigs_1_1.value;
1185
- _loop_1(config);
1186
- }
1187
- }
1188
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
1189
- finally {
1190
- try {
1191
- if (modelConfigs_1_1 && !modelConfigs_1_1.done && (_a = modelConfigs_1.return)) _a.call(modelConfigs_1);
1192
- }
1193
- finally { if (e_6) throw e_6.error; }
857
+ if (!searchClause) {
858
+ return res.json({ data: [] });
859
+ }
860
+ api_1.logger.debug("Admin search query", {
861
+ fields,
862
+ model: config.model.modelName,
863
+ q,
864
+ });
865
+ try {
866
+ const scoped = await buildAdminListQueryFilter(config, modelMeta?.searchFields, isOrganizationScoped)(req.user, {});
867
+ if (scoped === null) {
868
+ return res.json({ data: [] });
869
+ }
870
+ const results = await config.model
871
+ .find({ $and: [scoped, searchClause] })
872
+ .limit(20)
873
+ .lean();
874
+ api_1.logger.debug("Admin search results", {
875
+ count: results.length,
876
+ model: config.model.modelName,
877
+ });
878
+ return res.json({
879
+ data: results.map((doc) => scrubAdminResponse(doc, config, allModelAdmins)),
880
+ });
881
+ }
882
+ catch (err) {
883
+ api_1.logger.error("Admin search failed", {
884
+ error: err,
885
+ fields,
886
+ model: config.model.modelName,
887
+ });
888
+ throw err;
889
+ }
890
+ }));
1194
891
  }
1195
- var _loop_2 = function (config) {
1196
- var hiddenFieldSet = new Set((_g = config.hiddenFields) !== null && _g !== void 0 ? _g : []);
1197
- var readonlySet = new Set((_h = config.readonlyFields) !== null && _h !== void 0 ? _h : []);
1198
- var excludeFieldSet = new Set((_j = config.excludeFields) !== null && _j !== void 0 ? _j : []);
1199
- var modelMeta = (0, adminConfigIdentity_1.findAdminModelMetaByRoutePath)(configModels, "".concat(basePath).concat(config.routePath));
1200
- var allowlist = new Set((_k = modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.bulkPatchAllowlist) !== null && _k !== void 0 ? _k : []);
1201
- var adminPermission = function (allowed, action) {
892
+ // Mount modelRouter for each model with IsAdmin permissions
893
+ for (const config of modelConfigs) {
894
+ const isOrganizationScoped = this.isOrganizationScoped(config);
895
+ const hiddenFieldSet = new Set(config.hiddenFields ?? []);
896
+ const readonlySet = new Set(config.readonlyFields ?? []);
897
+ const excludeFieldSet = new Set(config.excludeFields ?? []);
898
+ const modelMeta = (0, adminConfigIdentity_1.findAdminModelMetaByRoutePath)(configModels, `${basePath}${config.routePath}`);
899
+ const allowlist = new Set(modelMeta?.bulkPatchAllowlist ?? []);
900
+ const adminPermission = (allowed, action) => {
1202
901
  if (allowed === false) {
1203
902
  return [];
1204
903
  }
1205
- return _this.resourceActionPermissions(config, action);
904
+ const permissions = this.resourceActionPermissions(config, action);
905
+ if (isOrganizationScoped && action !== "create") {
906
+ return [...permissions, api_1.Permissions.IsOrganizationMember];
907
+ }
908
+ return permissions;
1206
909
  };
1207
- var updatePermissions = this_1.resourceActionPermissions(config, "update");
1208
- var stripProtectedFromBody = function (body) {
1209
- var e_11, _a, e_12, _b, e_13, _c, e_14, _d;
910
+ const updatePermissions = adminPermission(config.permissions?.update, "update");
911
+ const stripProtectedFromBody = (body) => {
1210
912
  if (!body || typeof body !== "object" || Array.isArray(body)) {
1211
913
  return {};
1212
914
  }
1213
- var next = __assign({}, body);
1214
- try {
1215
- for (var readonlySet_1 = (e_11 = void 0, __values(readonlySet)), readonlySet_1_1 = readonlySet_1.next(); !readonlySet_1_1.done; readonlySet_1_1 = readonlySet_1.next()) {
1216
- var key = readonlySet_1_1.value;
1217
- delete next[key];
1218
- }
915
+ const next = { ...body };
916
+ for (const key of readonlySet) {
917
+ delete next[key];
1219
918
  }
1220
- catch (e_11_1) { e_11 = { error: e_11_1 }; }
1221
- finally {
1222
- try {
1223
- if (readonlySet_1_1 && !readonlySet_1_1.done && (_a = readonlySet_1.return)) _a.call(readonlySet_1);
1224
- }
1225
- finally { if (e_11) throw e_11.error; }
919
+ for (const key of hiddenFieldSet) {
920
+ delete next[key];
1226
921
  }
1227
- try {
1228
- for (var hiddenFieldSet_1 = (e_12 = void 0, __values(hiddenFieldSet)), hiddenFieldSet_1_1 = hiddenFieldSet_1.next(); !hiddenFieldSet_1_1.done; hiddenFieldSet_1_1 = hiddenFieldSet_1.next()) {
1229
- var key = hiddenFieldSet_1_1.value;
1230
- delete next[key];
1231
- }
922
+ for (const key of excludeFieldSet) {
923
+ delete next[key];
1232
924
  }
1233
- catch (e_12_1) { e_12 = { error: e_12_1 }; }
1234
- finally {
1235
- try {
1236
- if (hiddenFieldSet_1_1 && !hiddenFieldSet_1_1.done && (_b = hiddenFieldSet_1.return)) _b.call(hiddenFieldSet_1);
1237
- }
1238
- finally { if (e_12) throw e_12.error; }
1239
- }
1240
- try {
1241
- for (var excludeFieldSet_1 = (e_13 = void 0, __values(excludeFieldSet)), excludeFieldSet_1_1 = excludeFieldSet_1.next(); !excludeFieldSet_1_1.done; excludeFieldSet_1_1 = excludeFieldSet_1.next()) {
1242
- var key = excludeFieldSet_1_1.value;
1243
- delete next[key];
1244
- }
1245
- }
1246
- catch (e_13_1) { e_13 = { error: e_13_1 }; }
1247
- finally {
1248
- try {
1249
- if (excludeFieldSet_1_1 && !excludeFieldSet_1_1.done && (_c = excludeFieldSet_1.return)) _c.call(excludeFieldSet_1);
1250
- }
1251
- finally { if (e_13) throw e_13.error; }
1252
- }
1253
- try {
1254
- for (var SYSTEM_ADMIN_FIELDS_1 = (e_14 = void 0, __values(adminUiV2_1.SYSTEM_ADMIN_FIELDS)), SYSTEM_ADMIN_FIELDS_1_1 = SYSTEM_ADMIN_FIELDS_1.next(); !SYSTEM_ADMIN_FIELDS_1_1.done; SYSTEM_ADMIN_FIELDS_1_1 = SYSTEM_ADMIN_FIELDS_1.next()) {
1255
- var key = SYSTEM_ADMIN_FIELDS_1_1.value;
1256
- delete next[key];
1257
- }
1258
- }
1259
- catch (e_14_1) { e_14 = { error: e_14_1 }; }
1260
- finally {
1261
- try {
1262
- if (SYSTEM_ADMIN_FIELDS_1_1 && !SYSTEM_ADMIN_FIELDS_1_1.done && (_d = SYSTEM_ADMIN_FIELDS_1.return)) _d.call(SYSTEM_ADMIN_FIELDS_1);
1263
- }
1264
- finally { if (e_14) throw e_14.error; }
925
+ for (const key of adminUiV2_1.SYSTEM_ADMIN_FIELDS) {
926
+ delete next[key];
1265
927
  }
1266
928
  // Self-service never writes these fields. Admin CRUD may set `admin`.
1267
929
  // When RBAC is enabled, `roles` must go through RoleManager.assign and
1268
930
  // tenant membership is not a generic User document field.
1269
- if (config.model.modelName === "User" && _this.options.accessControl) {
931
+ if (config.model.modelName === "User" && this.options.accessControl) {
1270
932
  delete next.organizationIds;
1271
933
  delete next.roles;
1272
934
  }
1273
935
  return next;
1274
936
  };
1275
- var parseRoleNames = function (value) {
1276
- if (!Array.isArray(value) || value.some(function (roleName) { return typeof roleName !== "string"; })) {
937
+ const parseRoleNames = (value) => {
938
+ if (!Array.isArray(value) || value.some((roleName) => typeof roleName !== "string")) {
1277
939
  throw new api_1.APIError({ status: 400, title: "roles must be an array of strings" });
1278
940
  }
1279
941
  return value;
1280
942
  };
1281
- var takePendingUserRoles = function (body, request) {
1282
- if (config.model.modelName !== "User" || !_this.options.accessControl) {
943
+ const takePendingUserRoles = (body, request) => {
944
+ if (config.model.modelName !== "User" || !this.options.accessControl) {
1283
945
  return;
1284
946
  }
1285
947
  if (!("roles" in body)) {
@@ -1287,126 +949,81 @@ var AdminApp = /** @class */ (function () {
1287
949
  }
1288
950
  request.terrenoPendingUserRoles = parseRoleNames(body.roles);
1289
951
  };
1290
- var applyPendingUserRoles = function (value_1, request_1) {
1291
- var args_1 = [];
1292
- for (var _i = 2; _i < arguments.length; _i++) {
1293
- args_1[_i - 2] = arguments[_i];
952
+ const applyPendingUserRoles = async (value, request, rollbackOnFailure = false) => {
953
+ const pending = request
954
+ .terrenoPendingUserRoles;
955
+ if (!pending) {
956
+ return;
1294
957
  }
1295
- return __awaiter(_this, __spreadArray([value_1, request_1], __read(args_1), false), void 0, function (value, request, rollbackOnFailure) {
1296
- var pending, actor, accessControl, record, userId, error_1, rollbackError_1;
1297
- var _a;
1298
- if (rollbackOnFailure === void 0) { rollbackOnFailure = false; }
1299
- return __generator(this, function (_b) {
1300
- switch (_b.label) {
1301
- case 0:
1302
- pending = request
1303
- .terrenoPendingUserRoles;
1304
- if (!pending) {
1305
- return [2 /*return*/];
1306
- }
1307
- actor = request.user;
1308
- accessControl = this.options.accessControl;
1309
- if (!actor || !accessControl) {
1310
- throw new api_1.APIError({ status: 401, title: "Unauthorized" });
1311
- }
1312
- record = value;
1313
- userId = (_a = record.id) !== null && _a !== void 0 ? _a : (record._id != null ? String(record._id) : undefined);
1314
- if (!userId) {
1315
- throw new api_1.APIError({ status: 500, title: "User id missing after write" });
1316
- }
1317
- _b.label = 1;
1318
- case 1:
1319
- _b.trys.push([1, 3, , 8]);
1320
- return [4 /*yield*/, accessControl.roles.assign({ actor: actor, roleNames: pending, userId: userId })];
1321
- case 2:
1322
- _b.sent();
1323
- if (typeof record.set === "function") {
1324
- record.set("roles", __spreadArray([], __read(pending), false));
1325
- }
1326
- else {
1327
- record.roles = __spreadArray([], __read(pending), false);
1328
- }
1329
- return [3 /*break*/, 8];
1330
- case 3:
1331
- error_1 = _b.sent();
1332
- if (!rollbackOnFailure) return [3 /*break*/, 7];
1333
- _b.label = 4;
1334
- case 4:
1335
- _b.trys.push([4, 6, , 7]);
1336
- return [4 /*yield*/, config.model.deleteOne({ _id: userId })];
1337
- case 5:
1338
- _b.sent();
1339
- return [3 /*break*/, 7];
1340
- case 6:
1341
- rollbackError_1 = _b.sent();
1342
- api_1.logger.error("Failed to roll back user after role assignment failure", {
1343
- error: rollbackError_1,
1344
- userId: userId,
1345
- });
1346
- return [3 /*break*/, 7];
1347
- case 7: throw error_1;
1348
- case 8: return [2 /*return*/];
958
+ const actor = request.user;
959
+ const accessControl = this.options.accessControl;
960
+ if (!actor || !accessControl) {
961
+ throw new api_1.APIError({ status: 401, title: "Unauthorized" });
962
+ }
963
+ const record = value;
964
+ const userId = record.id ?? (record._id != null ? String(record._id) : undefined);
965
+ if (!userId) {
966
+ throw new api_1.APIError({ status: 500, title: "User id missing after write" });
967
+ }
968
+ try {
969
+ await accessControl.roles.assign({ actor, roleNames: pending, userId });
970
+ if (typeof record.set === "function") {
971
+ record.set("roles", [...pending]);
972
+ }
973
+ else {
974
+ record.roles = [...pending];
975
+ }
976
+ }
977
+ catch (error) {
978
+ if (rollbackOnFailure) {
979
+ try {
980
+ await config.model.deleteOne({ _id: userId });
1349
981
  }
1350
- });
1351
- });
982
+ catch (rollbackError) {
983
+ api_1.logger.error("Failed to roll back user after role assignment failure", {
984
+ error: rollbackError,
985
+ userId,
986
+ });
987
+ }
988
+ }
989
+ throw error;
990
+ }
1352
991
  };
1353
- var restoreUserFieldsAfterFailedRoleAssign = function (value, prev, cleanedBody) { return __awaiter(_this, void 0, void 0, function () {
1354
- var record, prevRecord, body, restore, _a, _b, key;
1355
- var e_15, _c;
1356
- return __generator(this, function (_d) {
1357
- switch (_d.label) {
1358
- case 0:
1359
- if (!prev || typeof prev !== "object" || !cleanedBody || typeof cleanedBody !== "object") {
1360
- return [2 /*return*/];
1361
- }
1362
- if (Array.isArray(cleanedBody)) {
1363
- return [2 /*return*/];
1364
- }
1365
- record = value;
1366
- prevRecord = prev;
1367
- body = cleanedBody;
1368
- restore = {};
1369
- try {
1370
- for (_a = __values(Object.keys(body)), _b = _a.next(); !_b.done; _b = _a.next()) {
1371
- key = _b.value;
1372
- if (key === "roles") {
1373
- continue;
1374
- }
1375
- restore[key] = prevRecord[key];
1376
- if (typeof record.set === "function") {
1377
- record.set(key, prevRecord[key]);
1378
- }
1379
- }
1380
- }
1381
- catch (e_15_1) { e_15 = { error: e_15_1 }; }
1382
- finally {
1383
- try {
1384
- if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
1385
- }
1386
- finally { if (e_15) throw e_15.error; }
1387
- }
1388
- if (Object.keys(restore).length === 0) {
1389
- return [2 /*return*/];
1390
- }
1391
- if (!(typeof record.save === "function")) return [3 /*break*/, 2];
1392
- return [4 /*yield*/, record.save()];
1393
- case 1:
1394
- _d.sent();
1395
- return [2 /*return*/];
1396
- case 2:
1397
- if (!(record._id != null)) return [3 /*break*/, 4];
1398
- return [4 /*yield*/, config.model.updateOne({ _id: record._id }, { $set: restore })];
1399
- case 3:
1400
- _d.sent();
1401
- _d.label = 4;
1402
- case 4: return [2 /*return*/];
992
+ const restoreUserFieldsAfterFailedRoleAssign = async (value, prev, cleanedBody) => {
993
+ if (!prev || typeof prev !== "object" || !cleanedBody || typeof cleanedBody !== "object") {
994
+ return;
995
+ }
996
+ if (Array.isArray(cleanedBody)) {
997
+ return;
998
+ }
999
+ const record = value;
1000
+ const prevRecord = prev;
1001
+ const body = cleanedBody;
1002
+ const restore = {};
1003
+ for (const key of Object.keys(body)) {
1004
+ if (key === "roles") {
1005
+ continue;
1403
1006
  }
1404
- });
1405
- }); };
1406
- var bulkPatchOpenApi = openApiMw
1007
+ restore[key] = prevRecord[key];
1008
+ if (typeof record.set === "function") {
1009
+ record.set(key, prevRecord[key]);
1010
+ }
1011
+ }
1012
+ if (Object.keys(restore).length === 0) {
1013
+ return;
1014
+ }
1015
+ if (typeof record.save === "function") {
1016
+ await record.save();
1017
+ return;
1018
+ }
1019
+ if (record._id != null) {
1020
+ await config.model.updateOne({ _id: record._id }, { $set: restore });
1021
+ }
1022
+ };
1023
+ const bulkPatchOpenApi = openApiMw
1407
1024
  ? (0, api_1.createOpenApiBuilder)({ openApi: openApiMw })
1408
1025
  .withTags(["admin"])
1409
- .withSummary("Bulk patch ".concat(config.model.modelName, " documents"))
1026
+ .withSummary(`Bulk patch ${(0, api_1.publicFrameworkModelName)(config.model.modelName)} documents`)
1410
1027
  .withRequestBody({
1411
1028
  ids: {
1412
1029
  description: "Document ids to update",
@@ -1426,841 +1043,612 @@ var AdminApp = /** @class */ (function () {
1426
1043
  })
1427
1044
  .build()
1428
1045
  : undefined;
1429
- var auditEligible = Boolean(onAdminAudit) && config.model.modelName !== "AdminAuditLog";
1430
- var auditHooks = auditEligible
1431
- ? {
1432
- postCreate: function (value, request) { return __awaiter(_this, void 0, void 0, function () {
1433
- var doc, rid;
1434
- return __generator(this, function (_a) {
1435
- switch (_a.label) {
1436
- case 0:
1437
- doc = auditDocumentToPlain(value);
1438
- rid = doc._id;
1439
- return [4 /*yield*/, safeOnAdminAudit(request, {
1440
- actorId: auditActorId(request),
1441
- modelName: config.model.modelName,
1442
- recordId: rid != null ? String(rid) : undefined,
1443
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1444
- verb: "created",
1445
- })];
1446
- case 1:
1447
- _a.sent();
1448
- return [2 /*return*/];
1449
- }
1450
- });
1451
- }); },
1452
- postDelete: function (request, value) { return __awaiter(_this, void 0, void 0, function () {
1453
- var doc, rid;
1454
- return __generator(this, function (_a) {
1455
- switch (_a.label) {
1456
- case 0:
1457
- doc = auditDocumentToPlain(value);
1458
- rid = doc._id;
1459
- return [4 /*yield*/, safeOnAdminAudit(request, {
1460
- actorId: auditActorId(request),
1461
- modelName: config.model.modelName,
1462
- recordId: rid != null ? String(rid) : undefined,
1463
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1464
- verb: "deleted",
1465
- })];
1466
- case 1:
1467
- _a.sent();
1468
- return [2 /*return*/];
1469
- }
1470
- });
1471
- }); },
1472
- postUpdate: function (value, _cleanedBody, request, _prev) { return __awaiter(_this, void 0, void 0, function () {
1473
- var doc, rid;
1474
- return __generator(this, function (_a) {
1475
- switch (_a.label) {
1476
- case 0:
1477
- doc = auditDocumentToPlain(value);
1478
- rid = doc._id;
1479
- return [4 /*yield*/, safeOnAdminAudit(request, {
1480
- actorId: auditActorId(request),
1481
- modelName: config.model.modelName,
1482
- recordId: rid != null ? String(rid) : undefined,
1483
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1484
- verb: "updated",
1485
- })];
1486
- case 1:
1487
- _a.sent();
1488
- return [2 /*return*/];
1489
- }
1490
- });
1491
- }); },
1046
+ const skipOnAdminAuditHook = config.model.modelName === "AdminAuditLog";
1047
+ const auditHooks = {
1048
+ postCreate: async (value, request) => {
1049
+ const doc = auditDocumentToPlain(value);
1050
+ const rid = doc._id;
1051
+ const recordLabel = auditLabelFromListFields(doc, config.listFields);
1052
+ await safeFrameworkAdminAudit({
1053
+ after: value,
1054
+ extraRedact: [...hiddenFieldSet, ...excludeFieldSet],
1055
+ modelName: config.model.modelName,
1056
+ recordLabel,
1057
+ request,
1058
+ verb: "created",
1059
+ });
1060
+ if (skipOnAdminAuditHook) {
1061
+ return;
1062
+ }
1063
+ await safeOnAdminAudit(request, {
1064
+ actorId: auditActorId(request),
1065
+ modelName: config.model.modelName,
1066
+ recordId: rid != null ? String(rid) : undefined,
1067
+ recordLabel,
1068
+ verb: "created",
1069
+ });
1070
+ },
1071
+ postDelete: async (request, value) => {
1072
+ const doc = auditDocumentToPlain(value);
1073
+ const rid = doc._id;
1074
+ const recordLabel = auditLabelFromListFields(doc, config.listFields);
1075
+ await safeFrameworkAdminAudit({
1076
+ before: value,
1077
+ extraRedact: [...hiddenFieldSet, ...excludeFieldSet],
1078
+ modelName: config.model.modelName,
1079
+ recordLabel,
1080
+ request,
1081
+ verb: "deleted",
1082
+ });
1083
+ if (skipOnAdminAuditHook) {
1084
+ return;
1085
+ }
1086
+ await safeOnAdminAudit(request, {
1087
+ actorId: auditActorId(request),
1088
+ modelName: config.model.modelName,
1089
+ recordId: rid != null ? String(rid) : undefined,
1090
+ recordLabel,
1091
+ verb: "deleted",
1092
+ });
1093
+ },
1094
+ postUpdate: async (value, _cleanedBody, request, prev) => {
1095
+ const doc = auditDocumentToPlain(value);
1096
+ const rid = doc._id;
1097
+ const recordLabel = auditLabelFromListFields(doc, config.listFields);
1098
+ await safeFrameworkAdminAudit({
1099
+ after: value,
1100
+ before: prev,
1101
+ extraRedact: [...hiddenFieldSet, ...excludeFieldSet],
1102
+ modelName: config.model.modelName,
1103
+ recordLabel,
1104
+ request,
1105
+ verb: "updated",
1106
+ });
1107
+ if (skipOnAdminAuditHook) {
1108
+ return;
1109
+ }
1110
+ await safeOnAdminAudit(request, {
1111
+ actorId: auditActorId(request),
1112
+ modelName: config.model.modelName,
1113
+ recordId: rid != null ? String(rid) : undefined,
1114
+ recordLabel,
1115
+ verb: "updated",
1116
+ });
1117
+ },
1118
+ };
1119
+ const assertCanWriteUserAdminFlag = async (body, request, currentAdmin = false, targetUserId) => {
1120
+ if (config.model.modelName !== "User" || !("admin" in body)) {
1121
+ return;
1492
1122
  }
1493
- : {};
1494
- var assertCanWriteUserAdminFlag = function (body_1, request_1) {
1495
- var args_1 = [];
1496
- for (var _i = 2; _i < arguments.length; _i++) {
1497
- args_1[_i - 2] = arguments[_i];
1123
+ const accessControl = this.options.accessControl;
1124
+ if (!accessControl) {
1125
+ return;
1498
1126
  }
1499
- return __awaiter(_this, __spreadArray([body_1, request_1], __read(args_1), false), void 0, function (body, request, currentAdmin, targetUserId) {
1500
- var accessControl, actor, result, nextAdmin, isGrantingAdmin, isRevokingAdmin, targetId;
1501
- var _a;
1502
- if (currentAdmin === void 0) { currentAdmin = false; }
1503
- return __generator(this, function (_b) {
1504
- switch (_b.label) {
1505
- case 0:
1506
- if (config.model.modelName !== "User" || !("admin" in body)) {
1507
- return [2 /*return*/];
1508
- }
1509
- accessControl = this.options.accessControl;
1510
- if (!accessControl) {
1511
- return [2 /*return*/];
1512
- }
1513
- if (coerceAdminFlag(body.admin) === Boolean(currentAdmin)) {
1514
- return [2 /*return*/];
1515
- }
1516
- actor = request.user;
1517
- if (!actor) {
1518
- throw new api_1.APIError({ status: 401, title: "Unauthorized" });
1519
- }
1520
- return [4 /*yield*/, accessControl.can({
1521
- permissions: { rbac: ["assignRoles"] },
1522
- user: actor,
1523
- })];
1524
- case 1:
1525
- result = _b.sent();
1526
- if (!result.allowed) {
1527
- throw new api_1.APIError({
1528
- status: 403,
1529
- title: "Missing rbac:assignRoles permission",
1530
- });
1531
- }
1532
- nextAdmin = coerceAdminFlag(body.admin);
1533
- isGrantingAdmin = nextAdmin === true && !currentAdmin;
1534
- isRevokingAdmin = nextAdmin === false && currentAdmin;
1535
- // assignRoles and manageRoles still cannot mint or strip the legacy admin
1536
- // plane (IsAdmin, password reset, owner bypass). Only an existing admin can.
1537
- if ((isGrantingAdmin || isRevokingAdmin) && !actor.admin) {
1538
- throw new api_1.APIError({
1539
- status: 403,
1540
- title: isGrantingAdmin
1541
- ? "Cannot grant the legacy admin flag without the admin privilege"
1542
- : "Cannot revoke the legacy admin flag without the admin privilege",
1543
- });
1544
- }
1545
- targetId = targetUserId !== null && targetUserId !== void 0 ? targetUserId : (_a = request.params) === null || _a === void 0 ? void 0 : _a.id;
1546
- if (!targetId) return [3 /*break*/, 3];
1547
- return [4 /*yield*/, accessControl.roles.assertCanModifyUser({ actor: actor, userId: String(targetId) })];
1548
- case 2:
1549
- _b.sent();
1550
- _b.label = 3;
1551
- case 3: return [2 /*return*/];
1552
- }
1553
- });
1127
+ if (coerceAdminFlag(body.admin) === Boolean(currentAdmin)) {
1128
+ return;
1129
+ }
1130
+ const actor = request.user;
1131
+ if (!actor) {
1132
+ throw new api_1.APIError({ status: 401, title: "Unauthorized" });
1133
+ }
1134
+ const result = await accessControl.can({
1135
+ permissions: { rbac: ["assignRoles"] },
1136
+ user: actor,
1554
1137
  });
1138
+ if (!result.allowed) {
1139
+ throw new api_1.APIError({
1140
+ status: 403,
1141
+ title: "Missing rbac:assignRoles permission",
1142
+ });
1143
+ }
1144
+ const nextAdmin = coerceAdminFlag(body.admin);
1145
+ const isGrantingAdmin = nextAdmin === true && !currentAdmin;
1146
+ const isRevokingAdmin = nextAdmin === false && currentAdmin;
1147
+ // assignRoles and manageRoles still cannot mint or strip the legacy admin
1148
+ // plane (IsAdmin, password reset, owner bypass). Only an existing admin can.
1149
+ if ((isGrantingAdmin || isRevokingAdmin) && !actor.admin) {
1150
+ throw new api_1.APIError({
1151
+ status: 403,
1152
+ title: isGrantingAdmin
1153
+ ? "Cannot grant the legacy admin flag without the admin privilege"
1154
+ : "Cannot revoke the legacy admin flag without the admin privilege",
1155
+ });
1156
+ }
1157
+ const targetId = targetUserId ?? request.params?.id;
1158
+ if (targetId) {
1159
+ await accessControl.roles.assertCanModifyUser({ actor, userId: String(targetId) });
1160
+ }
1555
1161
  };
1556
- var currentUserAdminFlag = function (request) { return __awaiter(_this, void 0, void 0, function () {
1557
- var id, existing;
1558
- var _a;
1559
- return __generator(this, function (_b) {
1560
- switch (_b.label) {
1561
- case 0:
1562
- id = (_a = request.params) === null || _a === void 0 ? void 0 : _a.id;
1563
- if (!id) {
1564
- return [2 /*return*/, false];
1565
- }
1566
- return [4 /*yield*/, config.model.findById(id).select("admin").lean()];
1567
- case 1:
1568
- existing = _b.sent();
1569
- return [2 /*return*/, Boolean(existing === null || existing === void 0 ? void 0 : existing.admin)];
1570
- }
1571
- });
1572
- }); };
1573
- var markAuthorizedUserAdminWrite = function (body, request) {
1162
+ const currentUserAdminFlag = async (request) => {
1163
+ const id = request.params?.id;
1164
+ if (!id) {
1165
+ return false;
1166
+ }
1167
+ const existing = await config.model.findById(id).select("admin").lean();
1168
+ return Boolean(existing?.admin);
1169
+ };
1170
+ const markAuthorizedUserAdminWrite = (body, request) => {
1574
1171
  if (config.model.modelName !== "User" ||
1575
- !_this.options.accessControl ||
1172
+ !this.options.accessControl ||
1576
1173
  !("admin" in body)) {
1577
1174
  return;
1578
1175
  }
1579
1176
  request.terrenoAllowUserAdminWrite = true;
1580
1177
  };
1581
- var addRecordCapabilities = function (value, request) { return __awaiter(_this, void 0, void 0, function () {
1582
- var scrubbed, sourceItems, scrubbedItems, withCapabilities;
1583
- var _this = this;
1584
- return __generator(this, function (_a) {
1585
- switch (_a.label) {
1586
- case 0:
1587
- scrubbed = scrubAdminResponse(value, config, allModelAdmins);
1588
- sourceItems = Array.isArray(value) ? value : [value];
1589
- scrubbedItems = Array.isArray(scrubbed) ? scrubbed : [scrubbed];
1590
- return [4 /*yield*/, Promise.all(scrubbedItems.map(function (item, index) { return __awaiter(_this, void 0, void 0, function () {
1591
- var instance, canUpdate, _a, canDelete, _b;
1592
- var _c, _d;
1593
- return __generator(this, function (_e) {
1594
- switch (_e.label) {
1595
- case 0:
1596
- if (!item || typeof item !== "object" || Array.isArray(item)) {
1597
- return [2 /*return*/, item];
1598
- }
1599
- instance = sourceItems[index];
1600
- _a = ((_c = config.permissions) === null || _c === void 0 ? void 0 : _c.update) !== false;
1601
- if (!_a) return [3 /*break*/, 2];
1602
- return [4 /*yield*/, (0, api_1.checkPermissions)("update", this.resourceActionPermissions(config, "update"), request.user, instance)];
1603
- case 1:
1604
- _a = (_e.sent());
1605
- _e.label = 2;
1606
- case 2:
1607
- canUpdate = _a;
1608
- _b = ((_d = config.permissions) === null || _d === void 0 ? void 0 : _d.delete) !== false;
1609
- if (!_b) return [3 /*break*/, 4];
1610
- return [4 /*yield*/, (0, api_1.checkPermissions)("delete", this.resourceActionPermissions(config, "delete"), request.user, instance)];
1611
- case 3:
1612
- _b = (_e.sent());
1613
- _e.label = 4;
1614
- case 4:
1615
- canDelete = _b;
1616
- return [2 /*return*/, __assign(__assign({}, item), { _adminCapabilities: { delete: canDelete, update: canUpdate } })];
1617
- }
1618
- });
1619
- }); }))];
1620
- case 1:
1621
- withCapabilities = _a.sent();
1622
- return [2 /*return*/, (Array.isArray(scrubbed) ? withCapabilities : withCapabilities[0])];
1178
+ const addRecordCapabilities = async (value, request) => {
1179
+ const scrubbed = scrubAdminResponse(value, config, allModelAdmins);
1180
+ const sourceItems = Array.isArray(value) ? value : [value];
1181
+ const scrubbedItems = Array.isArray(scrubbed) ? scrubbed : [scrubbed];
1182
+ const withCapabilities = await Promise.all(scrubbedItems.map(async (item, index) => {
1183
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
1184
+ return item;
1623
1185
  }
1624
- });
1625
- }); };
1186
+ const instance = sourceItems[index];
1187
+ const canUpdate = config.permissions?.update !== false &&
1188
+ (await (0, api_1.checkPermissions)("update", this.resourceActionPermissions(config, "update"), request.user, instance));
1189
+ const canDelete = config.permissions?.delete !== false &&
1190
+ (await (0, api_1.checkPermissions)("delete", this.resourceActionPermissions(config, "delete"), request.user, instance));
1191
+ return {
1192
+ ...item,
1193
+ _adminCapabilities: { delete: canDelete, update: canUpdate },
1194
+ };
1195
+ }));
1196
+ return (Array.isArray(scrubbed) ? withCapabilities : withCapabilities[0]);
1197
+ };
1626
1198
  // noExplicitAny: matches the Model<any> from AdminModelConfig above.
1627
1199
  // biome-ignore lint/suspicious/noExplicitAny: matches the Model<any> from AdminModelConfig above.
1628
- var routerOptions = __assign(__assign(__assign(__assign(__assign({}, (openApiMw ? { openApi: openApiMw } : {})), (this_1.options.accessControl ? { accessControl: this_1.options.accessControl } : {})), { defaultLimit: (_l = config.pageSize) !== null && _l !== void 0 ? _l : 100, maxLimit: 500, permissions: {
1629
- create: adminPermission((_m = config.permissions) === null || _m === void 0 ? void 0 : _m.create, "create"),
1630
- delete: adminPermission((_o = config.permissions) === null || _o === void 0 ? void 0 : _o.delete, "delete"),
1200
+ const routerOptions = {
1201
+ ...(openApiMw ? { openApi: openApiMw } : {}),
1202
+ ...(this.options.accessControl ? { accessControl: this.options.accessControl } : {}),
1203
+ defaultLimit: config.pageSize ?? 100,
1204
+ maxLimit: 500,
1205
+ permissions: {
1206
+ create: adminPermission(config.permissions?.create, "create"),
1207
+ delete: adminPermission(config.permissions?.delete, "delete"),
1631
1208
  list: adminPermission(true, "list"),
1632
1209
  read: adminPermission(true, "read"),
1633
- update: adminPermission((_p = config.permissions) === null || _p === void 0 ? void 0 : _p.update, "update"),
1634
- }, postCreate: function (value, request) { return __awaiter(_this, void 0, void 0, function () {
1635
- var _a;
1636
- return __generator(this, function (_b) {
1637
- switch (_b.label) {
1638
- case 0: return [4 /*yield*/, applyPendingUserRoles(value, request, true)];
1639
- case 1:
1640
- _b.sent();
1641
- return [4 /*yield*/, ((_a = auditHooks.postCreate) === null || _a === void 0 ? void 0 : _a.call(auditHooks, value, request))];
1642
- case 2:
1643
- _b.sent();
1644
- return [2 /*return*/];
1645
- }
1646
- });
1647
- }); }, postUpdate: function (value, cleanedBody, request, prev) { return __awaiter(_this, void 0, void 0, function () {
1648
- var error_2;
1649
- var _a;
1650
- return __generator(this, function (_b) {
1651
- switch (_b.label) {
1652
- case 0:
1653
- _b.trys.push([0, 2, , 4]);
1654
- return [4 /*yield*/, applyPendingUserRoles(value, request)];
1655
- case 1:
1656
- _b.sent();
1657
- return [3 /*break*/, 4];
1658
- case 2:
1659
- error_2 = _b.sent();
1660
- return [4 /*yield*/, restoreUserFieldsAfterFailedRoleAssign(value, prev, cleanedBody)];
1661
- case 3:
1662
- _b.sent();
1663
- throw error_2;
1664
- case 4: return [4 /*yield*/, ((_a = auditHooks.postUpdate) === null || _a === void 0 ? void 0 : _a.call(auditHooks, value, cleanedBody, request, prev))];
1665
- case 5:
1666
- _b.sent();
1667
- return [2 /*return*/];
1668
- }
1669
- });
1670
- }); }, preCreate: function (body, req) { return __awaiter(_this, void 0, void 0, function () {
1671
- var record;
1672
- return __generator(this, function (_a) {
1673
- switch (_a.label) {
1674
- case 0:
1675
- if (!body || typeof body !== "object") {
1676
- return [2 /*return*/, body];
1677
- }
1678
- record = body;
1679
- return [4 /*yield*/, (0, api_1.checkPermissions)("create", this.resourceActionPermissions(config, "create"), req.user, record)];
1680
- case 1:
1681
- if (!(_a.sent())) {
1682
- throw new api_1.APIError({ status: 403, title: "Admin create access denied" });
1683
- }
1684
- takePendingUserRoles(record, req);
1685
- return [4 /*yield*/, assertCanWriteUserAdminFlag(record, req)];
1686
- case 2:
1687
- _a.sent();
1688
- markAuthorizedUserAdminWrite(record, req);
1689
- return [2 /*return*/, stripProtectedFromBody(body)];
1690
- }
1691
- });
1692
- }); }, preUpdate: function (body, req) { return __awaiter(_this, void 0, void 0, function () {
1693
- var record, _a, _b;
1694
- return __generator(this, function (_c) {
1695
- switch (_c.label) {
1696
- case 0:
1697
- if (!body || typeof body !== "object") {
1698
- return [2 /*return*/, body];
1699
- }
1700
- record = body;
1701
- takePendingUserRoles(record, req);
1702
- _a = assertCanWriteUserAdminFlag;
1703
- _b = [record, req];
1704
- return [4 /*yield*/, currentUserAdminFlag(req)];
1705
- case 1: return [4 /*yield*/, _a.apply(void 0, _b.concat([_c.sent()]))];
1706
- case 2:
1707
- _c.sent();
1708
- markAuthorizedUserAdminWrite(record, req);
1709
- return [2 /*return*/, stripProtectedFromBody(body)];
1710
- }
1711
- });
1712
- }); }, queryFields: (0, adminUiV2_1.buildAdminModelQueryFields)({
1210
+ update: adminPermission(config.permissions?.update, "update"),
1211
+ },
1212
+ postCreate: async (value, request) => {
1213
+ await applyPendingUserRoles(value, request, true);
1214
+ await auditHooks.postCreate?.(value, request);
1215
+ },
1216
+ postUpdate: async (value, cleanedBody, request, prev) => {
1217
+ try {
1218
+ await applyPendingUserRoles(value, request);
1219
+ }
1220
+ catch (error) {
1221
+ await restoreUserFieldsAfterFailedRoleAssign(value, prev, cleanedBody);
1222
+ throw error;
1223
+ }
1224
+ await auditHooks.postUpdate?.(value, cleanedBody, request, prev);
1225
+ },
1226
+ preCreate: async (body, req) => {
1227
+ if (!body || typeof body !== "object") {
1228
+ return body;
1229
+ }
1230
+ const record = body;
1231
+ if (isOrganizationScoped) {
1232
+ record.organizationId = (0, api_1.getOrgContext)()?.organization?._id;
1233
+ }
1234
+ if (!(await (0, api_1.checkPermissions)("create", this.resourceActionPermissions(config, "create"), req.user, record))) {
1235
+ throw new api_1.APIError({ status: 403, title: "Admin create access denied" });
1236
+ }
1237
+ takePendingUserRoles(record, req);
1238
+ await assertCanWriteUserAdminFlag(record, req);
1239
+ markAuthorizedUserAdminWrite(record, req);
1240
+ return stripProtectedFromBody(body);
1241
+ },
1242
+ preUpdate: async (body, req) => {
1243
+ if (!body || typeof body !== "object") {
1244
+ return body;
1245
+ }
1246
+ const record = body;
1247
+ takePendingUserRoles(record, req);
1248
+ await assertCanWriteUserAdminFlag(record, req, await currentUserAdminFlag(req));
1249
+ markAuthorizedUserAdminWrite(record, req);
1250
+ return stripProtectedFromBody(body);
1251
+ },
1252
+ queryFields: (0, adminUiV2_1.buildAdminModelQueryFields)({
1713
1253
  filters: config.filters,
1714
1254
  listDisplay: config.listDisplay,
1715
1255
  listFields: config.listFields,
1716
- searchFields: (_q = modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.searchFields) !== null && _q !== void 0 ? _q : config.searchFields,
1717
- }), queryFilter: buildAdminListQueryFilter(config, modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.searchFields), responseHandler: function (value, _method, request) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
1718
- return [2 /*return*/, addRecordCapabilities(value, request)];
1719
- }); }); }, sort: (_r = config.defaultSort) !== null && _r !== void 0 ? _r : "-created" }), (config.populatePaths ? { populatePaths: config.populatePaths } : {})), (auditHooks.postDelete ? { postDelete: auditHooks.postDelete } : {}));
1720
- var modelBase = express_1.default.Router();
1721
- modelBase.use(validateAdminSortParam((_s = modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.sortableFields) !== null && _s !== void 0 ? _s : []));
1722
- modelBase.post.apply(modelBase, __spreadArray(__spreadArray(["/bulk-patch",
1723
- (0, api_1.authenticateMiddleware)()], __read(asMiddlewareList(bulkPatchOpenApi)), false), [(0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1724
- var body, ids, rawPatch, unknownKeys, patch, pendingRoles, updated, failures, actor, ids_1, ids_1_1, id, doc, previousPatch, _a, _b, key, roleError_1, err_4, message, e_16_1;
1725
- var e_16, _c, e_17, _d;
1726
- var _e, _f;
1727
- return __generator(this, function (_g) {
1728
- switch (_g.label) {
1729
- case 0: return [4 /*yield*/, (0, api_1.checkPermissions)("update", updatePermissions, req.user)];
1730
- case 1:
1731
- if (!(_g.sent())) {
1732
- throw new api_1.APIError({ status: 403, title: "Admin access required" });
1733
- }
1734
- if (((_e = config.permissions) === null || _e === void 0 ? void 0 : _e.update) === false) {
1735
- throw new api_1.APIError({ status: 403, title: "Updates are disabled for this model" });
1736
- }
1737
- body = req.body;
1738
- if (!Array.isArray(body.ids)) {
1739
- throw new api_1.APIError({ status: 400, title: "Request body must include an ids array" });
1740
- }
1741
- if (typeof body.patch !== "object" || body.patch === null || Array.isArray(body.patch)) {
1742
- throw new api_1.APIError({ status: 400, title: "Request body must include a patch object" });
1743
- }
1744
- ids = __spreadArray([], __read(new Set(body.ids.map(function (id) { return String(id); }))), false);
1745
- if (ids.length === 0) {
1746
- throw new api_1.APIError({ status: 400, title: "ids must include at least one id" });
1747
- }
1748
- if (ids.length > adminUiV2_1.MAX_BULK_PATCH_IDS) {
1749
- throw new api_1.APIError({
1750
- status: 400,
1751
- title: "At most ".concat(adminUiV2_1.MAX_BULK_PATCH_IDS, " ids may be patched at once"),
1752
- });
1753
- }
1754
- rawPatch = body.patch;
1755
- unknownKeys = Object.keys(rawPatch).filter(function (key) { return !allowlist.has(key); });
1756
- if (unknownKeys.length > 0) {
1757
- throw new api_1.APIError({
1758
- detail: unknownKeys.join(", "),
1759
- status: 400,
1760
- title: "Patch contains keys that are not allowlisted for bulk patch",
1761
- });
1762
- }
1763
- patch = stripProtectedFromBody(rawPatch);
1764
- if (config.model.modelName === "User" &&
1765
- this.options.accessControl &&
1766
- "roles" in rawPatch) {
1767
- pendingRoles = parseRoleNames(rawPatch.roles);
1768
- }
1769
- if (Object.keys(patch).length === 0 && pendingRoles === undefined) {
1770
- throw new api_1.APIError({
1771
- status: 400,
1772
- title: "Patch must include at least one writable field",
1773
- });
1774
- }
1775
- updated = 0;
1776
- failures = [];
1777
- actor = req.user;
1778
- _g.label = 2;
1779
- case 2:
1780
- _g.trys.push([2, 19, 20, 21]);
1781
- ids_1 = __values(ids), ids_1_1 = ids_1.next();
1782
- _g.label = 3;
1783
- case 3:
1784
- if (!!ids_1_1.done) return [3 /*break*/, 18];
1785
- id = ids_1_1.value;
1786
- if (!mongoose_1.default.isValidObjectId(id)) {
1787
- failures.push({ id: id, title: "Invalid id" });
1788
- return [3 /*break*/, 17];
1789
- }
1790
- _g.label = 4;
1791
- case 4:
1792
- _g.trys.push([4, 16, , 17]);
1793
- return [4 /*yield*/, config.model.findById(id)];
1794
- case 5:
1795
- doc = _g.sent();
1796
- if (!doc) {
1797
- failures.push({ id: id, title: "Not found" });
1798
- return [3 /*break*/, 17];
1799
- }
1800
- return [4 /*yield*/, (0, api_1.checkPermissions)("update", updatePermissions, actor, doc)];
1801
- case 6:
1802
- if (!(_g.sent())) {
1803
- failures.push({ id: id, title: "Forbidden" });
1804
- return [3 /*break*/, 17];
1805
- }
1806
- return [4 /*yield*/, assertCanWriteUserAdminFlag(rawPatch, req, Boolean(doc.admin), id)];
1807
- case 7:
1808
- _g.sent();
1809
- previousPatch = {};
1810
- try {
1811
- for (_a = (e_17 = void 0, __values(Object.keys(patch))), _b = _a.next(); !_b.done; _b = _a.next()) {
1812
- key = _b.value;
1813
- previousPatch[key] = doc[key];
1814
- }
1815
- }
1816
- catch (e_17_1) { e_17 = { error: e_17_1 }; }
1817
- finally {
1818
- try {
1819
- if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
1820
- }
1821
- finally { if (e_17) throw e_17.error; }
1822
- }
1823
- if (!(Object.keys(patch).length > 0)) return [3 /*break*/, 9];
1824
- return [4 /*yield*/, doc.updateOne({ $set: patch })];
1825
- case 8:
1826
- _g.sent();
1827
- _g.label = 9;
1828
- case 9:
1829
- _g.trys.push([9, 12, , 15]);
1830
- if (!pendingRoles) return [3 /*break*/, 11];
1831
- if (!actor) {
1832
- failures.push({ id: id, title: "Forbidden" });
1833
- return [3 /*break*/, 17];
1834
- }
1835
- return [4 /*yield*/, ((_f = this.options.accessControl) === null || _f === void 0 ? void 0 : _f.roles.assign({
1836
- actor: actor,
1837
- roleNames: pendingRoles,
1838
- userId: id,
1839
- }))];
1840
- case 10:
1841
- _g.sent();
1842
- _g.label = 11;
1843
- case 11: return [3 /*break*/, 15];
1844
- case 12:
1845
- roleError_1 = _g.sent();
1846
- if (!(Object.keys(previousPatch).length > 0)) return [3 /*break*/, 14];
1847
- return [4 /*yield*/, config.model.updateOne({ _id: id }, { $set: previousPatch })];
1848
- case 13:
1849
- _g.sent();
1850
- _g.label = 14;
1851
- case 14: throw roleError_1;
1852
- case 15:
1853
- updated += 1;
1854
- return [3 /*break*/, 17];
1855
- case 16:
1856
- err_4 = _g.sent();
1857
- message = err_4 instanceof Error ? err_4.message : String(err_4);
1858
- failures.push({ id: id, title: message });
1859
- return [3 /*break*/, 17];
1860
- case 17:
1861
- ids_1_1 = ids_1.next();
1862
- return [3 /*break*/, 3];
1863
- case 18: return [3 /*break*/, 21];
1864
- case 19:
1865
- e_16_1 = _g.sent();
1866
- e_16 = { error: e_16_1 };
1867
- return [3 /*break*/, 21];
1868
- case 20:
1869
- try {
1870
- if (ids_1_1 && !ids_1_1.done && (_c = ids_1.return)) _c.call(ids_1);
1871
- }
1872
- finally { if (e_16) throw e_16.error; }
1873
- return [7 /*endfinally*/];
1874
- case 21: return [2 /*return*/, res.json({ failures: failures.length > 0 ? failures : undefined, updated: updated })];
1875
- }
1876
- });
1877
- }); })], false));
1878
- modelBase.use((0, api_1.modelRouter)(config.model, routerOptions));
1879
- app.use("".concat(basePath).concat(config.routePath), modelBase);
1880
- };
1881
- var this_1 = this;
1882
- try {
1883
- // Mount modelRouter for each model with IsAdmin permissions
1884
- for (var modelConfigs_2 = __values(modelConfigs), modelConfigs_2_1 = modelConfigs_2.next(); !modelConfigs_2_1.done; modelConfigs_2_1 = modelConfigs_2.next()) {
1885
- var config = modelConfigs_2_1.value;
1886
- _loop_2(config);
1256
+ searchFields: modelMeta?.searchFields ?? config.searchFields,
1257
+ }),
1258
+ queryFilter: buildAdminListQueryFilter(config, modelMeta?.searchFields, isOrganizationScoped),
1259
+ responseHandler: async (value, _method, request) => addRecordCapabilities(value, request),
1260
+ sort: config.defaultSort ?? "-created",
1261
+ ...(config.populatePaths ? { populatePaths: config.populatePaths } : {}),
1262
+ ...(auditHooks.postDelete ? { postDelete: auditHooks.postDelete } : {}),
1263
+ };
1264
+ if (isOrganizationScoped) {
1265
+ disableOrgScopedAdminBroadcastSync(config.model.modelName);
1887
1266
  }
1888
- }
1889
- catch (e_7_1) { e_7 = { error: e_7_1 }; }
1890
- finally {
1891
- try {
1892
- if (modelConfigs_2_1 && !modelConfigs_2_1.done && (_b = modelConfigs_2.return)) _b.call(modelConfigs_2);
1267
+ const syncEntry = (0, api_1.findSyncEntryByModelName)(config.model.modelName);
1268
+ const adminBroadcastEnabled = syncEntry?.config.adminBroadcast === true;
1269
+ if (adminBroadcastEnabled) {
1270
+ (0, api_1.registerAdminBroadcastScope)(config.model.modelName, {
1271
+ listPermissions: adminPermission(true, "list"),
1272
+ queryFilter: routerOptions.queryFilter,
1273
+ readPermissions: adminPermission(true, "read"),
1274
+ });
1275
+ (0, api_1.registerAdminWindowMutationScope)(config.model.modelName, {
1276
+ accessControl: this.options.accessControl,
1277
+ createPermissions: adminPermission(config.permissions?.create, "create"),
1278
+ deletePermissions: adminPermission(config.permissions?.delete, "delete"),
1279
+ modelName: config.model.modelName,
1280
+ permissions: {
1281
+ create: config.permissions?.create !== false,
1282
+ delete: config.permissions?.delete !== false,
1283
+ update: config.permissions?.update !== false,
1284
+ },
1285
+ postCreate: routerOptions.postCreate,
1286
+ postDelete: routerOptions.postDelete,
1287
+ postUpdate: routerOptions.postUpdate,
1288
+ preCreate: routerOptions.preCreate,
1289
+ preUpdate: routerOptions.preUpdate,
1290
+ stripMutationData: (data) => stripProtectedFromBody(data),
1291
+ updatePermissions: adminPermission(config.permissions?.update, "update"),
1292
+ });
1893
1293
  }
1894
- finally { if (e_7) throw e_7.error; }
1895
- }
1896
- // Mount script routes
1897
- if (scriptConfigs.length > 0) {
1898
- var scriptsRouter = express_1.default.Router();
1899
- scriptsRouter.use((0, api_1.authenticateMiddleware)());
1900
- this.mountScriptRoutes(scriptsRouter, scriptConfigs);
1901
- app.use("".concat(basePath, "/scripts"), scriptsRouter);
1902
- }
1903
- };
1904
- AdminApp.prototype.mountScriptRoutes = function (router, scripts) {
1905
- var _this = this;
1906
- var scriptsByName = new Map(scripts.map(function (s) { return [s.name, s]; }));
1907
- var scriptNames = scripts.map(function (s) { return s.name; });
1908
- // GET /admin/scripts/runs — Paginated history of script runs (BackgroundTasks)
1909
- router.get("/runs", (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1910
- var user, _a, limit, page, skip, requestedName, taskTypeFilter, query, _b, tasks, total, data;
1911
- return __generator(this, function (_c) {
1912
- switch (_c.label) {
1913
- case 0:
1914
- user = req.user;
1915
- _a = !user;
1916
- if (_a) return [3 /*break*/, 2];
1917
- return [4 /*yield*/, this.hasScriptPermission(user, "viewBackgroundTasks")];
1918
- case 1:
1919
- _a = !(_c.sent());
1920
- _c.label = 2;
1921
- case 2:
1922
- if (_a) {
1923
- throw new api_1.APIError({ status: 403, title: "Only admins can view run history" });
1924
- }
1925
- limit = Math.min(Math.max(Number(req.query.limit) || 25, 1), 100);
1926
- page = Math.max(Number(req.query.page) || 1, 1);
1927
- skip = (page - 1) * limit;
1928
- requestedName = typeof req.query.name === "string" ? req.query.name : undefined;
1929
- if (requestedName !== undefined) {
1930
- taskTypeFilter = scriptNames.includes(requestedName) ? [requestedName] : [];
1931
- }
1932
- else {
1933
- taskTypeFilter = scriptNames;
1934
- }
1935
- query = taskTypeFilter.length > 0
1936
- ? { taskType: { $in: taskTypeFilter } }
1937
- : { taskType: { $in: [] } };
1938
- return [4 /*yield*/, Promise.all([
1939
- api_1.BackgroundTask.find(query)
1940
- .sort({ created: -1 })
1941
- .skip(skip)
1942
- .limit(limit)
1943
- .populate({ path: "createdBy", select: "name email" })
1944
- .lean(),
1945
- api_1.BackgroundTask.countDocuments(query),
1946
- ])];
1947
- case 3:
1948
- _b = __read.apply(void 0, [_c.sent(), 2]), tasks = _b[0], total = _b[1];
1949
- data = tasks.map(function (task) {
1950
- var _a;
1951
- var createdBy = task.createdBy;
1952
- var createdByName = createdBy &&
1953
- typeof createdBy === "object" &&
1954
- !(createdBy instanceof mongoose_1.default.Types.ObjectId)
1955
- ? ((_a = createdBy.name) !== null && _a !== void 0 ? _a : createdBy.email)
1956
- : undefined;
1957
- return __assign(__assign({}, task), { createdByName: createdByName });
1958
- });
1959
- return [2 /*return*/, res.json({ data: data, limit: limit, more: skip + tasks.length < total, page: page, total: total })];
1294
+ const modelBase = express_1.default.Router();
1295
+ if (isOrganizationScoped) {
1296
+ modelBase.use((0, api_1.authenticateMiddleware)(), (0, api_1.orgContextMiddleware)({ required: true }));
1297
+ }
1298
+ modelBase.use(validateAdminSortParam(modelMeta?.sortableFields ?? []));
1299
+ modelBase.post("/bulk-patch", (0, api_1.authenticateMiddleware)(), ...asMiddlewareList(bulkPatchOpenApi), (0, api_1.asyncHandler)(async (req, res) => {
1300
+ if (!(await (0, api_1.checkPermissions)("update", updatePermissions, req.user))) {
1301
+ throw new api_1.APIError({ status: 403, title: "Admin access required" });
1960
1302
  }
1961
- });
1962
- }); }));
1963
- // POST /admin/scripts/:name/run — Execute a script
1964
- router.post("/:name/run", (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1965
- var user, _a, script, isWetRun, argValues, _b, _c, _d, key, value, rawBody, bodyValues, _e, _f, _g, key, value, _h, args, argErrors, now, task, err_5, detail, ctx;
1966
- var e_18, _j, e_19, _k;
1967
- var _this = this;
1968
- var _l, _m;
1969
- return __generator(this, function (_o) {
1970
- switch (_o.label) {
1971
- case 0:
1972
- user = req.user;
1973
- _a = !user;
1974
- if (_a) return [3 /*break*/, 2];
1975
- return [4 /*yield*/, this.hasScriptPermission(user, "runScripts")];
1976
- case 1:
1977
- _a = !(_o.sent());
1978
- _o.label = 2;
1979
- case 2:
1980
- if (_a) {
1981
- throw new api_1.APIError({ status: 403, title: "Only admins can run scripts" });
1303
+ if (config.permissions?.update === false) {
1304
+ throw new api_1.APIError({ status: 403, title: "Updates are disabled for this model" });
1305
+ }
1306
+ const body = req.body;
1307
+ if (!Array.isArray(body.ids)) {
1308
+ throw new api_1.APIError({ status: 400, title: "Request body must include an ids array" });
1309
+ }
1310
+ if (typeof body.patch !== "object" || body.patch === null || Array.isArray(body.patch)) {
1311
+ throw new api_1.APIError({ status: 400, title: "Request body must include a patch object" });
1312
+ }
1313
+ const ids = [...new Set(body.ids.map((id) => String(id)))];
1314
+ if (ids.length === 0) {
1315
+ throw new api_1.APIError({ status: 400, title: "ids must include at least one id" });
1316
+ }
1317
+ if (ids.length > adminUiV2_1.MAX_BULK_PATCH_IDS) {
1318
+ throw new api_1.APIError({
1319
+ status: 400,
1320
+ title: `At most ${adminUiV2_1.MAX_BULK_PATCH_IDS} ids may be patched at once`,
1321
+ });
1322
+ }
1323
+ const rawPatch = body.patch;
1324
+ const unknownKeys = Object.keys(rawPatch).filter((key) => !allowlist.has(key));
1325
+ if (unknownKeys.length > 0) {
1326
+ throw new api_1.APIError({
1327
+ detail: unknownKeys.join(", "),
1328
+ status: 400,
1329
+ title: "Patch contains keys that are not allowlisted for bulk patch",
1330
+ });
1331
+ }
1332
+ const patch = stripProtectedFromBody(rawPatch);
1333
+ let pendingRoles;
1334
+ if (config.model.modelName === "User" &&
1335
+ this.options.accessControl &&
1336
+ "roles" in rawPatch) {
1337
+ pendingRoles = parseRoleNames(rawPatch.roles);
1338
+ }
1339
+ if (Object.keys(patch).length === 0 && pendingRoles === undefined) {
1340
+ throw new api_1.APIError({
1341
+ status: 400,
1342
+ title: "Patch must include at least one writable field",
1343
+ });
1344
+ }
1345
+ let updated = 0;
1346
+ const failures = [];
1347
+ const actor = req.user;
1348
+ for (const id of ids) {
1349
+ if (!mongoose_1.default.isValidObjectId(id)) {
1350
+ failures.push({ id, title: "Invalid id" });
1351
+ continue;
1352
+ }
1353
+ try {
1354
+ const doc = await config.model.findById(id);
1355
+ if (!doc) {
1356
+ failures.push({ id, title: "Not found" });
1357
+ continue;
1982
1358
  }
1983
- script = scriptsByName.get(req.params.name);
1984
- if (!script) {
1985
- throw new api_1.APIError({ status: 404, title: "Script not found: ".concat(req.params.name) });
1359
+ if (!(await (0, api_1.checkPermissions)("update", updatePermissions, actor, doc))) {
1360
+ failures.push({ id, title: "Forbidden" });
1361
+ continue;
1986
1362
  }
1987
- isWetRun = req.query.wetRun === "true";
1988
- argValues = {};
1989
- try {
1990
- for (_b = __values(Object.entries(req.query)), _c = _b.next(); !_c.done; _c = _b.next()) {
1991
- _d = __read(_c.value, 2), key = _d[0], value = _d[1];
1992
- if (scriptCli_1.RESERVED_SCRIPT_FLAGS.includes(key) || value === undefined) {
1993
- continue;
1994
- }
1995
- argValues[key] = value;
1996
- }
1363
+ await assertCanWriteUserAdminFlag(rawPatch, req, Boolean(doc.admin), id);
1364
+ const previousPatch = {};
1365
+ for (const key of Object.keys(patch)) {
1366
+ previousPatch[key] = doc[key];
1997
1367
  }
1998
- catch (e_18_1) { e_18 = { error: e_18_1 }; }
1999
- finally {
2000
- try {
2001
- if (_c && !_c.done && (_j = _b.return)) _j.call(_b);
2002
- }
2003
- finally { if (e_18) throw e_18.error; }
1368
+ if (Object.keys(patch).length > 0) {
1369
+ await doc.updateOne({ $set: patch });
2004
1370
  }
2005
- rawBody = req.body && typeof req.body === "object" && !Array.isArray(req.body)
2006
- ? req.body
2007
- : {};
2008
- bodyValues = rawBody.args && typeof rawBody.args === "object" && !Array.isArray(rawBody.args)
2009
- ? rawBody.args
2010
- : rawBody;
2011
1371
  try {
2012
- for (_e = __values(Object.entries(bodyValues)), _f = _e.next(); !_f.done; _f = _e.next()) {
2013
- _g = __read(_f.value, 2), key = _g[0], value = _g[1];
2014
- if (scriptCli_1.RESERVED_SCRIPT_FLAGS.includes(key)) {
1372
+ if (pendingRoles) {
1373
+ if (!actor) {
1374
+ failures.push({ id, title: "Forbidden" });
2015
1375
  continue;
2016
1376
  }
2017
- argValues[key] = value;
1377
+ await this.options.accessControl?.roles.assign({
1378
+ actor,
1379
+ roleNames: pendingRoles,
1380
+ userId: id,
1381
+ });
2018
1382
  }
2019
1383
  }
2020
- catch (e_19_1) { e_19 = { error: e_19_1 }; }
2021
- finally {
2022
- try {
2023
- if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
1384
+ catch (roleError) {
1385
+ if (Object.keys(previousPatch).length > 0) {
1386
+ await config.model.updateOne({ _id: id }, { $set: previousPatch });
2024
1387
  }
2025
- finally { if (e_19) throw e_19.error; }
1388
+ throw roleError;
2026
1389
  }
2027
- _h = (0, api_1.createScriptArgs)({
2028
- defs: (_l = script.args) !== null && _l !== void 0 ? _l : [],
2029
- values: argValues,
2030
- }), args = _h.args, argErrors = _h.errors;
2031
- if (argErrors.length > 0) {
2032
- throw new api_1.APIError({
2033
- detail: argErrors.join("; "),
2034
- status: 400,
2035
- title: "Invalid arguments for script: ".concat(script.name),
2036
- });
2037
- }
2038
- now = luxon_1.DateTime.now().toJSDate();
2039
- _o.label = 3;
2040
- case 3:
2041
- _o.trys.push([3, 5, , 6]);
2042
- return [4 /*yield*/, api_1.BackgroundTask.create({
2043
- createdBy: user._id,
2044
- isDryRun: !isWetRun,
2045
- logs: [
2046
- { level: "info", message: "Script started by ".concat((_m = user.name) !== null && _m !== void 0 ? _m : "admin"), timestamp: now },
2047
- ],
2048
- progress: { message: "Starting...", percentage: 0, stage: "Queued" },
2049
- startedAt: now,
2050
- status: "running",
2051
- taskType: script.name,
2052
- })];
2053
- case 4:
2054
- task = (_o.sent());
2055
- return [3 /*break*/, 6];
2056
- case 5:
2057
- err_5 = _o.sent();
2058
- detail = err_5 instanceof Error ? err_5.message : String(err_5);
2059
- api_1.logger.error("Failed to create background task for ".concat(script.name, ": ").concat(detail));
2060
- throw new api_1.APIError({
2061
- detail: detail,
2062
- status: 500,
2063
- title: "Failed to create background task for script: ".concat(script.name),
2064
- });
2065
- case 6:
2066
- ctx = {
2067
- addLog: function (level, message) { return __awaiter(_this, void 0, void 0, function () {
2068
- var current;
2069
- return __generator(this, function (_a) {
2070
- switch (_a.label) {
2071
- case 0: return [4 /*yield*/, api_1.BackgroundTask.findById(task._id)];
2072
- case 1:
2073
- current = _a.sent();
2074
- if (!current) return [3 /*break*/, 3];
2075
- return [4 /*yield*/, current.addLog(level, message)];
2076
- case 2:
2077
- _a.sent();
2078
- _a.label = 3;
2079
- case 3: return [2 /*return*/];
2080
- }
2081
- });
2082
- }); },
2083
- args: args,
2084
- checkCancellation: function () { return __awaiter(_this, void 0, void 0, function () {
2085
- return __generator(this, function (_a) {
2086
- switch (_a.label) {
2087
- case 0: return [4 /*yield*/, api_1.BackgroundTask.checkCancellation(task._id.toString())];
2088
- case 1:
2089
- _a.sent();
2090
- return [2 /*return*/];
2091
- }
2092
- });
2093
- }); },
2094
- updateProgress: function (percentage, stage, message) { return __awaiter(_this, void 0, void 0, function () {
2095
- var current;
2096
- return __generator(this, function (_a) {
2097
- switch (_a.label) {
2098
- case 0: return [4 /*yield*/, api_1.BackgroundTask.findById(task._id)];
2099
- case 1:
2100
- current = _a.sent();
2101
- if (!current) return [3 /*break*/, 3];
2102
- return [4 /*yield*/, current.updateProgress(percentage, stage, message)];
2103
- case 2:
2104
- _a.sent();
2105
- _a.label = 3;
2106
- case 3: return [2 /*return*/];
2107
- }
2108
- });
2109
- }); },
2110
- };
2111
- // Run the script asynchronously — use atomic updates to avoid overwriting
2112
- // cancellation or other intermediate state changes.
2113
- void (function () { return __awaiter(_this, void 0, void 0, function () {
2114
- var result, err_6, message;
2115
- return __generator(this, function (_a) {
2116
- switch (_a.label) {
2117
- case 0:
2118
- _a.trys.push([0, 3, , 5]);
2119
- return [4 /*yield*/, script.runner(isWetRun, ctx)];
2120
- case 1:
2121
- result = _a.sent();
2122
- // Atomically update only if still running (don't overwrite cancellation)
2123
- return [4 /*yield*/, api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: "running" }, {
2124
- $set: {
2125
- completedAt: luxon_1.DateTime.now().toJSDate(),
2126
- progress: { message: "Done", percentage: 100, stage: "Complete" },
2127
- result: result.results,
2128
- status: result.success ? "completed" : "failed",
2129
- },
2130
- })];
2131
- case 2:
2132
- // Atomically update only if still running (don't overwrite cancellation)
2133
- _a.sent();
2134
- return [3 /*break*/, 5];
2135
- case 3:
2136
- err_6 = _a.sent();
2137
- if (err_6 instanceof api_1.TaskCancelledError) {
2138
- return [2 /*return*/];
2139
- }
2140
- message = err_6 instanceof Error ? err_6.message : String(err_6);
2141
- api_1.logger.error("Script ".concat(script.name, " failed: ").concat(message));
2142
- // Atomically update only if still running
2143
- return [4 /*yield*/, api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: "running" }, {
2144
- $set: {
2145
- completedAt: luxon_1.DateTime.now().toJSDate(),
2146
- error: message,
2147
- result: [message],
2148
- status: "failed",
2149
- },
2150
- })];
2151
- case 4:
2152
- // Atomically update only if still running
2153
- _a.sent();
2154
- return [3 /*break*/, 5];
2155
- case 5: return [2 /*return*/];
2156
- }
2157
- });
2158
- }); })();
2159
- return [2 /*return*/, res.status(201).json({ taskId: task._id.toString() })];
1390
+ updated += 1;
1391
+ }
1392
+ catch (err) {
1393
+ const message = err instanceof Error ? err.message : String(err);
1394
+ failures.push({ id, title: message });
1395
+ }
2160
1396
  }
1397
+ return res.json({ failures: failures.length > 0 ? failures : undefined, updated });
1398
+ }));
1399
+ modelBase.use((0, api_1.modelRouter)(config.model, routerOptions));
1400
+ app.use(`${basePath}${config.routePath}`, modelBase);
1401
+ }
1402
+ // Mount script routes
1403
+ if (scriptConfigs.length > 0 || this.options.migrations?.dir) {
1404
+ const scriptsRouter = express_1.default.Router();
1405
+ scriptsRouter.use((0, api_1.authenticateMiddleware)());
1406
+ this.mountScriptRoutes(scriptsRouter, scriptConfigs);
1407
+ app.use(`${basePath}/scripts`, scriptsRouter);
1408
+ }
1409
+ (0, adminMigrations_1.mountAdminMigrationRoutes)({
1410
+ app,
1411
+ basePath,
1412
+ dir: this.options.migrations?.dir,
1413
+ ...(openApiMw ? { openApi: openApiMw } : {}),
1414
+ runPermissions: this.adminRunScriptsPermissions(),
1415
+ statusPermissions: this.adminAccessPermissions(),
1416
+ });
1417
+ }
1418
+ mountScriptRoutes(router, scripts) {
1419
+ const scriptsByName = new Map(scripts.map((s) => [s.name, s]));
1420
+ const scriptNames = scripts.map((s) => s.name);
1421
+ const jobs = (0, jobs_1.tryGetJobsService)();
1422
+ if (jobs) {
1423
+ (0, adminScriptJob_1.defineAdminScriptJob)(jobs, (name) => scriptsByName.get(name));
1424
+ }
1425
+ // GET /admin/scripts/runs — Paginated history of script runs (BackgroundTasks)
1426
+ router.get("/runs", (0, api_1.asyncHandler)(async (req, res) => {
1427
+ const user = req.user;
1428
+ if (!user || !(await this.hasScriptPermission(user, "viewBackgroundTasks"))) {
1429
+ throw new api_1.APIError({ status: 403, title: "Only admins can view run history" });
1430
+ }
1431
+ const limit = Math.min(Math.max(Number(req.query.limit) || 25, 1), 100);
1432
+ const page = Math.max(Number(req.query.page) || 1, 1);
1433
+ const skip = (page - 1) * limit;
1434
+ // Scope history to currently-registered scripts. An optional `name` query
1435
+ // narrows to a single script (used by the per-script "History" link). A
1436
+ // provided-but-unregistered name resolves to an empty filter so callers can
1437
+ // distinguish "unknown script" (no runs) from "show all".
1438
+ const requestedName = typeof req.query.name === "string" ? req.query.name : undefined;
1439
+ let taskTypeFilter;
1440
+ if (requestedName !== undefined) {
1441
+ taskTypeFilter = scriptNames.includes(requestedName) ? [requestedName] : [];
1442
+ }
1443
+ else {
1444
+ taskTypeFilter = scriptNames;
1445
+ }
1446
+ const query = taskTypeFilter.length > 0
1447
+ ? { taskType: { $in: taskTypeFilter } }
1448
+ : { taskType: { $in: [] } };
1449
+ const [tasks, total] = await Promise.all([
1450
+ api_1.BackgroundTask.find(query)
1451
+ .sort({ created: -1 })
1452
+ .skip(skip)
1453
+ .limit(limit)
1454
+ .populate({ path: "createdBy", select: "name email" })
1455
+ .lean(),
1456
+ api_1.BackgroundTask.countDocuments(query),
1457
+ ]);
1458
+ const data = tasks.map((task) => {
1459
+ const createdBy = task.createdBy;
1460
+ const createdByName = createdBy &&
1461
+ typeof createdBy === "object" &&
1462
+ !(createdBy instanceof mongoose_1.default.Types.ObjectId)
1463
+ ? (createdBy.name ?? createdBy.email)
1464
+ : undefined;
1465
+ return { ...task, createdByName };
2161
1466
  });
2162
- }); }));
2163
- // GET /admin/scripts/tasks/:id — Poll task status
2164
- router.get("/tasks/:id", (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
2165
- var user, _a, task, err_7, detail;
2166
- return __generator(this, function (_b) {
2167
- switch (_b.label) {
2168
- case 0:
2169
- user = req.user;
2170
- _a = !user;
2171
- if (_a) return [3 /*break*/, 2];
2172
- return [4 /*yield*/, this.hasScriptPermission(user, "viewBackgroundTasks")];
2173
- case 1:
2174
- _a = !(_b.sent());
2175
- _b.label = 2;
2176
- case 2:
2177
- if (_a) {
2178
- throw new api_1.APIError({ status: 403, title: "Only admins can view tasks" });
2179
- }
2180
- _b.label = 3;
2181
- case 3:
2182
- _b.trys.push([3, 5, , 6]);
2183
- return [4 /*yield*/, api_1.BackgroundTask.findById(req.params.id)];
2184
- case 4:
2185
- task = _b.sent();
2186
- return [3 /*break*/, 6];
2187
- case 5:
2188
- err_7 = _b.sent();
2189
- detail = err_7 instanceof Error ? err_7.message : String(err_7);
2190
- throw new api_1.APIError({ detail: detail, status: 400, title: "Invalid task ID" });
2191
- case 6:
2192
- if (!task) {
2193
- throw new api_1.APIError({ status: 404, title: "Task not found" });
2194
- }
2195
- return [2 /*return*/, res.json({ task: task.toObject() })];
1467
+ return res.json({ data, limit, more: skip + tasks.length < total, page, total });
1468
+ }));
1469
+ // POST /admin/scripts/:name/run — Execute a script
1470
+ router.post("/:name/run", (0, api_1.asyncHandler)(async (req, res) => {
1471
+ const user = req.user;
1472
+ if (!user || !(await this.hasScriptPermission(user, "runScripts"))) {
1473
+ throw new api_1.APIError({ status: 403, title: "Only admins can run scripts" });
1474
+ }
1475
+ const script = scriptsByName.get(req.params.name);
1476
+ if (!script) {
1477
+ throw new api_1.APIError({ status: 404, title: `Script not found: ${req.params.name}` });
1478
+ }
1479
+ const isWetRun = req.query.wetRun === "true";
1480
+ // Collect flexible arguments from the request. Query params and a JSON body
1481
+ // are both accepted; an explicit `args` object in the body takes precedence.
1482
+ // Reserved runner flags (wetRun, wet, dry, json, ...) are stripped so scripts
1483
+ // read args identically over HTTP and via the CLI.
1484
+ const argValues = {};
1485
+ for (const [key, value] of Object.entries(req.query)) {
1486
+ if (scriptCli_1.RESERVED_SCRIPT_FLAGS.includes(key) || value === undefined) {
1487
+ continue;
2196
1488
  }
2197
- });
2198
- }); }));
2199
- // DELETE /admin/scripts/tasks/:id — Cancel a running task
2200
- router.delete("/tasks/:id", (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
2201
- var user, _a, task, err_8, detail, cancelled;
2202
- var _b;
2203
- return __generator(this, function (_c) {
2204
- switch (_c.label) {
2205
- case 0:
2206
- user = req.user;
2207
- _a = !user;
2208
- if (_a) return [3 /*break*/, 2];
2209
- return [4 /*yield*/, this.hasScriptPermission(user, "runScripts")];
2210
- case 1:
2211
- _a = !(_c.sent());
2212
- _c.label = 2;
2213
- case 2:
2214
- if (_a) {
2215
- throw new api_1.APIError({ status: 403, title: "Only admins can cancel tasks" });
2216
- }
2217
- _c.label = 3;
2218
- case 3:
2219
- _c.trys.push([3, 5, , 6]);
2220
- return [4 /*yield*/, api_1.BackgroundTask.findById(req.params.id)];
2221
- case 4:
2222
- task = _c.sent();
2223
- return [3 /*break*/, 6];
2224
- case 5:
2225
- err_8 = _c.sent();
2226
- detail = err_8 instanceof Error ? err_8.message : String(err_8);
2227
- throw new api_1.APIError({ detail: detail, status: 400, title: "Invalid task ID" });
2228
- case 6:
2229
- if (!task) {
2230
- throw new api_1.APIError({ status: 404, title: "Task not found" });
2231
- }
2232
- if (task.status !== "pending" && task.status !== "running") {
2233
- throw new api_1.APIError({
2234
- status: 400,
2235
- title: "Cannot cancel task with status: ".concat(task.status),
2236
- });
2237
- }
2238
- return [4 /*yield*/, api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: { $in: ["pending", "running"] } }, {
2239
- $push: {
2240
- logs: {
2241
- level: "info",
2242
- message: "Task cancelled by ".concat((_b = user.name) !== null && _b !== void 0 ? _b : "admin"),
2243
- timestamp: luxon_1.DateTime.now().toJSDate(),
2244
- },
2245
- },
2246
- $set: {
2247
- completedAt: luxon_1.DateTime.now().toJSDate(),
2248
- status: "cancelled",
2249
- },
2250
- }, { returnDocument: "after" })];
2251
- case 7:
2252
- cancelled = _c.sent();
2253
- if (!cancelled) {
2254
- throw new api_1.APIError({
2255
- status: 409,
2256
- title: "Task already completed or cancelled",
2257
- });
2258
- }
2259
- return [2 /*return*/, res.json({ message: "Task cancelled", task: cancelled.toObject() })];
1489
+ argValues[key] = value;
1490
+ }
1491
+ const rawBody = req.body && typeof req.body === "object" && !Array.isArray(req.body)
1492
+ ? req.body
1493
+ : {};
1494
+ const bodyValues = rawBody.args && typeof rawBody.args === "object" && !Array.isArray(rawBody.args)
1495
+ ? rawBody.args
1496
+ : rawBody;
1497
+ for (const [key, value] of Object.entries(bodyValues)) {
1498
+ if (scriptCli_1.RESERVED_SCRIPT_FLAGS.includes(key)) {
1499
+ continue;
2260
1500
  }
1501
+ argValues[key] = value;
1502
+ }
1503
+ const { args, errors: argErrors } = (0, api_1.createScriptArgs)({
1504
+ defs: script.args ?? [],
1505
+ values: argValues,
2261
1506
  });
2262
- }); }));
2263
- };
2264
- return AdminApp;
2265
- }());
1507
+ if (argErrors.length > 0) {
1508
+ throw new api_1.APIError({
1509
+ detail: argErrors.join("; "),
1510
+ status: 400,
1511
+ title: `Invalid arguments for script: ${script.name}`,
1512
+ });
1513
+ }
1514
+ const now = luxon_1.DateTime.now().toJSDate();
1515
+ const queuedViaJobs = Boolean((0, jobs_1.tryGetJobsService)()?.getDefinition(adminScriptJob_1.ADMIN_SCRIPT_JOB_NAME));
1516
+ let task;
1517
+ try {
1518
+ task = (await api_1.BackgroundTask.create({
1519
+ createdBy: user._id,
1520
+ isDryRun: !isWetRun,
1521
+ logs: [
1522
+ { level: "info", message: `Script started by ${user.name ?? "admin"}`, timestamp: now },
1523
+ ],
1524
+ progress: {
1525
+ message: queuedViaJobs ? "Queued" : "Starting...",
1526
+ percentage: 0,
1527
+ stage: queuedViaJobs ? "Queued" : "Queued",
1528
+ },
1529
+ startedAt: queuedViaJobs ? undefined : now,
1530
+ status: queuedViaJobs ? "pending" : "running",
1531
+ taskType: script.name,
1532
+ }));
1533
+ }
1534
+ catch (err) {
1535
+ const detail = err instanceof Error ? err.message : String(err);
1536
+ api_1.logger.error(`Failed to create background task for ${script.name}: ${detail}`);
1537
+ throw new api_1.APIError({
1538
+ detail,
1539
+ status: 500,
1540
+ title: `Failed to create background task for script: ${script.name}`,
1541
+ });
1542
+ }
1543
+ const taskId = task._id.toString();
1544
+ let enqueued;
1545
+ try {
1546
+ enqueued = await (0, adminScriptJob_1.tryEnqueueAdminScriptJob)({
1547
+ args: args.raw,
1548
+ createdByName: user.name,
1549
+ scriptName: script.name,
1550
+ taskId,
1551
+ wetRun: isWetRun,
1552
+ });
1553
+ }
1554
+ catch (err) {
1555
+ const detail = err instanceof Error ? err.message : String(err);
1556
+ api_1.logger.error(`Failed to enqueue durable job for ${script.name}: ${detail}`);
1557
+ const failedAt = luxon_1.DateTime.now().toJSDate();
1558
+ await api_1.BackgroundTask.updateOne({ _id: task._id }, {
1559
+ $set: {
1560
+ completedAt: failedAt,
1561
+ error: detail,
1562
+ progress: {
1563
+ message: "Failed to enqueue",
1564
+ percentage: 100,
1565
+ stage: "Failed",
1566
+ },
1567
+ status: "failed",
1568
+ },
1569
+ });
1570
+ throw new api_1.APIError({
1571
+ detail,
1572
+ status: 500,
1573
+ title: `Failed to enqueue script: ${script.name}`,
1574
+ });
1575
+ }
1576
+ if (enqueued) {
1577
+ return res.status(201).json({ taskId });
1578
+ }
1579
+ void (0, adminScriptJob_1.runRegisteredScriptTask)({
1580
+ args,
1581
+ script,
1582
+ taskId,
1583
+ wetRun: isWetRun,
1584
+ });
1585
+ return res.status(201).json({ taskId });
1586
+ }));
1587
+ // GET /admin/scripts/tasks/:id — Poll task status
1588
+ router.get("/tasks/:id", (0, api_1.asyncHandler)(async (req, res) => {
1589
+ const user = req.user;
1590
+ if (!user || !(await this.hasScriptPermission(user, "viewBackgroundTasks"))) {
1591
+ throw new api_1.APIError({ status: 403, title: "Only admins can view tasks" });
1592
+ }
1593
+ let task;
1594
+ try {
1595
+ task = await api_1.BackgroundTask.findById(req.params.id);
1596
+ }
1597
+ catch (err) {
1598
+ const detail = err instanceof Error ? err.message : String(err);
1599
+ throw new api_1.APIError({ detail, status: 400, title: "Invalid task ID" });
1600
+ }
1601
+ if (!task) {
1602
+ throw new api_1.APIError({ status: 404, title: "Task not found" });
1603
+ }
1604
+ return res.json({ task: task.toObject() });
1605
+ }));
1606
+ // DELETE /admin/scripts/tasks/:id — Cancel a running task
1607
+ router.delete("/tasks/:id", (0, api_1.asyncHandler)(async (req, res) => {
1608
+ const user = req.user;
1609
+ if (!user || !(await this.hasScriptPermission(user, "runScripts"))) {
1610
+ throw new api_1.APIError({ status: 403, title: "Only admins can cancel tasks" });
1611
+ }
1612
+ let task;
1613
+ try {
1614
+ task = await api_1.BackgroundTask.findById(req.params.id);
1615
+ }
1616
+ catch (err) {
1617
+ const detail = err instanceof Error ? err.message : String(err);
1618
+ throw new api_1.APIError({ detail, status: 400, title: "Invalid task ID" });
1619
+ }
1620
+ if (!task) {
1621
+ throw new api_1.APIError({ status: 404, title: "Task not found" });
1622
+ }
1623
+ if (task.status !== "pending" && task.status !== "running") {
1624
+ throw new api_1.APIError({
1625
+ status: 400,
1626
+ title: `Cannot cancel task with status: ${task.status}`,
1627
+ });
1628
+ }
1629
+ // Atomically cancel only if still running/pending (avoids race with completion)
1630
+ const cancelled = await api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: { $in: ["pending", "running"] } }, {
1631
+ $push: {
1632
+ logs: {
1633
+ level: "info",
1634
+ message: `Task cancelled by ${user.name ?? "admin"}`,
1635
+ timestamp: luxon_1.DateTime.now().toJSDate(),
1636
+ },
1637
+ },
1638
+ $set: {
1639
+ completedAt: luxon_1.DateTime.now().toJSDate(),
1640
+ status: "cancelled",
1641
+ },
1642
+ }, { returnDocument: "after" });
1643
+ if (!cancelled) {
1644
+ throw new api_1.APIError({
1645
+ status: 409,
1646
+ title: "Task already completed or cancelled",
1647
+ });
1648
+ }
1649
+ await (0, adminScriptJob_1.tryCancelAdminScriptJob)(task._id.toString());
1650
+ return res.json({ message: "Task cancelled", task: cancelled.toObject() });
1651
+ }));
1652
+ }
1653
+ }
2266
1654
  exports.AdminApp = AdminApp;