@terreno/admin-backend 57.0.0 → 57.2.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 -0
- package/dist/adminApp.d.ts +25 -4
- package/dist/adminApp.js +1195 -269
- package/dist/adminConfigIdentity.d.ts +16 -0
- package/dist/adminConfigIdentity.js +100 -0
- package/dist/adminTextSearch.d.ts +17 -0
- package/dist/adminTextSearch.js +117 -0
- package/dist/adminUiV2.js +1 -1
- package/dist/aggregateAdmin.d.ts +20 -0
- package/dist/aggregateAdmin.js +276 -0
- package/dist/documentStorageApp.d.ts +3 -1
- package/dist/documentStorageApp.js +20 -42
- package/dist/filterParser.d.ts +11 -0
- package/dist/filterParser.js +260 -0
- package/dist/index.d.ts +10 -1
- package/dist/index.js +16 -1
- package/dist/legacy.d.ts +9 -0
- package/dist/legacy.js +61 -0
- package/dist/resolvedAdminModel.d.ts +23 -0
- package/dist/resolvedAdminModel.js +131 -0
- package/dist/routePath.d.ts +2 -0
- package/dist/routePath.js +18 -0
- package/package.json +5 -4
- package/src/adminApp.models.test.ts +1321 -1
- package/src/adminApp.test.ts +35 -1
- package/src/adminApp.ts +873 -102
- package/src/adminConfigIdentity.test.ts +56 -0
- package/src/adminConfigIdentity.ts +87 -0
- package/src/adminTextSearch.test.ts +73 -0
- package/src/adminTextSearch.ts +74 -0
- package/src/adminUiV2.test.ts +1 -0
- package/src/adminUiV2.ts +1 -1
- package/src/aggregateAdmin.test.ts +220 -0
- package/src/aggregateAdmin.ts +207 -0
- package/src/documentStorageApp.test.ts +11 -0
- package/src/documentStorageApp.ts +20 -39
- package/src/filterParser.test.ts +68 -0
- package/src/filterParser.ts +229 -0
- package/src/index.ts +36 -1
- package/src/legacy.test.ts +34 -0
- package/src/legacy.ts +63 -0
- package/src/resolvedAdminModel.ts +115 -0
- package/src/routePath.ts +14 -0
package/src/adminApp.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
|
+
ADMIN_PAGE_ACTION,
|
|
3
|
+
type AdminAccessConfig,
|
|
4
|
+
type AdminModelAdminMap,
|
|
5
|
+
type AnyTerrenoAccess,
|
|
2
6
|
APIError,
|
|
3
7
|
asyncHandler,
|
|
4
8
|
authenticateMiddleware,
|
|
@@ -13,6 +17,7 @@ import {
|
|
|
13
17
|
type ModelRouterOptions,
|
|
14
18
|
modelRouter,
|
|
15
19
|
type OpenApiMiddleware,
|
|
20
|
+
type PermissionMethod,
|
|
16
21
|
Permissions,
|
|
17
22
|
type PopulatePath,
|
|
18
23
|
type ScriptArgDef,
|
|
@@ -20,7 +25,9 @@ import {
|
|
|
20
25
|
type ScriptContext,
|
|
21
26
|
type ScriptResult,
|
|
22
27
|
type ScriptRunner,
|
|
28
|
+
scrubAdminFields,
|
|
23
29
|
TaskCancelledError,
|
|
30
|
+
type TerrenoApp,
|
|
24
31
|
type User,
|
|
25
32
|
VersionConfig,
|
|
26
33
|
} from "@terreno/api";
|
|
@@ -28,7 +35,12 @@ import express from "express";
|
|
|
28
35
|
import {DateTime} from "luxon";
|
|
29
36
|
import type {Model} from "mongoose";
|
|
30
37
|
import mongoose from "mongoose";
|
|
31
|
-
|
|
38
|
+
import {assignUniqueAdminConfigNames, findAdminModelMetaByRoutePath} from "./adminConfigIdentity";
|
|
39
|
+
import {
|
|
40
|
+
ADMIN_LIST_SEARCH_PARAM,
|
|
41
|
+
andMongoFilters,
|
|
42
|
+
buildAdminPartialSearchFilter,
|
|
43
|
+
} from "./adminTextSearch";
|
|
32
44
|
import {
|
|
33
45
|
ADMIN_SCHEMA_VERSION,
|
|
34
46
|
type AdminActionInput,
|
|
@@ -42,6 +54,9 @@ import {
|
|
|
42
54
|
normalizeAdminHome,
|
|
43
55
|
SYSTEM_ADMIN_FIELDS,
|
|
44
56
|
} from "./adminUiV2";
|
|
57
|
+
import {aggregateFromTerrenoApp} from "./aggregateAdmin";
|
|
58
|
+
import {parseAdminListFilters} from "./filterParser";
|
|
59
|
+
import type {ResolvedAdminModel} from "./resolvedAdminModel";
|
|
45
60
|
import {RESERVED_SCRIPT_FLAGS} from "./scriptCli";
|
|
46
61
|
|
|
47
62
|
/**
|
|
@@ -52,6 +67,18 @@ export interface AdminFieldOverride {
|
|
|
52
67
|
widget?: string;
|
|
53
68
|
}
|
|
54
69
|
|
|
70
|
+
/**
|
|
71
|
+
* Builds an ownership check for writeOwned admin access. The field may contain an id
|
|
72
|
+
* directly or a populated document with `_id`.
|
|
73
|
+
*/
|
|
74
|
+
export const adminOwnedBy = (field: string): NonNullable<AdminAccessConfig["isOwned"]> => {
|
|
75
|
+
return ({instance, user}): boolean => {
|
|
76
|
+
const value = (instance as Record<string, unknown> | undefined)?.[field];
|
|
77
|
+
const ownerId = (value as {_id?: unknown} | undefined)?._id ?? value;
|
|
78
|
+
return ownerId != null && String(ownerId) === String(user.id);
|
|
79
|
+
};
|
|
80
|
+
};
|
|
81
|
+
|
|
55
82
|
export interface AdminModelConfig {
|
|
56
83
|
/** The Mongoose model to expose in the admin panel */
|
|
57
84
|
// noExplicitAny: Model<T> is invariant; the admin panel must accept any document shape.
|
|
@@ -97,6 +124,8 @@ export interface AdminModelConfig {
|
|
|
97
124
|
populatePaths?: PopulatePath[];
|
|
98
125
|
/** UI-only hint that live updates may be available */
|
|
99
126
|
realtime?: boolean;
|
|
127
|
+
/** Fine-grained admin RBAC and optional ownership/custom authorization. */
|
|
128
|
+
adminAccess?: AdminAccessConfig;
|
|
100
129
|
/**
|
|
101
130
|
* Field key used for the edit screen title (browser tab / stack header). When omitted, the
|
|
102
131
|
* admin UI derives a label from common keys (`name`, `title`, …) then the first scalar
|
|
@@ -157,14 +186,16 @@ export interface AdminCustomScreenConfig {
|
|
|
157
186
|
name: string;
|
|
158
187
|
/** Optional subtitle or help text shown with the screen card in the admin UI */
|
|
159
188
|
description?: string;
|
|
189
|
+
/** RBAC or custom authorization for exposing this screen in admin metadata/navigation. */
|
|
190
|
+
adminAccess?: Pick<AdminAccessConfig, "authorize" | "resource"> & {action?: string};
|
|
160
191
|
}
|
|
161
192
|
|
|
162
193
|
/**
|
|
163
194
|
* Configuration options for the AdminApp plugin.
|
|
164
195
|
*/
|
|
165
196
|
export interface AdminOptions {
|
|
166
|
-
/**
|
|
167
|
-
models
|
|
197
|
+
/** Legacy model configurations (deprecated — prefer modelRouter `admin:` or plugin contributions). */
|
|
198
|
+
models?: AdminModelConfig[];
|
|
168
199
|
/** Array of scripts that can be run from the admin panel */
|
|
169
200
|
scripts?: AdminScriptConfig[];
|
|
170
201
|
/** Base path for all admin routes. Defaults to "/admin". */
|
|
@@ -178,6 +209,9 @@ export interface AdminOptions {
|
|
|
178
209
|
* Consumers typically persist to an `AdminAuditLog` collection.
|
|
179
210
|
*/
|
|
180
211
|
onAdminAudit?: (event: AdminAuditEvent, req: express.Request) => void | Promise<void>;
|
|
212
|
+
/** When set, admin shell entry requires `admin:access`; model CRUD also requires
|
|
213
|
+
* resource/action permissions (for example `user:update`) from the same Access instance. */
|
|
214
|
+
accessControl?: AnyTerrenoAccess;
|
|
181
215
|
}
|
|
182
216
|
|
|
183
217
|
interface AdminFieldMeta {
|
|
@@ -231,42 +265,148 @@ interface AdminScriptMeta {
|
|
|
231
265
|
}
|
|
232
266
|
|
|
233
267
|
interface AdminConfigResponse {
|
|
268
|
+
capabilities: {
|
|
269
|
+
actions: boolean;
|
|
270
|
+
fieldsets: boolean;
|
|
271
|
+
filters: boolean;
|
|
272
|
+
realtime: boolean;
|
|
273
|
+
};
|
|
234
274
|
customScreens?: AdminCustomScreenConfig[];
|
|
235
275
|
home: ReturnType<typeof normalizeAdminHome>;
|
|
236
276
|
models: AdminModelMeta[];
|
|
277
|
+
platformTools: {
|
|
278
|
+
configuration: boolean;
|
|
279
|
+
roles: boolean;
|
|
280
|
+
runScripts: boolean;
|
|
281
|
+
scripts: boolean;
|
|
282
|
+
version: boolean;
|
|
283
|
+
viewScripts: boolean;
|
|
284
|
+
};
|
|
237
285
|
schemaVersion: number;
|
|
238
286
|
scripts: AdminScriptMeta[];
|
|
287
|
+
widgetIds: string[];
|
|
239
288
|
}
|
|
240
289
|
|
|
241
|
-
const
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
"toObject" in value &&
|
|
246
|
-
typeof value.toObject === "function"
|
|
247
|
-
) {
|
|
248
|
-
return (value as {toObject: () => Record<string, unknown>}).toObject();
|
|
290
|
+
const buildAllModelAdminsMap = (models: ResolvedAdminModel[]): AdminModelAdminMap => {
|
|
291
|
+
const map: AdminModelAdminMap = {};
|
|
292
|
+
for (const config of models) {
|
|
293
|
+
map[config.model.modelName] = config.admin;
|
|
249
294
|
}
|
|
250
|
-
return
|
|
295
|
+
return map;
|
|
251
296
|
};
|
|
252
297
|
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
298
|
+
const scrubAdminResponse = (
|
|
299
|
+
value: unknown,
|
|
300
|
+
config: ResolvedAdminModel,
|
|
301
|
+
allModelAdmins: AdminModelAdminMap
|
|
302
|
+
): unknown => {
|
|
303
|
+
return scrubAdminFields(value, {
|
|
304
|
+
admin: config.admin,
|
|
305
|
+
allModelAdmins,
|
|
306
|
+
schema: config.model.schema,
|
|
307
|
+
});
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
const buildAdminListQueryFilter = (
|
|
311
|
+
config: ResolvedAdminModel,
|
|
312
|
+
/** Resolved (possibly derived) search fields from `/admin/config`, not just explicit config. */
|
|
313
|
+
resolvedSearchFields?: string[]
|
|
314
|
+
): NonNullable<ModelRouterOptions<unknown>["queryFilter"]> => {
|
|
315
|
+
const base = config.queryFilter;
|
|
316
|
+
const searchFields = resolvedSearchFields ?? config.searchFields ?? [];
|
|
317
|
+
return async (user, query) => {
|
|
318
|
+
const clientQuery: Record<string, unknown> = {...(query ?? {})};
|
|
319
|
+
const {consumedKeys, errors, filter} = parseAdminListFilters(clientQuery, config.filters ?? []);
|
|
320
|
+
if (Object.keys(errors).length > 0) {
|
|
321
|
+
throw new APIError({
|
|
322
|
+
detail: JSON.stringify(errors),
|
|
323
|
+
status: 400,
|
|
324
|
+
title: "Invalid filter",
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
for (const key of consumedKeys) {
|
|
328
|
+
delete clientQuery[key];
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
const rawSearch = clientQuery[ADMIN_LIST_SEARCH_PARAM];
|
|
332
|
+
delete clientQuery[ADMIN_LIST_SEARCH_PARAM];
|
|
333
|
+
const searchClause =
|
|
334
|
+
typeof rawSearch === "string"
|
|
335
|
+
? buildAdminPartialSearchFilter({
|
|
336
|
+
model: config.model,
|
|
337
|
+
q: rawSearch,
|
|
338
|
+
searchFields,
|
|
339
|
+
})
|
|
340
|
+
: undefined;
|
|
341
|
+
|
|
342
|
+
let merged: Record<string, unknown> = {...clientQuery, ...filter};
|
|
343
|
+
if (base) {
|
|
344
|
+
const baseResult = await base(user, merged);
|
|
345
|
+
if (baseResult === null) {
|
|
346
|
+
return null;
|
|
347
|
+
}
|
|
348
|
+
merged = {...merged, ...baseResult};
|
|
265
349
|
}
|
|
350
|
+
const result = andMongoFilters(merged, searchClause);
|
|
351
|
+
return {...result, [ADMIN_LIST_SEARCH_PARAM]: undefined};
|
|
352
|
+
};
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
const ADMIN_TIMESTAMP_SORT_FIELDS = ["created", "createdAt", "updated", "updatedAt"];
|
|
356
|
+
|
|
357
|
+
const sortTokensToFields = (sort: string | string[] | undefined): string[] => {
|
|
358
|
+
if (!sort) {
|
|
359
|
+
return [];
|
|
266
360
|
}
|
|
267
|
-
|
|
361
|
+
const raw = Array.isArray(sort) ? sort.join(" ") : sort;
|
|
362
|
+
return raw
|
|
363
|
+
.trim()
|
|
364
|
+
.split(/\s+/)
|
|
365
|
+
.map((token) => token.replace(/^-/, ""))
|
|
366
|
+
.filter((field) => field.length > 0);
|
|
268
367
|
};
|
|
269
368
|
|
|
369
|
+
const resolveAdminSortableFields = ({
|
|
370
|
+
defaultSort,
|
|
371
|
+
listDisplay,
|
|
372
|
+
sortableFields,
|
|
373
|
+
}: {
|
|
374
|
+
defaultSort?: string | string[];
|
|
375
|
+
listDisplay: string[];
|
|
376
|
+
sortableFields?: string[];
|
|
377
|
+
}): string[] => {
|
|
378
|
+
return [
|
|
379
|
+
...new Set([
|
|
380
|
+
...(sortableFields ?? listDisplay),
|
|
381
|
+
"_id",
|
|
382
|
+
...ADMIN_TIMESTAMP_SORT_FIELDS,
|
|
383
|
+
...sortTokensToFields(defaultSort),
|
|
384
|
+
]),
|
|
385
|
+
];
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
const validateAdminSortParam =
|
|
389
|
+
(sortableFields: string[]): express.RequestHandler =>
|
|
390
|
+
(req, _res, next) => {
|
|
391
|
+
const sort = req.query.sort;
|
|
392
|
+
if (typeof sort !== "string" || !sort.trim()) {
|
|
393
|
+
next();
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
const tokens = sort.trim().split(/\s+/);
|
|
397
|
+
for (const token of tokens) {
|
|
398
|
+
const field = token.replace(/^-/, "");
|
|
399
|
+
if (!sortableFields.includes(field)) {
|
|
400
|
+
throw new APIError({
|
|
401
|
+
detail: field,
|
|
402
|
+
status: 400,
|
|
403
|
+
title: "Invalid sort field",
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
next();
|
|
408
|
+
};
|
|
409
|
+
|
|
270
410
|
const auditDocumentToPlain = (value: unknown): Record<string, unknown> => {
|
|
271
411
|
if (
|
|
272
412
|
value &&
|
|
@@ -294,6 +434,24 @@ const auditLabelFromListFields = (
|
|
|
294
434
|
return id != null ? String(id) : undefined;
|
|
295
435
|
};
|
|
296
436
|
|
|
437
|
+
const coerceAdminFlag = (value: unknown): boolean => {
|
|
438
|
+
if (value === true || value === 1 || value === "1" || value === "true" || value === "yes") {
|
|
439
|
+
return true;
|
|
440
|
+
}
|
|
441
|
+
if (
|
|
442
|
+
value === false ||
|
|
443
|
+
value === 0 ||
|
|
444
|
+
value === "0" ||
|
|
445
|
+
value === "false" ||
|
|
446
|
+
value === "no" ||
|
|
447
|
+
value === "" ||
|
|
448
|
+
value == null
|
|
449
|
+
) {
|
|
450
|
+
return false;
|
|
451
|
+
}
|
|
452
|
+
throw new APIError({status: 400, title: "admin must be a boolean"});
|
|
453
|
+
};
|
|
454
|
+
|
|
297
455
|
const auditActorId = (request: express.Request): string | undefined => {
|
|
298
456
|
const user = request.user as {_id?: unknown} | undefined;
|
|
299
457
|
if (!user || user._id == null) {
|
|
@@ -445,6 +603,139 @@ export class AdminApp {
|
|
|
445
603
|
this.options = options;
|
|
446
604
|
}
|
|
447
605
|
|
|
606
|
+
private adminAccessPermissions(): PermissionMethod<unknown>[] {
|
|
607
|
+
if (this.options.accessControl) {
|
|
608
|
+
return [this.options.accessControl.permission({admin: [ADMIN_PAGE_ACTION]})];
|
|
609
|
+
}
|
|
610
|
+
return [Permissions.IsAdmin];
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
private async hasScriptPermission(
|
|
614
|
+
user: User | undefined,
|
|
615
|
+
action: "runScripts" | "viewBackgroundTasks"
|
|
616
|
+
): Promise<boolean> {
|
|
617
|
+
if (!this.options.accessControl) {
|
|
618
|
+
return Boolean(user?.admin);
|
|
619
|
+
}
|
|
620
|
+
const result = await this.options.accessControl.can({
|
|
621
|
+
permissions: {admin: [action]},
|
|
622
|
+
user,
|
|
623
|
+
});
|
|
624
|
+
return result.allowed;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
private async hasConfigurationPermission(
|
|
628
|
+
user: User | undefined,
|
|
629
|
+
action: "read" | "update"
|
|
630
|
+
): Promise<boolean> {
|
|
631
|
+
if (!this.options.accessControl) {
|
|
632
|
+
return Boolean(user?.admin);
|
|
633
|
+
}
|
|
634
|
+
const result = await this.options.accessControl.can({
|
|
635
|
+
permissions: {configuration: [action]},
|
|
636
|
+
user,
|
|
637
|
+
});
|
|
638
|
+
return result.allowed;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
private async canAnyResourceAction(
|
|
642
|
+
user: User | undefined,
|
|
643
|
+
resource: string,
|
|
644
|
+
actions: string[],
|
|
645
|
+
instance?: unknown
|
|
646
|
+
): Promise<boolean> {
|
|
647
|
+
const accessControl = this.options.accessControl;
|
|
648
|
+
if (!accessControl || !user) {
|
|
649
|
+
return Boolean(user?.admin);
|
|
650
|
+
}
|
|
651
|
+
for (const action of actions) {
|
|
652
|
+
const result = await accessControl.can({
|
|
653
|
+
doc: instance,
|
|
654
|
+
permissions: {[resource]: [action]},
|
|
655
|
+
user,
|
|
656
|
+
});
|
|
657
|
+
if (result.allowed) {
|
|
658
|
+
return true;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
return false;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
private adminResource(config: Pick<AdminModelConfig, "adminAccess" | "model">): string {
|
|
665
|
+
const accessControl = this.options.accessControl;
|
|
666
|
+
const explicit = config.adminAccess?.resource;
|
|
667
|
+
if (explicit) {
|
|
668
|
+
return explicit;
|
|
669
|
+
}
|
|
670
|
+
const standard = `admin${config.model.modelName}`;
|
|
671
|
+
if (accessControl?.statements[standard]) {
|
|
672
|
+
return standard;
|
|
673
|
+
}
|
|
674
|
+
return `${config.model.modelName.charAt(0).toLowerCase()}${config.model.modelName.slice(1)}`;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
private async isAdminModelOwned(
|
|
678
|
+
config: Pick<AdminModelConfig, "adminAccess">,
|
|
679
|
+
user: User,
|
|
680
|
+
instance: unknown
|
|
681
|
+
): Promise<boolean> {
|
|
682
|
+
if (config.adminAccess?.isOwned) {
|
|
683
|
+
return config.adminAccess.isOwned({instance, user});
|
|
684
|
+
}
|
|
685
|
+
const owner = (instance as {ownerId?: {_id?: unknown} | unknown} | undefined)?.ownerId;
|
|
686
|
+
const ownerId = (owner as {_id?: unknown} | undefined)?._id ?? owner;
|
|
687
|
+
return ownerId != null && String(ownerId) === String(user.id);
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
private resourceActionPermissions(
|
|
691
|
+
config: Pick<AdminModelConfig, "adminAccess" | "model">,
|
|
692
|
+
action: "list" | "read" | "create" | "update" | "delete"
|
|
693
|
+
): PermissionMethod<unknown>[] {
|
|
694
|
+
const shell = this.adminAccessPermissions();
|
|
695
|
+
const accessControl = this.options.accessControl;
|
|
696
|
+
if (!accessControl) {
|
|
697
|
+
return shell;
|
|
698
|
+
}
|
|
699
|
+
if (config.adminAccess?.authorize) {
|
|
700
|
+
return [
|
|
701
|
+
...shell,
|
|
702
|
+
async (_method, user, instance) =>
|
|
703
|
+
config.adminAccess?.authorize?.({action, instance, user}) ?? false,
|
|
704
|
+
];
|
|
705
|
+
}
|
|
706
|
+
const resource = this.adminResource(config);
|
|
707
|
+
const knownActions = accessControl.statements[resource];
|
|
708
|
+
if (!knownActions) {
|
|
709
|
+
return [];
|
|
710
|
+
}
|
|
711
|
+
const hasStandardAccess = knownActions.includes("write") || knownActions.includes("writeOwned");
|
|
712
|
+
if (hasStandardAccess) {
|
|
713
|
+
return [
|
|
714
|
+
...shell,
|
|
715
|
+
async (_method, user, instance) => {
|
|
716
|
+
if (!user) {
|
|
717
|
+
return false;
|
|
718
|
+
}
|
|
719
|
+
if (action === "list" || action === "read") {
|
|
720
|
+
return this.canAnyResourceAction(user, resource, ["read"], instance);
|
|
721
|
+
}
|
|
722
|
+
if (await this.canAnyResourceAction(user, resource, ["write"], instance)) {
|
|
723
|
+
return true;
|
|
724
|
+
}
|
|
725
|
+
if (!(await this.canAnyResourceAction(user, resource, ["writeOwned"], instance))) {
|
|
726
|
+
return false;
|
|
727
|
+
}
|
|
728
|
+
// writeOwned always allows create. Ownership applies to update/delete.
|
|
729
|
+
if (action === "create" || instance === undefined) {
|
|
730
|
+
return true;
|
|
731
|
+
}
|
|
732
|
+
return this.isAdminModelOwned(config, user, instance);
|
|
733
|
+
},
|
|
734
|
+
];
|
|
735
|
+
}
|
|
736
|
+
return [...shell, accessControl.permission({[resource]: [action]})];
|
|
737
|
+
}
|
|
738
|
+
|
|
448
739
|
/**
|
|
449
740
|
* Register admin routes with the Express application.
|
|
450
741
|
*
|
|
@@ -461,10 +752,15 @@ export class AdminApp {
|
|
|
461
752
|
*
|
|
462
753
|
* @param app - The Express application instance to register with
|
|
463
754
|
*/
|
|
464
|
-
register(app: express.Application, openApi?: unknown): void {
|
|
755
|
+
register(app: express.Application, openApi?: unknown, terrenoApp?: TerrenoApp): void {
|
|
465
756
|
const basePath = this.options.basePath ?? "/admin";
|
|
466
757
|
const openApiMw = openApi as OpenApiMiddleware | undefined;
|
|
467
|
-
const
|
|
758
|
+
const aggregated = aggregateFromTerrenoApp({
|
|
759
|
+
legacyModels: this.options.models ?? [],
|
|
760
|
+
terrenoApp,
|
|
761
|
+
});
|
|
762
|
+
const modelConfigs = aggregated.models;
|
|
763
|
+
const allModelAdmins = buildAllModelAdminsMap(modelConfigs);
|
|
468
764
|
const onAdminAudit = this.options.onAdminAudit;
|
|
469
765
|
|
|
470
766
|
/** Audit is best-effort: failures must not change HTTP outcomes after mutations succeed. */
|
|
@@ -484,7 +780,14 @@ export class AdminApp {
|
|
|
484
780
|
};
|
|
485
781
|
|
|
486
782
|
// Build config response with field metadata from Mongoose schemas
|
|
487
|
-
const
|
|
783
|
+
const configNames = assignUniqueAdminConfigNames(
|
|
784
|
+
modelConfigs.map((config) => ({
|
|
785
|
+
modelName: config.model.modelName,
|
|
786
|
+
routePath: config.routePath,
|
|
787
|
+
source: config.source,
|
|
788
|
+
}))
|
|
789
|
+
);
|
|
790
|
+
const configModels: AdminModelMeta[] = modelConfigs.map((config, configIndex) => {
|
|
488
791
|
const {properties, required} = getOpenApiSpecForModel(config.model) as {
|
|
489
792
|
properties: Record<string, OpenApiProperty>;
|
|
490
793
|
required: string[];
|
|
@@ -549,7 +852,11 @@ export class AdminApp {
|
|
|
549
852
|
const listDisplay = config.listDisplay ?? listFields;
|
|
550
853
|
const derivedSearchFields = listFields.filter((field) => fields[field]?.searchable);
|
|
551
854
|
const searchFields = config.searchFields ?? derivedSearchFields;
|
|
552
|
-
const sortableFields =
|
|
855
|
+
const sortableFields = resolveAdminSortableFields({
|
|
856
|
+
defaultSort: config.defaultSort,
|
|
857
|
+
listDisplay,
|
|
858
|
+
sortableFields: config.sortableFields,
|
|
859
|
+
});
|
|
553
860
|
const schemaPathKeys = new Set(Object.keys(config.model.schema.paths));
|
|
554
861
|
const bulkPatchAllowlist =
|
|
555
862
|
config.bulkPatchAllowlist ??
|
|
@@ -574,7 +881,7 @@ export class AdminApp {
|
|
|
574
881
|
listDisplay,
|
|
575
882
|
listDisplayLinks: config.listDisplayLinks ?? [],
|
|
576
883
|
listFields,
|
|
577
|
-
name: config.model.modelName,
|
|
884
|
+
name: configNames[configIndex] ?? config.model.modelName,
|
|
578
885
|
pageSize: config.pageSize,
|
|
579
886
|
permissions: {
|
|
580
887
|
create: config.permissions?.create !== false,
|
|
@@ -591,22 +898,137 @@ export class AdminApp {
|
|
|
591
898
|
});
|
|
592
899
|
|
|
593
900
|
// Build script metadata for config response
|
|
594
|
-
const scriptConfigs = this.options.scripts ?? [];
|
|
901
|
+
const scriptConfigs = [...(this.options.scripts ?? []), ...aggregated.scripts];
|
|
595
902
|
const configScripts: AdminScriptMeta[] = scriptConfigs.map((script) => ({
|
|
596
903
|
args: script.args ?? [],
|
|
597
904
|
description: script.description,
|
|
598
905
|
name: script.name,
|
|
599
906
|
}));
|
|
600
907
|
|
|
601
|
-
const defaultScreens = [
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
908
|
+
const defaultScreens: AdminCustomScreenConfig[] = [
|
|
909
|
+
{
|
|
910
|
+
adminAccess: {action: "read", resource: "configuration"},
|
|
911
|
+
displayName: "Version Config",
|
|
912
|
+
name: "version-config",
|
|
913
|
+
},
|
|
914
|
+
];
|
|
915
|
+
const mergedScreens: AdminCustomScreenConfig[] = [
|
|
916
|
+
...defaultScreens,
|
|
917
|
+
...aggregated.customScreens,
|
|
918
|
+
...(this.options.customScreens ?? []),
|
|
919
|
+
];
|
|
920
|
+
|
|
921
|
+
const baseConfigResponse: AdminConfigResponse = {
|
|
922
|
+
capabilities: {
|
|
923
|
+
actions: true,
|
|
924
|
+
fieldsets: true,
|
|
925
|
+
filters: true,
|
|
926
|
+
realtime: modelConfigs.some((config) => config.realtime === true),
|
|
927
|
+
},
|
|
605
928
|
customScreens: mergedScreens,
|
|
606
929
|
home: normalizeAdminHome(this.options.home),
|
|
607
930
|
models: configModels,
|
|
931
|
+
platformTools: {
|
|
932
|
+
configuration: true,
|
|
933
|
+
roles: true,
|
|
934
|
+
runScripts: true,
|
|
935
|
+
scripts: true,
|
|
936
|
+
version: true,
|
|
937
|
+
viewScripts: true,
|
|
938
|
+
},
|
|
608
939
|
schemaVersion: ADMIN_SCHEMA_VERSION,
|
|
609
940
|
scripts: configScripts,
|
|
941
|
+
widgetIds: aggregated.widgetIds,
|
|
942
|
+
};
|
|
943
|
+
|
|
944
|
+
const buildAuthorizedConfig = async (user: User | undefined): Promise<AdminConfigResponse> => {
|
|
945
|
+
const authorizedModels = (
|
|
946
|
+
await Promise.all(
|
|
947
|
+
configModels.map(async (modelMeta, index): Promise<AdminModelMeta | null> => {
|
|
948
|
+
const config = modelConfigs[index];
|
|
949
|
+
if (!config) {
|
|
950
|
+
return null;
|
|
951
|
+
}
|
|
952
|
+
const canRead = await checkPermissions(
|
|
953
|
+
"list",
|
|
954
|
+
this.resourceActionPermissions(config, "list"),
|
|
955
|
+
user
|
|
956
|
+
);
|
|
957
|
+
if (!canRead) {
|
|
958
|
+
return null;
|
|
959
|
+
}
|
|
960
|
+
const canCreate =
|
|
961
|
+
modelMeta.permissions.create &&
|
|
962
|
+
(await checkPermissions(
|
|
963
|
+
"create",
|
|
964
|
+
this.resourceActionPermissions(config, "create"),
|
|
965
|
+
user
|
|
966
|
+
));
|
|
967
|
+
const canDelete =
|
|
968
|
+
modelMeta.permissions.delete &&
|
|
969
|
+
(await checkPermissions(
|
|
970
|
+
"delete",
|
|
971
|
+
this.resourceActionPermissions(config, "delete"),
|
|
972
|
+
user
|
|
973
|
+
));
|
|
974
|
+
const canUpdate =
|
|
975
|
+
modelMeta.permissions.update &&
|
|
976
|
+
(await checkPermissions(
|
|
977
|
+
"update",
|
|
978
|
+
this.resourceActionPermissions(config, "update"),
|
|
979
|
+
user
|
|
980
|
+
));
|
|
981
|
+
return {
|
|
982
|
+
...modelMeta,
|
|
983
|
+
permissions: {create: canCreate, delete: canDelete, update: canUpdate},
|
|
984
|
+
};
|
|
985
|
+
})
|
|
986
|
+
)
|
|
987
|
+
).filter((model): model is AdminModelMeta => model !== null);
|
|
988
|
+
|
|
989
|
+
const authorizedScreens = (
|
|
990
|
+
await Promise.all(
|
|
991
|
+
mergedScreens.map(async (screen): Promise<AdminCustomScreenConfig | null> => {
|
|
992
|
+
if (!screen.adminAccess) {
|
|
993
|
+
return screen;
|
|
994
|
+
}
|
|
995
|
+
if (screen.adminAccess.authorize) {
|
|
996
|
+
const allowed = await screen.adminAccess.authorize({
|
|
997
|
+
action: screen.adminAccess.action ?? "read",
|
|
998
|
+
user,
|
|
999
|
+
});
|
|
1000
|
+
return allowed ? screen : null;
|
|
1001
|
+
}
|
|
1002
|
+
if (!screen.adminAccess.resource) {
|
|
1003
|
+
return screen;
|
|
1004
|
+
}
|
|
1005
|
+
const allowed = await this.canAnyResourceAction(user, screen.adminAccess.resource, [
|
|
1006
|
+
screen.adminAccess.action ?? "read",
|
|
1007
|
+
]);
|
|
1008
|
+
return allowed ? screen : null;
|
|
1009
|
+
})
|
|
1010
|
+
)
|
|
1011
|
+
).filter((screen): screen is AdminCustomScreenConfig => screen !== null);
|
|
1012
|
+
|
|
1013
|
+
const canReadConfiguration = await this.hasConfigurationPermission(user, "read");
|
|
1014
|
+
const canReadRoles = await this.canAnyResourceAction(user, "rbac", ["read"]);
|
|
1015
|
+
const canRunScripts = await this.hasScriptPermission(user, "runScripts");
|
|
1016
|
+
const canViewScripts = await this.hasScriptPermission(user, "viewBackgroundTasks");
|
|
1017
|
+
const canUseScripts = canRunScripts || canViewScripts;
|
|
1018
|
+
return {
|
|
1019
|
+
...baseConfigResponse,
|
|
1020
|
+
customScreens: authorizedScreens.map(({adminAccess: _adminAccess, ...screen}) => screen),
|
|
1021
|
+
models: authorizedModels,
|
|
1022
|
+
platformTools: {
|
|
1023
|
+
configuration: canReadConfiguration,
|
|
1024
|
+
roles: canReadRoles,
|
|
1025
|
+
runScripts: canRunScripts,
|
|
1026
|
+
scripts: canUseScripts,
|
|
1027
|
+
version: canReadConfiguration,
|
|
1028
|
+
viewScripts: canViewScripts,
|
|
1029
|
+
},
|
|
1030
|
+
scripts: canUseScripts ? configScripts : [],
|
|
1031
|
+
};
|
|
610
1032
|
};
|
|
611
1033
|
|
|
612
1034
|
const adminConfigOpenApi = openApiMw
|
|
@@ -614,6 +1036,15 @@ export class AdminApp {
|
|
|
614
1036
|
.withTags(["admin"])
|
|
615
1037
|
.withSummary("Admin panel configuration")
|
|
616
1038
|
.withResponse(200, {
|
|
1039
|
+
capabilities: {
|
|
1040
|
+
properties: {
|
|
1041
|
+
actions: {type: "boolean"},
|
|
1042
|
+
fieldsets: {type: "boolean"},
|
|
1043
|
+
filters: {type: "boolean"},
|
|
1044
|
+
realtime: {type: "boolean"},
|
|
1045
|
+
},
|
|
1046
|
+
type: "object",
|
|
1047
|
+
},
|
|
617
1048
|
customScreens: {
|
|
618
1049
|
items: {
|
|
619
1050
|
properties: {
|
|
@@ -627,6 +1058,17 @@ export class AdminApp {
|
|
|
627
1058
|
},
|
|
628
1059
|
home: {type: "object"},
|
|
629
1060
|
models: {type: "array"},
|
|
1061
|
+
platformTools: {
|
|
1062
|
+
properties: {
|
|
1063
|
+
configuration: {type: "boolean"},
|
|
1064
|
+
roles: {type: "boolean"},
|
|
1065
|
+
runScripts: {type: "boolean"},
|
|
1066
|
+
scripts: {type: "boolean"},
|
|
1067
|
+
version: {type: "boolean"},
|
|
1068
|
+
viewScripts: {type: "boolean"},
|
|
1069
|
+
},
|
|
1070
|
+
type: "object",
|
|
1071
|
+
},
|
|
630
1072
|
schemaVersion: {type: "number"},
|
|
631
1073
|
scripts: {
|
|
632
1074
|
items: {
|
|
@@ -639,6 +1081,7 @@ export class AdminApp {
|
|
|
639
1081
|
},
|
|
640
1082
|
type: "array",
|
|
641
1083
|
},
|
|
1084
|
+
widgetIds: {items: {type: "string"}, type: "array"},
|
|
642
1085
|
})
|
|
643
1086
|
.build()
|
|
644
1087
|
: undefined;
|
|
@@ -650,11 +1093,15 @@ export class AdminApp {
|
|
|
650
1093
|
...asMiddlewareList(adminConfigOpenApi),
|
|
651
1094
|
asyncHandler(async (req, res) => {
|
|
652
1095
|
if (
|
|
653
|
-
!(await checkPermissions(
|
|
1096
|
+
!(await checkPermissions(
|
|
1097
|
+
"read",
|
|
1098
|
+
this.adminAccessPermissions(),
|
|
1099
|
+
req.user as User | undefined
|
|
1100
|
+
))
|
|
654
1101
|
) {
|
|
655
1102
|
throw new APIError({status: 403, title: "Admin access required"});
|
|
656
1103
|
}
|
|
657
|
-
return res.json(
|
|
1104
|
+
return res.json(await buildAuthorizedConfig(req.user as User | undefined));
|
|
658
1105
|
})
|
|
659
1106
|
);
|
|
660
1107
|
|
|
@@ -693,12 +1140,11 @@ export class AdminApp {
|
|
|
693
1140
|
authenticateMiddleware(),
|
|
694
1141
|
...asMiddlewareList(backgroundTasksOpenApi),
|
|
695
1142
|
asyncHandler(async (req, res) => {
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
) {
|
|
1143
|
+
const actor = req.user as User | undefined;
|
|
1144
|
+
if (!actor || !(await this.hasScriptPermission(actor, "runScripts"))) {
|
|
699
1145
|
throw new APIError({status: 403, title: "Admin access required"});
|
|
700
1146
|
}
|
|
701
|
-
const user =
|
|
1147
|
+
const user = actor as {_id: unknown};
|
|
702
1148
|
const raw = req.body as {
|
|
703
1149
|
ids?: unknown;
|
|
704
1150
|
kind?: unknown;
|
|
@@ -753,9 +1199,7 @@ export class AdminApp {
|
|
|
753
1199
|
versionConfigPath,
|
|
754
1200
|
authenticateMiddleware(),
|
|
755
1201
|
asyncHandler(async (req, res) => {
|
|
756
|
-
if (
|
|
757
|
-
!(await checkPermissions("read", [Permissions.IsAdmin], req.user as User | undefined))
|
|
758
|
-
) {
|
|
1202
|
+
if (!(await this.hasConfigurationPermission(req.user as User | undefined, "read"))) {
|
|
759
1203
|
throw new APIError({status: 403, title: "Admin access required"});
|
|
760
1204
|
}
|
|
761
1205
|
const config = await VersionConfig.findOneOrNone({_singleton: "config"});
|
|
@@ -775,9 +1219,7 @@ export class AdminApp {
|
|
|
775
1219
|
versionConfigPath,
|
|
776
1220
|
authenticateMiddleware(),
|
|
777
1221
|
asyncHandler(async (req, res) => {
|
|
778
|
-
if (
|
|
779
|
-
!(await checkPermissions("update", [Permissions.IsAdmin], req.user as User | undefined))
|
|
780
|
-
) {
|
|
1222
|
+
if (!(await this.hasConfigurationPermission(req.user as User | undefined, "update"))) {
|
|
781
1223
|
throw new APIError({status: 403, title: "Admin access required"});
|
|
782
1224
|
}
|
|
783
1225
|
const raw = req.body as Record<string, unknown>;
|
|
@@ -822,7 +1264,10 @@ export class AdminApp {
|
|
|
822
1264
|
// not the OpenAPI type (which reports ObjectId as "string")
|
|
823
1265
|
const searchableFields: string[] = [];
|
|
824
1266
|
const objectIdFields: string[] = [];
|
|
825
|
-
const modelMeta =
|
|
1267
|
+
const modelMeta = findAdminModelMetaByRoutePath(
|
|
1268
|
+
configModels,
|
|
1269
|
+
`${basePath}${config.routePath}`
|
|
1270
|
+
);
|
|
826
1271
|
if (modelMeta) {
|
|
827
1272
|
for (const key of Object.keys(modelMeta.fields)) {
|
|
828
1273
|
const schemaPath = config.model.schema.path(key);
|
|
@@ -838,8 +1283,13 @@ export class AdminApp {
|
|
|
838
1283
|
`${basePath}${config.routePath}/search`,
|
|
839
1284
|
authenticateMiddleware(),
|
|
840
1285
|
asyncHandler(async (req, res) => {
|
|
841
|
-
|
|
842
|
-
|
|
1286
|
+
if (
|
|
1287
|
+
!(await checkPermissions(
|
|
1288
|
+
"list",
|
|
1289
|
+
this.resourceActionPermissions(config, "list"),
|
|
1290
|
+
req.user as User | undefined
|
|
1291
|
+
))
|
|
1292
|
+
) {
|
|
843
1293
|
throw new APIError({
|
|
844
1294
|
disableExternalErrorTracking: true,
|
|
845
1295
|
status: 403,
|
|
@@ -851,24 +1301,19 @@ export class AdminApp {
|
|
|
851
1301
|
return res.json({data: []});
|
|
852
1302
|
}
|
|
853
1303
|
|
|
854
|
-
const escapedQ = q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
855
|
-
const regex = new RegExp(escapedQ, "i");
|
|
856
|
-
|
|
857
1304
|
const fields =
|
|
858
1305
|
typeof req.query.fields === "string"
|
|
859
1306
|
? req.query.fields.split(",").filter((f: string) => searchableFields.includes(f))
|
|
860
1307
|
: searchableFields;
|
|
861
1308
|
|
|
862
|
-
const
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
}
|
|
869
|
-
}
|
|
1309
|
+
const searchClause = buildAdminPartialSearchFilter({
|
|
1310
|
+
extraObjectIdFields: objectIdFields,
|
|
1311
|
+
model: config.model,
|
|
1312
|
+
q,
|
|
1313
|
+
searchFields: fields,
|
|
1314
|
+
});
|
|
870
1315
|
|
|
871
|
-
if (
|
|
1316
|
+
if (!searchClause) {
|
|
872
1317
|
return res.json({data: []});
|
|
873
1318
|
}
|
|
874
1319
|
logger.debug("Admin search query", {
|
|
@@ -877,12 +1322,24 @@ export class AdminApp {
|
|
|
877
1322
|
q,
|
|
878
1323
|
});
|
|
879
1324
|
try {
|
|
880
|
-
const
|
|
1325
|
+
const scoped = await buildAdminListQueryFilter(config, modelMeta?.searchFields)(
|
|
1326
|
+
req.user as User | undefined,
|
|
1327
|
+
{}
|
|
1328
|
+
);
|
|
1329
|
+
if (scoped === null) {
|
|
1330
|
+
return res.json({data: []});
|
|
1331
|
+
}
|
|
1332
|
+
const results = await config.model
|
|
1333
|
+
.find({$and: [scoped, searchClause]})
|
|
1334
|
+
.limit(20)
|
|
1335
|
+
.lean();
|
|
881
1336
|
logger.debug("Admin search results", {
|
|
882
1337
|
count: results.length,
|
|
883
1338
|
model: config.model.modelName,
|
|
884
1339
|
});
|
|
885
|
-
return res.json({
|
|
1340
|
+
return res.json({
|
|
1341
|
+
data: results.map((doc) => scrubAdminResponse(doc, config, allModelAdmins)),
|
|
1342
|
+
});
|
|
886
1343
|
} catch (err) {
|
|
887
1344
|
logger.error("Admin search failed", {
|
|
888
1345
|
error: err,
|
|
@@ -899,16 +1356,25 @@ export class AdminApp {
|
|
|
899
1356
|
for (const config of modelConfigs) {
|
|
900
1357
|
const hiddenFieldSet = new Set(config.hiddenFields ?? []);
|
|
901
1358
|
const readonlySet = new Set(config.readonlyFields ?? []);
|
|
902
|
-
const
|
|
1359
|
+
const excludeFieldSet = new Set(config.excludeFields ?? []);
|
|
1360
|
+
const modelMeta = findAdminModelMetaByRoutePath(
|
|
1361
|
+
configModels,
|
|
1362
|
+
`${basePath}${config.routePath}`
|
|
1363
|
+
);
|
|
903
1364
|
const allowlist = new Set(modelMeta?.bulkPatchAllowlist ?? []);
|
|
904
1365
|
|
|
905
|
-
const adminPermission = (
|
|
1366
|
+
const adminPermission = (
|
|
1367
|
+
allowed: boolean | undefined,
|
|
1368
|
+
action: "list" | "read" | "create" | "update" | "delete"
|
|
1369
|
+
): PermissionMethod<unknown>[] => {
|
|
906
1370
|
if (allowed === false) {
|
|
907
1371
|
return [];
|
|
908
1372
|
}
|
|
909
|
-
return
|
|
1373
|
+
return this.resourceActionPermissions(config, action);
|
|
910
1374
|
};
|
|
911
1375
|
|
|
1376
|
+
const updatePermissions = this.resourceActionPermissions(config, "update");
|
|
1377
|
+
|
|
912
1378
|
const stripProtectedFromBody = (body: unknown): Record<string, unknown> => {
|
|
913
1379
|
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
914
1380
|
return {};
|
|
@@ -920,12 +1386,131 @@ export class AdminApp {
|
|
|
920
1386
|
for (const key of hiddenFieldSet) {
|
|
921
1387
|
delete next[key];
|
|
922
1388
|
}
|
|
1389
|
+
for (const key of excludeFieldSet) {
|
|
1390
|
+
delete next[key];
|
|
1391
|
+
}
|
|
923
1392
|
for (const key of SYSTEM_ADMIN_FIELDS) {
|
|
924
1393
|
delete next[key];
|
|
925
1394
|
}
|
|
1395
|
+
// Self-service never writes these fields. Admin CRUD may set `admin`.
|
|
1396
|
+
// When RBAC is enabled, `roles` must go through RoleManager.assign and
|
|
1397
|
+
// tenant membership is not a generic User document field.
|
|
1398
|
+
if (config.model.modelName === "User" && this.options.accessControl) {
|
|
1399
|
+
delete next.organizationIds;
|
|
1400
|
+
delete next.roles;
|
|
1401
|
+
}
|
|
926
1402
|
return next;
|
|
927
1403
|
};
|
|
928
1404
|
|
|
1405
|
+
const parseRoleNames = (value: unknown): string[] => {
|
|
1406
|
+
if (!Array.isArray(value) || value.some((roleName) => typeof roleName !== "string")) {
|
|
1407
|
+
throw new APIError({status: 400, title: "roles must be an array of strings"});
|
|
1408
|
+
}
|
|
1409
|
+
return value as string[];
|
|
1410
|
+
};
|
|
1411
|
+
|
|
1412
|
+
const takePendingUserRoles = (
|
|
1413
|
+
body: Record<string, unknown>,
|
|
1414
|
+
request: express.Request
|
|
1415
|
+
): void => {
|
|
1416
|
+
if (config.model.modelName !== "User" || !this.options.accessControl) {
|
|
1417
|
+
return;
|
|
1418
|
+
}
|
|
1419
|
+
if (!("roles" in body)) {
|
|
1420
|
+
return;
|
|
1421
|
+
}
|
|
1422
|
+
(
|
|
1423
|
+
request as express.Request & {terrenoPendingUserRoles?: string[]}
|
|
1424
|
+
).terrenoPendingUserRoles = parseRoleNames(body.roles);
|
|
1425
|
+
};
|
|
1426
|
+
|
|
1427
|
+
const applyPendingUserRoles = async (
|
|
1428
|
+
value: unknown,
|
|
1429
|
+
request: express.Request,
|
|
1430
|
+
rollbackOnFailure = false
|
|
1431
|
+
): Promise<void> => {
|
|
1432
|
+
const pending = (request as express.Request & {terrenoPendingUserRoles?: string[]})
|
|
1433
|
+
.terrenoPendingUserRoles;
|
|
1434
|
+
if (!pending) {
|
|
1435
|
+
return;
|
|
1436
|
+
}
|
|
1437
|
+
const actor = request.user as User | undefined;
|
|
1438
|
+
const accessControl = this.options.accessControl;
|
|
1439
|
+
if (!actor || !accessControl) {
|
|
1440
|
+
throw new APIError({status: 401, title: "Unauthorized"});
|
|
1441
|
+
}
|
|
1442
|
+
const record = value as {
|
|
1443
|
+
_id?: unknown;
|
|
1444
|
+
id?: string;
|
|
1445
|
+
roles?: string[];
|
|
1446
|
+
set?: (path: string, value: unknown) => void;
|
|
1447
|
+
};
|
|
1448
|
+
const userId = record.id ?? (record._id != null ? String(record._id) : undefined);
|
|
1449
|
+
if (!userId) {
|
|
1450
|
+
throw new APIError({status: 500, title: "User id missing after write"});
|
|
1451
|
+
}
|
|
1452
|
+
try {
|
|
1453
|
+
await accessControl.roles.assign({actor, roleNames: pending, userId});
|
|
1454
|
+
if (typeof record.set === "function") {
|
|
1455
|
+
record.set("roles", [...pending]);
|
|
1456
|
+
} else {
|
|
1457
|
+
record.roles = [...pending];
|
|
1458
|
+
}
|
|
1459
|
+
} catch (error) {
|
|
1460
|
+
if (rollbackOnFailure) {
|
|
1461
|
+
try {
|
|
1462
|
+
await config.model.deleteOne({_id: userId});
|
|
1463
|
+
} catch (rollbackError) {
|
|
1464
|
+
logger.error("Failed to roll back user after role assignment failure", {
|
|
1465
|
+
error: rollbackError,
|
|
1466
|
+
userId,
|
|
1467
|
+
});
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
throw error;
|
|
1471
|
+
}
|
|
1472
|
+
};
|
|
1473
|
+
|
|
1474
|
+
const restoreUserFieldsAfterFailedRoleAssign = async (
|
|
1475
|
+
value: unknown,
|
|
1476
|
+
prev: unknown,
|
|
1477
|
+
cleanedBody: unknown
|
|
1478
|
+
): Promise<void> => {
|
|
1479
|
+
if (!prev || typeof prev !== "object" || !cleanedBody || typeof cleanedBody !== "object") {
|
|
1480
|
+
return;
|
|
1481
|
+
}
|
|
1482
|
+
if (Array.isArray(cleanedBody)) {
|
|
1483
|
+
return;
|
|
1484
|
+
}
|
|
1485
|
+
const record = value as {
|
|
1486
|
+
_id?: unknown;
|
|
1487
|
+
save?: () => Promise<unknown>;
|
|
1488
|
+
set?: (path: string, next: unknown) => void;
|
|
1489
|
+
};
|
|
1490
|
+
const prevRecord = prev as Record<string, unknown>;
|
|
1491
|
+
const body = cleanedBody as Record<string, unknown>;
|
|
1492
|
+
const restore: Record<string, unknown> = {};
|
|
1493
|
+
for (const key of Object.keys(body)) {
|
|
1494
|
+
if (key === "roles") {
|
|
1495
|
+
continue;
|
|
1496
|
+
}
|
|
1497
|
+
restore[key] = prevRecord[key];
|
|
1498
|
+
if (typeof record.set === "function") {
|
|
1499
|
+
record.set(key, prevRecord[key]);
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
if (Object.keys(restore).length === 0) {
|
|
1503
|
+
return;
|
|
1504
|
+
}
|
|
1505
|
+
if (typeof record.save === "function") {
|
|
1506
|
+
await record.save();
|
|
1507
|
+
return;
|
|
1508
|
+
}
|
|
1509
|
+
if (record._id != null) {
|
|
1510
|
+
await config.model.updateOne({_id: record._id}, {$set: restore});
|
|
1511
|
+
}
|
|
1512
|
+
};
|
|
1513
|
+
|
|
929
1514
|
const bulkPatchOpenApi = openApiMw
|
|
930
1515
|
? createOpenApiBuilder({openApi: openApiMw})
|
|
931
1516
|
.withTags(["admin"])
|
|
@@ -994,56 +1579,198 @@ export class AdminApp {
|
|
|
994
1579
|
}
|
|
995
1580
|
: {};
|
|
996
1581
|
|
|
1582
|
+
const assertCanWriteUserAdminFlag = async (
|
|
1583
|
+
body: Record<string, unknown>,
|
|
1584
|
+
request: express.Request,
|
|
1585
|
+
currentAdmin = false,
|
|
1586
|
+
targetUserId?: string
|
|
1587
|
+
): Promise<void> => {
|
|
1588
|
+
if (config.model.modelName !== "User" || !("admin" in body)) {
|
|
1589
|
+
return;
|
|
1590
|
+
}
|
|
1591
|
+
const accessControl = this.options.accessControl;
|
|
1592
|
+
if (!accessControl) {
|
|
1593
|
+
return;
|
|
1594
|
+
}
|
|
1595
|
+
if (coerceAdminFlag(body.admin) === Boolean(currentAdmin)) {
|
|
1596
|
+
return;
|
|
1597
|
+
}
|
|
1598
|
+
const actor = request.user as User | undefined;
|
|
1599
|
+
if (!actor) {
|
|
1600
|
+
throw new APIError({status: 401, title: "Unauthorized"});
|
|
1601
|
+
}
|
|
1602
|
+
const result = await accessControl.can({
|
|
1603
|
+
permissions: {rbac: ["assignRoles"]},
|
|
1604
|
+
user: actor,
|
|
1605
|
+
});
|
|
1606
|
+
if (!result.allowed) {
|
|
1607
|
+
throw new APIError({
|
|
1608
|
+
status: 403,
|
|
1609
|
+
title: "Missing rbac:assignRoles permission",
|
|
1610
|
+
});
|
|
1611
|
+
}
|
|
1612
|
+
const nextAdmin = coerceAdminFlag(body.admin);
|
|
1613
|
+
const isGrantingAdmin = nextAdmin === true && !currentAdmin;
|
|
1614
|
+
const isRevokingAdmin = nextAdmin === false && currentAdmin;
|
|
1615
|
+
// assignRoles and manageRoles still cannot mint or strip the legacy admin
|
|
1616
|
+
// plane (IsAdmin, password reset, owner bypass). Only an existing admin can.
|
|
1617
|
+
if ((isGrantingAdmin || isRevokingAdmin) && !actor.admin) {
|
|
1618
|
+
throw new APIError({
|
|
1619
|
+
status: 403,
|
|
1620
|
+
title: isGrantingAdmin
|
|
1621
|
+
? "Cannot grant the legacy admin flag without the admin privilege"
|
|
1622
|
+
: "Cannot revoke the legacy admin flag without the admin privilege",
|
|
1623
|
+
});
|
|
1624
|
+
}
|
|
1625
|
+
const targetId = targetUserId ?? request.params?.id;
|
|
1626
|
+
if (targetId) {
|
|
1627
|
+
await accessControl.roles.assertCanModifyUser({actor, userId: String(targetId)});
|
|
1628
|
+
}
|
|
1629
|
+
};
|
|
1630
|
+
|
|
1631
|
+
const currentUserAdminFlag = async (request: express.Request): Promise<boolean> => {
|
|
1632
|
+
const id = request.params?.id;
|
|
1633
|
+
if (!id) {
|
|
1634
|
+
return false;
|
|
1635
|
+
}
|
|
1636
|
+
const existing = await config.model.findById(id).select("admin").lean();
|
|
1637
|
+
return Boolean((existing as {admin?: boolean} | null)?.admin);
|
|
1638
|
+
};
|
|
1639
|
+
|
|
1640
|
+
const markAuthorizedUserAdminWrite = (
|
|
1641
|
+
body: Record<string, unknown>,
|
|
1642
|
+
request: express.Request
|
|
1643
|
+
): void => {
|
|
1644
|
+
if (
|
|
1645
|
+
config.model.modelName !== "User" ||
|
|
1646
|
+
!this.options.accessControl ||
|
|
1647
|
+
!("admin" in body)
|
|
1648
|
+
) {
|
|
1649
|
+
return;
|
|
1650
|
+
}
|
|
1651
|
+
(
|
|
1652
|
+
request as express.Request & {terrenoAllowUserAdminWrite?: boolean}
|
|
1653
|
+
).terrenoAllowUserAdminWrite = true;
|
|
1654
|
+
};
|
|
1655
|
+
|
|
1656
|
+
const addRecordCapabilities = async (
|
|
1657
|
+
value: unknown,
|
|
1658
|
+
request: express.Request
|
|
1659
|
+
): Promise<JSONValue> => {
|
|
1660
|
+
const scrubbed = scrubAdminResponse(value, config, allModelAdmins);
|
|
1661
|
+
const sourceItems = Array.isArray(value) ? value : [value];
|
|
1662
|
+
const scrubbedItems = Array.isArray(scrubbed) ? scrubbed : [scrubbed];
|
|
1663
|
+
const withCapabilities = await Promise.all(
|
|
1664
|
+
scrubbedItems.map(async (item, index) => {
|
|
1665
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) {
|
|
1666
|
+
return item;
|
|
1667
|
+
}
|
|
1668
|
+
const instance = sourceItems[index];
|
|
1669
|
+
const canUpdate =
|
|
1670
|
+
config.permissions?.update !== false &&
|
|
1671
|
+
(await checkPermissions(
|
|
1672
|
+
"update",
|
|
1673
|
+
this.resourceActionPermissions(config, "update"),
|
|
1674
|
+
request.user as User | undefined,
|
|
1675
|
+
instance
|
|
1676
|
+
));
|
|
1677
|
+
const canDelete =
|
|
1678
|
+
config.permissions?.delete !== false &&
|
|
1679
|
+
(await checkPermissions(
|
|
1680
|
+
"delete",
|
|
1681
|
+
this.resourceActionPermissions(config, "delete"),
|
|
1682
|
+
request.user as User | undefined,
|
|
1683
|
+
instance
|
|
1684
|
+
));
|
|
1685
|
+
return {
|
|
1686
|
+
...(item as Record<string, unknown>),
|
|
1687
|
+
_adminCapabilities: {delete: canDelete, update: canUpdate},
|
|
1688
|
+
};
|
|
1689
|
+
})
|
|
1690
|
+
);
|
|
1691
|
+
return (Array.isArray(scrubbed) ? withCapabilities : withCapabilities[0]) as JSONValue;
|
|
1692
|
+
};
|
|
1693
|
+
|
|
997
1694
|
// noExplicitAny: matches the Model<any> from AdminModelConfig above.
|
|
998
1695
|
// biome-ignore lint/suspicious/noExplicitAny: matches the Model<any> from AdminModelConfig above.
|
|
999
1696
|
const routerOptions: ModelRouterOptions<any> = {
|
|
1000
1697
|
...(openApiMw ? {openApi: openApiMw} : {}),
|
|
1698
|
+
...(this.options.accessControl ? {accessControl: this.options.accessControl} : {}),
|
|
1001
1699
|
defaultLimit: config.pageSize ?? 100,
|
|
1002
1700
|
maxLimit: 500,
|
|
1003
1701
|
permissions: {
|
|
1004
|
-
create: adminPermission(config.permissions?.create),
|
|
1005
|
-
delete: adminPermission(config.permissions?.delete),
|
|
1006
|
-
list:
|
|
1007
|
-
read:
|
|
1008
|
-
update: adminPermission(config.permissions?.update),
|
|
1702
|
+
create: adminPermission(config.permissions?.create, "create"),
|
|
1703
|
+
delete: adminPermission(config.permissions?.delete, "delete"),
|
|
1704
|
+
list: adminPermission(true, "list"),
|
|
1705
|
+
read: adminPermission(true, "read"),
|
|
1706
|
+
update: adminPermission(config.permissions?.update, "update"),
|
|
1009
1707
|
},
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1708
|
+
postCreate: async (value, request) => {
|
|
1709
|
+
await applyPendingUserRoles(value, request, true);
|
|
1710
|
+
await auditHooks.postCreate?.(value, request);
|
|
1711
|
+
},
|
|
1712
|
+
postUpdate: async (value, cleanedBody, request, prev) => {
|
|
1713
|
+
try {
|
|
1714
|
+
await applyPendingUserRoles(value, request);
|
|
1715
|
+
} catch (error) {
|
|
1716
|
+
await restoreUserFieldsAfterFailedRoleAssign(value, prev, cleanedBody);
|
|
1717
|
+
throw error;
|
|
1718
|
+
}
|
|
1719
|
+
await auditHooks.postUpdate?.(value, cleanedBody, request, prev);
|
|
1720
|
+
},
|
|
1721
|
+
preCreate: async (body, req) => {
|
|
1018
1722
|
if (!body || typeof body !== "object") {
|
|
1019
1723
|
return body;
|
|
1020
1724
|
}
|
|
1725
|
+
const record = body as Record<string, unknown>;
|
|
1726
|
+
if (
|
|
1727
|
+
!(await checkPermissions(
|
|
1728
|
+
"create",
|
|
1729
|
+
this.resourceActionPermissions(config, "create"),
|
|
1730
|
+
req.user as User | undefined,
|
|
1731
|
+
record
|
|
1732
|
+
))
|
|
1733
|
+
) {
|
|
1734
|
+
throw new APIError({status: 403, title: "Admin create access denied"});
|
|
1735
|
+
}
|
|
1736
|
+
takePendingUserRoles(record, req);
|
|
1737
|
+
await assertCanWriteUserAdminFlag(record, req);
|
|
1738
|
+
markAuthorizedUserAdminWrite(record, req);
|
|
1021
1739
|
return stripProtectedFromBody(body) as typeof body;
|
|
1022
1740
|
},
|
|
1023
|
-
preUpdate: async (body,
|
|
1741
|
+
preUpdate: async (body, req) => {
|
|
1024
1742
|
if (!body || typeof body !== "object") {
|
|
1025
1743
|
return body;
|
|
1026
1744
|
}
|
|
1745
|
+
const record = body as Record<string, unknown>;
|
|
1746
|
+
takePendingUserRoles(record, req);
|
|
1747
|
+
await assertCanWriteUserAdminFlag(record, req, await currentUserAdminFlag(req));
|
|
1748
|
+
markAuthorizedUserAdminWrite(record, req);
|
|
1027
1749
|
return stripProtectedFromBody(body) as typeof body;
|
|
1028
1750
|
},
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1751
|
+
queryFields: buildAdminModelQueryFields({
|
|
1752
|
+
filters: config.filters,
|
|
1753
|
+
listDisplay: config.listDisplay,
|
|
1754
|
+
listFields: config.listFields,
|
|
1755
|
+
searchFields: modelMeta?.searchFields ?? config.searchFields,
|
|
1756
|
+
}),
|
|
1757
|
+
queryFilter: buildAdminListQueryFilter(config, modelMeta?.searchFields),
|
|
1758
|
+
responseHandler: async (value, _method, request): Promise<JSONValue> =>
|
|
1759
|
+
addRecordCapabilities(value, request),
|
|
1034
1760
|
sort: config.defaultSort ?? "-created",
|
|
1035
1761
|
...(config.populatePaths ? {populatePaths: config.populatePaths} : {}),
|
|
1036
|
-
...auditHooks,
|
|
1762
|
+
...(auditHooks.postDelete ? {postDelete: auditHooks.postDelete} : {}),
|
|
1037
1763
|
};
|
|
1038
1764
|
|
|
1039
1765
|
const modelBase = express.Router();
|
|
1766
|
+
modelBase.use(validateAdminSortParam(modelMeta?.sortableFields ?? []));
|
|
1040
1767
|
modelBase.post(
|
|
1041
1768
|
"/bulk-patch",
|
|
1042
1769
|
authenticateMiddleware(),
|
|
1043
1770
|
...asMiddlewareList(bulkPatchOpenApi),
|
|
1044
1771
|
asyncHandler(async (req, res) => {
|
|
1045
1772
|
if (
|
|
1046
|
-
!(await checkPermissions("update",
|
|
1773
|
+
!(await checkPermissions("update", updatePermissions, req.user as User | undefined))
|
|
1047
1774
|
) {
|
|
1048
1775
|
throw new APIError({status: 403, title: "Admin access required"});
|
|
1049
1776
|
}
|
|
@@ -1077,7 +1804,15 @@ export class AdminApp {
|
|
|
1077
1804
|
});
|
|
1078
1805
|
}
|
|
1079
1806
|
const patch = stripProtectedFromBody(rawPatch);
|
|
1080
|
-
|
|
1807
|
+
let pendingRoles: string[] | undefined;
|
|
1808
|
+
if (
|
|
1809
|
+
config.model.modelName === "User" &&
|
|
1810
|
+
this.options.accessControl &&
|
|
1811
|
+
"roles" in rawPatch
|
|
1812
|
+
) {
|
|
1813
|
+
pendingRoles = parseRoleNames(rawPatch.roles);
|
|
1814
|
+
}
|
|
1815
|
+
if (Object.keys(patch).length === 0 && pendingRoles === undefined) {
|
|
1081
1816
|
throw new APIError({
|
|
1082
1817
|
status: 400,
|
|
1083
1818
|
title: "Patch must include at least one writable field",
|
|
@@ -1085,18 +1820,54 @@ export class AdminApp {
|
|
|
1085
1820
|
}
|
|
1086
1821
|
let updated = 0;
|
|
1087
1822
|
const failures: {id: string; title: string}[] = [];
|
|
1823
|
+
const actor = req.user as User | undefined;
|
|
1088
1824
|
for (const id of ids) {
|
|
1089
1825
|
if (!mongoose.isValidObjectId(id)) {
|
|
1090
1826
|
failures.push({id, title: "Invalid id"});
|
|
1091
1827
|
continue;
|
|
1092
1828
|
}
|
|
1093
1829
|
try {
|
|
1094
|
-
const
|
|
1095
|
-
if (
|
|
1830
|
+
const doc = await config.model.findById(id);
|
|
1831
|
+
if (!doc) {
|
|
1096
1832
|
failures.push({id, title: "Not found"});
|
|
1097
|
-
|
|
1098
|
-
|
|
1833
|
+
continue;
|
|
1834
|
+
}
|
|
1835
|
+
if (!(await checkPermissions("update", updatePermissions, actor, doc))) {
|
|
1836
|
+
failures.push({id, title: "Forbidden"});
|
|
1837
|
+
continue;
|
|
1838
|
+
}
|
|
1839
|
+
await assertCanWriteUserAdminFlag(
|
|
1840
|
+
rawPatch,
|
|
1841
|
+
req,
|
|
1842
|
+
Boolean((doc as {admin?: boolean}).admin),
|
|
1843
|
+
id
|
|
1844
|
+
);
|
|
1845
|
+
const previousPatch: Record<string, unknown> = {};
|
|
1846
|
+
for (const key of Object.keys(patch)) {
|
|
1847
|
+
previousPatch[key] = (doc as unknown as Record<string, unknown>)[key];
|
|
1848
|
+
}
|
|
1849
|
+
if (Object.keys(patch).length > 0) {
|
|
1850
|
+
await doc.updateOne({$set: patch});
|
|
1851
|
+
}
|
|
1852
|
+
try {
|
|
1853
|
+
if (pendingRoles) {
|
|
1854
|
+
if (!actor) {
|
|
1855
|
+
failures.push({id, title: "Forbidden"});
|
|
1856
|
+
continue;
|
|
1857
|
+
}
|
|
1858
|
+
await this.options.accessControl?.roles.assign({
|
|
1859
|
+
actor,
|
|
1860
|
+
roleNames: pendingRoles,
|
|
1861
|
+
userId: id,
|
|
1862
|
+
});
|
|
1863
|
+
}
|
|
1864
|
+
} catch (roleError) {
|
|
1865
|
+
if (Object.keys(previousPatch).length > 0) {
|
|
1866
|
+
await config.model.updateOne({_id: id}, {$set: previousPatch});
|
|
1867
|
+
}
|
|
1868
|
+
throw roleError;
|
|
1099
1869
|
}
|
|
1870
|
+
updated += 1;
|
|
1100
1871
|
} catch (err: unknown) {
|
|
1101
1872
|
const message = err instanceof Error ? err.message : String(err);
|
|
1102
1873
|
failures.push({id, title: message});
|
|
@@ -1129,8 +1900,8 @@ export class AdminApp {
|
|
|
1129
1900
|
router.get(
|
|
1130
1901
|
"/runs",
|
|
1131
1902
|
asyncHandler(async (req: express.Request, res: express.Response) => {
|
|
1132
|
-
const user = req.user as
|
|
1133
|
-
if (!user
|
|
1903
|
+
const user = req.user as User | undefined;
|
|
1904
|
+
if (!user || !(await this.hasScriptPermission(user, "viewBackgroundTasks"))) {
|
|
1134
1905
|
throw new APIError({status: 403, title: "Only admins can view run history"});
|
|
1135
1906
|
}
|
|
1136
1907
|
|
|
@@ -1187,8 +1958,8 @@ export class AdminApp {
|
|
|
1187
1958
|
router.post(
|
|
1188
1959
|
"/:name/run",
|
|
1189
1960
|
asyncHandler(async (req: express.Request<{name: string}>, res: express.Response) => {
|
|
1190
|
-
const user = req.user as {_id: unknown;
|
|
1191
|
-
if (!user
|
|
1961
|
+
const user = req.user as (User & {_id: unknown; name?: string}) | undefined;
|
|
1962
|
+
if (!user || !(await this.hasScriptPermission(user, "runScripts"))) {
|
|
1192
1963
|
throw new APIError({status: 403, title: "Only admins can run scripts"});
|
|
1193
1964
|
}
|
|
1194
1965
|
|
|
@@ -1242,7 +2013,7 @@ export class AdminApp {
|
|
|
1242
2013
|
let task: BackgroundTaskDocument;
|
|
1243
2014
|
try {
|
|
1244
2015
|
task = (await BackgroundTask.create({
|
|
1245
|
-
createdBy: user._id as mongoose.Types.ObjectId,
|
|
2016
|
+
createdBy: user._id as unknown as mongoose.Types.ObjectId,
|
|
1246
2017
|
isDryRun: !isWetRun,
|
|
1247
2018
|
logs: [
|
|
1248
2019
|
{level: "info", message: `Script started by ${user.name ?? "admin"}`, timestamp: now},
|
|
@@ -1330,8 +2101,8 @@ export class AdminApp {
|
|
|
1330
2101
|
router.get(
|
|
1331
2102
|
"/tasks/:id",
|
|
1332
2103
|
asyncHandler(async (req: express.Request<{id: string}>, res: express.Response) => {
|
|
1333
|
-
const user = req.user as
|
|
1334
|
-
if (!user
|
|
2104
|
+
const user = req.user as User | undefined;
|
|
2105
|
+
if (!user || !(await this.hasScriptPermission(user, "viewBackgroundTasks"))) {
|
|
1335
2106
|
throw new APIError({status: 403, title: "Only admins can view tasks"});
|
|
1336
2107
|
}
|
|
1337
2108
|
|
|
@@ -1354,8 +2125,8 @@ export class AdminApp {
|
|
|
1354
2125
|
router.delete(
|
|
1355
2126
|
"/tasks/:id",
|
|
1356
2127
|
asyncHandler(async (req: express.Request<{id: string}>, res: express.Response) => {
|
|
1357
|
-
const user = req.user as
|
|
1358
|
-
if (!user
|
|
2128
|
+
const user = req.user as (User & {name?: string}) | undefined;
|
|
2129
|
+
if (!user || !(await this.hasScriptPermission(user, "runScripts"))) {
|
|
1359
2130
|
throw new APIError({status: 403, title: "Only admins can cancel tasks"});
|
|
1360
2131
|
}
|
|
1361
2132
|
|