@terreno/admin-backend 57.3.0 → 57.4.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 (44) hide show
  1. package/bunfig.toml +9 -1
  2. package/dist/adminApp.d.ts +20 -2
  3. package/dist/adminApp.js +468 -363
  4. package/dist/adminConfigIdentity.d.ts +1 -0
  5. package/dist/adminConfigIdentity.js +1 -0
  6. package/dist/adminMigrations.d.ts +10 -0
  7. package/dist/adminMigrations.js +205 -0
  8. package/dist/adminScriptJob.d.ts +32 -0
  9. package/dist/adminScriptJob.js +360 -0
  10. package/dist/adminTextSearch.d.ts +1 -0
  11. package/dist/adminTextSearch.js +1 -0
  12. package/dist/adminUiV2.d.ts +2 -0
  13. package/dist/aggregateAdmin.js +2 -0
  14. package/dist/enrichAdminListFilters.d.ts +7 -0
  15. package/dist/enrichAdminListFilters.js +37 -0
  16. package/dist/filterParser.js +139 -12
  17. package/dist/index.d.ts +2 -0
  18. package/dist/index.js +4 -1
  19. package/dist/legacy.js +4 -2
  20. package/dist/resolvedAdminModel.js +2 -1
  21. package/package.json +7 -7
  22. package/src/adminApp.migrations.test.ts +232 -0
  23. package/src/adminApp.models.test.ts +645 -1
  24. package/src/adminApp.syncMeta.test.ts +237 -0
  25. package/src/adminApp.test.ts +92 -0
  26. package/src/adminApp.ts +344 -124
  27. package/src/adminConfigIdentity.ts +1 -0
  28. package/src/adminHttpGoldens.test.ts +337 -0
  29. package/src/adminMigrations.ts +157 -0
  30. package/src/adminScriptJob.test.ts +297 -0
  31. package/src/adminScriptJob.ts +271 -0
  32. package/src/adminSyncMutationAuthMismatch.test.ts +650 -0
  33. package/src/adminTextSearch.test.ts +28 -0
  34. package/src/adminTextSearch.ts +1 -0
  35. package/src/adminUiV2.ts +2 -0
  36. package/src/aggregateAdmin.test.ts +125 -0
  37. package/src/aggregateAdmin.ts +2 -0
  38. package/src/enrichAdminListFilters.test.ts +44 -0
  39. package/src/enrichAdminListFilters.ts +29 -0
  40. package/src/filterParser.test.ts +95 -0
  41. package/src/filterParser.ts +156 -10
  42. package/src/index.ts +2 -0
  43. package/src/legacy.ts +5 -1
  44. package/src/resolvedAdminModel.ts +2 -1
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,45 @@ 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
+ registerAdminBroadcastScope,
31
+ registerAdminWindowMutationScope,
24
32
  type ScriptArgDef,
25
33
  type ScriptArgValue,
26
- type ScriptContext,
27
- type ScriptResult,
28
34
  type ScriptRunner,
29
35
  scrubAdminFields,
30
- TaskCancelledError,
31
36
  type TerrenoApp,
32
37
  type User,
38
+ updateSyncRegistryOptions,
33
39
  VersionConfig,
34
40
  } from "@terreno/api";
41
+ import {tryGetJobsService} from "@terreno/jobs";
35
42
  import express from "express";
36
43
  import {DateTime} from "luxon";
37
44
  import type {Model} from "mongoose";
38
45
  import mongoose from "mongoose";
39
46
  import {assignUniqueAdminConfigNames, findAdminModelMetaByRoutePath} from "./adminConfigIdentity";
47
+ import {mountAdminMigrationRoutes} from "./adminMigrations";
48
+ import {
49
+ ADMIN_SCRIPT_JOB_NAME,
50
+ defineAdminScriptJob,
51
+ runRegisteredScriptTask,
52
+ tryCancelAdminScriptJob,
53
+ tryEnqueueAdminScriptJob,
54
+ } from "./adminScriptJob";
40
55
  import {
41
56
  ADMIN_LIST_SEARCH_PARAM,
42
57
  andMongoFilters,
@@ -187,6 +202,9 @@ export interface AdminCustomScreenConfig {
187
202
  name: string;
188
203
  /** Optional subtitle or help text shown with the screen card in the admin UI */
189
204
  description?: string;
205
+ /** Sidebar group label; grouped screens render with matching model groups in AdminShell. */
206
+ group?: string;
207
+ icon?: string;
190
208
  /** RBAC or custom authorization for exposing this screen in admin metadata/navigation. */
191
209
  adminAccess?: Pick<AdminAccessConfig, "authorize" | "resource"> & {action?: string};
192
210
  }
@@ -206,13 +224,23 @@ export interface AdminOptions {
206
224
  /** Extra custom screens merged with built-ins (e.g. version-config) */
207
225
  customScreens?: AdminCustomScreenConfig[];
208
226
  /**
209
- * Optional audit sink for admin CRUD after modelRouter succeeds.
210
- * Consumers typically persist to an `AdminAuditLog` collection.
227
+ * Extra audit sink after successful admin CRUD. When `AuditApp` is registered,
228
+ * AdminApp also writes `AuditEvent` rows (`source: "admin"`) without this hook.
211
229
  */
212
230
  onAdminAudit?: (event: AdminAuditEvent, req: express.Request) => void | Promise<void>;
213
231
  /** When set, admin shell entry requires `admin:access`; model CRUD also requires
214
232
  * resource/action permissions (for example `user:update`) from the same Access instance. */
215
233
  accessControl?: AnyTerrenoAccess;
234
+ /**
235
+ * When `dir` is set, admin exposes GET/POST `/migrations` and
236
+ * `GET /admin/config` includes `migrations.enabled: true`.
237
+ */
238
+ migrations?: {dir: string};
239
+ /**
240
+ * Scope admin CRUD for models with an `organizationId` schema path.
241
+ * Default false so existing single-tenant admin panels remain unchanged.
242
+ */
243
+ organizations?: boolean;
216
244
  }
217
245
 
218
246
  interface AdminFieldMeta {
@@ -242,6 +270,15 @@ interface AdminModelMeta {
242
270
  fieldOrder?: string[];
243
271
  fieldsets?: AdminFieldsetInput[];
244
272
  fields: Record<string, AdminFieldMeta>;
273
+ /** True when the model’s app `sync` config set `adminBroadcast`. */
274
+ adminBroadcast: boolean;
275
+ /** True when AdminApp `organizations` is on and the model has `organizationId`. */
276
+ organizationScoped: boolean;
277
+ /**
278
+ * Sync collection tag (`routePath` without a leading slash) when
279
+ * `adminBroadcast` is true. Omitted otherwise.
280
+ */
281
+ syncCollection?: string;
245
282
  filters: AdminListFilter[];
246
283
  group?: string;
247
284
  hiddenFields: string[];
@@ -286,8 +323,37 @@ interface AdminConfigResponse {
286
323
  schemaVersion: number;
287
324
  scripts: AdminScriptMeta[];
288
325
  widgetIds: string[];
326
+ migrations?: {enabled: boolean};
289
327
  }
290
328
 
329
+ const syncMetaForAdminModel = (
330
+ modelName: string,
331
+ isOrganizationScoped = false
332
+ ): {adminBroadcast: boolean; syncCollection?: string} => {
333
+ if (isOrganizationScoped) {
334
+ return {adminBroadcast: false};
335
+ }
336
+ const entry = findSyncEntryByModelName(modelName);
337
+ if (entry?.config.adminBroadcast !== true) {
338
+ return {adminBroadcast: false};
339
+ }
340
+ return {adminBroadcast: true, syncCollection: entry.collectionTag};
341
+ };
342
+
343
+ const disableOrgScopedAdminBroadcastSync = (modelName: string): void => {
344
+ const syncEntry = findSyncEntryByModelName(modelName);
345
+ if (syncEntry?.config.adminBroadcast !== true) {
346
+ return;
347
+ }
348
+ updateSyncRegistryOptions(syncEntry.routePath, {
349
+ ...syncEntry.options,
350
+ sync: {
351
+ ...syncEntry.config,
352
+ adminBroadcast: false,
353
+ },
354
+ });
355
+ };
356
+
291
357
  const buildAllModelAdminsMap = (models: ResolvedAdminModel[]): AdminModelAdminMap => {
292
358
  const map: AdminModelAdminMap = {};
293
359
  for (const config of models) {
@@ -311,7 +377,8 @@ const scrubAdminResponse = (
311
377
  const buildAdminListQueryFilter = (
312
378
  config: ResolvedAdminModel,
313
379
  /** Resolved (possibly derived) search fields from `/admin/config`, not just explicit config. */
314
- resolvedSearchFields?: string[]
380
+ resolvedSearchFields?: string[],
381
+ isOrganizationScoped = false
315
382
  ): NonNullable<ModelRouterOptions<unknown>["queryFilter"]> => {
316
383
  const base = config.queryFilter;
317
384
  const searchFields = resolvedSearchFields ?? config.searchFields ?? [];
@@ -348,8 +415,17 @@ const buildAdminListQueryFilter = (
348
415
  }
349
416
  merged = {...merged, ...baseResult};
350
417
  }
418
+ if (isOrganizationScoped) {
419
+ merged = {...merged, ...OrgQueryFilter(user, merged)};
420
+ }
351
421
  const result = andMongoFilters(merged, searchClause);
352
- return {...result, [ADMIN_LIST_SEARCH_PARAM]: undefined};
422
+ const overrides: Record<string, unknown> = {...filter};
423
+ for (const key of consumedKeys) {
424
+ if (!(key in overrides)) {
425
+ overrides[key] = undefined;
426
+ }
427
+ }
428
+ return {...result, ...overrides, [ADMIN_LIST_SEARCH_PARAM]: undefined};
353
429
  };
354
430
  };
355
431
 
@@ -453,19 +529,14 @@ const coerceAdminFlag = (value: unknown): boolean => {
453
529
  throw new APIError({status: 400, title: "admin must be a boolean"});
454
530
  };
455
531
 
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
- };
532
+ const auditActorId = auditActorIdFromRequest;
463
533
 
464
534
  interface ArraySchemaTypeCompatibility {
465
535
  caster?: mongoose.SchemaType;
466
536
  getEmbeddedSchemaType?: () => mongoose.SchemaType | undefined;
467
537
  }
468
538
 
539
+ /** @internal */
469
540
  export const getArrayEmbeddedSchemaType = (
470
541
  schemaPath: mongoose.SchemaType
471
542
  ): mongoose.SchemaType | undefined => {
@@ -552,6 +623,18 @@ export class AdminApp {
552
623
  this.options = options;
553
624
  }
554
625
 
626
+ private isOrganizationScoped(config: Pick<AdminModelConfig, "model">): boolean {
627
+ if (!this.options.organizations) {
628
+ return false;
629
+ }
630
+ // Platform audit rows may omit organizationId. Requiring a selected org hides
631
+ // those events and skips Recent Activity / the AuditEvent changelist.
632
+ if (config.model.modelName === "AuditEvent") {
633
+ return false;
634
+ }
635
+ return Boolean(config.model.schema.path("organizationId"));
636
+ }
637
+
555
638
  private adminAccessPermissions(): PermissionMethod<unknown>[] {
556
639
  if (this.options.accessControl) {
557
640
  return [this.options.accessControl.permission({admin: [ADMIN_PAGE_ACTION]})];
@@ -559,6 +642,13 @@ export class AdminApp {
559
642
  return [Permissions.IsAdmin];
560
643
  }
561
644
 
645
+ private adminRunScriptsPermissions(): PermissionMethod<unknown>[] {
646
+ if (this.options.accessControl) {
647
+ return [this.options.accessControl.permission({admin: ["runScripts"]})];
648
+ }
649
+ return [Permissions.IsAdmin];
650
+ }
651
+
562
652
  private async hasScriptPermission(
563
653
  user: User | undefined,
564
654
  action: "runScripts" | "viewBackgroundTasks"
@@ -728,6 +818,37 @@ export class AdminApp {
728
818
  }
729
819
  };
730
820
 
821
+ const safeFrameworkAdminAudit = async ({
822
+ after,
823
+ before,
824
+ extraRedact,
825
+ modelName,
826
+ recordLabel,
827
+ request,
828
+ verb,
829
+ }: {
830
+ after?: unknown;
831
+ before?: unknown;
832
+ extraRedact?: string[];
833
+ modelName: string;
834
+ recordLabel?: string;
835
+ request: express.Request;
836
+ verb: AdminAuditEvent["verb"];
837
+ }): Promise<void> => {
838
+ if (modelName === "AuditEvent") {
839
+ return;
840
+ }
841
+ void maybeRecordAdminAudit({
842
+ after,
843
+ before,
844
+ extraRedact,
845
+ modelName,
846
+ recordLabel,
847
+ req: request,
848
+ verb,
849
+ });
850
+ };
851
+
731
852
  // Build config response with field metadata from Mongoose schemas
732
853
  const configNames = assignUniqueAdminConfigNames(
733
854
  modelConfigs.map((config) => ({
@@ -768,9 +889,12 @@ export class AdminApp {
768
889
  readonlyFields,
769
890
  schemaPaths: schemaPathKeys,
770
891
  });
892
+ const isOrgScopedModel = this.isOrganizationScoped(config);
893
+ const syncMeta = syncMetaForAdminModel(config.model.modelName, isOrgScopedModel);
771
894
 
772
895
  return {
773
896
  actions: config.actions ?? [],
897
+ adminBroadcast: syncMeta.adminBroadcast,
774
898
  bulkPatchAllowlist,
775
899
  defaultSort: config.defaultSort ?? "-created",
776
900
  displayName: config.displayName,
@@ -784,6 +908,7 @@ export class AdminApp {
784
908
  listDisplayLinks: config.listDisplayLinks ?? [],
785
909
  listFields,
786
910
  name: configNames[configIndex] ?? config.model.modelName,
911
+ organizationScoped: isOrgScopedModel,
787
912
  pageSize: config.pageSize,
788
913
  permissions: {
789
914
  create: config.permissions?.create !== false,
@@ -796,6 +921,7 @@ export class AdminApp {
796
921
  routePath: `${basePath}${config.routePath}`,
797
922
  searchFields,
798
923
  sortableFields,
924
+ ...(syncMeta.syncCollection ? {syncCollection: syncMeta.syncCollection} : {}),
799
925
  };
800
926
  });
801
927
 
@@ -912,6 +1038,7 @@ export class AdminApp {
912
1038
  return {
913
1039
  ...baseConfigResponse,
914
1040
  customScreens: authorizedScreens.map(({adminAccess: _adminAccess, ...screen}) => screen),
1041
+ migrations: {enabled: Boolean(this.options.migrations?.dir)},
915
1042
  models: authorizedModels,
916
1043
  platformTools: {
917
1044
  configuration: canReadConfiguration,
@@ -944,6 +1071,8 @@ export class AdminApp {
944
1071
  properties: {
945
1072
  description: {type: "string"},
946
1073
  displayName: {type: "string"},
1074
+ group: {type: "string"},
1075
+ icon: {type: "string"},
947
1076
  name: {type: "string"},
948
1077
  },
949
1078
  type: "object",
@@ -1154,6 +1283,7 @@ export class AdminApp {
1154
1283
 
1155
1284
  // Mount search endpoint for each model
1156
1285
  for (const config of modelConfigs) {
1286
+ const isOrganizationScoped = this.isOrganizationScoped(config);
1157
1287
  // Determine searchable fields from the actual Mongoose schema type,
1158
1288
  // not the OpenAPI type (which reports ObjectId as "string")
1159
1289
  const searchableFields: string[] = [];
@@ -1176,6 +1306,7 @@ export class AdminApp {
1176
1306
  app.get(
1177
1307
  `${basePath}${config.routePath}/search`,
1178
1308
  authenticateMiddleware(),
1309
+ ...(isOrganizationScoped ? [orgContextMiddleware({required: true})] : []),
1179
1310
  asyncHandler(async (req, res) => {
1180
1311
  if (
1181
1312
  !(await checkPermissions(
@@ -1216,10 +1347,11 @@ export class AdminApp {
1216
1347
  q,
1217
1348
  });
1218
1349
  try {
1219
- const scoped = await buildAdminListQueryFilter(config, modelMeta?.searchFields)(
1220
- req.user as User | undefined,
1221
- {}
1222
- );
1350
+ const scoped = await buildAdminListQueryFilter(
1351
+ config,
1352
+ modelMeta?.searchFields,
1353
+ isOrganizationScoped
1354
+ )(req.user as User | undefined, {});
1223
1355
  if (scoped === null) {
1224
1356
  return res.json({data: []});
1225
1357
  }
@@ -1248,6 +1380,7 @@ export class AdminApp {
1248
1380
 
1249
1381
  // Mount modelRouter for each model with IsAdmin permissions
1250
1382
  for (const config of modelConfigs) {
1383
+ const isOrganizationScoped = this.isOrganizationScoped(config);
1251
1384
  const hiddenFieldSet = new Set(config.hiddenFields ?? []);
1252
1385
  const readonlySet = new Set(config.readonlyFields ?? []);
1253
1386
  const excludeFieldSet = new Set(config.excludeFields ?? []);
@@ -1264,10 +1397,14 @@ export class AdminApp {
1264
1397
  if (allowed === false) {
1265
1398
  return [];
1266
1399
  }
1267
- return this.resourceActionPermissions(config, action);
1400
+ const permissions = this.resourceActionPermissions(config, action);
1401
+ if (isOrganizationScoped && action !== "create") {
1402
+ return [...permissions, Permissions.IsOrganizationMember];
1403
+ }
1404
+ return permissions;
1268
1405
  };
1269
1406
 
1270
- const updatePermissions = this.resourceActionPermissions(config, "update");
1407
+ const updatePermissions = adminPermission(config.permissions?.update, "update");
1271
1408
 
1272
1409
  const stripProtectedFromBody = (body: unknown): Record<string, unknown> => {
1273
1410
  if (!body || typeof body !== "object" || Array.isArray(body)) {
@@ -1429,49 +1566,84 @@ export class AdminApp {
1429
1566
  .build()
1430
1567
  : undefined;
1431
1568
 
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
- },
1569
+ const skipOnAdminAuditHook = config.model.modelName === "AdminAuditLog";
1570
+ const auditHooks = {
1571
+ postCreate: async (value: unknown, request: express.Request): Promise<void> => {
1572
+ const doc = auditDocumentToPlain(value);
1573
+ const rid = doc._id;
1574
+ const recordLabel = auditLabelFromListFields(doc, config.listFields);
1575
+ await safeFrameworkAdminAudit({
1576
+ after: value,
1577
+ extraRedact: [...hiddenFieldSet, ...excludeFieldSet],
1578
+ modelName: config.model.modelName,
1579
+ recordLabel,
1580
+ request,
1581
+ verb: "created",
1582
+ });
1583
+ if (skipOnAdminAuditHook) {
1584
+ return;
1585
+ }
1586
+ await safeOnAdminAudit(request, {
1587
+ actorId: auditActorId(request),
1588
+ modelName: config.model.modelName,
1589
+ recordId: rid != null ? String(rid) : undefined,
1590
+ recordLabel,
1591
+ verb: "created",
1592
+ });
1593
+ },
1594
+ postDelete: async (request: express.Request, value: unknown): Promise<void> => {
1595
+ const doc = auditDocumentToPlain(value);
1596
+ const rid = doc._id;
1597
+ const recordLabel = auditLabelFromListFields(doc, config.listFields);
1598
+ await safeFrameworkAdminAudit({
1599
+ before: value,
1600
+ extraRedact: [...hiddenFieldSet, ...excludeFieldSet],
1601
+ modelName: config.model.modelName,
1602
+ recordLabel,
1603
+ request,
1604
+ verb: "deleted",
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: "deleted",
1615
+ });
1616
+ },
1617
+ postUpdate: async (
1618
+ value: unknown,
1619
+ _cleanedBody: unknown,
1620
+ request: express.Request,
1621
+ prev: unknown
1622
+ ): Promise<void> => {
1623
+ const doc = auditDocumentToPlain(value);
1624
+ const rid = doc._id;
1625
+ const recordLabel = auditLabelFromListFields(doc, config.listFields);
1626
+ await safeFrameworkAdminAudit({
1627
+ after: value,
1628
+ before: prev,
1629
+ extraRedact: [...hiddenFieldSet, ...excludeFieldSet],
1630
+ modelName: config.model.modelName,
1631
+ recordLabel,
1632
+ request,
1633
+ verb: "updated",
1634
+ });
1635
+ if (skipOnAdminAuditHook) {
1636
+ return;
1473
1637
  }
1474
- : {};
1638
+ await safeOnAdminAudit(request, {
1639
+ actorId: auditActorId(request),
1640
+ modelName: config.model.modelName,
1641
+ recordId: rid != null ? String(rid) : undefined,
1642
+ recordLabel,
1643
+ verb: "updated",
1644
+ });
1645
+ },
1646
+ };
1475
1647
 
1476
1648
  const assertCanWriteUserAdminFlag = async (
1477
1649
  body: Record<string, unknown>,
@@ -1617,6 +1789,9 @@ export class AdminApp {
1617
1789
  return body;
1618
1790
  }
1619
1791
  const record = body as Record<string, unknown>;
1792
+ if (isOrganizationScoped) {
1793
+ record.organizationId = getOrgContext()?.organization?._id;
1794
+ }
1620
1795
  if (
1621
1796
  !(await checkPermissions(
1622
1797
  "create",
@@ -1648,7 +1823,11 @@ export class AdminApp {
1648
1823
  listFields: config.listFields,
1649
1824
  searchFields: modelMeta?.searchFields ?? config.searchFields,
1650
1825
  }),
1651
- queryFilter: buildAdminListQueryFilter(config, modelMeta?.searchFields),
1826
+ queryFilter: buildAdminListQueryFilter(
1827
+ config,
1828
+ modelMeta?.searchFields,
1829
+ isOrganizationScoped
1830
+ ),
1652
1831
  responseHandler: async (value, _method, request): Promise<JSONValue> =>
1653
1832
  addRecordCapabilities(value, request),
1654
1833
  sort: config.defaultSort ?? "-created",
@@ -1656,7 +1835,42 @@ export class AdminApp {
1656
1835
  ...(auditHooks.postDelete ? {postDelete: auditHooks.postDelete} : {}),
1657
1836
  };
1658
1837
 
1838
+ if (isOrganizationScoped) {
1839
+ disableOrgScopedAdminBroadcastSync(config.model.modelName);
1840
+ }
1841
+ const syncEntry = findSyncEntryByModelName(config.model.modelName);
1842
+ const adminBroadcastEnabled = syncEntry?.config.adminBroadcast === true;
1843
+ if (adminBroadcastEnabled) {
1844
+ registerAdminBroadcastScope(config.model.modelName, {
1845
+ listPermissions: adminPermission(true, "list"),
1846
+ queryFilter: routerOptions.queryFilter,
1847
+ readPermissions: adminPermission(true, "read"),
1848
+ });
1849
+
1850
+ registerAdminWindowMutationScope(config.model.modelName, {
1851
+ accessControl: this.options.accessControl,
1852
+ createPermissions: adminPermission(config.permissions?.create, "create"),
1853
+ deletePermissions: adminPermission(config.permissions?.delete, "delete"),
1854
+ modelName: config.model.modelName,
1855
+ permissions: {
1856
+ create: config.permissions?.create !== false,
1857
+ delete: config.permissions?.delete !== false,
1858
+ update: config.permissions?.update !== false,
1859
+ },
1860
+ postCreate: routerOptions.postCreate,
1861
+ postDelete: routerOptions.postDelete,
1862
+ postUpdate: routerOptions.postUpdate,
1863
+ preCreate: routerOptions.preCreate,
1864
+ preUpdate: routerOptions.preUpdate,
1865
+ stripMutationData: (data) => stripProtectedFromBody(data),
1866
+ updatePermissions: adminPermission(config.permissions?.update, "update"),
1867
+ });
1868
+ }
1869
+
1659
1870
  const modelBase = express.Router();
1871
+ if (isOrganizationScoped) {
1872
+ modelBase.use(authenticateMiddleware(), orgContextMiddleware({required: true}));
1873
+ }
1660
1874
  modelBase.use(validateAdminSortParam(modelMeta?.sortableFields ?? []));
1661
1875
  modelBase.post(
1662
1876
  "/bulk-patch",
@@ -1776,7 +1990,7 @@ export class AdminApp {
1776
1990
  }
1777
1991
 
1778
1992
  // Mount script routes
1779
- if (scriptConfigs.length > 0) {
1993
+ if (scriptConfigs.length > 0 || this.options.migrations?.dir) {
1780
1994
  const scriptsRouter = express.Router();
1781
1995
  scriptsRouter.use(authenticateMiddleware());
1782
1996
 
@@ -1784,11 +1998,24 @@ export class AdminApp {
1784
1998
 
1785
1999
  app.use(`${basePath}/scripts`, scriptsRouter);
1786
2000
  }
2001
+
2002
+ mountAdminMigrationRoutes({
2003
+ app,
2004
+ basePath,
2005
+ dir: this.options.migrations?.dir,
2006
+ ...(openApiMw ? {openApi: openApiMw} : {}),
2007
+ runPermissions: this.adminRunScriptsPermissions(),
2008
+ statusPermissions: this.adminAccessPermissions(),
2009
+ });
1787
2010
  }
1788
2011
 
1789
2012
  private mountScriptRoutes(router: express.Router, scripts: AdminScriptConfig[]): void {
1790
2013
  const scriptsByName = new Map(scripts.map((s) => [s.name, s]));
1791
2014
  const scriptNames = scripts.map((s) => s.name);
2015
+ const jobs = tryGetJobsService();
2016
+ if (jobs) {
2017
+ defineAdminScriptJob(jobs, (name) => scriptsByName.get(name));
2018
+ }
1792
2019
 
1793
2020
  // GET /admin/scripts/runs — Paginated history of script runs (BackgroundTasks)
1794
2021
  router.get(
@@ -1903,6 +2130,7 @@ export class AdminApp {
1903
2130
  }
1904
2131
 
1905
2132
  const now = DateTime.now().toJSDate();
2133
+ const queuedViaJobs = Boolean(tryGetJobsService()?.getDefinition(ADMIN_SCRIPT_JOB_NAME));
1906
2134
 
1907
2135
  let task: BackgroundTaskDocument;
1908
2136
  try {
@@ -1912,9 +2140,13 @@ export class AdminApp {
1912
2140
  logs: [
1913
2141
  {level: "info", message: `Script started by ${user.name ?? "admin"}`, timestamp: now},
1914
2142
  ],
1915
- progress: {message: "Starting...", percentage: 0, stage: "Queued"},
1916
- startedAt: now,
1917
- status: "running",
2143
+ progress: {
2144
+ message: queuedViaJobs ? "Queued" : "Starting...",
2145
+ percentage: 0,
2146
+ stage: queuedViaJobs ? "Queued" : "Queued",
2147
+ },
2148
+ startedAt: queuedViaJobs ? undefined : now,
2149
+ status: queuedViaJobs ? "pending" : "running",
1918
2150
  taskType: script.name,
1919
2151
  })) as BackgroundTaskDocument;
1920
2152
  } catch (err: unknown) {
@@ -1927,67 +2159,53 @@ export class AdminApp {
1927
2159
  });
1928
2160
  }
1929
2161
 
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",
2162
+ const taskId = task._id.toString();
2163
+ let enqueued: {id: string} | undefined;
2164
+ try {
2165
+ enqueued = await tryEnqueueAdminScriptJob({
2166
+ args: args.raw,
2167
+ createdByName: user.name,
2168
+ scriptName: script.name,
2169
+ taskId,
2170
+ wetRun: isWetRun,
2171
+ });
2172
+ } catch (err: unknown) {
2173
+ const detail = err instanceof Error ? err.message : String(err);
2174
+ logger.error(`Failed to enqueue durable job for ${script.name}: ${detail}`);
2175
+ const failedAt = DateTime.now().toJSDate();
2176
+ await BackgroundTask.updateOne(
2177
+ {_id: task._id},
2178
+ {
2179
+ $set: {
2180
+ completedAt: failedAt,
2181
+ error: detail,
2182
+ progress: {
2183
+ message: "Failed to enqueue",
2184
+ percentage: 100,
2185
+ stage: "Failed",
1965
2186
  },
1966
- }
1967
- );
1968
- } catch (err: unknown) {
1969
- if (err instanceof TaskCancelledError) {
1970
- return;
2187
+ status: "failed",
2188
+ },
1971
2189
  }
1972
- const message = err instanceof Error ? err.message : String(err);
1973
- logger.error(`Script ${script.name} failed: ${message}`);
2190
+ );
2191
+ throw new APIError({
2192
+ detail,
2193
+ status: 500,
2194
+ title: `Failed to enqueue script: ${script.name}`,
2195
+ });
2196
+ }
2197
+ if (enqueued) {
2198
+ return res.status(201).json({taskId});
2199
+ }
1974
2200
 
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
- })();
2201
+ void runRegisteredScriptTask({
2202
+ args,
2203
+ script,
2204
+ taskId,
2205
+ wetRun: isWetRun,
2206
+ });
1989
2207
 
1990
- return res.status(201).json({taskId: task._id.toString()});
2208
+ return res.status(201).json({taskId});
1991
2209
  })
1992
2210
  );
1993
2211
 
@@ -2068,6 +2286,8 @@ export class AdminApp {
2068
2286
  });
2069
2287
  }
2070
2288
 
2289
+ await tryCancelAdminScriptJob(task._id.toString());
2290
+
2071
2291
  return res.json({message: "Task cancelled", task: cancelled.toObject()});
2072
2292
  })
2073
2293
  );