@terreno/admin-backend 57.16.1 → 57.17.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.
@@ -69,7 +69,8 @@ export interface AdminModelConfig {
69
69
  /** Allowlisted keys for POST .../bulk-patch (defaults from listFields minus system/readonly/hidden) */
70
70
  bulkPatchAllowlist?: string[];
71
71
  /**
72
- * Per-model `modelRouter` query filter (list and other query-shaped reads).
72
+ * Per-model admin row scope. List and search add it to the query; by-id read/update/delete,
73
+ * bulk-patch, and admin-window sync writes deny documents outside it.
73
74
  * Same contract as {@link ModelRouterOptions.queryFilter} in `@terreno/api`: merge into the
74
75
  * Mongoose query, return the incoming `query` unchanged if allowed, or return `null` to yield
75
76
  * an empty list without error.
@@ -217,7 +218,13 @@ export declare class AdminApp {
217
218
  private canAnyResourceAction;
218
219
  private adminResource;
219
220
  private isAdminModelOwned;
221
+ /**
222
+ * Admin permissions for one model action: the admin page gate plus RBAC (or IsAdmin), ANDed
223
+ * with the model's `admin.adminPermissions[action]` methods. An explicitly empty array denies
224
+ * the action.
225
+ */
220
226
  private resourceActionPermissions;
227
+ private baseResourceActionPermissions;
221
228
  /**
222
229
  * Register admin routes with the Express application.
223
230
  *
package/dist/adminApp.js CHANGED
@@ -11,6 +11,7 @@ const luxon_1 = require("luxon");
11
11
  const mongoose_1 = __importDefault(require("mongoose"));
12
12
  const adminConfigIdentity_1 = require("./adminConfigIdentity");
13
13
  const adminMigrations_1 = require("./adminMigrations");
14
+ const adminRowScope_1 = require("./adminRowScope");
14
15
  const adminScriptJob_1 = require("./adminScriptJob");
15
16
  const adminTextSearch_1 = require("./adminTextSearch");
16
17
  const adminUiV2_1 = require("./adminUiV2");
@@ -118,13 +119,16 @@ resolvedSearchFields, isOrganizationScoped = false) => {
118
119
  merged = { ...merged, ...(0, api_1.OrgQueryFilter)(user, merged) };
119
120
  }
120
121
  const result = (0, adminTextSearch_1.andMongoFilters)(merged, searchClause);
121
- const overrides = { ...filter };
122
- for (const key of consumedKeys) {
123
- if (!(key in overrides)) {
124
- overrides[key] = undefined;
122
+ // modelRouter spreads this over the raw request query. Clear consumed raw keys that the
123
+ // result does not set, and spread the result last so the row scope always wins over a
124
+ // client filter on the same field.
125
+ const cleared = {};
126
+ for (const key of [...consumedKeys, ...Object.keys(filter)]) {
127
+ if (!(key in result)) {
128
+ cleared[key] = undefined;
125
129
  }
126
130
  }
127
- return { ...result, ...overrides, [adminTextSearch_1.ADMIN_LIST_SEARCH_PARAM]: undefined };
131
+ return { ...cleared, ...result, [adminTextSearch_1.ADMIN_LIST_SEARCH_PARAM]: undefined };
128
132
  };
129
133
  };
130
134
  const ADMIN_TIMESTAMP_SORT_FIELDS = ["created", "createdAt", "updated", "updatedAt"];
@@ -363,7 +367,23 @@ class AdminApp {
363
367
  const ownerId = owner?._id ?? owner;
364
368
  return ownerId != null && String(ownerId) === String(user.id);
365
369
  }
370
+ /**
371
+ * Admin permissions for one model action: the admin page gate plus RBAC (or IsAdmin), ANDed
372
+ * with the model's `admin.adminPermissions[action]` methods. An explicitly empty array denies
373
+ * the action.
374
+ */
366
375
  resourceActionPermissions(config, action) {
376
+ const base = this.baseResourceActionPermissions(config, action);
377
+ const configured = config.admin?.adminPermissions?.[action];
378
+ if (!configured) {
379
+ return base;
380
+ }
381
+ if (configured.length === 0 || base.length === 0) {
382
+ return [];
383
+ }
384
+ return [...base, ...configured];
385
+ }
386
+ baseResourceActionPermissions(config, action) {
367
387
  const shell = this.adminAccessPermissions();
368
388
  const accessControl = this.options.accessControl;
369
389
  if (!accessControl) {
@@ -907,30 +927,43 @@ class AdminApp {
907
927
  }
908
928
  return permissions;
909
929
  };
910
- const updatePermissions = adminPermission(config.permissions?.update, "update");
930
+ // Read/update/delete of one document must stay inside the same row scope list and search use.
931
+ const rowScopePermission = config.queryFilter
932
+ ? (0, adminRowScope_1.buildAdminRowScopePermission)(config)
933
+ : undefined;
934
+ const withRowScope = (permissions) => {
935
+ if (!rowScopePermission || permissions.length === 0) {
936
+ return permissions;
937
+ }
938
+ return [...permissions, rowScopePermission];
939
+ };
940
+ const updatePermissions = withRowScope(adminPermission(config.permissions?.update, "update"));
941
+ // The RBAC user model: "User" or the userModel given to createAccess, whatever its name.
942
+ const isRbacUserModel = (0, api_1.isRbacUserModelName)(config.model.modelName, this.options.accessControl);
911
943
  const stripProtectedFromBody = (body) => {
912
944
  if (!body || typeof body !== "object" || Array.isArray(body)) {
913
945
  return {};
914
946
  }
915
- const next = { ...body };
916
- for (const key of readonlySet) {
917
- delete next[key];
918
- }
919
- for (const key of hiddenFieldSet) {
920
- delete next[key];
921
- }
922
- for (const key of excludeFieldSet) {
923
- delete next[key];
924
- }
925
- for (const key of adminUiV2_1.SYSTEM_ADMIN_FIELDS) {
926
- delete next[key];
927
- }
947
+ const protectedFields = [
948
+ ...readonlySet,
949
+ ...hiddenFieldSet,
950
+ ...excludeFieldSet,
951
+ ...adminUiV2_1.SYSTEM_ADMIN_FIELDS,
952
+ ];
928
953
  // Self-service never writes these fields. Admin CRUD may set `admin`.
929
954
  // When RBAC is enabled, `roles` must go through RoleManager.assign and
930
955
  // tenant membership is not a generic User document field.
931
- if (config.model.modelName === "User" && this.options.accessControl) {
932
- delete next.organizationIds;
933
- delete next.roles;
956
+ if (isRbacUserModel) {
957
+ protectedFields.push("organizationIds", "roles");
958
+ }
959
+ // Mongoose applies dotted keys (`roles.0`) as paths, so drop paths inside a protected
960
+ // field as well as the field itself.
961
+ const next = {};
962
+ for (const [key, value] of Object.entries(body)) {
963
+ if (protectedFields.some((field) => (0, api_1.isWriteKeyForField)(key, field))) {
964
+ continue;
965
+ }
966
+ next[key] = value;
934
967
  }
935
968
  return next;
936
969
  };
@@ -941,7 +974,7 @@ class AdminApp {
941
974
  return value;
942
975
  };
943
976
  const takePendingUserRoles = (body, request) => {
944
- if (config.model.modelName !== "User" || !this.options.accessControl) {
977
+ if (!isRbacUserModel) {
945
978
  return;
946
979
  }
947
980
  if (!("roles" in body)) {
@@ -1117,7 +1150,7 @@ class AdminApp {
1117
1150
  },
1118
1151
  };
1119
1152
  const assertCanWriteUserAdminFlag = async (body, request, currentAdmin = false, targetUserId) => {
1120
- if (config.model.modelName !== "User" || !("admin" in body)) {
1153
+ if (!isRbacUserModel || !("admin" in body)) {
1121
1154
  return;
1122
1155
  }
1123
1156
  const accessControl = this.options.accessControl;
@@ -1167,10 +1200,25 @@ class AdminApp {
1167
1200
  const existing = await config.model.findById(id).select("admin").lean();
1168
1201
  return Boolean(existing?.admin);
1169
1202
  };
1203
+ // The document an update applies to: the one the REST permission check loaded, or (for
1204
+ // admin-window sync updates, which set req.params.id) the stored row.
1205
+ const currentDocumentForUpdate = async (request) => {
1206
+ const loaded = request.obj;
1207
+ if (loaded) {
1208
+ return loaded;
1209
+ }
1210
+ const id = request.params?.id;
1211
+ if (!id || !rowScopePermission) {
1212
+ return undefined;
1213
+ }
1214
+ const query = { _id: id };
1215
+ if (config.model.schema.path("deleted")) {
1216
+ query.deleted = { $in: [true, false] };
1217
+ }
1218
+ return config.model.findById(id).where(query).lean();
1219
+ };
1170
1220
  const markAuthorizedUserAdminWrite = (body, request) => {
1171
- if (config.model.modelName !== "User" ||
1172
- !this.options.accessControl ||
1173
- !("admin" in body)) {
1221
+ if (!isRbacUserModel || !("admin" in body)) {
1174
1222
  return;
1175
1223
  }
1176
1224
  request.terrenoAllowUserAdminWrite = true;
@@ -1204,10 +1252,10 @@ class AdminApp {
1204
1252
  maxLimit: 500,
1205
1253
  permissions: {
1206
1254
  create: adminPermission(config.permissions?.create, "create"),
1207
- delete: adminPermission(config.permissions?.delete, "delete"),
1255
+ delete: withRowScope(adminPermission(config.permissions?.delete, "delete")),
1208
1256
  list: adminPermission(true, "list"),
1209
- read: adminPermission(true, "read"),
1210
- update: adminPermission(config.permissions?.update, "update"),
1257
+ read: withRowScope(adminPermission(true, "read")),
1258
+ update: updatePermissions,
1211
1259
  },
1212
1260
  postCreate: async (value, request) => {
1213
1261
  await applyPendingUserRoles(value, request, true);
@@ -1247,7 +1295,14 @@ class AdminApp {
1247
1295
  takePendingUserRoles(record, req);
1248
1296
  await assertCanWriteUserAdminFlag(record, req, await currentUserAdminFlag(req));
1249
1297
  markAuthorizedUserAdminWrite(record, req);
1250
- return stripProtectedFromBody(body);
1298
+ const stripped = stripProtectedFromBody(body);
1299
+ await (0, adminRowScope_1.assertAdminRowScopeAfterUpdate)({
1300
+ config,
1301
+ current: await currentDocumentForUpdate(req),
1302
+ patch: stripped,
1303
+ user: req.user,
1304
+ });
1305
+ return stripped;
1251
1306
  },
1252
1307
  queryFields: (0, adminUiV2_1.buildAdminModelQueryFields)({
1253
1308
  filters: config.filters,
@@ -1258,6 +1313,7 @@ class AdminApp {
1258
1313
  queryFilter: buildAdminListQueryFilter(config, modelMeta?.searchFields, isOrganizationScoped),
1259
1314
  responseHandler: async (value, _method, request) => addRecordCapabilities(value, request),
1260
1315
  sort: config.defaultSort ?? "-created",
1316
+ sortFields: modelMeta?.sortableFields ?? [],
1261
1317
  ...(config.populatePaths ? { populatePaths: config.populatePaths } : {}),
1262
1318
  ...(auditHooks.postDelete ? { postDelete: auditHooks.postDelete } : {}),
1263
1319
  };
@@ -1275,7 +1331,7 @@ class AdminApp {
1275
1331
  (0, api_1.registerAdminWindowMutationScope)(config.model.modelName, {
1276
1332
  accessControl: this.options.accessControl,
1277
1333
  createPermissions: adminPermission(config.permissions?.create, "create"),
1278
- deletePermissions: adminPermission(config.permissions?.delete, "delete"),
1334
+ deletePermissions: withRowScope(adminPermission(config.permissions?.delete, "delete")),
1279
1335
  modelName: config.model.modelName,
1280
1336
  permissions: {
1281
1337
  create: config.permissions?.create !== false,
@@ -1288,7 +1344,7 @@ class AdminApp {
1288
1344
  preCreate: routerOptions.preCreate,
1289
1345
  preUpdate: routerOptions.preUpdate,
1290
1346
  stripMutationData: (data) => stripProtectedFromBody(data),
1291
- updatePermissions: adminPermission(config.permissions?.update, "update"),
1347
+ updatePermissions,
1292
1348
  });
1293
1349
  }
1294
1350
  const modelBase = express_1.default.Router();
@@ -1331,9 +1387,7 @@ class AdminApp {
1331
1387
  }
1332
1388
  const patch = stripProtectedFromBody(rawPatch);
1333
1389
  let pendingRoles;
1334
- if (config.model.modelName === "User" &&
1335
- this.options.accessControl &&
1336
- "roles" in rawPatch) {
1390
+ if (isRbacUserModel && "roles" in rawPatch) {
1337
1391
  pendingRoles = parseRoleNames(rawPatch.roles);
1338
1392
  }
1339
1393
  if (Object.keys(patch).length === 0 && pendingRoles === undefined) {
@@ -1360,6 +1414,20 @@ class AdminApp {
1360
1414
  failures.push({ id, title: "Forbidden" });
1361
1415
  continue;
1362
1416
  }
1417
+ await (0, adminRowScope_1.assertAdminRowScopeAfterUpdate)({ config, current: doc, patch, user: actor });
1418
+ await (0, api_1.assertCanWriteTargetUser)({
1419
+ accessControl: this.options.accessControl,
1420
+ actor,
1421
+ modelName: config.model.modelName,
1422
+ target: doc,
1423
+ });
1424
+ await (0, api_1.assertCanWriteUserIdentity)({
1425
+ accessControl: this.options.accessControl,
1426
+ actor,
1427
+ body: patch,
1428
+ modelName: config.model.modelName,
1429
+ target: doc,
1430
+ });
1363
1431
  await assertCanWriteUserAdminFlag(rawPatch, req, Boolean(doc.admin), id);
1364
1432
  const previousPatch = {};
1365
1433
  for (const key of Object.keys(patch)) {
@@ -0,0 +1,26 @@
1
+ import { type PermissionMethod, type User } from "@terreno/api";
2
+ import type { Model } from "mongoose";
3
+ /**
4
+ * AdminApp row scope: the per-model `queryFilter` (or `adminFilter`, which resolves to it) that
5
+ * limits which rows an admin may see. List and search apply it as a query constraint; the helpers
6
+ * here apply the same scope to routes that resolve one document by id.
7
+ */
8
+ export interface AdminRowScopeConfig {
9
+ model: Pick<Model<unknown>, "exists" | "schema">;
10
+ queryFilter?: (user?: User, query?: Record<string, unknown>) => Record<string, unknown> | null | Promise<Record<string, unknown> | null>;
11
+ }
12
+ /**
13
+ * Permission method that denies read/update/delete of a document outside the admin row scope.
14
+ * Collection-level checks (no instance) pass, so list and the bulk-patch pre-check are unchanged.
15
+ */
16
+ export declare const buildAdminRowScopePermission: (config: AdminRowScopeConfig) => PermissionMethod<unknown>;
17
+ /**
18
+ * Rejects an update whose result would leave the admin row scope (for example changing the
19
+ * scoped tenant or owner field). Only runs when the patch writes a field the scope constrains.
20
+ */
21
+ export declare const assertAdminRowScopeAfterUpdate: ({ config, current, patch, user, }: {
22
+ config: AdminRowScopeConfig;
23
+ current: unknown;
24
+ patch: Record<string, unknown>;
25
+ user: User | undefined;
26
+ }) => Promise<void>;
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertAdminRowScopeAfterUpdate = exports.buildAdminRowScopePermission = void 0;
4
+ const api_1 = require("@terreno/api");
5
+ const resolveAdminRowScope = async (config, user) => {
6
+ if (!config.queryFilter) {
7
+ return { denied: false };
8
+ }
9
+ const resolved = await config.queryFilter(user, {});
10
+ if (resolved === null) {
11
+ return { denied: true };
12
+ }
13
+ if (Object.keys(resolved).length === 0) {
14
+ return { denied: false };
15
+ }
16
+ return { denied: false, filter: resolved };
17
+ };
18
+ const documentId = (instance) => {
19
+ if (!instance || typeof instance !== "object") {
20
+ return undefined;
21
+ }
22
+ return instance._id;
23
+ };
24
+ const toPlainDocument = (instance) => {
25
+ const withToObject = instance;
26
+ if (typeof withToObject?.toObject === "function") {
27
+ return withToObject.toObject();
28
+ }
29
+ return { ...instance };
30
+ };
31
+ /** Top-level field names a Mongo filter constrains, including those inside `$and` / `$or` / `$nor`. */
32
+ const filterRootKeys = (filter, keys = new Set()) => {
33
+ for (const [key, value] of Object.entries(filter)) {
34
+ if (key === "$and" || key === "$or" || key === "$nor") {
35
+ if (Array.isArray(value)) {
36
+ for (const clause of value) {
37
+ if (clause && typeof clause === "object") {
38
+ filterRootKeys(clause, keys);
39
+ }
40
+ }
41
+ }
42
+ continue;
43
+ }
44
+ if (key.startsWith("$")) {
45
+ continue;
46
+ }
47
+ keys.add(key.split(".")[0] ?? key);
48
+ }
49
+ return keys;
50
+ };
51
+ /**
52
+ * Whether the stored document is inside the row scope. Evaluated by MongoDB so the scope has the
53
+ * same semantics here as on the list query. Soft-deleted rows are included so admin-window writes
54
+ * on them are judged by scope, not by the deleted flag.
55
+ */
56
+ const isStoredDocumentInScope = async (config, instance, filter) => {
57
+ const id = documentId(instance);
58
+ if (id == null) {
59
+ return false;
60
+ }
61
+ const query = { $and: [filter, { _id: id }] };
62
+ if (config.model.schema.path("deleted")) {
63
+ query.deleted = { $in: [true, false] };
64
+ }
65
+ return (await config.model.exists(query)) !== null;
66
+ };
67
+ /**
68
+ * Permission method that denies read/update/delete of a document outside the admin row scope.
69
+ * Collection-level checks (no instance) pass, so list and the bulk-patch pre-check are unchanged.
70
+ */
71
+ const buildAdminRowScopePermission = (config) => {
72
+ return async (_method, user, instance) => {
73
+ if (instance === undefined || instance === null) {
74
+ return true;
75
+ }
76
+ const scope = await resolveAdminRowScope(config, user);
77
+ if (scope.denied) {
78
+ return false;
79
+ }
80
+ if (!scope.filter) {
81
+ return true;
82
+ }
83
+ return isStoredDocumentInScope(config, instance, scope.filter);
84
+ };
85
+ };
86
+ exports.buildAdminRowScopePermission = buildAdminRowScopePermission;
87
+ /**
88
+ * Rejects an update whose result would leave the admin row scope (for example changing the
89
+ * scoped tenant or owner field). Only runs when the patch writes a field the scope constrains.
90
+ */
91
+ const assertAdminRowScopeAfterUpdate = async ({ config, current, patch, user, }) => {
92
+ if (!config.queryFilter || !current) {
93
+ return;
94
+ }
95
+ const touched = Object.keys(patch).map((key) => key.split(".")[0] ?? key);
96
+ if (touched.length === 0) {
97
+ return;
98
+ }
99
+ const scope = await resolveAdminRowScope(config, user);
100
+ if (scope.denied) {
101
+ throw new api_1.APIError({ status: 403, title: "Admin write outside row scope" });
102
+ }
103
+ if (!scope.filter) {
104
+ return;
105
+ }
106
+ const scopedKeys = filterRootKeys(scope.filter);
107
+ if (!touched.some((key) => scopedKeys.has(key))) {
108
+ return;
109
+ }
110
+ const nextState = { ...toPlainDocument(current), ...patch };
111
+ if (!(0, api_1.matchesQuery)(nextState, scope.filter)) {
112
+ throw new api_1.APIError({ status: 403, title: "Admin write outside row scope" });
113
+ }
114
+ };
115
+ exports.assertAdminRowScopeAfterUpdate = assertAdminRowScopeAfterUpdate;
@@ -17,8 +17,14 @@ export interface AdminScriptJobPayload {
17
17
  export interface JobsDefineHost {
18
18
  define: (name: string, definition: JobDefinition) => unknown;
19
19
  }
20
- export declare const runRegisteredScriptTask: ({ args, script, signal, taskId, wetRun, }: {
20
+ /**
21
+ * Run an admin script against its BackgroundTask row. `requirePending` makes the run conditional
22
+ * on winning the task's pending -> running transition, so a durable job delivered twice never
23
+ * starts the script twice. The in-process path creates its task already running and omits it.
24
+ */
25
+ export declare const runRegisteredScriptTask: ({ args, requirePending, script, signal, taskId, wetRun, }: {
21
26
  args: ScriptArgs;
27
+ requirePending?: boolean;
22
28
  script: AdminScriptJobTarget;
23
29
  signal?: AbortSignal;
24
30
  taskId: string;
@@ -59,15 +59,31 @@ const isAbortLike = (error) => {
59
59
  }
60
60
  return error.name === "AbortError" || error.name === "TaskCancelledError";
61
61
  };
62
- const runRegisteredScriptTask = async ({ args, script, signal, taskId, wetRun, }) => {
62
+ /**
63
+ * Run an admin script against its BackgroundTask row. `requirePending` makes the run conditional
64
+ * on winning the task's pending -> running transition, so a durable job delivered twice never
65
+ * starts the script twice. The in-process path creates its task already running and omits it.
66
+ */
67
+ const runRegisteredScriptTask = async ({ args, requirePending = false, script, signal, taskId, wetRun, }) => {
63
68
  const now = luxon_1.DateTime.now().toJSDate();
64
- await api_1.BackgroundTask.findOneAndUpdate({ _id: taskId, status: { $in: ["pending", "running"] } }, {
69
+ const started = await api_1.BackgroundTask.findOneAndUpdate({ _id: taskId, status: requirePending ? "pending" : { $in: ["pending", "running"] } }, {
65
70
  $set: {
66
71
  progress: { message: "Starting...", percentage: 0, stage: "Running" },
67
72
  startedAt: now,
68
73
  status: "running",
69
74
  },
70
75
  });
76
+ if (!started && requirePending) {
77
+ const current = await api_1.BackgroundTask.findById(taskId);
78
+ if (current?.status === "cancelled") {
79
+ return;
80
+ }
81
+ throw new api_1.APIError({
82
+ detail: `Task ${taskId} is ${current?.status ?? "missing"}`,
83
+ status: 409,
84
+ title: "Admin script task already started",
85
+ });
86
+ }
71
87
  const ctx = {
72
88
  addLog: async (level, message) => {
73
89
  const current = await api_1.BackgroundTask.findById(taskId);
@@ -152,6 +168,7 @@ const createAdminScriptHandler = (getScript) => {
152
168
  }
153
169
  await (0, exports.runRegisteredScriptTask)({
154
170
  args,
171
+ requirePending: true,
155
172
  script,
156
173
  signal: ctx.signal,
157
174
  taskId: parsed.taskId,
package/package.json CHANGED
@@ -5,8 +5,8 @@
5
5
  },
6
6
  "dependencies": {
7
7
  "@google-cloud/storage": "^7.15.0",
8
- "@terreno/api": "57.16.1",
9
- "@terreno/jobs": "57.16.1",
8
+ "@terreno/api": "57.17.0",
9
+ "@terreno/jobs": "57.17.0",
10
10
  "express": "^5.2.1",
11
11
  "luxon": "^3.7.2",
12
12
  "multer": "2.2.0"
@@ -14,7 +14,7 @@
14
14
  "description": "Admin panel backend plugin for @terreno/api — part of Terreno, the batteries-included TypeScript framework for universal apps.",
15
15
  "devDependencies": {
16
16
  "@biomejs/biome": "^2.3.6",
17
- "@terreno/test": "57.16.1",
17
+ "@terreno/test": "57.17.0",
18
18
  "@types/bun": "^1.4.0",
19
19
  "@types/express": "^5.0.6",
20
20
  "@types/luxon": "^3.7.1",
@@ -55,5 +55,5 @@
55
55
  "test:coverage": "bun run ../scripts/check-coverage.ts"
56
56
  },
57
57
  "types": "dist/index.d.ts",
58
- "version": "57.16.1"
58
+ "version": "57.17.0"
59
59
  }