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