@terreno/api 58.0.5 → 58.1.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 (75) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/dist/actions.d.ts +6 -0
  3. package/dist/api.d.ts +21 -0
  4. package/dist/api.js +57 -32
  5. package/dist/bulk.d.ts +79 -0
  6. package/dist/bulk.js +449 -0
  7. package/dist/bulkOpenApi.d.ts +15 -0
  8. package/dist/bulkOpenApi.js +103 -0
  9. package/dist/bulkTransaction.d.ts +33 -0
  10. package/dist/bulkTransaction.js +126 -0
  11. package/dist/errors.d.ts +2 -0
  12. package/dist/errors.js +8 -6
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +6 -3
  15. package/dist/mcp/actionTools.js +2 -0
  16. package/dist/mcp/grantAccess.d.ts +27 -0
  17. package/dist/mcp/grantAccess.js +29 -0
  18. package/dist/mcp/oauth.js +86 -5
  19. package/dist/mcp/oauthMetadata.d.ts +32 -1
  20. package/dist/mcp/oauthMetadata.js +53 -2
  21. package/dist/mcp/registry.d.ts +8 -1
  22. package/dist/mcp/server.js +6 -1
  23. package/dist/mcp/toolGenerator.d.ts +5 -1
  24. package/dist/mcp/toolGenerator.js +11 -0
  25. package/dist/mcp/types.d.ts +11 -0
  26. package/dist/modelRouterWrites.d.ts +23 -0
  27. package/dist/modelRouterWrites.js +54 -0
  28. package/dist/openApi.d.ts +7 -0
  29. package/dist/openApi.js +6 -6
  30. package/dist/permissions.js +5 -4
  31. package/dist/rbac/access.js +2 -0
  32. package/dist/rbac/routes.js +1 -0
  33. package/dist/rbac/statements.d.ts +12 -1
  34. package/dist/rbac/statements.js +89 -1
  35. package/dist/rbac/types.d.ts +9 -2
  36. package/dist/sync/executors.d.ts +6 -4
  37. package/dist/sync/executors.js +6 -2
  38. package/package.json +6 -6
  39. package/src/actions.ts +6 -0
  40. package/src/api.ts +95 -33
  41. package/src/bulk.test.ts +1256 -0
  42. package/src/bulk.ts +680 -0
  43. package/src/bulkOpenApi.test.ts +172 -0
  44. package/src/bulkOpenApi.ts +126 -0
  45. package/src/bulkTransaction.test.ts +197 -0
  46. package/src/bulkTransaction.ts +149 -0
  47. package/src/errors.ts +2 -2
  48. package/src/index.ts +6 -0
  49. package/src/isolated/bulkAtomic.isolated.ts +630 -0
  50. package/src/isolated/bulkStandalone.isolated.ts +133 -0
  51. package/src/isolated/mongoTopology.isolated.ts +29 -0
  52. package/src/mcp/actionTools.ts +2 -0
  53. package/src/mcp/grantAccess.test.ts +107 -0
  54. package/src/mcp/grantAccess.ts +49 -0
  55. package/src/mcp/oauth.test.ts +327 -0
  56. package/src/mcp/oauth.ts +113 -5
  57. package/src/mcp/oauthMetadata.test.ts +125 -1
  58. package/src/mcp/oauthMetadata.ts +99 -2
  59. package/src/mcp/registry.ts +8 -1
  60. package/src/mcp/server.test.ts +419 -2
  61. package/src/mcp/server.ts +8 -1
  62. package/src/mcp/toolGenerator.ts +17 -0
  63. package/src/mcp/types.ts +12 -0
  64. package/src/modelRouterWrites.ts +72 -0
  65. package/src/openApi.ts +1 -1
  66. package/src/permissions.ts +5 -5
  67. package/src/rbac/access.ts +3 -1
  68. package/src/rbac/routes.test.ts +15 -0
  69. package/src/rbac/routes.ts +1 -0
  70. package/src/rbac/statements.test.ts +23 -0
  71. package/src/rbac/statements.ts +100 -1
  72. package/src/rbac/types.ts +9 -2
  73. package/src/sync/executors.test.ts +27 -0
  74. package/src/sync/executors.ts +12 -4
  75. package/src/tests/mongoTopology.ts +53 -0
@@ -8,6 +8,7 @@ const logger_1 = require("../logger");
8
8
  const requestContext_1 = require("../requestContext");
9
9
  const adminTracking_1 = require("./adminTracking");
10
10
  const auth_1 = require("./auth");
11
+ const grantAccess_1 = require("./grantAccess");
11
12
  const oauthMetadata_1 = require("./oauthMetadata");
12
13
  const toolGenerator_1 = require("./toolGenerator");
13
14
  // Auth is resolved once in the Express handler (which may answer 401) and read back by the
@@ -31,7 +32,11 @@ const mountMCPServer = (app, options) => {
31
32
  });
32
33
  }
33
34
  const buildServer = async (auth) => {
34
- const served = options.toolSettings ? await (0, adminTracking_1.filterEnabledMcpTools)(tools) : tools;
35
+ const enabled = options.toolSettings ? await (0, adminTracking_1.filterEnabledMcpTools)(tools) : tools;
36
+ // Tools the caller's OAuth grants do not allow are left off this request's server, so
37
+ // tools/list hides them and tools/call fails as for an unknown tool.
38
+ const grants = options.mcpOAuth?.grants;
39
+ const served = enabled.filter((tool) => (0, grantAccess_1.canUseMcpTool)({ credential: auth?.credential, grants, tokenScopes: auth?.scopes, tool }));
35
40
  const onToolCall = options.requestLog
36
41
  ? (record) => {
37
42
  (0, adminTracking_1.recordMcpToolCall)({ ...record, auth }, options.requestLog);
@@ -1,12 +1,16 @@
1
1
  import { type ZodType } from "zod";
2
2
  import type { User } from "../auth";
3
- import type { MCPRegistryEntry, MCPToolArgs, MCPToolInputSchema, MCPToolResult } from "./types";
3
+ import type { MCPRegistryEntry, MCPToolAccess, MCPToolArgs, MCPToolInputSchema, MCPToolResult } from "./types";
4
4
  export interface MCPToolDefinition {
5
5
  name: string;
6
6
  description: string;
7
7
  inputSchema: MCPToolInputSchema;
8
8
  zodSchema: ZodType;
9
9
  handler: (args: MCPToolArgs, user?: User) => Promise<MCPToolResult>;
10
+ /** `read` tools only read data; `write` tools can change it. Enforced for OAuth grants. */
11
+ access: MCPToolAccess;
12
+ /** When set, an OAuth token must hold exactly this scope to see and call the tool. */
13
+ scope?: string;
10
14
  }
11
15
  export declare const generateToolsForEntry: (entry: MCPRegistryEntry) => MCPToolDefinition[];
12
16
  export declare const generateAllTools: (entries: MCPRegistryEntry[]) => MCPToolDefinition[];
@@ -9,6 +9,13 @@ const handlers_1 = require("./handlers");
9
9
  const registry_1 = require("./registry");
10
10
  const schemaGenerator_1 = require("./schemaGenerator");
11
11
  const toolExecution_1 = require("./toolExecution");
12
+ const METHOD_ACCESS = {
13
+ create: "write",
14
+ delete: "write",
15
+ list: "read",
16
+ read: "read",
17
+ update: "write",
18
+ };
12
19
  const getToolPrefix = (entry) => {
13
20
  if (entry.config.toolPrefix) {
14
21
  return entry.config.toolPrefix;
@@ -46,6 +53,7 @@ const generateToolsForEntry = (entry) => {
46
53
  const handler = METHOD_HANDLERS[method];
47
54
  const toolName = `${prefix}_${method}`;
48
55
  tools.push({
56
+ access: METHOD_ACCESS[method],
49
57
  description: (0, schemaGenerator_1.generateToolDescription)(entry.model, method, entry.config, entry.options.queryFields, entry.options.populatePaths, restExcludeFields),
50
58
  handler: (args, user) => (0, toolExecution_1.executeTool)({
51
59
  labels: { mcpMethod: method, mcpModel: entry.modelName, mcpTool: toolName },
@@ -54,6 +62,7 @@ const generateToolsForEntry = (entry) => {
54
62
  }),
55
63
  inputSchema: inputSchema,
56
64
  name: toolName,
65
+ scope: entry.config.scopes?.[method],
57
66
  zodSchema,
58
67
  });
59
68
  }
@@ -75,10 +84,12 @@ exports.generateAllTools = generateAllTools;
75
84
  const getAllMCPTools = () => {
76
85
  const customTools = (0, registry_1.getMCPCustomTools)().map((tool) => {
77
86
  return {
87
+ access: tool.access ?? "write",
78
88
  description: tool.description,
79
89
  handler: tool.handler,
80
90
  inputSchema: (0, zod_1.toJSONSchema)(tool.zodSchema),
81
91
  name: tool.name,
92
+ scope: tool.scope,
82
93
  zodSchema: tool.zodSchema,
83
94
  };
84
95
  });
@@ -2,6 +2,11 @@ import type { HydratedDocument, Model } from "mongoose";
2
2
  import type { JSONValue, ModelRouterOptions } from "../api";
3
3
  import type { User } from "../auth";
4
4
  export type MCPMethod = "create" | "list" | "read" | "update" | "delete";
5
+ /**
6
+ * Whether a tool only reads data or can change it. Under `mcpOAuth.grants`, a `read` grant
7
+ * allows `read` tools and a `write` grant allows both.
8
+ */
9
+ export type MCPToolAccess = "read" | "write";
5
10
  /** Arguments an MCP client sends for a tool call, validated against the tool's Zod schema. */
6
11
  export type MCPToolArgs = Record<string, unknown>;
7
12
  /**
@@ -74,6 +79,12 @@ export interface MCPConfig {
74
79
  excludeFields?: string[];
75
80
  /** Max items returned by list tool (default: 50) */
76
81
  maxLimit?: number;
82
+ /**
83
+ * OAuth scope a token must hold to see and call a method's tool, for example
84
+ * `{delete: "todos:admin"}`. Only enforced when `mcpOAuth.grants` is set. A method without an
85
+ * explicit scope follows its access level: `list` and `read` are `read`, the rest `write`.
86
+ */
87
+ scopes?: Partial<Record<MCPMethod, string>>;
77
88
  /** MCP-specific serialization (separate from REST responseHandler) */
78
89
  mcpResponseHandler?: (value: unknown, method: MCPMethod, user?: User) => Promise<JSONValue>;
79
90
  }
@@ -0,0 +1,23 @@
1
+ import { APIError } from "./errors";
2
+ import type { ExecutorConcurrencyCheck } from "./sync/executors";
3
+ /** The 405 every modelRouter write answers when the method permission denies the user. */
4
+ export declare const methodPermissionDeniedError: ({ method, modelName, userId, }: {
5
+ method: string;
6
+ modelName: string;
7
+ userId?: string;
8
+ }) => APIError;
9
+ /**
10
+ * The last-write-wins check an update builds from the client's timestamp. The precise header wins
11
+ * over the HTTP header, which wins over the body's `_updatedAt`. None set means no check.
12
+ */
13
+ export declare const timestampConcurrencyCheck: ({ preciseHeader, httpHeader, bodyUpdatedAt, }: {
14
+ preciseHeader?: string;
15
+ httpHeader?: string;
16
+ bodyUpdatedAt?: unknown;
17
+ }) => ExecutorConcurrencyCheck | undefined;
18
+ /** The 409 body an update returns when the document changed since the client read it. */
19
+ export declare const conflictResponseBody: (data: unknown) => {
20
+ data: unknown;
21
+ error: string;
22
+ message: string;
23
+ };
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.conflictResponseBody = exports.timestampConcurrencyCheck = exports.methodPermissionDeniedError = void 0;
4
+ /**
5
+ * Pieces of the modelRouter write contract shared by the single-document routes (`api.ts`,
6
+ * `permissions.ts`) and `POST /bulk` (`bulk.ts`), so a bulk item answers exactly as the single
7
+ * route would.
8
+ */
9
+ const luxon_1 = require("luxon");
10
+ const errors_1 = require("./errors");
11
+ /** The 405 every modelRouter write answers when the method permission denies the user. */
12
+ const methodPermissionDeniedError = ({ method, modelName, userId, }) => new errors_1.APIError({
13
+ status: 405,
14
+ title: `Access to ${method.toUpperCase()} on ${modelName} denied for ${userId}`,
15
+ });
16
+ exports.methodPermissionDeniedError = methodPermissionDeniedError;
17
+ /**
18
+ * The last-write-wins check an update builds from the client's timestamp. The precise header wins
19
+ * over the HTTP header, which wins over the body's `_updatedAt`. None set means no check.
20
+ */
21
+ const timestampConcurrencyCheck = ({ preciseHeader, httpHeader, bodyUpdatedAt, }) => {
22
+ if (preciseHeader) {
23
+ return {
24
+ ifUnmodifiedSince: luxon_1.DateTime.fromISO(preciseHeader).toJSDate(),
25
+ invalidTimestampDetail: "X-Unmodified-Since-ISO header could not be parsed as an ISO date",
26
+ type: "timestamp",
27
+ };
28
+ }
29
+ if (httpHeader) {
30
+ return {
31
+ ifUnmodifiedSince: luxon_1.DateTime.fromHTTP(httpHeader).toJSDate(),
32
+ invalidTimestampDetail: "If-Unmodified-Since header could not be parsed as an HTTP date",
33
+ type: "timestamp",
34
+ };
35
+ }
36
+ if (!bodyUpdatedAt) {
37
+ return undefined;
38
+ }
39
+ // An unparseable value round-trips as an invalid Date; the executor turns it into the 400
40
+ // "Invalid conflict-detection timestamp" error after preUpdate has run.
41
+ return {
42
+ ifUnmodifiedSince: luxon_1.DateTime.fromISO(String(bodyUpdatedAt)).toJSDate(),
43
+ invalidTimestampDetail: "_updatedAt body field could not be parsed as an ISO date",
44
+ type: "timestamp",
45
+ };
46
+ };
47
+ exports.timestampConcurrencyCheck = timestampConcurrencyCheck;
48
+ /** The 409 body an update returns when the document changed since the client read it. */
49
+ const conflictResponseBody = (data) => ({
50
+ data,
51
+ error: "Conflict",
52
+ message: "Document was modified since your last read",
53
+ });
54
+ exports.conflictResponseBody = conflictResponseBody;
package/dist/openApi.d.ts CHANGED
@@ -1,6 +1,13 @@
1
1
  import type express from "express";
2
2
  import type { Model } from "mongoose";
3
3
  import type { ModelRouterOptions } from "./api";
4
+ export declare const apiErrorContent: {
5
+ "application/json": {
6
+ schema: {
7
+ $ref: string;
8
+ };
9
+ };
10
+ };
4
11
  export declare const defaultOpenApiErrorResponses: {
5
12
  400: {
6
13
  content: {
package/dist/openApi.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.readOpenApiMiddleware = exports.deleteOpenApiMiddleware = exports.patchOpenApiMiddleware = exports.createOpenApiMiddleware = exports.listOpenApiMiddleware = exports.getOpenApiMiddleware = exports.defaultOpenApiErrorResponses = void 0;
6
+ exports.readOpenApiMiddleware = exports.deleteOpenApiMiddleware = exports.patchOpenApiMiddleware = exports.createOpenApiMiddleware = exports.listOpenApiMiddleware = exports.getOpenApiMiddleware = exports.defaultOpenApiErrorResponses = exports.apiErrorContent = void 0;
7
7
  const flatten_1 = __importDefault(require("lodash/flatten"));
8
8
  const merge_1 = __importDefault(require("lodash/merge"));
9
9
  const mongoose_to_swagger_1 = __importDefault(require("mongoose-to-swagger"));
@@ -13,7 +13,7 @@ const noop = (_a, _b, next) => next();
13
13
  const m2sOptions = {
14
14
  props: ["readOnly", "required", "enum", "default"],
15
15
  };
16
- const apiErrorContent = {
16
+ exports.apiErrorContent = {
17
17
  "application/json": {
18
18
  schema: { $ref: "#/components/schemas/APIError" },
19
19
  },
@@ -21,22 +21,22 @@ const apiErrorContent = {
21
21
  // Default error responses
22
22
  exports.defaultOpenApiErrorResponses = {
23
23
  400: {
24
- content: apiErrorContent,
24
+ content: exports.apiErrorContent,
25
25
  description: "Bad request",
26
26
  },
27
27
  401: {
28
28
  description: "The user must be authenticated",
29
29
  },
30
30
  403: {
31
- content: apiErrorContent,
31
+ content: exports.apiErrorContent,
32
32
  description: "The user is not allowed to perform this action on this document",
33
33
  },
34
34
  404: {
35
- content: apiErrorContent,
35
+ content: exports.apiErrorContent,
36
36
  description: "Document not found",
37
37
  },
38
38
  405: {
39
- content: apiErrorContent,
39
+ content: exports.apiErrorContent,
40
40
  description: "The user is not allowed to perform this action on any document",
41
41
  },
42
42
  };
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.permissionMiddleware = exports.checkPermissions = exports.Permissions = exports.OrganizationQueryFilter = exports.getUserOrganizationIds = exports.OwnerQueryFilter = exports.requireOAuthScope = void 0;
4
4
  const docLoader_1 = require("./docLoader");
5
5
  const errors_1 = require("./errors");
6
+ const modelRouterWrites_1 = require("./modelRouterWrites");
6
7
  const orgPermissions_1 = require("./orgs/orgPermissions");
7
8
  const requestContext_1 = require("./requestContext");
8
9
  /**
@@ -142,10 +143,10 @@ const permissionMiddleware = (model, options) => {
142
143
  // All methods check for permissions.
143
144
  const methodPermissions = options.permissions?.[method] ?? [];
144
145
  if (!(await (0, exports.checkPermissions)(method, methodPermissions, req.user))) {
145
- throw new errors_1.APIError({
146
- status: 405,
147
- title: `Access to ${method.toUpperCase()} on ${model.modelName} ` +
148
- `denied for ${req.user?.id}`,
146
+ throw (0, modelRouterWrites_1.methodPermissionDeniedError)({
147
+ method,
148
+ modelName: model.modelName,
149
+ userId: req.user?.id,
149
150
  });
150
151
  }
151
152
  if (method === "create" || method === "list") {
@@ -29,6 +29,7 @@ const createAccess = (options) => {
29
29
  });
30
30
  }
31
31
  const mergedStatements = (0, statements_1.mergeStatements)(options.statements);
32
+ const statementDescriptions = (0, statements_1.mergeStatementDescriptions)(options.statementDescriptions);
32
33
  const rbacRoleModel = (0, roleModel_1.createRbacRoleModel)(options.connection);
33
34
  const extraRoles = [...(options.defaultRoles ?? [])];
34
35
  if (options.organizations && !extraRoles.some((role) => role.name === "operator")) {
@@ -162,6 +163,7 @@ const createAccess = (options) => {
162
163
  permission: (0, middleware_1.createIsPermitted)({ can }),
163
164
  queryFilter,
164
165
  roles: roleManager,
166
+ statementDescriptions,
165
167
  statements: mergedStatements,
166
168
  userModel: options.userModel,
167
169
  };
@@ -21,6 +21,7 @@ const rbacRouter = ({ access, userModel, basePath = "/rbac", }) => {
21
21
  router.get("/statements", (0, auth_1.authenticateMiddleware)(), access.middleware({ rbac: ["read"] }), (0, api_1.asyncHandler)(async (_req, res) => {
22
22
  return res.json({
23
23
  data: {
24
+ statementDescriptions: access.statementDescriptions,
24
25
  statements: access.statements,
25
26
  },
26
27
  });
@@ -42,13 +42,24 @@ export type Statements = Record<string, readonly string[]>;
42
42
  export type PermissionSet = {
43
43
  [resource: string]: readonly string[];
44
44
  };
45
+ /** Optional human labels for permissions, keyed by resource then action. */
46
+ export interface StatementDescriptions {
47
+ [resource: string]: Record<string, string>;
48
+ }
45
49
  export declare const READ_ACTIONS: readonly ["read", "list", "view"];
46
50
  export declare const READ_ONLY_ROLE_PERMISSIONS: {
47
51
  readonly readOnly: true;
48
52
  };
49
53
  export type RolePermissionSpec = PermissionSet | "*" | typeof READ_ONLY_ROLE_PERMISSIONS;
50
54
  export declare const mergeStatements: <S extends Statements>(appStatements: S) => Statements & S;
51
- export declare const terrenoStatementDescriptions: Record<string, Record<string, string>>;
55
+ export declare const adminModelDescriptions: (noun: string) => Record<string, string>;
56
+ export declare const modelCrudDescriptions: (noun: string) => Record<string, string>;
57
+ export declare const terrenoStatementDescriptions: StatementDescriptions;
58
+ /**
59
+ * Framework labels, then the app's. An app label replaces the framework label for that
60
+ * action. A blank string is ignored, so it does not erase a framework label.
61
+ */
62
+ export declare const mergeStatementDescriptions: (appDescriptions?: StatementDescriptions) => StatementDescriptions;
52
63
  /** Add missing actions for selected resources without removing consumer-defined grants. */
53
64
  export declare const mergeMissingResourcePermissions: (existing: PermissionSet, defaults: PermissionSet, resources: readonly string[]) => PermissionSet;
54
65
  export declare const expandRolePermissions: (spec: RolePermissionSpec, statements: Statements, readActions: readonly string[]) => PermissionSet;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.expandRolePermissions = exports.mergeMissingResourcePermissions = exports.terrenoStatementDescriptions = exports.mergeStatements = exports.READ_ONLY_ROLE_PERMISSIONS = exports.READ_ACTIONS = exports.terrenoStatements = exports.ORGANIZATION_ACTIONS = exports.ADMIN_PAGE_PERMISSION = exports.ADMIN_PAGE_ACTION = exports.ADMIN_PAGE_RESOURCE = exports.OBSERVABILITY_RBAC_RESOURCES = exports.AI_EXPERIMENT_ACTIONS = exports.AI_REVIEW_ACTIONS = exports.AI_TRACE_ACTIONS = exports.AI_PROMPT_ACTIONS = exports.ADMIN_MODEL_ACCESS = void 0;
3
+ exports.expandRolePermissions = exports.mergeMissingResourcePermissions = exports.mergeStatementDescriptions = exports.terrenoStatementDescriptions = exports.modelCrudDescriptions = exports.adminModelDescriptions = exports.mergeStatements = exports.READ_ONLY_ROLE_PERMISSIONS = exports.READ_ACTIONS = exports.terrenoStatements = exports.ORGANIZATION_ACTIONS = exports.ADMIN_PAGE_PERMISSION = exports.ADMIN_PAGE_ACTION = exports.ADMIN_PAGE_RESOURCE = exports.OBSERVABILITY_RBAC_RESOURCES = exports.AI_EXPERIMENT_ACTIONS = exports.AI_REVIEW_ACTIONS = exports.AI_TRACE_ACTIONS = exports.AI_PROMPT_ACTIONS = exports.ADMIN_MODEL_ACCESS = void 0;
4
4
  const MODEL_CRUD = ["create", "list", "read", "update", "delete"];
5
5
  exports.ADMIN_MODEL_ACCESS = ["read", "write", "writeOwned"];
6
6
  exports.AI_PROMPT_ACTIONS = [
@@ -88,7 +88,34 @@ const mergeStatements = (appStatements) => {
88
88
  };
89
89
  };
90
90
  exports.mergeStatements = mergeStatements;
91
+ const adminModelDescriptions = (noun) => ({
92
+ read: `View ${noun} in the admin panel`,
93
+ write: `Create and update any ${noun} in the admin panel`,
94
+ writeOwned: `Create and update ${noun} you own in the admin panel`,
95
+ });
96
+ exports.adminModelDescriptions = adminModelDescriptions;
97
+ const modelCrudDescriptions = (noun) => ({
98
+ create: `Create ${noun}`,
99
+ delete: `Delete ${noun}`,
100
+ list: `List ${noun}`,
101
+ read: `View ${noun}`,
102
+ update: `Update ${noun}`,
103
+ });
104
+ exports.modelCrudDescriptions = modelCrudDescriptions;
91
105
  exports.terrenoStatementDescriptions = {
106
+ admin: {
107
+ access: "Open the admin panel",
108
+ jobs: "Open the jobs admin screen",
109
+ runScripts: "Run admin scripts",
110
+ viewBackgroundTasks: "View background tasks",
111
+ },
112
+ adminAnnouncement: (0, exports.adminModelDescriptions)("announcements"),
113
+ adminAnnouncementAcknowledgement: (0, exports.adminModelDescriptions)("announcement acknowledgements"),
114
+ adminAnnouncementClickEvent: (0, exports.adminModelDescriptions)("announcement click events"),
115
+ adminAnnouncementImpression: (0, exports.adminModelDescriptions)("announcement impressions"),
116
+ adminConsentForm: (0, exports.adminModelDescriptions)("consent forms"),
117
+ adminConsentResponse: (0, exports.adminModelDescriptions)("consent responses"),
118
+ adminFeatureFlag: (0, exports.adminModelDescriptions)("feature flags"),
92
119
  aiDataset: {
93
120
  create: "Create datasets",
94
121
  delete: "Delete datasets",
@@ -127,17 +154,78 @@ exports.terrenoStatementDescriptions = {
127
154
  list: "List traces and observability status",
128
155
  read: "View trace detail and run trace test helpers",
129
156
  },
157
+ announcement: (0, exports.modelCrudDescriptions)("announcements"),
158
+ announcementAcknowledgement: {
159
+ list: "List announcement acknowledgements",
160
+ read: "View announcement acknowledgements",
161
+ },
162
+ announcementImpression: {
163
+ list: "List announcement impressions",
164
+ read: "View announcement impressions",
165
+ },
166
+ configuration: {
167
+ read: "View configuration",
168
+ update: "Update configuration",
169
+ },
170
+ consentForm: (0, exports.modelCrudDescriptions)("consent forms"),
130
171
  consentResponse: {
131
172
  list: "List consent responses",
132
173
  read: "View consent responses",
133
174
  signOnBehalf: "Record, view, and void provisional consent signatures for other users",
134
175
  },
176
+ featureFlag: (0, exports.modelCrudDescriptions)("feature flags"),
177
+ organization: {
178
+ create: "Create organizations",
179
+ delete: "Delete organizations",
180
+ disable: "Disable an organization",
181
+ list: "List organizations",
182
+ manageMembers: "Add, update, and remove organization members",
183
+ read: "View an organization",
184
+ update: "Update an organization",
185
+ },
186
+ rbac: {
187
+ assignRoles: "Assign roles to users",
188
+ manageRoles: "Create and edit roles",
189
+ read: "View roles and the permission vocabulary",
190
+ },
135
191
  user: {
192
+ ...(0, exports.modelCrudDescriptions)("users"),
193
+ impersonate: "Sign in as another user",
136
194
  issueSignInLink: "Create a sign-in account for a legacy user and hand them a set-password link (AccountSecurityApp)",
137
195
  manageSecurity: "View any user's sign-in methods and run account recovery (AccountSecurityApp)",
196
+ setPassword: "Set another user's password",
138
197
  updateIdentity: "Change another user's email, disabled flag, email verification, or linked Better Auth and GitHub ids",
139
198
  },
140
199
  };
200
+ const copyStatementDescriptions = (target, source) => {
201
+ for (const [resource, actions] of Object.entries(source ?? {})) {
202
+ const next = { ...(target[resource] ?? {}) };
203
+ for (const [action, description] of Object.entries(actions ?? {})) {
204
+ if (typeof description !== "string") {
205
+ continue;
206
+ }
207
+ const trimmed = description.trim();
208
+ if (trimmed.length === 0) {
209
+ continue;
210
+ }
211
+ next[action] = trimmed;
212
+ }
213
+ if (Object.keys(next).length > 0) {
214
+ target[resource] = next;
215
+ }
216
+ }
217
+ };
218
+ /**
219
+ * Framework labels, then the app's. An app label replaces the framework label for that
220
+ * action. A blank string is ignored, so it does not erase a framework label.
221
+ */
222
+ const mergeStatementDescriptions = (appDescriptions) => {
223
+ const merged = {};
224
+ copyStatementDescriptions(merged, exports.terrenoStatementDescriptions);
225
+ copyStatementDescriptions(merged, appDescriptions);
226
+ return merged;
227
+ };
228
+ exports.mergeStatementDescriptions = mergeStatementDescriptions;
141
229
  /** Add missing actions for selected resources without removing consumer-defined grants. */
142
230
  const mergeMissingResourcePermissions = (existing, defaults, resources) => {
143
231
  const merged = { ...existing };
@@ -7,7 +7,7 @@ import type { User, UserModel } from "../auth";
7
7
  import type { PermissionMethod } from "../permissions";
8
8
  import type { RbacAuditWrite } from "./auditModel";
9
9
  import type { RbacRoleDocument, RoleDefinition } from "./roleModel";
10
- import type { PermissionSet, Statements } from "./statements";
10
+ import type { PermissionSet, StatementDescriptions, Statements } from "./statements";
11
11
  /**
12
12
  * Non-generic TerrenoAccess for runtime wiring (modelRouter, rbacRouter, TerrenoApp).
13
13
  * `queryFilter` / `fieldMask` take `resource: string` so a concrete
@@ -172,7 +172,12 @@ export interface AccessOptions<S extends Statements> {
172
172
  resolvePermissions?: (args: {
173
173
  user: User;
174
174
  }) => Promise<PermissionSet | null>;
175
- statementDescriptions?: Record<string, Record<string, string>>;
175
+ /**
176
+ * Optional labels for permissions (resource → action → description). Merged over
177
+ * `terrenoStatementDescriptions`; a blank string does not erase a framework label.
178
+ * Returned by `GET /rbac/statements`.
179
+ */
180
+ statementDescriptions?: StatementDescriptions;
176
181
  /**
177
182
  * Extra destinations for RoleManager audit records (e.g. a consuming-app audit log).
178
183
  * The built-in `RbacAudit` collection is still written unless `persistAudit` is false.
@@ -186,6 +191,8 @@ export interface AccessOptions<S extends Statements> {
186
191
  }
187
192
  export interface TerrenoAccess<S extends Statements> {
188
193
  readonly statements: S;
194
+ /** Labels for permissions, including framework defaults and `createAccess` overrides. */
195
+ readonly statementDescriptions: StatementDescriptions;
189
196
  readonly ac: ReturnType<typeof createAccessControl<S>>;
190
197
  can: (args: AccessCheckArgs<S>) => Promise<AccessResult>;
191
198
  /**
@@ -18,6 +18,9 @@ import type express from "express";
18
18
  import type { Document, Model } from "mongoose";
19
19
  import { type ModelRouterOptions } from "../api";
20
20
  import { type User } from "../auth";
21
+ import { loadDocOr404 } from "../docLoader";
22
+ /** Re-exported so `api.ts` can hand it to the bulk route without importing `docLoader` itself. */
23
+ export { loadDocOr404 };
21
24
  import { APIError, type APIErrorConstructor } from "../errors";
22
25
  /** A hydrated mongoose document joined with the router's base type. */
23
26
  export type ExecutorDoc<T> = Document<unknown, unknown, unknown> & T;
@@ -36,9 +39,9 @@ export interface ExecutorResult<T> {
36
39
  */
37
40
  cleanedBody?: Partial<T>;
38
41
  /**
39
- * C5 (FIX 6): present only when `executeUpdate` was called with
40
- * `skipPostHooks: true` — the pre-update document snapshot, needed to
41
- * run `postUpdate` later via `runPostUpdate`.
42
+ * C5 (FIX 6): present only when `executeUpdate` or `executeDelete` was called with
43
+ * `skipPostHooks: true` — the document snapshot from before the write, needed to run
44
+ * `postUpdate` later via `runPostUpdate` and for audit `before` snapshots.
42
45
  */
43
46
  prevDoc?: T;
44
47
  }
@@ -211,4 +214,3 @@ export declare const runPostDelete: <T>({ doc, options, request, }: {
211
214
  options: ModelRouterOptions<T>;
212
215
  request: express.Request;
213
216
  }) => Promise<void>;
214
- export {};
@@ -3,12 +3,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.runPostDelete = exports.executeDelete = exports.runPostUpdate = exports.executeUpdate = exports.runPostCreate = exports.executeCreate = exports.isVersionError = exports.isExecutorConflictError = exports.ExecutorConflictError = void 0;
6
+ exports.runPostDelete = exports.executeDelete = exports.runPostUpdate = exports.executeUpdate = exports.runPostCreate = exports.executeCreate = exports.isVersionError = exports.isExecutorConflictError = exports.ExecutorConflictError = exports.loadDocOr404 = void 0;
7
7
  const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
8
8
  const luxon_1 = require("luxon");
9
9
  const api_1 = require("../api");
10
10
  const auth_1 = require("../auth");
11
11
  const docLoader_1 = require("../docLoader");
12
+ Object.defineProperty(exports, "loadDocOr404", { enumerable: true, get: function () { return docLoader_1.loadDocOr404; } });
12
13
  const errors_1 = require("../errors");
13
14
  const permissions_1 = require("../permissions");
14
15
  const modelRouterAccess_1 = require("../rbac/modelRouterAccess");
@@ -630,6 +631,9 @@ const executeDelete = async ({ model, options, user, id, existingDoc, req, skipP
630
631
  });
631
632
  }
632
633
  }
634
+ // The caller that defers postDelete (bulk, sync) also needs the doc as it was before the
635
+ // tombstone, e.g. for the audit `before` snapshot.
636
+ const prevDoc = skipPostHooks ? (0, cloneDeep_1.default)(doc) : undefined;
633
637
  // Support .deleted from isDeleted plugin
634
638
  if (Object.keys(model.schema.paths).includes("deleted") &&
635
639
  model.schema.paths.deleted.instance === "Boolean") {
@@ -661,7 +665,7 @@ const executeDelete = async ({ model, options, user, id, existingDoc, req, skipP
661
665
  });
662
666
  }
663
667
  }
664
- return { doc };
668
+ return prevDoc ? { doc, prevDoc } : { doc };
665
669
  };
666
670
  exports.executeDelete = executeDelete;
667
671
  /** C5 (FIX 6): run `postDelete` outside the write/ledger-finalize window — see `runPostCreate`. */
package/package.json CHANGED
@@ -13,7 +13,7 @@
13
13
  "@modelcontextprotocol/node": "^2.1.2",
14
14
  "@modelcontextprotocol/server": "^2.0.0",
15
15
  "@sentry/bun": "^11.0.0",
16
- "@terreno/test": "58.0.5",
16
+ "@terreno/test": "58.1.0",
17
17
  "@thream/socketio-jwt": "^3.1.4",
18
18
  "@types/qs": "^6.14.0",
19
19
  "ajv": "8.20.0",
@@ -51,7 +51,7 @@
51
51
  "devDependencies": {
52
52
  "@biomejs/biome": "2.5.13",
53
53
  "@modelcontextprotocol/client": "^2.0.0",
54
- "@terreno/syncdb": "58.0.5",
54
+ "@terreno/syncdb": "58.1.0",
55
55
  "@types/bun": "^1.4.0",
56
56
  "@types/cors": "^2.8.17",
57
57
  "@types/express": "^5.0.6",
@@ -141,16 +141,16 @@
141
141
  "lint:unsafefix": "biome check --fix --unsafe ./src",
142
142
  "load": "bun src/sync/loadHarness.ts",
143
143
  "smoke": "bun e2e/smoke.ts",
144
- "test": "bun ../scripts/test-shards.ts -- --update-snapshots",
145
- "test:agent": "AGENT=1 bun ../scripts/test-shards.ts -- --only-failures",
144
+ "test": "bun ../scripts/test-shards.ts --isolated -- --update-snapshots",
145
+ "test:agent": "AGENT=1 bun ../scripts/test-shards.ts --isolated -- --only-failures",
146
146
  "test:cache:clean": "bun ./src/tests/mongoTestSetup.ts clean",
147
147
  "test:cache:setup": "bun ./src/tests/mongoTestSetup.ts setup",
148
148
  "test:cache:status": "bun ./src/tests/mongoTestSetup.ts status",
149
- "test:ci": "bun ../scripts/test-shards.ts",
149
+ "test:ci": "bun ../scripts/test-shards.ts --isolated --",
150
150
  "test:coverage": "bun run ../scripts/check-coverage.ts",
151
151
  "typecheck": "tsc -p tsconfig.typecheck.json",
152
152
  "updateSnapshot": "bun test --update-snapshots"
153
153
  },
154
154
  "types": "dist/index.d.ts",
155
- "version": "58.0.5"
155
+ "version": "58.1.0"
156
156
  }
package/src/actions.ts CHANGED
@@ -32,6 +32,12 @@ export interface ActionMCPConfig {
32
32
  name: string;
33
33
  /** Tool description shown to the model. Defaults to the action's description or summary. */
34
34
  description?: string;
35
+ /**
36
+ * OAuth scope a token must hold to see and call this tool. Only enforced when
37
+ * `mcpOAuth.grants` is set. Without it, a GET action is a `read` tool and any other a `write`
38
+ * tool.
39
+ */
40
+ scope?: string;
35
41
  }
36
42
 
37
43
  // MCP tool names: letters, digits, underscore, dot, and hyphen, up to 64 characters.