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