@terreno/admin-backend 0.20.1 → 0.21.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/src/adminApp.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  BackgroundTask,
6
6
  type BackgroundTaskDocument,
7
7
  checkPermissions,
8
+ createOpenApiBuilder,
8
9
  getOpenApiSpecForModel,
9
10
  type JSONValue,
10
11
  logger,
@@ -24,6 +25,20 @@ import {DateTime} from "luxon";
24
25
  import type {Model} from "mongoose";
25
26
  import mongoose from "mongoose";
26
27
 
28
+ import {
29
+ ADMIN_SCHEMA_VERSION,
30
+ type AdminActionInput,
31
+ type AdminFieldsetInput,
32
+ type AdminHomeInput,
33
+ type AdminListFilter,
34
+ type AdminModelPermissionsInput,
35
+ buildAdminModelQueryFields,
36
+ defaultBulkPatchAllowlistFrom,
37
+ MAX_BULK_PATCH_IDS,
38
+ normalizeAdminHome,
39
+ SYSTEM_ADMIN_FIELDS,
40
+ } from "./adminUiV2";
41
+
27
42
  /**
28
43
  * Configuration for a single model in the admin panel.
29
44
  */
@@ -50,6 +65,48 @@ export interface AdminModelConfig {
50
65
  fieldOrder?: string[];
51
66
  /** Fields to hide from admin forms/responses (e.g., password hash fields). */
52
67
  hiddenFields?: string[];
68
+ /** Optional sidebar / nav grouping label for schema v2 shells */
69
+ group?: string;
70
+ /** Changelist columns (defaults to listFields) */
71
+ listDisplay?: string[];
72
+ /** Subset of list columns rendered as links to detail */
73
+ listDisplayLinks?: string[];
74
+ /** Fields the changelist may sort by (informational + future enforcement) */
75
+ sortableFields?: string[];
76
+ /** Fields exposed to text / quick search in the admin UI */
77
+ searchFields?: string[];
78
+ /** Typed list filters (queryFields-compatible on the wire) */
79
+ filters?: AdminListFilter[];
80
+ /** Form layout: grouped fields */
81
+ fieldsets?: AdminFieldsetInput[];
82
+ /** Fields shown read-only in forms; stripped from PATCH bodies server-side */
83
+ readonlyFields?: string[];
84
+ /** Declarative row / selection actions */
85
+ actions?: AdminActionInput[];
86
+ /** Fine-grained CRUD toggles for admin UI + route wiring */
87
+ permissions?: AdminModelPermissionsInput;
88
+ /** Suggested page size for the changelist */
89
+ pageSize?: number;
90
+ /** UI-only hint that live updates may be available */
91
+ realtime?: boolean;
92
+ /**
93
+ * Field key used for the edit screen title (browser tab / stack header). When omitted, the
94
+ * admin UI derives a label from common keys (`name`, `title`, …) then the first scalar
95
+ * {@link listFields} column, matching audit label heuristics.
96
+ */
97
+ recordTitleField?: string;
98
+ /** Allowlisted keys for POST .../bulk-patch (defaults from listFields minus system/readonly/hidden) */
99
+ bulkPatchAllowlist?: string[];
100
+ /**
101
+ * Per-model `modelRouter` query filter (list and other query-shaped reads).
102
+ * Same contract as {@link ModelRouterOptions.queryFilter} in `@terreno/api`: merge into the
103
+ * Mongoose query, return the incoming `query` unchanged if allowed, or return `null` to yield
104
+ * an empty list without error.
105
+ */
106
+ queryFilter?: (
107
+ user?: User,
108
+ query?: Record<string, unknown>
109
+ ) => Record<string, unknown> | null | Promise<Record<string, unknown> | null>;
53
110
  }
54
111
 
55
112
  /**
@@ -64,6 +121,30 @@ export interface AdminScriptConfig {
64
121
  runner: ScriptRunner;
65
122
  }
66
123
 
124
+ /**
125
+ * Emitted after successful admin modelRouter mutations when {@link AdminOptions.onAdminAudit}
126
+ * is configured.
127
+ */
128
+ export interface AdminAuditEvent {
129
+ /** Terreno user id performing the action, when available */
130
+ actorId?: string;
131
+ /** Mongoose model name (e.g. "Todo") */
132
+ modelName: string;
133
+ /** Target document id when known */
134
+ recordId?: string;
135
+ /** Short human-readable label derived from list fields */
136
+ recordLabel?: string;
137
+ verb: "created" | "deleted" | "updated";
138
+ }
139
+
140
+ /** Declares an extra admin UI screen route merged with built-ins (e.g. version-config). */
141
+ export interface AdminCustomScreenConfig {
142
+ displayName: string;
143
+ name: string;
144
+ /** Optional subtitle or help text shown with the screen card in the admin UI */
145
+ description?: string;
146
+ }
147
+
67
148
  /**
68
149
  * Configuration options for the AdminApp plugin.
69
150
  */
@@ -74,6 +155,15 @@ export interface AdminOptions {
74
155
  scripts?: AdminScriptConfig[];
75
156
  /** Base path for all admin routes. Defaults to "/admin". */
76
157
  basePath?: string;
158
+ /** Optional home dashboard layout (schema v2 slots) */
159
+ home?: AdminHomeInput;
160
+ /** Extra custom screens merged with built-ins (e.g. version-config) */
161
+ customScreens?: AdminCustomScreenConfig[];
162
+ /**
163
+ * Optional audit sink for admin CRUD after modelRouter succeeds.
164
+ * Consumers typically persist to an `AdminAuditLog` collection.
165
+ */
166
+ onAdminAudit?: (event: AdminAuditEvent, req: express.Request) => void | Promise<void>;
77
167
  }
78
168
 
79
169
  interface AdminFieldMeta {
@@ -96,13 +186,28 @@ interface AdminFieldMeta {
96
186
  }
97
187
 
98
188
  interface AdminModelMeta {
99
- name: string;
100
- routePath: string;
101
- displayName: string;
102
- listFields: string[];
189
+ actions: AdminActionInput[];
190
+ bulkPatchAllowlist: string[];
103
191
  defaultSort: string;
104
- fields: Record<string, AdminFieldMeta>;
192
+ displayName: string;
105
193
  fieldOrder?: string[];
194
+ fieldsets?: AdminFieldsetInput[];
195
+ fields: Record<string, AdminFieldMeta>;
196
+ filters: AdminListFilter[];
197
+ group?: string;
198
+ hiddenFields: string[];
199
+ listDisplay: string[];
200
+ listDisplayLinks: string[];
201
+ listFields: string[];
202
+ name: string;
203
+ pageSize?: number;
204
+ permissions: {create: boolean; delete: boolean; update: boolean};
205
+ readonlyFields: string[];
206
+ realtime: boolean;
207
+ recordTitleField?: string;
208
+ routePath: string;
209
+ searchFields: string[];
210
+ sortableFields: string[];
106
211
  }
107
212
 
108
213
  interface AdminScriptMeta {
@@ -111,8 +216,10 @@ interface AdminScriptMeta {
111
216
  }
112
217
 
113
218
  interface AdminConfigResponse {
114
- customScreens?: {displayName: string; name: string}[];
219
+ customScreens?: AdminCustomScreenConfig[];
220
+ home: ReturnType<typeof normalizeAdminHome>;
115
221
  models: AdminModelMeta[];
222
+ schemaVersion: number;
116
223
  scripts: AdminScriptMeta[];
117
224
  }
118
225
 
@@ -145,6 +252,41 @@ const removeHiddenFields = (value: unknown, hiddenFieldSet: Set<string>): unknow
145
252
  return nextValue;
146
253
  };
147
254
 
255
+ const auditDocumentToPlain = (value: unknown): Record<string, unknown> => {
256
+ if (
257
+ value &&
258
+ typeof value === "object" &&
259
+ "toObject" in value &&
260
+ typeof (value as {toObject?: unknown}).toObject === "function"
261
+ ) {
262
+ return (value as {toObject: () => Record<string, unknown>}).toObject();
263
+ }
264
+ return value as Record<string, unknown>;
265
+ };
266
+
267
+ const auditLabelFromListFields = (
268
+ doc: Record<string, unknown>,
269
+ listFields: string[]
270
+ ): string | undefined => {
271
+ for (const key of listFields) {
272
+ const fieldValue = doc[key];
273
+ if (fieldValue == null || typeof fieldValue === "object") {
274
+ continue;
275
+ }
276
+ return String(fieldValue);
277
+ }
278
+ const id = doc._id;
279
+ return id != null ? String(id) : undefined;
280
+ };
281
+
282
+ const auditActorId = (request: express.Request): string | undefined => {
283
+ const user = request.user as {_id?: unknown} | undefined;
284
+ if (!user || user._id == null) {
285
+ return undefined;
286
+ }
287
+ return String(user._id);
288
+ };
289
+
148
290
  interface OpenApiProperty {
149
291
  default?: unknown;
150
292
  description?: string;
@@ -207,6 +349,18 @@ const extractFieldMeta = (
207
349
  return fields;
208
350
  };
209
351
 
352
+ const asMiddlewareList = (
353
+ middleware: express.RequestHandler | express.RequestHandler[] | undefined
354
+ ): express.RequestHandler[] => {
355
+ if (middleware === undefined) {
356
+ return [];
357
+ }
358
+ if (Array.isArray(middleware)) {
359
+ return middleware;
360
+ }
361
+ return [middleware];
362
+ };
363
+
210
364
  /**
211
365
  * TerrenoPlugin that auto-generates admin CRUD endpoints for Mongoose models.
212
366
  *
@@ -233,6 +387,8 @@ const extractFieldMeta = (
233
387
  * routePath: "/todos",
234
388
  * displayName: "Todos",
235
389
  * listFields: ["title", "completed", "ownerId"],
390
+ * // Optional: constrain admin list queries (e.g. tenant) — same as modelRouter queryFilter.
391
+ * queryFilter: (_user, query) => ({...query, tenantId: "acme"}),
236
392
  * },
237
393
  * ],
238
394
  * });
@@ -277,7 +433,25 @@ export class AdminApp {
277
433
  */
278
434
  register(app: express.Application, openApi?: unknown): void {
279
435
  const basePath = this.options.basePath ?? "/admin";
436
+ const openApiMw = openApi as OpenApiMiddleware | undefined;
280
437
  const modelConfigs = this.options.models;
438
+ const onAdminAudit = this.options.onAdminAudit;
439
+
440
+ /** Audit is best-effort: failures must not change HTTP outcomes after mutations succeed. */
441
+ const safeOnAdminAudit = async (
442
+ request: express.Request,
443
+ event: AdminAuditEvent
444
+ ): Promise<void> => {
445
+ if (!onAdminAudit) {
446
+ return;
447
+ }
448
+ try {
449
+ await onAdminAudit(event, request);
450
+ } catch (err: unknown) {
451
+ const detail = err instanceof Error ? err.message : String(err);
452
+ logger.error(`onAdminAudit failed after ${event.verb} on ${event.modelName}: ${detail}`);
453
+ }
454
+ };
281
455
 
282
456
  // Build config response with field metadata from Mongoose schemas
283
457
  const configModels: AdminModelMeta[] = modelConfigs.map((config) => {
@@ -345,14 +519,49 @@ export class AdminApp {
345
519
  }
346
520
  }
347
521
 
522
+ const readonlyFields = config.readonlyFields ?? [];
523
+ const listFields = config.listFields.filter((field) => !hiddenFieldSet.has(field));
524
+ const listDisplay = config.listDisplay ?? listFields;
525
+ const derivedSearchFields = listFields.filter((field) => fields[field]?.searchable);
526
+ const searchFields = config.searchFields ?? derivedSearchFields;
527
+ const sortableFields = config.sortableFields ?? [...listDisplay, "_id"];
528
+ const schemaPathKeys = new Set(Object.keys(config.model.schema.paths));
529
+ const bulkPatchAllowlist =
530
+ config.bulkPatchAllowlist ??
531
+ defaultBulkPatchAllowlistFrom({
532
+ hiddenFieldSet,
533
+ listFields,
534
+ readonlyFields,
535
+ schemaPaths: schemaPathKeys,
536
+ });
537
+
348
538
  return {
539
+ actions: config.actions ?? [],
540
+ bulkPatchAllowlist,
349
541
  defaultSort: config.defaultSort ?? "-created",
350
542
  displayName: config.displayName,
351
543
  fieldOrder: config.fieldOrder,
352
544
  fields,
353
- listFields: config.listFields.filter((field) => !hiddenFieldSet.has(field)),
545
+ fieldsets: config.fieldsets,
546
+ filters: config.filters ?? [],
547
+ group: config.group,
548
+ hiddenFields: [...hiddenFieldSet],
549
+ listDisplay,
550
+ listDisplayLinks: config.listDisplayLinks ?? [],
551
+ listFields,
354
552
  name: config.model.modelName,
553
+ pageSize: config.pageSize,
554
+ permissions: {
555
+ create: config.permissions?.create !== false,
556
+ delete: config.permissions?.delete !== false,
557
+ update: config.permissions?.update !== false,
558
+ },
559
+ readonlyFields,
560
+ realtime: config.realtime ?? false,
561
+ recordTitleField: config.recordTitleField,
355
562
  routePath: `${basePath}${config.routePath}`,
563
+ searchFields,
564
+ sortableFields,
356
565
  };
357
566
  });
358
567
 
@@ -363,21 +572,55 @@ export class AdminApp {
363
572
  name: script.name,
364
573
  }));
365
574
 
575
+ const defaultScreens = [{displayName: "Version Config", name: "version-config"}];
576
+ const mergedScreens = [...defaultScreens, ...(this.options.customScreens ?? [])];
577
+
366
578
  const configResponse: AdminConfigResponse = {
367
- customScreens: [
368
- {
369
- displayName: "Version Config",
370
- name: "version-config",
371
- },
372
- ],
579
+ customScreens: mergedScreens,
580
+ home: normalizeAdminHome(this.options.home),
373
581
  models: configModels,
582
+ schemaVersion: ADMIN_SCHEMA_VERSION,
374
583
  scripts: configScripts,
375
584
  };
376
585
 
586
+ const adminConfigOpenApi = openApiMw
587
+ ? createOpenApiBuilder({openApi: openApiMw})
588
+ .withTags(["admin"])
589
+ .withSummary("Admin panel configuration")
590
+ .withResponse(200, {
591
+ customScreens: {
592
+ items: {
593
+ properties: {
594
+ description: {type: "string"},
595
+ displayName: {type: "string"},
596
+ name: {type: "string"},
597
+ },
598
+ type: "object",
599
+ },
600
+ type: "array",
601
+ },
602
+ home: {type: "object"},
603
+ models: {type: "array"},
604
+ schemaVersion: {type: "number"},
605
+ scripts: {
606
+ items: {
607
+ properties: {
608
+ description: {type: "string"},
609
+ name: {type: "string"},
610
+ },
611
+ type: "object",
612
+ },
613
+ type: "array",
614
+ },
615
+ })
616
+ .build()
617
+ : undefined;
618
+
377
619
  // GET /admin/config
378
620
  app.get(
379
621
  `${basePath}/config`,
380
622
  authenticateMiddleware(),
623
+ ...asMiddlewareList(adminConfigOpenApi),
381
624
  asyncHandler(async (req, res) => {
382
625
  if (
383
626
  !(await checkPermissions("read", [Permissions.IsAdmin], req.user as User | undefined))
@@ -388,6 +631,95 @@ export class AdminApp {
388
631
  })
389
632
  );
390
633
 
634
+ const backgroundTasksOpenApi = openApiMw
635
+ ? createOpenApiBuilder({openApi: openApiMw})
636
+ .withTags(["admin"])
637
+ .withSummary("Enqueue a generic admin background task")
638
+ .withRequestBody<{
639
+ ids?: string[];
640
+ kind: string;
641
+ metadata?: Record<string, unknown>;
642
+ resourceRoute?: string;
643
+ }>({
644
+ ids: {
645
+ description: "Optional target document ids",
646
+ items: {type: "string"},
647
+ type: "array",
648
+ },
649
+ kind: {
650
+ description: "Task kind label persisted as taskType",
651
+ required: true,
652
+ type: "string",
653
+ },
654
+ metadata: {description: "Opaque JSON metadata for workers", type: "object"},
655
+ resourceRoute: {
656
+ description: "Optional admin model route this task relates to",
657
+ type: "string",
658
+ },
659
+ })
660
+ .withResponse(201, {taskId: {type: "string"}})
661
+ .build()
662
+ : undefined;
663
+
664
+ app.post(
665
+ `${basePath}/background-tasks`,
666
+ authenticateMiddleware(),
667
+ ...asMiddlewareList(backgroundTasksOpenApi),
668
+ asyncHandler(async (req, res) => {
669
+ if (
670
+ !(await checkPermissions("update", [Permissions.IsAdmin], req.user as User | undefined))
671
+ ) {
672
+ throw new APIError({status: 403, title: "Admin access required"});
673
+ }
674
+ const user = req.user as {_id: unknown} | undefined;
675
+ const raw = req.body as {
676
+ ids?: unknown;
677
+ kind?: unknown;
678
+ metadata?: unknown;
679
+ resourceRoute?: unknown;
680
+ };
681
+ if (typeof raw.kind !== "string" || !raw.kind.trim()) {
682
+ throw new APIError({status: 400, title: "kind is required"});
683
+ }
684
+ const now = DateTime.now().toJSDate();
685
+ const summary = {
686
+ ids: Array.isArray(raw.ids) ? raw.ids : [],
687
+ metadata:
688
+ raw.metadata && typeof raw.metadata === "object" && !Array.isArray(raw.metadata)
689
+ ? raw.metadata
690
+ : {},
691
+ resourceRoute: typeof raw.resourceRoute === "string" ? raw.resourceRoute : undefined,
692
+ };
693
+ let task: BackgroundTaskDocument;
694
+ try {
695
+ task = (await BackgroundTask.create({
696
+ createdBy: user?._id as mongoose.Types.ObjectId,
697
+ isDryRun: false,
698
+ logs: [
699
+ {
700
+ level: "info",
701
+ message: `Queued background task ${raw.kind}: ${JSON.stringify(summary)}`,
702
+ timestamp: now,
703
+ },
704
+ ],
705
+ progress: {message: "Queued", percentage: 0, stage: "Queued"},
706
+ startedAt: now,
707
+ status: "pending",
708
+ taskType: raw.kind,
709
+ })) as BackgroundTaskDocument;
710
+ } catch (err: unknown) {
711
+ const detail = err instanceof Error ? err.message : String(err);
712
+ logger.error(`Failed to create admin background task: ${detail}`);
713
+ throw new APIError({
714
+ detail,
715
+ status: 500,
716
+ title: "Failed to enqueue background task",
717
+ });
718
+ }
719
+ return res.status(201).json({taskId: task._id.toString()});
720
+ })
721
+ );
722
+
391
723
  // Version config singleton routes (GET/PUT /admin/version-config)
392
724
  const versionConfigPath = `${basePath}/version-config`;
393
725
  app.get(
@@ -474,10 +806,6 @@ export class AdminApp {
474
806
  }
475
807
  }
476
808
  }
477
- logger.info(`Admin search fields for ${config.model.modelName}`, {
478
- objectIdFields,
479
- searchableFields,
480
- });
481
809
 
482
810
  app.get(
483
811
  `${basePath}${config.routePath}/search`,
@@ -543,15 +871,132 @@ export class AdminApp {
543
871
  // Mount modelRouter for each model with IsAdmin permissions
544
872
  for (const config of modelConfigs) {
545
873
  const hiddenFieldSet = new Set(config.hiddenFields ?? []);
874
+ const readonlySet = new Set(config.readonlyFields ?? []);
875
+ const modelMeta = configModels.find((m) => m.name === config.model.modelName);
876
+ const allowlist = new Set(modelMeta?.bulkPatchAllowlist ?? []);
877
+
878
+ const adminPermission = (allowed: boolean | undefined): (typeof Permissions.IsAdmin)[] => {
879
+ if (allowed === false) {
880
+ return [];
881
+ }
882
+ return [Permissions.IsAdmin];
883
+ };
884
+
885
+ const stripProtectedFromBody = (body: unknown): Record<string, unknown> => {
886
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
887
+ return {};
888
+ }
889
+ const next = {...(body as Record<string, unknown>)};
890
+ for (const key of readonlySet) {
891
+ delete next[key];
892
+ }
893
+ for (const key of hiddenFieldSet) {
894
+ delete next[key];
895
+ }
896
+ for (const key of SYSTEM_ADMIN_FIELDS) {
897
+ delete next[key];
898
+ }
899
+ return next;
900
+ };
901
+
902
+ const bulkPatchOpenApi = openApiMw
903
+ ? createOpenApiBuilder({openApi: openApiMw})
904
+ .withTags(["admin"])
905
+ .withSummary(`Bulk patch ${config.model.modelName} documents`)
906
+ .withRequestBody<{ids: string[]; patch: Record<string, unknown>}>({
907
+ ids: {
908
+ description: "Document ids to update",
909
+ items: {type: "string"},
910
+ required: true,
911
+ type: "array",
912
+ },
913
+ patch: {
914
+ description: "Partial document; keys must be allowlisted for this model",
915
+ required: true,
916
+ type: "object",
917
+ },
918
+ })
919
+ .withResponse(200, {
920
+ failures: {type: "array"},
921
+ updated: {type: "number"},
922
+ })
923
+ .build()
924
+ : undefined;
925
+
926
+ const auditEligible = Boolean(onAdminAudit) && config.model.modelName !== "AdminAuditLog";
927
+ const auditHooks = auditEligible
928
+ ? {
929
+ postCreate: async (value: unknown, request: express.Request): Promise<void> => {
930
+ const doc = auditDocumentToPlain(value);
931
+ const rid = doc._id;
932
+ await safeOnAdminAudit(request, {
933
+ actorId: auditActorId(request),
934
+ modelName: config.model.modelName,
935
+ recordId: rid != null ? String(rid) : undefined,
936
+ recordLabel: auditLabelFromListFields(doc, config.listFields),
937
+ verb: "created",
938
+ });
939
+ },
940
+ postDelete: async (request: express.Request, value: unknown): Promise<void> => {
941
+ const doc = auditDocumentToPlain(value);
942
+ const rid = doc._id;
943
+ await safeOnAdminAudit(request, {
944
+ actorId: auditActorId(request),
945
+ modelName: config.model.modelName,
946
+ recordId: rid != null ? String(rid) : undefined,
947
+ recordLabel: auditLabelFromListFields(doc, config.listFields),
948
+ verb: "deleted",
949
+ });
950
+ },
951
+ postUpdate: async (
952
+ value: unknown,
953
+ _cleanedBody: unknown,
954
+ request: express.Request,
955
+ _prev: unknown
956
+ ): Promise<void> => {
957
+ const doc = auditDocumentToPlain(value);
958
+ const rid = doc._id;
959
+ await safeOnAdminAudit(request, {
960
+ actorId: auditActorId(request),
961
+ modelName: config.model.modelName,
962
+ recordId: rid != null ? String(rid) : undefined,
963
+ recordLabel: auditLabelFromListFields(doc, config.listFields),
964
+ verb: "updated",
965
+ });
966
+ },
967
+ }
968
+ : {};
969
+
546
970
  // biome-ignore lint/suspicious/noExplicitAny: matches the Model<any> from AdminModelConfig above.
547
971
  const routerOptions: ModelRouterOptions<any> = {
548
- ...(openApi ? {openApi: openApi as OpenApiMiddleware} : {}),
972
+ ...(openApiMw ? {openApi: openApiMw} : {}),
973
+ defaultLimit: config.pageSize ?? 100,
974
+ maxLimit: 500,
549
975
  permissions: {
550
- create: [Permissions.IsAdmin],
551
- delete: [Permissions.IsAdmin],
976
+ create: adminPermission(config.permissions?.create),
977
+ delete: adminPermission(config.permissions?.delete),
552
978
  list: [Permissions.IsAdmin],
553
979
  read: [Permissions.IsAdmin],
554
- update: [Permissions.IsAdmin],
980
+ update: adminPermission(config.permissions?.update),
981
+ },
982
+ queryFields: buildAdminModelQueryFields({
983
+ filters: config.filters,
984
+ listDisplay: config.listDisplay,
985
+ listFields: config.listFields,
986
+ searchFields: config.searchFields,
987
+ }),
988
+ ...(config.queryFilter ? {queryFilter: config.queryFilter} : {}),
989
+ preCreate: async (body, _req) => {
990
+ if (!body || typeof body !== "object") {
991
+ return body;
992
+ }
993
+ return stripProtectedFromBody(body) as typeof body;
994
+ },
995
+ preUpdate: async (body, _req) => {
996
+ if (!body || typeof body !== "object") {
997
+ return body;
998
+ }
999
+ return stripProtectedFromBody(body) as typeof body;
555
1000
  },
556
1001
  responseHandler:
557
1002
  hiddenFieldSet.size > 0
@@ -559,9 +1004,81 @@ export class AdminApp {
559
1004
  removeHiddenFields(value, hiddenFieldSet) as JSONValue
560
1005
  : undefined,
561
1006
  sort: config.defaultSort ?? "-created",
1007
+ ...auditHooks,
562
1008
  };
563
1009
 
564
- app.use(`${basePath}${config.routePath}`, modelRouter(config.model, routerOptions));
1010
+ const modelBase = express.Router();
1011
+ modelBase.post(
1012
+ "/bulk-patch",
1013
+ authenticateMiddleware(),
1014
+ ...asMiddlewareList(bulkPatchOpenApi),
1015
+ asyncHandler(async (req, res) => {
1016
+ if (
1017
+ !(await checkPermissions("update", [Permissions.IsAdmin], req.user as User | undefined))
1018
+ ) {
1019
+ throw new APIError({status: 403, title: "Admin access required"});
1020
+ }
1021
+ if (config.permissions?.update === false) {
1022
+ throw new APIError({status: 403, title: "Updates are disabled for this model"});
1023
+ }
1024
+ const body = req.body as {ids?: unknown; patch?: unknown};
1025
+ if (!Array.isArray(body.ids)) {
1026
+ throw new APIError({status: 400, title: "Request body must include an ids array"});
1027
+ }
1028
+ if (typeof body.patch !== "object" || body.patch === null || Array.isArray(body.patch)) {
1029
+ throw new APIError({status: 400, title: "Request body must include a patch object"});
1030
+ }
1031
+ const ids = [...new Set(body.ids.map((id) => String(id)))];
1032
+ if (ids.length === 0) {
1033
+ throw new APIError({status: 400, title: "ids must include at least one id"});
1034
+ }
1035
+ if (ids.length > MAX_BULK_PATCH_IDS) {
1036
+ throw new APIError({
1037
+ status: 400,
1038
+ title: `At most ${MAX_BULK_PATCH_IDS} ids may be patched at once`,
1039
+ });
1040
+ }
1041
+ const rawPatch = body.patch as Record<string, unknown>;
1042
+ const unknownKeys = Object.keys(rawPatch).filter((key) => !allowlist.has(key));
1043
+ if (unknownKeys.length > 0) {
1044
+ throw new APIError({
1045
+ detail: unknownKeys.join(", "),
1046
+ status: 400,
1047
+ title: "Patch contains keys that are not allowlisted for bulk patch",
1048
+ });
1049
+ }
1050
+ const patch = stripProtectedFromBody(rawPatch);
1051
+ if (Object.keys(patch).length === 0) {
1052
+ throw new APIError({
1053
+ status: 400,
1054
+ title: "Patch must include at least one writable field",
1055
+ });
1056
+ }
1057
+ let updated = 0;
1058
+ const failures: {id: string; title: string}[] = [];
1059
+ for (const id of ids) {
1060
+ if (!mongoose.isValidObjectId(id)) {
1061
+ failures.push({id, title: "Invalid id"});
1062
+ continue;
1063
+ }
1064
+ try {
1065
+ const resUpdate = await config.model.updateOne({_id: id}, {$set: patch});
1066
+ if (resUpdate.matchedCount === 0) {
1067
+ failures.push({id, title: "Not found"});
1068
+ } else {
1069
+ updated += 1;
1070
+ }
1071
+ } catch (err: unknown) {
1072
+ const message = err instanceof Error ? err.message : String(err);
1073
+ failures.push({id, title: message});
1074
+ }
1075
+ }
1076
+ return res.json({failures: failures.length > 0 ? failures : undefined, updated});
1077
+ })
1078
+ );
1079
+ modelBase.use(modelRouter(config.model, routerOptions));
1080
+
1081
+ app.use(`${basePath}${config.routePath}`, modelBase);
565
1082
  }
566
1083
 
567
1084
  // Mount script routes
@@ -577,6 +1094,65 @@ export class AdminApp {
577
1094
 
578
1095
  private mountScriptRoutes(router: express.Router, scripts: AdminScriptConfig[]): void {
579
1096
  const scriptsByName = new Map(scripts.map((s) => [s.name, s]));
1097
+ const scriptNames = scripts.map((s) => s.name);
1098
+
1099
+ // GET /admin/scripts/runs — Paginated history of script runs (BackgroundTasks)
1100
+ router.get(
1101
+ "/runs",
1102
+ asyncHandler(async (req: express.Request, res: express.Response) => {
1103
+ const user = req.user as {admin?: boolean} | undefined;
1104
+ if (!user?.admin) {
1105
+ throw new APIError({status: 403, title: "Only admins can view run history"});
1106
+ }
1107
+
1108
+ const limit = Math.min(Math.max(Number(req.query.limit) || 25, 1), 100);
1109
+ const page = Math.max(Number(req.query.page) || 1, 1);
1110
+ const skip = (page - 1) * limit;
1111
+
1112
+ // Scope history to currently-registered scripts. An optional `name` query
1113
+ // narrows to a single script (used by the per-script "History" link). A
1114
+ // provided-but-unregistered name resolves to an empty filter so callers can
1115
+ // distinguish "unknown script" (no runs) from "show all".
1116
+ const requestedName = typeof req.query.name === "string" ? req.query.name : undefined;
1117
+ let taskTypeFilter: string[];
1118
+ if (requestedName !== undefined) {
1119
+ taskTypeFilter = scriptNames.includes(requestedName) ? [requestedName] : [];
1120
+ } else {
1121
+ taskTypeFilter = scriptNames;
1122
+ }
1123
+
1124
+ const query =
1125
+ taskTypeFilter.length > 0
1126
+ ? {taskType: {$in: taskTypeFilter}}
1127
+ : {taskType: {$in: [] as string[]}};
1128
+
1129
+ const [tasks, total] = await Promise.all([
1130
+ BackgroundTask.find(query)
1131
+ .sort({created: -1})
1132
+ .skip(skip)
1133
+ .limit(limit)
1134
+ .populate({path: "createdBy", select: "name email"})
1135
+ .lean(),
1136
+ BackgroundTask.countDocuments(query),
1137
+ ]);
1138
+
1139
+ const data = tasks.map((task) => {
1140
+ const createdBy = task.createdBy as unknown as
1141
+ | {name?: string; email?: string}
1142
+ | mongoose.Types.ObjectId
1143
+ | undefined;
1144
+ const createdByName =
1145
+ createdBy &&
1146
+ typeof createdBy === "object" &&
1147
+ !(createdBy instanceof mongoose.Types.ObjectId)
1148
+ ? (createdBy.name ?? createdBy.email)
1149
+ : undefined;
1150
+ return {...task, createdByName};
1151
+ });
1152
+
1153
+ return res.json({data, limit, more: skip + tasks.length < total, page, total});
1154
+ })
1155
+ );
580
1156
 
581
1157
  // POST /admin/scripts/:name/run — Execute a script
582
1158
  router.post(