@terreno/admin-backend 57.2.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 (53) hide show
  1. package/.ai/guidelines/core.md +12 -4
  2. package/.claude/CLAUDE.local.md +17 -2
  3. package/.cursor/rules/00-root.mdc +17 -2
  4. package/.github/copilot-instructions.md +17 -2
  5. package/AGENTS.md +17 -2
  6. package/README.md +3 -1
  7. package/bunfig.toml +9 -1
  8. package/dist/adminApp.d.ts +20 -2
  9. package/dist/adminApp.js +480 -474
  10. package/dist/adminConfigIdentity.d.ts +1 -0
  11. package/dist/adminConfigIdentity.js +1 -0
  12. package/dist/adminMigrations.d.ts +10 -0
  13. package/dist/adminMigrations.js +205 -0
  14. package/dist/adminScriptJob.d.ts +32 -0
  15. package/dist/adminScriptJob.js +360 -0
  16. package/dist/adminTextSearch.d.ts +1 -0
  17. package/dist/adminTextSearch.js +1 -0
  18. package/dist/adminUiV2.d.ts +2 -0
  19. package/dist/aggregateAdmin.js +6 -1
  20. package/dist/documentStorageApp.js +1 -4
  21. package/dist/enrichAdminListFilters.d.ts +7 -0
  22. package/dist/enrichAdminListFilters.js +37 -0
  23. package/dist/filterParser.js +139 -12
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.js +4 -1
  26. package/dist/legacy.js +4 -2
  27. package/dist/resolvedAdminModel.js +2 -1
  28. package/package.json +8 -8
  29. package/src/adminApp.migrations.test.ts +232 -0
  30. package/src/adminApp.models.test.ts +647 -5
  31. package/src/adminApp.syncMeta.test.ts +237 -0
  32. package/src/adminApp.test.ts +92 -0
  33. package/src/adminApp.ts +354 -240
  34. package/src/adminConfigIdentity.ts +1 -0
  35. package/src/adminHttpGoldens.test.ts +337 -0
  36. package/src/adminMigrations.ts +157 -0
  37. package/src/adminScriptJob.test.ts +297 -0
  38. package/src/adminScriptJob.ts +271 -0
  39. package/src/adminSyncMutationAuthMismatch.test.ts +650 -0
  40. package/src/adminTextSearch.test.ts +28 -0
  41. package/src/adminTextSearch.ts +1 -0
  42. package/src/adminUiV2.test.ts +71 -1
  43. package/src/adminUiV2.ts +2 -0
  44. package/src/aggregateAdmin.test.ts +125 -0
  45. package/src/aggregateAdmin.ts +7 -4
  46. package/src/documentStorageApp.ts +1 -3
  47. package/src/enrichAdminListFilters.test.ts +44 -0
  48. package/src/enrichAdminListFilters.ts +29 -0
  49. package/src/filterParser.test.ts +95 -0
  50. package/src/filterParser.ts +156 -10
  51. package/src/index.ts +2 -0
  52. package/src/legacy.ts +5 -1
  53. package/src/resolvedAdminModel.ts +2 -1
package/src/adminApp.ts CHANGED
@@ -5,37 +5,53 @@ import {
5
5
  type AnyTerrenoAccess,
6
6
  APIError,
7
7
  asyncHandler,
8
+ auditActorIdFromRequest,
8
9
  authenticateMiddleware,
9
10
  BackgroundTask,
10
11
  type BackgroundTaskDocument,
11
12
  checkPermissions,
12
13
  createOpenApiBuilder,
13
14
  createScriptArgs,
14
- getOpenApiSpecForModel,
15
+ describeModel,
16
+ findSyncEntryByModelName,
17
+ getOrgContext,
15
18
  type JSONValue,
16
19
  logger,
17
20
  type ModelRouterOptions,
21
+ maybeRecordAdminAudit,
22
+ modelDescriptionToAdminFields,
18
23
  modelRouter,
19
24
  type OpenApiMiddleware,
25
+ OrgQueryFilter,
26
+ orgContextMiddleware,
20
27
  type PermissionMethod,
21
28
  Permissions,
22
29
  type PopulatePath,
30
+ registerAdminBroadcastScope,
31
+ registerAdminWindowMutationScope,
23
32
  type ScriptArgDef,
24
33
  type ScriptArgValue,
25
- type ScriptContext,
26
- type ScriptResult,
27
34
  type ScriptRunner,
28
35
  scrubAdminFields,
29
- TaskCancelledError,
30
36
  type TerrenoApp,
31
37
  type User,
38
+ updateSyncRegistryOptions,
32
39
  VersionConfig,
33
40
  } from "@terreno/api";
41
+ import {tryGetJobsService} from "@terreno/jobs";
34
42
  import express from "express";
35
43
  import {DateTime} from "luxon";
36
44
  import type {Model} from "mongoose";
37
45
  import mongoose from "mongoose";
38
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";
39
55
  import {
40
56
  ADMIN_LIST_SEARCH_PARAM,
41
57
  andMongoFilters,
@@ -186,6 +202,9 @@ export interface AdminCustomScreenConfig {
186
202
  name: string;
187
203
  /** Optional subtitle or help text shown with the screen card in the admin UI */
188
204
  description?: string;
205
+ /** Sidebar group label; grouped screens render with matching model groups in AdminShell. */
206
+ group?: string;
207
+ icon?: string;
189
208
  /** RBAC or custom authorization for exposing this screen in admin metadata/navigation. */
190
209
  adminAccess?: Pick<AdminAccessConfig, "authorize" | "resource"> & {action?: string};
191
210
  }
@@ -205,13 +224,23 @@ export interface AdminOptions {
205
224
  /** Extra custom screens merged with built-ins (e.g. version-config) */
206
225
  customScreens?: AdminCustomScreenConfig[];
207
226
  /**
208
- * Optional audit sink for admin CRUD after modelRouter succeeds.
209
- * 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.
210
229
  */
211
230
  onAdminAudit?: (event: AdminAuditEvent, req: express.Request) => void | Promise<void>;
212
231
  /** When set, admin shell entry requires `admin:access`; model CRUD also requires
213
232
  * resource/action permissions (for example `user:update`) from the same Access instance. */
214
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;
215
244
  }
216
245
 
217
246
  interface AdminFieldMeta {
@@ -241,6 +270,15 @@ interface AdminModelMeta {
241
270
  fieldOrder?: string[];
242
271
  fieldsets?: AdminFieldsetInput[];
243
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;
244
282
  filters: AdminListFilter[];
245
283
  group?: string;
246
284
  hiddenFields: string[];
@@ -285,8 +323,37 @@ interface AdminConfigResponse {
285
323
  schemaVersion: number;
286
324
  scripts: AdminScriptMeta[];
287
325
  widgetIds: string[];
326
+ migrations?: {enabled: boolean};
288
327
  }
289
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
+
290
357
  const buildAllModelAdminsMap = (models: ResolvedAdminModel[]): AdminModelAdminMap => {
291
358
  const map: AdminModelAdminMap = {};
292
359
  for (const config of models) {
@@ -310,7 +377,8 @@ const scrubAdminResponse = (
310
377
  const buildAdminListQueryFilter = (
311
378
  config: ResolvedAdminModel,
312
379
  /** Resolved (possibly derived) search fields from `/admin/config`, not just explicit config. */
313
- resolvedSearchFields?: string[]
380
+ resolvedSearchFields?: string[],
381
+ isOrganizationScoped = false
314
382
  ): NonNullable<ModelRouterOptions<unknown>["queryFilter"]> => {
315
383
  const base = config.queryFilter;
316
384
  const searchFields = resolvedSearchFields ?? config.searchFields ?? [];
@@ -347,8 +415,17 @@ const buildAdminListQueryFilter = (
347
415
  }
348
416
  merged = {...merged, ...baseResult};
349
417
  }
418
+ if (isOrganizationScoped) {
419
+ merged = {...merged, ...OrgQueryFilter(user, merged)};
420
+ }
350
421
  const result = andMongoFilters(merged, searchClause);
351
- 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};
352
429
  };
353
430
  };
354
431
 
@@ -452,36 +529,14 @@ const coerceAdminFlag = (value: unknown): boolean => {
452
529
  throw new APIError({status: 400, title: "admin must be a boolean"});
453
530
  };
454
531
 
455
- const auditActorId = (request: express.Request): string | undefined => {
456
- const user = request.user as {_id?: unknown} | undefined;
457
- if (!user || user._id == null) {
458
- return undefined;
459
- }
460
- return String(user._id);
461
- };
462
-
463
- interface OpenApiProperty {
464
- default?: unknown;
465
- description?: string;
466
- enum?: string[];
467
- $ref?: string;
468
- type?: string;
469
- format?: string;
470
- items?: {
471
- properties?: Record<string, OpenApiProperty>;
472
- required?: string[];
473
- type?: string;
474
- enum?: string[];
475
- format?: string;
476
- $ref?: string;
477
- };
478
- }
532
+ const auditActorId = auditActorIdFromRequest;
479
533
 
480
534
  interface ArraySchemaTypeCompatibility {
481
535
  caster?: mongoose.SchemaType;
482
536
  getEmbeddedSchemaType?: () => mongoose.SchemaType | undefined;
483
537
  }
484
538
 
539
+ /** @internal */
485
540
  export const getArrayEmbeddedSchemaType = (
486
541
  schemaPath: mongoose.SchemaType
487
542
  ): mongoose.SchemaType | undefined => {
@@ -492,49 +547,14 @@ export const getArrayEmbeddedSchemaType = (
492
547
  return compatiblePath.caster;
493
548
  };
494
549
 
495
- const extractFieldMeta = (
496
- properties: Record<string, OpenApiProperty>,
497
- required: string[]
550
+ const extractFieldMetaFromDescription = (
551
+ model: Model<unknown>,
552
+ hiddenFields: string[]
498
553
  ): Record<string, AdminFieldMeta> => {
499
- const fields: Record<string, AdminFieldMeta> = {};
500
- for (const [key, prop] of Object.entries(properties)) {
501
- const fieldType = prop.type ?? "string";
502
- fields[key] = {
503
- default: prop.default,
504
- description: prop.description,
505
- enum: prop.enum,
506
- ref: prop.$ref ? prop.$ref.replace("#/components/schemas/", "") : undefined,
507
- required: required.includes(key),
508
- searchable: fieldType === "string" && !prop.enum,
509
- type: fieldType,
510
- };
511
-
512
- // For array fields, extract item sub-field metadata
513
- if (prop.type === "array" && prop.items?.properties) {
514
- const itemRequired: string[] = prop.items.required ?? [];
515
- fields[key].items = extractFieldMeta(
516
- prop.items.properties as Record<string, OpenApiProperty>,
517
- itemRequired
518
- );
519
- }
520
-
521
- // For array fields of primitives, capture the item type and enum
522
- if (prop.type === "array" && prop.items && !prop.items.properties) {
523
- const itemProp = prop.items as OpenApiProperty;
524
- if (itemProp.type) {
525
- fields[key].itemType = itemProp.type;
526
- }
527
- if (itemProp.enum) {
528
- fields[key].itemEnum = itemProp.enum;
529
- }
530
- }
531
-
532
- // Check for ObjectId references in the raw property
533
- if (!fields[key].ref && prop.type === "string" && prop.format === "objectid") {
534
- // mongoose-to-swagger may not preserve ref directly; we'll handle this in register()
535
- }
536
- }
537
- return fields;
554
+ const hiddenFieldSet = new Set(hiddenFields);
555
+ const description = describeModel(model);
556
+ const fields = modelDescriptionToAdminFields(description);
557
+ return Object.fromEntries(Object.entries(fields).filter(([key]) => !hiddenFieldSet.has(key)));
538
558
  };
539
559
 
540
560
  const asMiddlewareList = (
@@ -603,6 +623,18 @@ export class AdminApp {
603
623
  this.options = options;
604
624
  }
605
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
+
606
638
  private adminAccessPermissions(): PermissionMethod<unknown>[] {
607
639
  if (this.options.accessControl) {
608
640
  return [this.options.accessControl.permission({admin: [ADMIN_PAGE_ACTION]})];
@@ -610,6 +642,13 @@ export class AdminApp {
610
642
  return [Permissions.IsAdmin];
611
643
  }
612
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
+
613
652
  private async hasScriptPermission(
614
653
  user: User | undefined,
615
654
  action: "runScripts" | "viewBackgroundTasks"
@@ -779,6 +818,37 @@ export class AdminApp {
779
818
  }
780
819
  };
781
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
+
782
852
  // Build config response with field metadata from Mongoose schemas
783
853
  const configNames = assignUniqueAdminConfigNames(
784
854
  modelConfigs.map((config) => ({
@@ -788,55 +858,8 @@ export class AdminApp {
788
858
  }))
789
859
  );
790
860
  const configModels: AdminModelMeta[] = modelConfigs.map((config, configIndex) => {
791
- const {properties, required} = getOpenApiSpecForModel(config.model) as {
792
- properties: Record<string, OpenApiProperty>;
793
- required: string[];
794
- };
795
861
  const hiddenFieldSet = new Set(config.hiddenFields ?? []);
796
- const filteredProperties = Object.fromEntries(
797
- Object.entries(properties).filter(([key]) => !hiddenFieldSet.has(key))
798
- );
799
- const filteredRequired = required.filter((key) => !hiddenFieldSet.has(key));
800
-
801
- // Extract ref information directly from the Mongoose schema
802
- const fields = extractFieldMeta(filteredProperties, filteredRequired);
803
- for (const [key, field] of Object.entries(fields)) {
804
- const schemaPath = config.model.schema.path(key);
805
- if (schemaPath) {
806
- const pathOptions = schemaPath.options;
807
- if (pathOptions?.ref) {
808
- field.ref = pathOptions.ref;
809
- }
810
- // Handle array of refs (legacy: also set ref for back-compat)
811
- if (Array.isArray(pathOptions?.type) && pathOptions.type[0]?.ref) {
812
- field.ref = pathOptions.type[0].ref;
813
- }
814
- // For arrays, use the public embedded schema type to infer the primitive item type/ref.
815
- if (schemaPath.instance === "Array") {
816
- const embeddedSchemaType = getArrayEmbeddedSchemaType(schemaPath);
817
- if (embeddedSchemaType?.instance && !field.items) {
818
- const instanceToType: Record<string, string> = {
819
- Boolean: "boolean",
820
- Number: "number",
821
- ObjectID: "objectid",
822
- ObjectId: "objectid",
823
- SchemaObjectId: "objectid",
824
- String: "string",
825
- };
826
- const mapped = instanceToType[embeddedSchemaType.instance];
827
- if (mapped) {
828
- field.itemType = mapped;
829
- }
830
- if (embeddedSchemaType.options?.ref) {
831
- field.itemRef = embeddedSchemaType.options.ref;
832
- }
833
- if (Array.isArray(embeddedSchemaType.options?.enum)) {
834
- field.itemEnum = embeddedSchemaType.options.enum;
835
- }
836
- }
837
- }
838
- }
839
- }
862
+ const fields = extractFieldMetaFromDescription(config.model, [...hiddenFieldSet]);
840
863
 
841
864
  // Apply field overrides (e.g., widget: "markdown")
842
865
  if (config.fieldOverrides) {
@@ -866,9 +889,12 @@ export class AdminApp {
866
889
  readonlyFields,
867
890
  schemaPaths: schemaPathKeys,
868
891
  });
892
+ const isOrgScopedModel = this.isOrganizationScoped(config);
893
+ const syncMeta = syncMetaForAdminModel(config.model.modelName, isOrgScopedModel);
869
894
 
870
895
  return {
871
896
  actions: config.actions ?? [],
897
+ adminBroadcast: syncMeta.adminBroadcast,
872
898
  bulkPatchAllowlist,
873
899
  defaultSort: config.defaultSort ?? "-created",
874
900
  displayName: config.displayName,
@@ -882,6 +908,7 @@ export class AdminApp {
882
908
  listDisplayLinks: config.listDisplayLinks ?? [],
883
909
  listFields,
884
910
  name: configNames[configIndex] ?? config.model.modelName,
911
+ organizationScoped: isOrgScopedModel,
885
912
  pageSize: config.pageSize,
886
913
  permissions: {
887
914
  create: config.permissions?.create !== false,
@@ -894,6 +921,7 @@ export class AdminApp {
894
921
  routePath: `${basePath}${config.routePath}`,
895
922
  searchFields,
896
923
  sortableFields,
924
+ ...(syncMeta.syncCollection ? {syncCollection: syncMeta.syncCollection} : {}),
897
925
  };
898
926
  });
899
927
 
@@ -905,15 +933,7 @@ export class AdminApp {
905
933
  name: script.name,
906
934
  }));
907
935
 
908
- const defaultScreens: AdminCustomScreenConfig[] = [
909
- {
910
- adminAccess: {action: "read", resource: "configuration"},
911
- displayName: "Version Config",
912
- name: "version-config",
913
- },
914
- ];
915
936
  const mergedScreens: AdminCustomScreenConfig[] = [
916
- ...defaultScreens,
917
937
  ...aggregated.customScreens,
918
938
  ...(this.options.customScreens ?? []),
919
939
  ];
@@ -1018,6 +1038,7 @@ export class AdminApp {
1018
1038
  return {
1019
1039
  ...baseConfigResponse,
1020
1040
  customScreens: authorizedScreens.map(({adminAccess: _adminAccess, ...screen}) => screen),
1041
+ migrations: {enabled: Boolean(this.options.migrations?.dir)},
1021
1042
  models: authorizedModels,
1022
1043
  platformTools: {
1023
1044
  configuration: canReadConfiguration,
@@ -1050,6 +1071,8 @@ export class AdminApp {
1050
1071
  properties: {
1051
1072
  description: {type: "string"},
1052
1073
  displayName: {type: "string"},
1074
+ group: {type: "string"},
1075
+ icon: {type: "string"},
1053
1076
  name: {type: "string"},
1054
1077
  },
1055
1078
  type: "object",
@@ -1260,6 +1283,7 @@ export class AdminApp {
1260
1283
 
1261
1284
  // Mount search endpoint for each model
1262
1285
  for (const config of modelConfigs) {
1286
+ const isOrganizationScoped = this.isOrganizationScoped(config);
1263
1287
  // Determine searchable fields from the actual Mongoose schema type,
1264
1288
  // not the OpenAPI type (which reports ObjectId as "string")
1265
1289
  const searchableFields: string[] = [];
@@ -1282,6 +1306,7 @@ export class AdminApp {
1282
1306
  app.get(
1283
1307
  `${basePath}${config.routePath}/search`,
1284
1308
  authenticateMiddleware(),
1309
+ ...(isOrganizationScoped ? [orgContextMiddleware({required: true})] : []),
1285
1310
  asyncHandler(async (req, res) => {
1286
1311
  if (
1287
1312
  !(await checkPermissions(
@@ -1322,10 +1347,11 @@ export class AdminApp {
1322
1347
  q,
1323
1348
  });
1324
1349
  try {
1325
- const scoped = await buildAdminListQueryFilter(config, modelMeta?.searchFields)(
1326
- req.user as User | undefined,
1327
- {}
1328
- );
1350
+ const scoped = await buildAdminListQueryFilter(
1351
+ config,
1352
+ modelMeta?.searchFields,
1353
+ isOrganizationScoped
1354
+ )(req.user as User | undefined, {});
1329
1355
  if (scoped === null) {
1330
1356
  return res.json({data: []});
1331
1357
  }
@@ -1354,6 +1380,7 @@ export class AdminApp {
1354
1380
 
1355
1381
  // Mount modelRouter for each model with IsAdmin permissions
1356
1382
  for (const config of modelConfigs) {
1383
+ const isOrganizationScoped = this.isOrganizationScoped(config);
1357
1384
  const hiddenFieldSet = new Set(config.hiddenFields ?? []);
1358
1385
  const readonlySet = new Set(config.readonlyFields ?? []);
1359
1386
  const excludeFieldSet = new Set(config.excludeFields ?? []);
@@ -1370,10 +1397,14 @@ export class AdminApp {
1370
1397
  if (allowed === false) {
1371
1398
  return [];
1372
1399
  }
1373
- 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;
1374
1405
  };
1375
1406
 
1376
- const updatePermissions = this.resourceActionPermissions(config, "update");
1407
+ const updatePermissions = adminPermission(config.permissions?.update, "update");
1377
1408
 
1378
1409
  const stripProtectedFromBody = (body: unknown): Record<string, unknown> => {
1379
1410
  if (!body || typeof body !== "object" || Array.isArray(body)) {
@@ -1535,49 +1566,84 @@ export class AdminApp {
1535
1566
  .build()
1536
1567
  : undefined;
1537
1568
 
1538
- const auditEligible = Boolean(onAdminAudit) && config.model.modelName !== "AdminAuditLog";
1539
- const auditHooks = auditEligible
1540
- ? {
1541
- postCreate: async (value: unknown, request: express.Request): Promise<void> => {
1542
- const doc = auditDocumentToPlain(value);
1543
- const rid = doc._id;
1544
- await safeOnAdminAudit(request, {
1545
- actorId: auditActorId(request),
1546
- modelName: config.model.modelName,
1547
- recordId: rid != null ? String(rid) : undefined,
1548
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1549
- verb: "created",
1550
- });
1551
- },
1552
- postDelete: async (request: express.Request, value: unknown): Promise<void> => {
1553
- const doc = auditDocumentToPlain(value);
1554
- const rid = doc._id;
1555
- await safeOnAdminAudit(request, {
1556
- actorId: auditActorId(request),
1557
- modelName: config.model.modelName,
1558
- recordId: rid != null ? String(rid) : undefined,
1559
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1560
- verb: "deleted",
1561
- });
1562
- },
1563
- postUpdate: async (
1564
- value: unknown,
1565
- _cleanedBody: unknown,
1566
- request: express.Request,
1567
- _prev: unknown
1568
- ): Promise<void> => {
1569
- const doc = auditDocumentToPlain(value);
1570
- const rid = doc._id;
1571
- await safeOnAdminAudit(request, {
1572
- actorId: auditActorId(request),
1573
- modelName: config.model.modelName,
1574
- recordId: rid != null ? String(rid) : undefined,
1575
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1576
- verb: "updated",
1577
- });
1578
- },
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;
1579
1637
  }
1580
- : {};
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
+ };
1581
1647
 
1582
1648
  const assertCanWriteUserAdminFlag = async (
1583
1649
  body: Record<string, unknown>,
@@ -1723,6 +1789,9 @@ export class AdminApp {
1723
1789
  return body;
1724
1790
  }
1725
1791
  const record = body as Record<string, unknown>;
1792
+ if (isOrganizationScoped) {
1793
+ record.organizationId = getOrgContext()?.organization?._id;
1794
+ }
1726
1795
  if (
1727
1796
  !(await checkPermissions(
1728
1797
  "create",
@@ -1754,7 +1823,11 @@ export class AdminApp {
1754
1823
  listFields: config.listFields,
1755
1824
  searchFields: modelMeta?.searchFields ?? config.searchFields,
1756
1825
  }),
1757
- queryFilter: buildAdminListQueryFilter(config, modelMeta?.searchFields),
1826
+ queryFilter: buildAdminListQueryFilter(
1827
+ config,
1828
+ modelMeta?.searchFields,
1829
+ isOrganizationScoped
1830
+ ),
1758
1831
  responseHandler: async (value, _method, request): Promise<JSONValue> =>
1759
1832
  addRecordCapabilities(value, request),
1760
1833
  sort: config.defaultSort ?? "-created",
@@ -1762,7 +1835,42 @@ export class AdminApp {
1762
1835
  ...(auditHooks.postDelete ? {postDelete: auditHooks.postDelete} : {}),
1763
1836
  };
1764
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
+
1765
1870
  const modelBase = express.Router();
1871
+ if (isOrganizationScoped) {
1872
+ modelBase.use(authenticateMiddleware(), orgContextMiddleware({required: true}));
1873
+ }
1766
1874
  modelBase.use(validateAdminSortParam(modelMeta?.sortableFields ?? []));
1767
1875
  modelBase.post(
1768
1876
  "/bulk-patch",
@@ -1882,7 +1990,7 @@ export class AdminApp {
1882
1990
  }
1883
1991
 
1884
1992
  // Mount script routes
1885
- if (scriptConfigs.length > 0) {
1993
+ if (scriptConfigs.length > 0 || this.options.migrations?.dir) {
1886
1994
  const scriptsRouter = express.Router();
1887
1995
  scriptsRouter.use(authenticateMiddleware());
1888
1996
 
@@ -1890,11 +1998,24 @@ export class AdminApp {
1890
1998
 
1891
1999
  app.use(`${basePath}/scripts`, scriptsRouter);
1892
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
+ });
1893
2010
  }
1894
2011
 
1895
2012
  private mountScriptRoutes(router: express.Router, scripts: AdminScriptConfig[]): void {
1896
2013
  const scriptsByName = new Map(scripts.map((s) => [s.name, s]));
1897
2014
  const scriptNames = scripts.map((s) => s.name);
2015
+ const jobs = tryGetJobsService();
2016
+ if (jobs) {
2017
+ defineAdminScriptJob(jobs, (name) => scriptsByName.get(name));
2018
+ }
1898
2019
 
1899
2020
  // GET /admin/scripts/runs — Paginated history of script runs (BackgroundTasks)
1900
2021
  router.get(
@@ -2009,6 +2130,7 @@ export class AdminApp {
2009
2130
  }
2010
2131
 
2011
2132
  const now = DateTime.now().toJSDate();
2133
+ const queuedViaJobs = Boolean(tryGetJobsService()?.getDefinition(ADMIN_SCRIPT_JOB_NAME));
2012
2134
 
2013
2135
  let task: BackgroundTaskDocument;
2014
2136
  try {
@@ -2018,9 +2140,13 @@ export class AdminApp {
2018
2140
  logs: [
2019
2141
  {level: "info", message: `Script started by ${user.name ?? "admin"}`, timestamp: now},
2020
2142
  ],
2021
- progress: {message: "Starting...", percentage: 0, stage: "Queued"},
2022
- startedAt: now,
2023
- 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",
2024
2150
  taskType: script.name,
2025
2151
  })) as BackgroundTaskDocument;
2026
2152
  } catch (err: unknown) {
@@ -2033,67 +2159,53 @@ export class AdminApp {
2033
2159
  });
2034
2160
  }
2035
2161
 
2036
- // Build context for cancellation, progress reporting, and arguments
2037
- const ctx: ScriptContext = {
2038
- addLog: async (level, message) => {
2039
- const current = await BackgroundTask.findById(task._id);
2040
- if (current) {
2041
- await current.addLog(level, message);
2042
- }
2043
- },
2044
- args,
2045
- checkCancellation: async () => {
2046
- await BackgroundTask.checkCancellation(task._id.toString());
2047
- },
2048
- updateProgress: async (percentage, stage, message) => {
2049
- const current = await BackgroundTask.findById(task._id);
2050
- if (current) {
2051
- await current.updateProgress(percentage, stage, message);
2052
- }
2053
- },
2054
- };
2055
-
2056
- // Run the script asynchronously — use atomic updates to avoid overwriting
2057
- // cancellation or other intermediate state changes.
2058
- void (async () => {
2059
- try {
2060
- const result: ScriptResult = await script.runner(isWetRun, ctx);
2061
-
2062
- // Atomically update only if still running (don't overwrite cancellation)
2063
- await BackgroundTask.findOneAndUpdate(
2064
- {_id: task._id, status: "running"},
2065
- {
2066
- $set: {
2067
- completedAt: DateTime.now().toJSDate(),
2068
- progress: {message: "Done", percentage: 100, stage: "Complete"},
2069
- result: result.results,
2070
- 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",
2071
2186
  },
2072
- }
2073
- );
2074
- } catch (err: unknown) {
2075
- if (err instanceof TaskCancelledError) {
2076
- return;
2187
+ status: "failed",
2188
+ },
2077
2189
  }
2078
- const message = err instanceof Error ? err.message : String(err);
2079
- 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
+ }
2080
2200
 
2081
- // Atomically update only if still running
2082
- await BackgroundTask.findOneAndUpdate(
2083
- {_id: task._id, status: "running"},
2084
- {
2085
- $set: {
2086
- completedAt: DateTime.now().toJSDate(),
2087
- error: message,
2088
- result: [message],
2089
- status: "failed",
2090
- },
2091
- }
2092
- );
2093
- }
2094
- })();
2201
+ void runRegisteredScriptTask({
2202
+ args,
2203
+ script,
2204
+ taskId,
2205
+ wetRun: isWetRun,
2206
+ });
2095
2207
 
2096
- return res.status(201).json({taskId: task._id.toString()});
2208
+ return res.status(201).json({taskId});
2097
2209
  })
2098
2210
  );
2099
2211
 
@@ -2174,6 +2286,8 @@ export class AdminApp {
2174
2286
  });
2175
2287
  }
2176
2288
 
2289
+ await tryCancelAdminScriptJob(task._id.toString());
2290
+
2177
2291
  return res.json({message: "Task cancelled", task: cancelled.toObject()});
2178
2292
  })
2179
2293
  );