@terreno/admin-backend 57.3.0 → 57.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +3 -3
  2. package/bunfig.toml +9 -1
  3. package/dist/adminApp.d.ts +20 -2
  4. package/dist/adminApp.js +1261 -1873
  5. package/dist/adminConfigIdentity.d.ts +1 -0
  6. package/dist/adminConfigIdentity.js +27 -50
  7. package/dist/adminMigrations.d.ts +10 -0
  8. package/dist/adminMigrations.js +120 -0
  9. package/dist/adminScriptJob.d.ts +32 -0
  10. package/dist/adminScriptJob.js +202 -0
  11. package/dist/adminTextSearch.d.ts +1 -0
  12. package/dist/adminTextSearch.js +22 -78
  13. package/dist/adminUiV2.d.ts +2 -0
  14. package/dist/adminUiV2.js +49 -146
  15. package/dist/aggregateAdmin.js +104 -227
  16. package/dist/documentStorageApp.js +184 -325
  17. package/dist/enrichAdminListFilters.d.ts +7 -0
  18. package/dist/enrichAdminListFilters.js +26 -0
  19. package/dist/filterParser.js +230 -183
  20. package/dist/index.d.ts +2 -0
  21. package/dist/index.js +4 -1
  22. package/dist/legacy.js +21 -23
  23. package/dist/resolvedAdminModel.js +23 -78
  24. package/dist/routePath.js +3 -3
  25. package/dist/scriptCli.js +161 -307
  26. package/dist/tests/bunSetup.js +1 -1
  27. package/package.json +10 -10
  28. package/src/adminApp.migrations.test.ts +232 -0
  29. package/src/adminApp.models.test.ts +731 -1
  30. package/src/adminApp.syncMeta.test.ts +237 -0
  31. package/src/adminApp.test.ts +92 -0
  32. package/src/adminApp.ts +373 -130
  33. package/src/adminConfigIdentity.ts +1 -0
  34. package/src/adminHttpGoldens.test.ts +337 -0
  35. package/src/adminMigrations.ts +157 -0
  36. package/src/adminScriptJob.test.ts +297 -0
  37. package/src/adminScriptJob.ts +271 -0
  38. package/src/adminSyncMutationAuthMismatch.test.ts +650 -0
  39. package/src/adminTextSearch.test.ts +28 -0
  40. package/src/adminTextSearch.ts +1 -0
  41. package/src/adminUiV2.ts +2 -0
  42. package/src/aggregateAdmin.test.ts +125 -0
  43. package/src/aggregateAdmin.ts +2 -0
  44. package/src/enrichAdminListFilters.test.ts +44 -0
  45. package/src/enrichAdminListFilters.ts +29 -0
  46. package/src/filterParser.test.ts +95 -0
  47. package/src/filterParser.ts +156 -10
  48. package/src/index.ts +2 -0
  49. package/src/legacy.ts +5 -1
  50. package/src/resolvedAdminModel.ts +2 -1
  51. package/tsconfig.json +6 -21
package/src/adminApp.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  type AnyTerrenoAccess,
6
6
  APIError,
7
7
  asyncHandler,
8
+ auditActorIdFromRequest,
8
9
  authenticateMiddleware,
9
10
  BackgroundTask,
10
11
  type BackgroundTaskDocument,
@@ -12,31 +13,46 @@ import {
12
13
  createOpenApiBuilder,
13
14
  createScriptArgs,
14
15
  describeModel,
16
+ findSyncEntryByModelName,
17
+ getOrgContext,
15
18
  type JSONValue,
16
19
  logger,
17
20
  type ModelRouterOptions,
21
+ maybeRecordAdminAudit,
18
22
  modelDescriptionToAdminFields,
19
23
  modelRouter,
20
24
  type OpenApiMiddleware,
25
+ OrgQueryFilter,
26
+ orgContextMiddleware,
21
27
  type PermissionMethod,
22
28
  Permissions,
23
29
  type PopulatePath,
30
+ publicFrameworkModelName,
31
+ registerAdminBroadcastScope,
32
+ registerAdminWindowMutationScope,
24
33
  type ScriptArgDef,
25
34
  type ScriptArgValue,
26
- type ScriptContext,
27
- type ScriptResult,
28
35
  type ScriptRunner,
29
36
  scrubAdminFields,
30
- TaskCancelledError,
31
37
  type TerrenoApp,
32
38
  type User,
39
+ updateSyncRegistryOptions,
33
40
  VersionConfig,
34
41
  } from "@terreno/api";
42
+ import {tryGetJobsService} from "@terreno/jobs";
35
43
  import express from "express";
36
44
  import {DateTime} from "luxon";
37
45
  import type {Model} from "mongoose";
38
46
  import mongoose from "mongoose";
39
47
  import {assignUniqueAdminConfigNames, findAdminModelMetaByRoutePath} from "./adminConfigIdentity";
48
+ import {mountAdminMigrationRoutes} from "./adminMigrations";
49
+ import {
50
+ ADMIN_SCRIPT_JOB_NAME,
51
+ defineAdminScriptJob,
52
+ runRegisteredScriptTask,
53
+ tryCancelAdminScriptJob,
54
+ tryEnqueueAdminScriptJob,
55
+ } from "./adminScriptJob";
40
56
  import {
41
57
  ADMIN_LIST_SEARCH_PARAM,
42
58
  andMongoFilters,
@@ -60,6 +76,8 @@ import {parseAdminListFilters} from "./filterParser";
60
76
  import type {ResolvedAdminModel} from "./resolvedAdminModel";
61
77
  import {RESERVED_SCRIPT_FLAGS} from "./scriptCli";
62
78
 
79
+ const AUDIT_EVENT_MODEL_NAMES = new Set(["AuditEvent", "TerrenoAuditEvent"]);
80
+
63
81
  /**
64
82
  * Configuration for a single model in the admin panel.
65
83
  */
@@ -187,6 +205,9 @@ export interface AdminCustomScreenConfig {
187
205
  name: string;
188
206
  /** Optional subtitle or help text shown with the screen card in the admin UI */
189
207
  description?: string;
208
+ /** Sidebar group label; grouped screens render with matching model groups in AdminShell. */
209
+ group?: string;
210
+ icon?: string;
190
211
  /** RBAC or custom authorization for exposing this screen in admin metadata/navigation. */
191
212
  adminAccess?: Pick<AdminAccessConfig, "authorize" | "resource"> & {action?: string};
192
213
  }
@@ -206,13 +227,23 @@ export interface AdminOptions {
206
227
  /** Extra custom screens merged with built-ins (e.g. version-config) */
207
228
  customScreens?: AdminCustomScreenConfig[];
208
229
  /**
209
- * Optional audit sink for admin CRUD after modelRouter succeeds.
210
- * Consumers typically persist to an `AdminAuditLog` collection.
230
+ * Extra audit sink after successful admin CRUD. When `AuditApp` is registered,
231
+ * AdminApp also writes `AuditEvent` rows (`source: "admin"`) without this hook.
211
232
  */
212
233
  onAdminAudit?: (event: AdminAuditEvent, req: express.Request) => void | Promise<void>;
213
234
  /** When set, admin shell entry requires `admin:access`; model CRUD also requires
214
235
  * resource/action permissions (for example `user:update`) from the same Access instance. */
215
236
  accessControl?: AnyTerrenoAccess;
237
+ /**
238
+ * When `dir` is set, admin exposes GET/POST `/migrations` and
239
+ * `GET /admin/config` includes `migrations.enabled: true`.
240
+ */
241
+ migrations?: {dir: string};
242
+ /**
243
+ * Scope admin CRUD for models with an `organizationId` schema path.
244
+ * Default false so existing single-tenant admin panels remain unchanged.
245
+ */
246
+ organizations?: boolean;
216
247
  }
217
248
 
218
249
  interface AdminFieldMeta {
@@ -234,6 +265,21 @@ interface AdminFieldMeta {
234
265
  itemRef?: string;
235
266
  }
236
267
 
268
+ const publicFrameworkFieldMeta = (field: AdminFieldMeta): AdminFieldMeta => {
269
+ return {
270
+ ...field,
271
+ ...(field.ref ? {ref: publicFrameworkModelName(field.ref)} : {}),
272
+ ...(field.itemRef ? {itemRef: publicFrameworkModelName(field.itemRef)} : {}),
273
+ ...(field.items
274
+ ? {
275
+ items: Object.fromEntries(
276
+ Object.entries(field.items).map(([key, item]) => [key, publicFrameworkFieldMeta(item)])
277
+ ),
278
+ }
279
+ : {}),
280
+ };
281
+ };
282
+
237
283
  interface AdminModelMeta {
238
284
  actions: AdminActionInput[];
239
285
  bulkPatchAllowlist: string[];
@@ -242,6 +288,15 @@ interface AdminModelMeta {
242
288
  fieldOrder?: string[];
243
289
  fieldsets?: AdminFieldsetInput[];
244
290
  fields: Record<string, AdminFieldMeta>;
291
+ /** True when the model’s app `sync` config set `adminBroadcast`. */
292
+ adminBroadcast: boolean;
293
+ /** True when AdminApp `organizations` is on and the model has `organizationId`. */
294
+ organizationScoped: boolean;
295
+ /**
296
+ * Sync collection tag (`routePath` without a leading slash) when
297
+ * `adminBroadcast` is true. Omitted otherwise.
298
+ */
299
+ syncCollection?: string;
245
300
  filters: AdminListFilter[];
246
301
  group?: string;
247
302
  hiddenFields: string[];
@@ -286,8 +341,37 @@ interface AdminConfigResponse {
286
341
  schemaVersion: number;
287
342
  scripts: AdminScriptMeta[];
288
343
  widgetIds: string[];
344
+ migrations?: {enabled: boolean};
289
345
  }
290
346
 
347
+ const syncMetaForAdminModel = (
348
+ modelName: string,
349
+ isOrganizationScoped = false
350
+ ): {adminBroadcast: boolean; syncCollection?: string} => {
351
+ if (isOrganizationScoped) {
352
+ return {adminBroadcast: false};
353
+ }
354
+ const entry = findSyncEntryByModelName(modelName);
355
+ if (entry?.config.adminBroadcast !== true) {
356
+ return {adminBroadcast: false};
357
+ }
358
+ return {adminBroadcast: true, syncCollection: entry.collectionTag};
359
+ };
360
+
361
+ const disableOrgScopedAdminBroadcastSync = (modelName: string): void => {
362
+ const syncEntry = findSyncEntryByModelName(modelName);
363
+ if (syncEntry?.config.adminBroadcast !== true) {
364
+ return;
365
+ }
366
+ updateSyncRegistryOptions(syncEntry.routePath, {
367
+ ...syncEntry.options,
368
+ sync: {
369
+ ...syncEntry.config,
370
+ adminBroadcast: false,
371
+ },
372
+ });
373
+ };
374
+
291
375
  const buildAllModelAdminsMap = (models: ResolvedAdminModel[]): AdminModelAdminMap => {
292
376
  const map: AdminModelAdminMap = {};
293
377
  for (const config of models) {
@@ -311,7 +395,8 @@ const scrubAdminResponse = (
311
395
  const buildAdminListQueryFilter = (
312
396
  config: ResolvedAdminModel,
313
397
  /** Resolved (possibly derived) search fields from `/admin/config`, not just explicit config. */
314
- resolvedSearchFields?: string[]
398
+ resolvedSearchFields?: string[],
399
+ isOrganizationScoped = false
315
400
  ): NonNullable<ModelRouterOptions<unknown>["queryFilter"]> => {
316
401
  const base = config.queryFilter;
317
402
  const searchFields = resolvedSearchFields ?? config.searchFields ?? [];
@@ -348,8 +433,17 @@ const buildAdminListQueryFilter = (
348
433
  }
349
434
  merged = {...merged, ...baseResult};
350
435
  }
436
+ if (isOrganizationScoped) {
437
+ merged = {...merged, ...OrgQueryFilter(user, merged)};
438
+ }
351
439
  const result = andMongoFilters(merged, searchClause);
352
- return {...result, [ADMIN_LIST_SEARCH_PARAM]: undefined};
440
+ const overrides: Record<string, unknown> = {...filter};
441
+ for (const key of consumedKeys) {
442
+ if (!(key in overrides)) {
443
+ overrides[key] = undefined;
444
+ }
445
+ }
446
+ return {...result, ...overrides, [ADMIN_LIST_SEARCH_PARAM]: undefined};
353
447
  };
354
448
  };
355
449
 
@@ -453,19 +547,14 @@ const coerceAdminFlag = (value: unknown): boolean => {
453
547
  throw new APIError({status: 400, title: "admin must be a boolean"});
454
548
  };
455
549
 
456
- const auditActorId = (request: express.Request): string | undefined => {
457
- const user = request.user as {_id?: unknown} | undefined;
458
- if (!user || user._id == null) {
459
- return undefined;
460
- }
461
- return String(user._id);
462
- };
550
+ const auditActorId = auditActorIdFromRequest;
463
551
 
464
552
  interface ArraySchemaTypeCompatibility {
465
553
  caster?: mongoose.SchemaType;
466
554
  getEmbeddedSchemaType?: () => mongoose.SchemaType | undefined;
467
555
  }
468
556
 
557
+ /** @internal */
469
558
  export const getArrayEmbeddedSchemaType = (
470
559
  schemaPath: mongoose.SchemaType
471
560
  ): mongoose.SchemaType | undefined => {
@@ -483,7 +572,11 @@ const extractFieldMetaFromDescription = (
483
572
  const hiddenFieldSet = new Set(hiddenFields);
484
573
  const description = describeModel(model);
485
574
  const fields = modelDescriptionToAdminFields(description);
486
- return Object.fromEntries(Object.entries(fields).filter(([key]) => !hiddenFieldSet.has(key)));
575
+ return Object.fromEntries(
576
+ Object.entries(fields)
577
+ .filter(([key]) => !hiddenFieldSet.has(key))
578
+ .map(([key, field]) => [key, publicFrameworkFieldMeta(field)])
579
+ );
487
580
  };
488
581
 
489
582
  const asMiddlewareList = (
@@ -552,6 +645,18 @@ export class AdminApp {
552
645
  this.options = options;
553
646
  }
554
647
 
648
+ private isOrganizationScoped(config: Pick<AdminModelConfig, "model">): boolean {
649
+ if (!this.options.organizations) {
650
+ return false;
651
+ }
652
+ // Platform audit rows may omit organizationId. Requiring a selected org hides
653
+ // those events and skips Recent Activity / the AuditEvent changelist.
654
+ if (AUDIT_EVENT_MODEL_NAMES.has(config.model.modelName)) {
655
+ return false;
656
+ }
657
+ return Boolean(config.model.schema.path("organizationId"));
658
+ }
659
+
555
660
  private adminAccessPermissions(): PermissionMethod<unknown>[] {
556
661
  if (this.options.accessControl) {
557
662
  return [this.options.accessControl.permission({admin: [ADMIN_PAGE_ACTION]})];
@@ -559,6 +664,13 @@ export class AdminApp {
559
664
  return [Permissions.IsAdmin];
560
665
  }
561
666
 
667
+ private adminRunScriptsPermissions(): PermissionMethod<unknown>[] {
668
+ if (this.options.accessControl) {
669
+ return [this.options.accessControl.permission({admin: ["runScripts"]})];
670
+ }
671
+ return [Permissions.IsAdmin];
672
+ }
673
+
562
674
  private async hasScriptPermission(
563
675
  user: User | undefined,
564
676
  action: "runScripts" | "viewBackgroundTasks"
@@ -616,11 +728,12 @@ export class AdminApp {
616
728
  if (explicit) {
617
729
  return explicit;
618
730
  }
619
- const standard = `admin${config.model.modelName}`;
731
+ const publicName = publicFrameworkModelName(config.model.modelName);
732
+ const standard = `admin${publicName}`;
620
733
  if (accessControl?.statements[standard]) {
621
734
  return standard;
622
735
  }
623
- return `${config.model.modelName.charAt(0).toLowerCase()}${config.model.modelName.slice(1)}`;
736
+ return `${publicName.charAt(0).toLowerCase()}${publicName.slice(1)}`;
624
737
  }
625
738
 
626
739
  private async isAdminModelOwned(
@@ -728,10 +841,41 @@ export class AdminApp {
728
841
  }
729
842
  };
730
843
 
844
+ const safeFrameworkAdminAudit = async ({
845
+ after,
846
+ before,
847
+ extraRedact,
848
+ modelName,
849
+ recordLabel,
850
+ request,
851
+ verb,
852
+ }: {
853
+ after?: unknown;
854
+ before?: unknown;
855
+ extraRedact?: string[];
856
+ modelName: string;
857
+ recordLabel?: string;
858
+ request: express.Request;
859
+ verb: AdminAuditEvent["verb"];
860
+ }): Promise<void> => {
861
+ if (AUDIT_EVENT_MODEL_NAMES.has(modelName)) {
862
+ return;
863
+ }
864
+ void maybeRecordAdminAudit({
865
+ after,
866
+ before,
867
+ extraRedact,
868
+ modelName,
869
+ recordLabel,
870
+ req: request,
871
+ verb,
872
+ });
873
+ };
874
+
731
875
  // Build config response with field metadata from Mongoose schemas
732
876
  const configNames = assignUniqueAdminConfigNames(
733
877
  modelConfigs.map((config) => ({
734
- modelName: config.model.modelName,
878
+ modelName: publicFrameworkModelName(config.model.modelName),
735
879
  routePath: config.routePath,
736
880
  source: config.source,
737
881
  }))
@@ -768,9 +912,12 @@ export class AdminApp {
768
912
  readonlyFields,
769
913
  schemaPaths: schemaPathKeys,
770
914
  });
915
+ const isOrgScopedModel = this.isOrganizationScoped(config);
916
+ const syncMeta = syncMetaForAdminModel(config.model.modelName, isOrgScopedModel);
771
917
 
772
918
  return {
773
919
  actions: config.actions ?? [],
920
+ adminBroadcast: syncMeta.adminBroadcast,
774
921
  bulkPatchAllowlist,
775
922
  defaultSort: config.defaultSort ?? "-created",
776
923
  displayName: config.displayName,
@@ -783,7 +930,8 @@ export class AdminApp {
783
930
  listDisplay,
784
931
  listDisplayLinks: config.listDisplayLinks ?? [],
785
932
  listFields,
786
- name: configNames[configIndex] ?? config.model.modelName,
933
+ name: configNames[configIndex] ?? publicFrameworkModelName(config.model.modelName),
934
+ organizationScoped: isOrgScopedModel,
787
935
  pageSize: config.pageSize,
788
936
  permissions: {
789
937
  create: config.permissions?.create !== false,
@@ -796,6 +944,7 @@ export class AdminApp {
796
944
  routePath: `${basePath}${config.routePath}`,
797
945
  searchFields,
798
946
  sortableFields,
947
+ ...(syncMeta.syncCollection ? {syncCollection: syncMeta.syncCollection} : {}),
799
948
  };
800
949
  });
801
950
 
@@ -912,6 +1061,7 @@ export class AdminApp {
912
1061
  return {
913
1062
  ...baseConfigResponse,
914
1063
  customScreens: authorizedScreens.map(({adminAccess: _adminAccess, ...screen}) => screen),
1064
+ migrations: {enabled: Boolean(this.options.migrations?.dir)},
915
1065
  models: authorizedModels,
916
1066
  platformTools: {
917
1067
  configuration: canReadConfiguration,
@@ -944,6 +1094,8 @@ export class AdminApp {
944
1094
  properties: {
945
1095
  description: {type: "string"},
946
1096
  displayName: {type: "string"},
1097
+ group: {type: "string"},
1098
+ icon: {type: "string"},
947
1099
  name: {type: "string"},
948
1100
  },
949
1101
  type: "object",
@@ -1154,6 +1306,7 @@ export class AdminApp {
1154
1306
 
1155
1307
  // Mount search endpoint for each model
1156
1308
  for (const config of modelConfigs) {
1309
+ const isOrganizationScoped = this.isOrganizationScoped(config);
1157
1310
  // Determine searchable fields from the actual Mongoose schema type,
1158
1311
  // not the OpenAPI type (which reports ObjectId as "string")
1159
1312
  const searchableFields: string[] = [];
@@ -1176,6 +1329,7 @@ export class AdminApp {
1176
1329
  app.get(
1177
1330
  `${basePath}${config.routePath}/search`,
1178
1331
  authenticateMiddleware(),
1332
+ ...(isOrganizationScoped ? [orgContextMiddleware({required: true})] : []),
1179
1333
  asyncHandler(async (req, res) => {
1180
1334
  if (
1181
1335
  !(await checkPermissions(
@@ -1216,10 +1370,11 @@ export class AdminApp {
1216
1370
  q,
1217
1371
  });
1218
1372
  try {
1219
- const scoped = await buildAdminListQueryFilter(config, modelMeta?.searchFields)(
1220
- req.user as User | undefined,
1221
- {}
1222
- );
1373
+ const scoped = await buildAdminListQueryFilter(
1374
+ config,
1375
+ modelMeta?.searchFields,
1376
+ isOrganizationScoped
1377
+ )(req.user as User | undefined, {});
1223
1378
  if (scoped === null) {
1224
1379
  return res.json({data: []});
1225
1380
  }
@@ -1248,6 +1403,7 @@ export class AdminApp {
1248
1403
 
1249
1404
  // Mount modelRouter for each model with IsAdmin permissions
1250
1405
  for (const config of modelConfigs) {
1406
+ const isOrganizationScoped = this.isOrganizationScoped(config);
1251
1407
  const hiddenFieldSet = new Set(config.hiddenFields ?? []);
1252
1408
  const readonlySet = new Set(config.readonlyFields ?? []);
1253
1409
  const excludeFieldSet = new Set(config.excludeFields ?? []);
@@ -1264,10 +1420,14 @@ export class AdminApp {
1264
1420
  if (allowed === false) {
1265
1421
  return [];
1266
1422
  }
1267
- return this.resourceActionPermissions(config, action);
1423
+ const permissions = this.resourceActionPermissions(config, action);
1424
+ if (isOrganizationScoped && action !== "create") {
1425
+ return [...permissions, Permissions.IsOrganizationMember];
1426
+ }
1427
+ return permissions;
1268
1428
  };
1269
1429
 
1270
- const updatePermissions = this.resourceActionPermissions(config, "update");
1430
+ const updatePermissions = adminPermission(config.permissions?.update, "update");
1271
1431
 
1272
1432
  const stripProtectedFromBody = (body: unknown): Record<string, unknown> => {
1273
1433
  if (!body || typeof body !== "object" || Array.isArray(body)) {
@@ -1408,7 +1568,7 @@ export class AdminApp {
1408
1568
  const bulkPatchOpenApi = openApiMw
1409
1569
  ? createOpenApiBuilder({openApi: openApiMw})
1410
1570
  .withTags(["admin"])
1411
- .withSummary(`Bulk patch ${config.model.modelName} documents`)
1571
+ .withSummary(`Bulk patch ${publicFrameworkModelName(config.model.modelName)} documents`)
1412
1572
  .withRequestBody<{ids: string[]; patch: Record<string, unknown>}>({
1413
1573
  ids: {
1414
1574
  description: "Document ids to update",
@@ -1429,49 +1589,84 @@ export class AdminApp {
1429
1589
  .build()
1430
1590
  : undefined;
1431
1591
 
1432
- const auditEligible = Boolean(onAdminAudit) && config.model.modelName !== "AdminAuditLog";
1433
- const auditHooks = auditEligible
1434
- ? {
1435
- postCreate: async (value: unknown, request: express.Request): Promise<void> => {
1436
- const doc = auditDocumentToPlain(value);
1437
- const rid = doc._id;
1438
- await safeOnAdminAudit(request, {
1439
- actorId: auditActorId(request),
1440
- modelName: config.model.modelName,
1441
- recordId: rid != null ? String(rid) : undefined,
1442
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1443
- verb: "created",
1444
- });
1445
- },
1446
- postDelete: async (request: express.Request, value: unknown): Promise<void> => {
1447
- const doc = auditDocumentToPlain(value);
1448
- const rid = doc._id;
1449
- await safeOnAdminAudit(request, {
1450
- actorId: auditActorId(request),
1451
- modelName: config.model.modelName,
1452
- recordId: rid != null ? String(rid) : undefined,
1453
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1454
- verb: "deleted",
1455
- });
1456
- },
1457
- postUpdate: async (
1458
- value: unknown,
1459
- _cleanedBody: unknown,
1460
- request: express.Request,
1461
- _prev: unknown
1462
- ): Promise<void> => {
1463
- const doc = auditDocumentToPlain(value);
1464
- const rid = doc._id;
1465
- await safeOnAdminAudit(request, {
1466
- actorId: auditActorId(request),
1467
- modelName: config.model.modelName,
1468
- recordId: rid != null ? String(rid) : undefined,
1469
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1470
- verb: "updated",
1471
- });
1472
- },
1592
+ const skipOnAdminAuditHook = config.model.modelName === "AdminAuditLog";
1593
+ const auditHooks = {
1594
+ postCreate: async (value: unknown, request: express.Request): Promise<void> => {
1595
+ const doc = auditDocumentToPlain(value);
1596
+ const rid = doc._id;
1597
+ const recordLabel = auditLabelFromListFields(doc, config.listFields);
1598
+ await safeFrameworkAdminAudit({
1599
+ after: value,
1600
+ extraRedact: [...hiddenFieldSet, ...excludeFieldSet],
1601
+ modelName: config.model.modelName,
1602
+ recordLabel,
1603
+ request,
1604
+ verb: "created",
1605
+ });
1606
+ if (skipOnAdminAuditHook) {
1607
+ return;
1608
+ }
1609
+ await safeOnAdminAudit(request, {
1610
+ actorId: auditActorId(request),
1611
+ modelName: config.model.modelName,
1612
+ recordId: rid != null ? String(rid) : undefined,
1613
+ recordLabel,
1614
+ verb: "created",
1615
+ });
1616
+ },
1617
+ postDelete: async (request: express.Request, value: unknown): Promise<void> => {
1618
+ const doc = auditDocumentToPlain(value);
1619
+ const rid = doc._id;
1620
+ const recordLabel = auditLabelFromListFields(doc, config.listFields);
1621
+ await safeFrameworkAdminAudit({
1622
+ before: value,
1623
+ extraRedact: [...hiddenFieldSet, ...excludeFieldSet],
1624
+ modelName: config.model.modelName,
1625
+ recordLabel,
1626
+ request,
1627
+ verb: "deleted",
1628
+ });
1629
+ if (skipOnAdminAuditHook) {
1630
+ return;
1473
1631
  }
1474
- : {};
1632
+ await safeOnAdminAudit(request, {
1633
+ actorId: auditActorId(request),
1634
+ modelName: config.model.modelName,
1635
+ recordId: rid != null ? String(rid) : undefined,
1636
+ recordLabel,
1637
+ verb: "deleted",
1638
+ });
1639
+ },
1640
+ postUpdate: async (
1641
+ value: unknown,
1642
+ _cleanedBody: unknown,
1643
+ request: express.Request,
1644
+ prev: unknown
1645
+ ): Promise<void> => {
1646
+ const doc = auditDocumentToPlain(value);
1647
+ const rid = doc._id;
1648
+ const recordLabel = auditLabelFromListFields(doc, config.listFields);
1649
+ await safeFrameworkAdminAudit({
1650
+ after: value,
1651
+ before: prev,
1652
+ extraRedact: [...hiddenFieldSet, ...excludeFieldSet],
1653
+ modelName: config.model.modelName,
1654
+ recordLabel,
1655
+ request,
1656
+ verb: "updated",
1657
+ });
1658
+ if (skipOnAdminAuditHook) {
1659
+ return;
1660
+ }
1661
+ await safeOnAdminAudit(request, {
1662
+ actorId: auditActorId(request),
1663
+ modelName: config.model.modelName,
1664
+ recordId: rid != null ? String(rid) : undefined,
1665
+ recordLabel,
1666
+ verb: "updated",
1667
+ });
1668
+ },
1669
+ };
1475
1670
 
1476
1671
  const assertCanWriteUserAdminFlag = async (
1477
1672
  body: Record<string, unknown>,
@@ -1617,6 +1812,9 @@ export class AdminApp {
1617
1812
  return body;
1618
1813
  }
1619
1814
  const record = body as Record<string, unknown>;
1815
+ if (isOrganizationScoped) {
1816
+ record.organizationId = getOrgContext()?.organization?._id;
1817
+ }
1620
1818
  if (
1621
1819
  !(await checkPermissions(
1622
1820
  "create",
@@ -1648,7 +1846,11 @@ export class AdminApp {
1648
1846
  listFields: config.listFields,
1649
1847
  searchFields: modelMeta?.searchFields ?? config.searchFields,
1650
1848
  }),
1651
- queryFilter: buildAdminListQueryFilter(config, modelMeta?.searchFields),
1849
+ queryFilter: buildAdminListQueryFilter(
1850
+ config,
1851
+ modelMeta?.searchFields,
1852
+ isOrganizationScoped
1853
+ ),
1652
1854
  responseHandler: async (value, _method, request): Promise<JSONValue> =>
1653
1855
  addRecordCapabilities(value, request),
1654
1856
  sort: config.defaultSort ?? "-created",
@@ -1656,7 +1858,42 @@ export class AdminApp {
1656
1858
  ...(auditHooks.postDelete ? {postDelete: auditHooks.postDelete} : {}),
1657
1859
  };
1658
1860
 
1861
+ if (isOrganizationScoped) {
1862
+ disableOrgScopedAdminBroadcastSync(config.model.modelName);
1863
+ }
1864
+ const syncEntry = findSyncEntryByModelName(config.model.modelName);
1865
+ const adminBroadcastEnabled = syncEntry?.config.adminBroadcast === true;
1866
+ if (adminBroadcastEnabled) {
1867
+ registerAdminBroadcastScope(config.model.modelName, {
1868
+ listPermissions: adminPermission(true, "list"),
1869
+ queryFilter: routerOptions.queryFilter,
1870
+ readPermissions: adminPermission(true, "read"),
1871
+ });
1872
+
1873
+ registerAdminWindowMutationScope(config.model.modelName, {
1874
+ accessControl: this.options.accessControl,
1875
+ createPermissions: adminPermission(config.permissions?.create, "create"),
1876
+ deletePermissions: adminPermission(config.permissions?.delete, "delete"),
1877
+ modelName: config.model.modelName,
1878
+ permissions: {
1879
+ create: config.permissions?.create !== false,
1880
+ delete: config.permissions?.delete !== false,
1881
+ update: config.permissions?.update !== false,
1882
+ },
1883
+ postCreate: routerOptions.postCreate,
1884
+ postDelete: routerOptions.postDelete,
1885
+ postUpdate: routerOptions.postUpdate,
1886
+ preCreate: routerOptions.preCreate,
1887
+ preUpdate: routerOptions.preUpdate,
1888
+ stripMutationData: (data) => stripProtectedFromBody(data),
1889
+ updatePermissions: adminPermission(config.permissions?.update, "update"),
1890
+ });
1891
+ }
1892
+
1659
1893
  const modelBase = express.Router();
1894
+ if (isOrganizationScoped) {
1895
+ modelBase.use(authenticateMiddleware(), orgContextMiddleware({required: true}));
1896
+ }
1660
1897
  modelBase.use(validateAdminSortParam(modelMeta?.sortableFields ?? []));
1661
1898
  modelBase.post(
1662
1899
  "/bulk-patch",
@@ -1776,7 +2013,7 @@ export class AdminApp {
1776
2013
  }
1777
2014
 
1778
2015
  // Mount script routes
1779
- if (scriptConfigs.length > 0) {
2016
+ if (scriptConfigs.length > 0 || this.options.migrations?.dir) {
1780
2017
  const scriptsRouter = express.Router();
1781
2018
  scriptsRouter.use(authenticateMiddleware());
1782
2019
 
@@ -1784,11 +2021,24 @@ export class AdminApp {
1784
2021
 
1785
2022
  app.use(`${basePath}/scripts`, scriptsRouter);
1786
2023
  }
2024
+
2025
+ mountAdminMigrationRoutes({
2026
+ app,
2027
+ basePath,
2028
+ dir: this.options.migrations?.dir,
2029
+ ...(openApiMw ? {openApi: openApiMw} : {}),
2030
+ runPermissions: this.adminRunScriptsPermissions(),
2031
+ statusPermissions: this.adminAccessPermissions(),
2032
+ });
1787
2033
  }
1788
2034
 
1789
2035
  private mountScriptRoutes(router: express.Router, scripts: AdminScriptConfig[]): void {
1790
2036
  const scriptsByName = new Map(scripts.map((s) => [s.name, s]));
1791
2037
  const scriptNames = scripts.map((s) => s.name);
2038
+ const jobs = tryGetJobsService();
2039
+ if (jobs) {
2040
+ defineAdminScriptJob(jobs, (name) => scriptsByName.get(name));
2041
+ }
1792
2042
 
1793
2043
  // GET /admin/scripts/runs — Paginated history of script runs (BackgroundTasks)
1794
2044
  router.get(
@@ -1903,6 +2153,7 @@ export class AdminApp {
1903
2153
  }
1904
2154
 
1905
2155
  const now = DateTime.now().toJSDate();
2156
+ const queuedViaJobs = Boolean(tryGetJobsService()?.getDefinition(ADMIN_SCRIPT_JOB_NAME));
1906
2157
 
1907
2158
  let task: BackgroundTaskDocument;
1908
2159
  try {
@@ -1912,9 +2163,13 @@ export class AdminApp {
1912
2163
  logs: [
1913
2164
  {level: "info", message: `Script started by ${user.name ?? "admin"}`, timestamp: now},
1914
2165
  ],
1915
- progress: {message: "Starting...", percentage: 0, stage: "Queued"},
1916
- startedAt: now,
1917
- status: "running",
2166
+ progress: {
2167
+ message: queuedViaJobs ? "Queued" : "Starting...",
2168
+ percentage: 0,
2169
+ stage: queuedViaJobs ? "Queued" : "Queued",
2170
+ },
2171
+ startedAt: queuedViaJobs ? undefined : now,
2172
+ status: queuedViaJobs ? "pending" : "running",
1918
2173
  taskType: script.name,
1919
2174
  })) as BackgroundTaskDocument;
1920
2175
  } catch (err: unknown) {
@@ -1927,67 +2182,53 @@ export class AdminApp {
1927
2182
  });
1928
2183
  }
1929
2184
 
1930
- // Build context for cancellation, progress reporting, and arguments
1931
- const ctx: ScriptContext = {
1932
- addLog: async (level, message) => {
1933
- const current = await BackgroundTask.findById(task._id);
1934
- if (current) {
1935
- await current.addLog(level, message);
1936
- }
1937
- },
1938
- args,
1939
- checkCancellation: async () => {
1940
- await BackgroundTask.checkCancellation(task._id.toString());
1941
- },
1942
- updateProgress: async (percentage, stage, message) => {
1943
- const current = await BackgroundTask.findById(task._id);
1944
- if (current) {
1945
- await current.updateProgress(percentage, stage, message);
1946
- }
1947
- },
1948
- };
1949
-
1950
- // Run the script asynchronously — use atomic updates to avoid overwriting
1951
- // cancellation or other intermediate state changes.
1952
- void (async () => {
1953
- try {
1954
- const result: ScriptResult = await script.runner(isWetRun, ctx);
1955
-
1956
- // Atomically update only if still running (don't overwrite cancellation)
1957
- await BackgroundTask.findOneAndUpdate(
1958
- {_id: task._id, status: "running"},
1959
- {
1960
- $set: {
1961
- completedAt: DateTime.now().toJSDate(),
1962
- progress: {message: "Done", percentage: 100, stage: "Complete"},
1963
- result: result.results,
1964
- status: result.success ? "completed" : "failed",
2185
+ const taskId = task._id.toString();
2186
+ let enqueued: {id: string} | undefined;
2187
+ try {
2188
+ enqueued = await tryEnqueueAdminScriptJob({
2189
+ args: args.raw,
2190
+ createdByName: user.name,
2191
+ scriptName: script.name,
2192
+ taskId,
2193
+ wetRun: isWetRun,
2194
+ });
2195
+ } catch (err: unknown) {
2196
+ const detail = err instanceof Error ? err.message : String(err);
2197
+ logger.error(`Failed to enqueue durable job for ${script.name}: ${detail}`);
2198
+ const failedAt = DateTime.now().toJSDate();
2199
+ await BackgroundTask.updateOne(
2200
+ {_id: task._id},
2201
+ {
2202
+ $set: {
2203
+ completedAt: failedAt,
2204
+ error: detail,
2205
+ progress: {
2206
+ message: "Failed to enqueue",
2207
+ percentage: 100,
2208
+ stage: "Failed",
1965
2209
  },
1966
- }
1967
- );
1968
- } catch (err: unknown) {
1969
- if (err instanceof TaskCancelledError) {
1970
- return;
2210
+ status: "failed",
2211
+ },
1971
2212
  }
1972
- const message = err instanceof Error ? err.message : String(err);
1973
- logger.error(`Script ${script.name} failed: ${message}`);
2213
+ );
2214
+ throw new APIError({
2215
+ detail,
2216
+ status: 500,
2217
+ title: `Failed to enqueue script: ${script.name}`,
2218
+ });
2219
+ }
2220
+ if (enqueued) {
2221
+ return res.status(201).json({taskId});
2222
+ }
1974
2223
 
1975
- // Atomically update only if still running
1976
- await BackgroundTask.findOneAndUpdate(
1977
- {_id: task._id, status: "running"},
1978
- {
1979
- $set: {
1980
- completedAt: DateTime.now().toJSDate(),
1981
- error: message,
1982
- result: [message],
1983
- status: "failed",
1984
- },
1985
- }
1986
- );
1987
- }
1988
- })();
2224
+ void runRegisteredScriptTask({
2225
+ args,
2226
+ script,
2227
+ taskId,
2228
+ wetRun: isWetRun,
2229
+ });
1989
2230
 
1990
- return res.status(201).json({taskId: task._id.toString()});
2231
+ return res.status(201).json({taskId});
1991
2232
  })
1992
2233
  );
1993
2234
 
@@ -2068,6 +2309,8 @@ export class AdminApp {
2068
2309
  });
2069
2310
  }
2070
2311
 
2312
+ await tryCancelAdminScriptJob(task._id.toString());
2313
+
2071
2314
  return res.json({message: "Task cancelled", task: cancelled.toObject()});
2072
2315
  })
2073
2316
  );