@terreno/api 57.16.2 → 57.18.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.
- package/dist/actions.d.ts +26 -3
- package/dist/actions.js +102 -16
- package/dist/api.d.ts +7 -0
- package/dist/api.js +59 -3
- package/dist/auth.d.ts +28 -4
- package/dist/auth.js +140 -15
- package/dist/authRecovery.d.ts +31 -0
- package/dist/authRecovery.js +86 -6
- package/dist/betterAuth.d.ts +86 -0
- package/dist/betterAuthApp.d.ts +17 -0
- package/dist/betterAuthApp.js +12 -1
- package/dist/betterAuthOAuthHandoff.d.ts +24 -0
- package/dist/betterAuthOAuthHandoff.js +305 -0
- package/dist/betterAuthSetup.d.ts +37 -2
- package/dist/betterAuthSetup.js +304 -24
- package/dist/expressServer.d.ts +16 -0
- package/dist/expressServer.js +61 -14
- package/dist/githubAuth.d.ts +9 -0
- package/dist/githubAuth.js +230 -31
- package/dist/index.d.ts +9 -1
- package/dist/index.js +27 -3
- package/dist/mcp/actionTools.d.ts +4 -0
- package/dist/mcp/actionTools.js +158 -0
- package/dist/mcp/auth.d.ts +30 -0
- package/dist/mcp/auth.js +83 -28
- package/dist/mcp/createMCPRequest.d.ts +5 -1
- package/dist/mcp/createMCPRequest.js +3 -3
- package/dist/mcp/handlers.d.ts +3 -0
- package/dist/mcp/handlers.js +43 -27
- package/dist/mcp/oauth.d.ts +14 -0
- package/dist/mcp/oauth.js +618 -0
- package/dist/mcp/oauthMetadata.d.ts +89 -0
- package/dist/mcp/oauthMetadata.js +137 -0
- package/dist/mcp/registry.d.ts +5 -0
- package/dist/mcp/registry.js +9 -1
- package/dist/mcp/server.d.ts +6 -0
- package/dist/mcp/server.js +44 -7
- package/dist/mcp/serviceTokens.js +12 -2
- package/dist/mcp/toolExecution.d.ts +12 -0
- package/dist/mcp/toolExecution.js +60 -0
- package/dist/mcp/toolGenerator.d.ts +4 -1
- package/dist/mcp/toolGenerator.js +26 -60
- package/dist/mcp/types.d.ts +4 -4
- package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
- package/dist/models/mcpOAuthAuthorization.js +86 -0
- package/dist/models/mcpOAuthClient.d.ts +2 -0
- package/dist/models/mcpOAuthClient.js +42 -0
- package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
- package/dist/models/mcpOAuthRevokedFamily.js +36 -0
- package/dist/models/mcpOAuthToken.d.ts +12 -0
- package/dist/models/mcpOAuthToken.js +159 -0
- package/dist/models/mcpServiceToken.d.ts +1 -0
- package/dist/models/mcpServiceToken.js +21 -4
- package/dist/permissions.d.ts +7 -0
- package/dist/permissions.js +18 -1
- package/dist/rateLimit/policies.d.ts +4 -0
- package/dist/rateLimit/policies.js +46 -7
- package/dist/rbac/access.js +1 -0
- package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
- package/dist/rbac/membershipOrgAdminSource.js +5 -0
- package/dist/rbac/modelRouterAccess.d.ts +7 -1
- package/dist/rbac/modelRouterAccess.js +37 -24
- package/dist/rbac/realtimeAccess.js +17 -3
- package/dist/rbac/resolve.js +66 -9
- package/dist/rbac/roleManager.js +60 -5
- package/dist/rbac/roleModel.js +1 -1
- package/dist/rbac/statements.d.ts +1 -1
- package/dist/rbac/statements.js +13 -1
- package/dist/rbac/types.d.ts +12 -0
- package/dist/rbac/userWriteGuards.d.ts +50 -0
- package/dist/rbac/userWriteGuards.js +156 -0
- package/dist/realtime/changeStreamWatcher.d.ts +4 -1
- package/dist/realtime/changeStreamWatcher.js +157 -73
- package/dist/realtime/queryMatcher.d.ts +3 -0
- package/dist/realtime/queryMatcher.js +25 -10
- package/dist/realtime/realtimeApp.d.ts +16 -1
- package/dist/realtime/realtimeApp.js +76 -8
- package/dist/realtime/socketAuth.d.ts +17 -6
- package/dist/realtime/socketAuth.js +77 -16
- package/dist/realtime/types.d.ts +8 -5
- package/dist/requestContext.d.ts +22 -0
- package/dist/requestContext.js +22 -1
- package/dist/seedRunner.js +3 -1
- package/dist/sortFields.d.ts +33 -0
- package/dist/sortFields.js +55 -0
- package/dist/sync/executors.js +140 -2
- package/dist/sync/models.d.ts +2 -0
- package/dist/sync/models.js +5 -0
- package/dist/sync/mutationHandler.js +70 -7
- package/dist/sync/routes.js +4 -2
- package/dist/sync/syncSeqPlugin.js +6 -5
- package/dist/terrenoApp.d.ts +14 -0
- package/dist/terrenoApp.js +21 -6
- package/dist/types/mcpOAuth.d.ts +101 -0
- package/dist/types/mcpOAuth.js +2 -0
- package/dist/types/mcpServiceToken.d.ts +8 -0
- package/package.json +3 -3
- package/src/actions.test.ts +118 -0
- package/src/actions.ts +139 -17
- package/src/api.arrayOperations.test.ts +78 -0
- package/src/api.test.ts +36 -0
- package/src/api.ts +76 -4
- package/src/auth.test.ts +521 -3
- package/src/auth.ts +171 -17
- package/src/authRecovery.test.ts +99 -0
- package/src/authRecovery.ts +117 -5
- package/src/authVerification.test.ts +3 -3
- package/src/betterAuth.ts +104 -1
- package/src/betterAuthApp.test.ts +634 -1
- package/src/betterAuthApp.ts +28 -0
- package/src/betterAuthOAuthHandoff.test.ts +946 -0
- package/src/betterAuthOAuthHandoff.ts +375 -0
- package/src/betterAuthSetup.test.ts +393 -4
- package/src/betterAuthSetup.ts +402 -29
- package/src/expressServer.test.ts +93 -0
- package/src/expressServer.ts +81 -14
- package/src/githubAuth.test.ts +448 -6
- package/src/githubAuth.ts +276 -34
- package/src/index.ts +35 -1
- package/src/mcp/actionTools.test.ts +498 -0
- package/src/mcp/actionTools.ts +220 -0
- package/src/mcp/auth.test.ts +114 -1
- package/src/mcp/auth.ts +122 -35
- package/src/mcp/createMCPRequest.ts +8 -2
- package/src/mcp/handlers.test.ts +27 -0
- package/src/mcp/handlers.ts +21 -6
- package/src/mcp/oauth.test.ts +1026 -0
- package/src/mcp/oauth.ts +798 -0
- package/src/mcp/oauthMetadata.ts +234 -0
- package/src/mcp/registry.ts +11 -0
- package/src/mcp/server.ts +54 -14
- package/src/mcp/serviceTokens.ts +16 -3
- package/src/mcp/toolExecution.ts +67 -0
- package/src/mcp/toolGenerator.ts +27 -83
- package/src/mcp/types.ts +4 -4
- package/src/models/mcpOAuthAuthorization.ts +97 -0
- package/src/models/mcpOAuthClient.ts +49 -0
- package/src/models/mcpOAuthRevokedFamily.ts +47 -0
- package/src/models/mcpOAuthToken.test.ts +82 -0
- package/src/models/mcpOAuthToken.ts +195 -0
- package/src/models/mcpServiceToken.ts +26 -2
- package/src/permissions.ts +17 -0
- package/src/rateLimit/policies.ts +54 -10
- package/src/rateLimit/rateLimit.test.ts +41 -0
- package/src/rbac/access.ts +1 -0
- package/src/rbac/membershipOrgAdminSource.ts +5 -0
- package/src/rbac/modelRouterAccess.ts +40 -23
- package/src/rbac/realtimeAccess.test.ts +43 -0
- package/src/rbac/realtimeAccess.ts +23 -3
- package/src/rbac/resolve.test.ts +179 -1
- package/src/rbac/resolve.ts +78 -9
- package/src/rbac/roleManager.test.ts +132 -0
- package/src/rbac/roleManager.ts +69 -5
- package/src/rbac/roleModel.ts +1 -1
- package/src/rbac/statements.ts +14 -1
- package/src/rbac/types.ts +12 -0
- package/src/rbac/userWriteGuards.test.ts +407 -0
- package/src/rbac/userWriteGuards.ts +185 -0
- package/src/realtime/changeStreamWatcher.ts +203 -75
- package/src/realtime/queryMatcher.ts +30 -13
- package/src/realtime/realtime.test.ts +132 -0
- package/src/realtime/realtimeApp.ts +94 -10
- package/src/realtime/realtimeAppSetup.test.ts +282 -1
- package/src/realtime/socketAuth.test.ts +140 -8
- package/src/realtime/socketAuth.ts +90 -19
- package/src/realtime/types.ts +8 -5
- package/src/requestContext.ts +52 -1
- package/src/requestCredential.test.ts +89 -0
- package/src/seedRunner.test.ts +21 -0
- package/src/seedRunner.ts +3 -1
- package/src/sortFields.ts +69 -0
- package/src/sync/executors.test.ts +382 -3
- package/src/sync/executors.ts +179 -4
- package/src/sync/models.ts +8 -0
- package/src/sync/mutationHandler.test.ts +166 -2
- package/src/sync/mutationHandler.ts +97 -5
- package/src/sync/routes.ts +4 -2
- package/src/sync/syncFrontier.test.ts +11 -0
- package/src/sync/syncPhaseC.test.ts +18 -0
- package/src/sync/syncSeqPlugin.ts +6 -5
- package/src/sync/syncSocket.test.ts +92 -0
- package/src/terrenoApp.ts +36 -21
- package/src/types/mcpOAuth.ts +129 -0
- package/src/types/mcpServiceToken.ts +6 -1
package/dist/actions.d.ts
CHANGED
|
@@ -15,7 +15,14 @@ export interface ActionContext<TDoc, TBody, TQuery> {
|
|
|
15
15
|
query: TQuery;
|
|
16
16
|
doc: TDoc;
|
|
17
17
|
}
|
|
18
|
-
|
|
18
|
+
/** Exposes an action as an MCP tool on `/mcp`. */
|
|
19
|
+
export interface ActionMCPConfig {
|
|
20
|
+
/** MCP tool name, unique across every tool the app exposes (e.g. `todos_bulk_complete`). */
|
|
21
|
+
name: string;
|
|
22
|
+
/** Tool description shown to the model. Defaults to the action's description or summary. */
|
|
23
|
+
description?: string;
|
|
24
|
+
}
|
|
25
|
+
export interface BaseActionConfig<TBody, TQuery, TResponse> {
|
|
19
26
|
method: "GET" | "POST";
|
|
20
27
|
allowAnonymous?: boolean;
|
|
21
28
|
permissions?: PermissionMethod<unknown>[];
|
|
@@ -30,6 +37,21 @@ interface BaseActionConfig<TBody, TQuery, TResponse> {
|
|
|
30
37
|
description?: string;
|
|
31
38
|
tag?: string;
|
|
32
39
|
status?: number;
|
|
40
|
+
/**
|
|
41
|
+
* Also register the action as an MCP tool. The tool runs the same permission chain
|
|
42
|
+
* (including RBAC `access`) and the same zod validation as REST. Its input is `{id, ...body}`
|
|
43
|
+
* for an instance POST action, `{id, ...query}` for an instance GET action, and the body or
|
|
44
|
+
* query alone for a collection action. The handler gets an MCP request
|
|
45
|
+
* (`req.isMCPRequest === true`) and a `res` that throws if touched, so actions that write to
|
|
46
|
+
* `res` directly cannot opt in.
|
|
47
|
+
*/
|
|
48
|
+
mcp?: ActionMCPConfig;
|
|
49
|
+
/**
|
|
50
|
+
* REST only. Send the handler's return value as the response body (with `status`) instead
|
|
51
|
+
* of wrapping it as `{data: …}`. Use it to keep an existing route's response contract when
|
|
52
|
+
* converting it to an action. An `undefined` return sends an empty body.
|
|
53
|
+
*/
|
|
54
|
+
unwrapResponse?: boolean;
|
|
33
55
|
}
|
|
34
56
|
export interface InstanceActionConfig<TDoc, TBody, TQuery, TResponse> extends BaseActionConfig<TBody, TQuery, TResponse> {
|
|
35
57
|
handler: (ctx: ActionContext<TDoc, TBody, TQuery>) => TResponse | Promise<TResponse>;
|
|
@@ -39,7 +61,7 @@ export interface CollectionActionConfig<TBody, TQuery, TResponse> extends BaseAc
|
|
|
39
61
|
}
|
|
40
62
|
export declare const defineInstanceAction: <TDoc, TBody = unknown, TQuery = unknown, TResponse = unknown>(config: InstanceActionConfig<TDoc, TBody, TQuery, TResponse>) => InstanceActionConfig<TDoc, TBody, TQuery, TResponse>;
|
|
41
63
|
export declare const defineCollectionAction: <TBody = unknown, TQuery = unknown, TResponse = unknown>(config: CollectionActionConfig<TBody, TQuery, TResponse>) => CollectionActionConfig<TBody, TQuery, TResponse>;
|
|
42
|
-
type ActionScope = "instance" | "collection";
|
|
64
|
+
export type ActionScope = "instance" | "collection";
|
|
43
65
|
export declare const runActionPermissions: <T>(action: BaseActionConfig<unknown, unknown, unknown>, scope: ActionScope, model: Model<T>, req: Request, doc?: T, accessControl?: AnyTerrenoAccess, routerAccess?: ModelRouterAccessOptions) => Promise<void>;
|
|
44
66
|
export declare const validateActionRequest: <TBody, TQuery>({ action, req, }: {
|
|
45
67
|
action: BaseActionConfig<TBody, TQuery, unknown>;
|
|
@@ -57,5 +79,6 @@ export declare const createActionOpenApiMiddleware: <T>({ action, scope, actionN
|
|
|
57
79
|
options: Partial<ModelRouterOptions<T>>;
|
|
58
80
|
}) => express.RequestHandler;
|
|
59
81
|
export declare const assertNoActionCollisions: <T>(model: Model<T>, options: Pick<ModelRouterOptions<T>, "instanceActions" | "collectionActions">) => void;
|
|
82
|
+
/** True when any instance or collection action opts into MCP with `mcp`. */
|
|
83
|
+
export declare const hasMCPActions: <T>(options: Pick<ModelRouterOptions<T>, "instanceActions" | "collectionActions">) => boolean;
|
|
60
84
|
export declare const registerActionRoutes: <T>(router: express.Router, model: Model<T>, options: Partial<ModelRouterOptions<T>>) => void;
|
|
61
|
-
export {};
|
package/dist/actions.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.registerActionRoutes = exports.assertNoActionCollisions = exports.createActionOpenApiMiddleware = exports.wrapActionResponse = exports.validateActionRequest = exports.runActionPermissions = exports.defineCollectionAction = exports.defineInstanceAction = exports.ACTION_NAME_PATTERN = void 0;
|
|
3
|
+
exports.registerActionRoutes = exports.hasMCPActions = exports.assertNoActionCollisions = exports.createActionOpenApiMiddleware = exports.wrapActionResponse = exports.validateActionRequest = exports.runActionPermissions = exports.defineCollectionAction = exports.defineInstanceAction = exports.ACTION_NAME_PATTERN = void 0;
|
|
4
4
|
const zod_to_openapi_1 = require("@asteasolutions/zod-to-openapi");
|
|
5
5
|
const api_1 = require("./api");
|
|
6
6
|
const auth_1 = require("./auth");
|
|
@@ -9,8 +9,12 @@ const errors_1 = require("./errors");
|
|
|
9
9
|
const openApi_1 = require("./openApi");
|
|
10
10
|
const permissions_1 = require("./permissions");
|
|
11
11
|
const middleware_1 = require("./rbac/middleware");
|
|
12
|
+
const modelRouterAccess_1 = require("./rbac/modelRouterAccess");
|
|
13
|
+
const userWriteGuards_1 = require("./rbac/userWriteGuards");
|
|
12
14
|
// At least two characters: leading letter plus one or more alphanumeric/_/- chars.
|
|
13
15
|
exports.ACTION_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]+$/;
|
|
16
|
+
// MCP tool names: letters, digits, underscore, dot, and hyphen, up to 64 characters.
|
|
17
|
+
const MCP_TOOL_NAME_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
14
18
|
const defineInstanceAction = (config) => {
|
|
15
19
|
return config;
|
|
16
20
|
};
|
|
@@ -51,7 +55,17 @@ const runActionPermissions = async (action, scope, model, req, doc, accessContro
|
|
|
51
55
|
const rbacCheck = isPermitted({
|
|
52
56
|
[rbacAccess.resource]: [rbacAccess.action],
|
|
53
57
|
});
|
|
54
|
-
|
|
58
|
+
// Same resource as the router: its per-document `access.scope` and `access.also` apply to
|
|
59
|
+
// the action exactly as they do to the mapped CRUD method.
|
|
60
|
+
const routerChecks = [];
|
|
61
|
+
if (routerAccess && routerAccess.resource === rbacAccess.resource) {
|
|
62
|
+
const scopeCheck = (0, modelRouterAccess_1.buildAccessScopeCheck)(accessControl, routerAccess, rbacAccess.action);
|
|
63
|
+
if (scopeCheck) {
|
|
64
|
+
routerChecks.push(scopeCheck);
|
|
65
|
+
}
|
|
66
|
+
routerChecks.push(...(routerAccess.also?.[method] ?? []));
|
|
67
|
+
}
|
|
68
|
+
permissions = [...(action.permissions ?? []), rbacCheck, ...routerChecks];
|
|
55
69
|
}
|
|
56
70
|
if (!permissions) {
|
|
57
71
|
throw new errors_1.APIError({ status: 500, title: "Action missing permissions configuration" });
|
|
@@ -129,7 +143,16 @@ const wrapActionResponse = (handlerResult, action, res) => {
|
|
|
129
143
|
if (res.headersSent) {
|
|
130
144
|
return;
|
|
131
145
|
}
|
|
132
|
-
|
|
146
|
+
const status = action.status ?? 200;
|
|
147
|
+
if (!action.unwrapResponse) {
|
|
148
|
+
res.status(status).json({ data: handlerResult ?? null });
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (handlerResult === undefined) {
|
|
152
|
+
res.status(status).end();
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
res.status(status).json(handlerResult);
|
|
133
156
|
};
|
|
134
157
|
exports.wrapActionResponse = wrapActionResponse;
|
|
135
158
|
let inlineOpenApiSchemaCounter = 0;
|
|
@@ -185,20 +208,24 @@ const createActionOpenApiMiddleware = ({ action, scope, actionName, model, optio
|
|
|
185
208
|
[statusCode]: {
|
|
186
209
|
content: {
|
|
187
210
|
"application/json": {
|
|
188
|
-
schema: action.
|
|
189
|
-
?
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
211
|
+
schema: action.unwrapResponse
|
|
212
|
+
? action.response
|
|
213
|
+
? zodToJsonSchema(action.response)
|
|
214
|
+
: { type: "object" }
|
|
215
|
+
: action.response
|
|
216
|
+
? {
|
|
217
|
+
properties: {
|
|
218
|
+
data: zodToJsonSchema(action.response),
|
|
219
|
+
},
|
|
220
|
+
required: ["data"],
|
|
221
|
+
type: "object",
|
|
222
|
+
}
|
|
223
|
+
: {
|
|
224
|
+
properties: {
|
|
225
|
+
data: { type: "object" },
|
|
226
|
+
},
|
|
227
|
+
type: "object",
|
|
199
228
|
},
|
|
200
|
-
type: "object",
|
|
201
|
-
},
|
|
202
229
|
},
|
|
203
230
|
},
|
|
204
231
|
description: "Successful response",
|
|
@@ -253,6 +280,41 @@ const validateActionConfig = (scope, name, config) => {
|
|
|
253
280
|
title: `Action "${name}" (${scope}) only supports GET and POST methods`,
|
|
254
281
|
});
|
|
255
282
|
}
|
|
283
|
+
if (config.mcp) {
|
|
284
|
+
validateActionMCPConfig(scope, name, config);
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
const zodObjectShape = (schema) => {
|
|
288
|
+
const def = schema.def;
|
|
289
|
+
return def?.type === "object" ? def.shape : undefined;
|
|
290
|
+
};
|
|
291
|
+
/** The MCP tool's arguments are one object, so the action's input schema must be an object. */
|
|
292
|
+
const validateActionMCPConfig = (scope, name, config) => {
|
|
293
|
+
const mcpName = config.mcp?.name;
|
|
294
|
+
if (!mcpName || !MCP_TOOL_NAME_PATTERN.test(mcpName)) {
|
|
295
|
+
throw new errors_1.APIError({
|
|
296
|
+
status: 500,
|
|
297
|
+
title: `Action "${name}" (${scope}) has an invalid mcp.name "${mcpName ?? ""}". MCP tool names must match ${MCP_TOOL_NAME_PATTERN.toString()}`,
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
const inputField = config.method === "GET" ? "query" : "body";
|
|
301
|
+
const inputSchema = config.method === "GET" ? config.query : config.body;
|
|
302
|
+
if (!inputSchema) {
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
const shape = zodObjectShape(inputSchema);
|
|
306
|
+
if (!shape) {
|
|
307
|
+
throw new errors_1.APIError({
|
|
308
|
+
status: 500,
|
|
309
|
+
title: `Action "${name}" (${scope}) sets mcp, so its ${inputField} schema must be a z.object()`,
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
if (scope === "instance" && "id" in shape) {
|
|
313
|
+
throw new errors_1.APIError({
|
|
314
|
+
status: 500,
|
|
315
|
+
title: `Action "${name}" (instance) sets mcp, so its ${inputField} schema cannot define "id"; the MCP tool uses id for the document`,
|
|
316
|
+
});
|
|
317
|
+
}
|
|
256
318
|
};
|
|
257
319
|
const assertNoActionCollisions = (model, options) => {
|
|
258
320
|
const arrayFields = new Set(getArrayFieldNames(model));
|
|
@@ -293,6 +355,22 @@ const buildActionMiddleware = (model, options, registered) => {
|
|
|
293
355
|
const doc = await (0, docLoader_1.loadDocOr404)(model, req.params.id, options.populatePaths);
|
|
294
356
|
req.obj = doc;
|
|
295
357
|
await (0, exports.runActionPermissions)(action, scope, model, req, doc, options.accessControl, options.access);
|
|
358
|
+
// A write action on a user record is a write to that user.
|
|
359
|
+
if (action.method !== "GET") {
|
|
360
|
+
await (0, userWriteGuards_1.assertCanWriteTargetUser)({
|
|
361
|
+
accessControl: options.accessControl,
|
|
362
|
+
actor: req.user,
|
|
363
|
+
modelName: model.modelName,
|
|
364
|
+
target: doc,
|
|
365
|
+
});
|
|
366
|
+
await (0, userWriteGuards_1.assertCanWriteUserIdentity)({
|
|
367
|
+
accessControl: options.accessControl,
|
|
368
|
+
actor: req.user,
|
|
369
|
+
body: req.body,
|
|
370
|
+
modelName: model.modelName,
|
|
371
|
+
target: doc,
|
|
372
|
+
});
|
|
373
|
+
}
|
|
296
374
|
return next();
|
|
297
375
|
}
|
|
298
376
|
catch (error) {
|
|
@@ -327,6 +405,14 @@ const buildActionMiddleware = (model, options, registered) => {
|
|
|
327
405
|
chain.push(validateAndRun);
|
|
328
406
|
return chain;
|
|
329
407
|
};
|
|
408
|
+
/** True when any instance or collection action opts into MCP with `mcp`. */
|
|
409
|
+
const hasMCPActions = (options) => {
|
|
410
|
+
return [
|
|
411
|
+
...Object.values(options.instanceActions ?? {}),
|
|
412
|
+
...Object.values(options.collectionActions ?? {}),
|
|
413
|
+
].some((config) => Boolean(config.mcp));
|
|
414
|
+
};
|
|
415
|
+
exports.hasMCPActions = hasMCPActions;
|
|
330
416
|
const registerActionRoutes = (router, model, options) => {
|
|
331
417
|
const instanceActions = options.instanceActions ?? {};
|
|
332
418
|
const collectionActions = options.collectionActions ?? {};
|
package/dist/api.d.ts
CHANGED
|
@@ -116,6 +116,13 @@ export interface ModelRouterOptions<T> {
|
|
|
116
116
|
sort?: string | {
|
|
117
117
|
[key: string]: "ascending" | "descending";
|
|
118
118
|
};
|
|
119
|
+
/**
|
|
120
|
+
* Extra fields that list requests may sort by. A client `sort` may name only fields in
|
|
121
|
+
* `queryFields`, fields named in `sort`, and fields listed here; any other field returns
|
|
122
|
+
* 400 `sort-field-not-allowed`. Do not list fields that some readers cannot see (RBAC
|
|
123
|
+
* field views, responseHandler stripping): sort order reveals their values.
|
|
124
|
+
*/
|
|
125
|
+
sortFields?: string[];
|
|
119
126
|
/**
|
|
120
127
|
* Default queries to provide to Mongo before any user queries or transforms happen when making
|
|
121
128
|
* list queries. Accepts any Mongoose-style queries, and runs for all user types.
|
package/dist/api.js
CHANGED
|
@@ -60,7 +60,9 @@ const openApi_1 = require("./openApi");
|
|
|
60
60
|
const openApiValidator_1 = require("./openApiValidator");
|
|
61
61
|
const permissions_1 = require("./permissions");
|
|
62
62
|
const modelRouterAccess_1 = require("./rbac/modelRouterAccess");
|
|
63
|
+
const userWriteGuards_1 = require("./rbac/userWriteGuards");
|
|
63
64
|
const deprecation_1 = require("./realtime/deprecation");
|
|
65
|
+
const sortFields_1 = require("./sortFields");
|
|
64
66
|
const executors_1 = require("./sync/executors");
|
|
65
67
|
const transformers_1 = require("./transformers");
|
|
66
68
|
const utils_1 = require("./utils");
|
|
@@ -183,6 +185,33 @@ const checkQueryParamAllowed = (queryParam, queryParamValue, queryFields = [], m
|
|
|
183
185
|
});
|
|
184
186
|
}
|
|
185
187
|
};
|
|
188
|
+
// Sorting by a field discloses its order even when responses hide it, so list sorts are
|
|
189
|
+
// limited to fields the router declares sortable (queryFields, options.sort, sortFields).
|
|
190
|
+
const checkListSortAllowed = (sort, options, modelName) => {
|
|
191
|
+
const allowed = (0, sortFields_1.getAllowedSortFields)(options);
|
|
192
|
+
const result = (0, sortFields_1.checkSortFields)(sort, allowed);
|
|
193
|
+
if (result.allowed) {
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (result.error === "invalid-sort") {
|
|
197
|
+
throw new errors_1.BadRequestError({
|
|
198
|
+
code: "invalid-sort",
|
|
199
|
+
detail: "sort must be a space-separated list of fields, each optionally prefixed with -.",
|
|
200
|
+
source: { parameter: "sort" },
|
|
201
|
+
title: "Invalid sort",
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
const allowedList = allowed.length > 0 ? allowed.join(", ") : "(none)";
|
|
205
|
+
throw new errors_1.BadRequestError({
|
|
206
|
+
code: "sort-field-not-allowed",
|
|
207
|
+
detail: `${result.field} is not allowed as a sort field. ` +
|
|
208
|
+
`Add "${result.field}" to sortFields or queryFields on the ${modelName} modelRouter ` +
|
|
209
|
+
`to sort on it. Allowed: ${allowedList}.`,
|
|
210
|
+
meta: { allowedSortFields: allowed, model: modelName, sortField: result.field },
|
|
211
|
+
source: { parameter: "sort" },
|
|
212
|
+
title: "Sort field not allowed",
|
|
213
|
+
});
|
|
214
|
+
};
|
|
186
215
|
// Handles dot notation patches, creates a normal object to be used for updates.
|
|
187
216
|
// function flattenDotNotationPatch(data: any) {
|
|
188
217
|
// const result = {};
|
|
@@ -277,6 +306,9 @@ function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
|
|
|
277
306
|
if (options.mcp && path === undefined) {
|
|
278
307
|
(0, registry_1.registerMCPModel)(model, options.mcp, options);
|
|
279
308
|
}
|
|
309
|
+
else if (path === undefined && (0, actions_1.hasMCPActions)(options)) {
|
|
310
|
+
(0, registry_1.registerMCPActionModel)(model, options);
|
|
311
|
+
}
|
|
280
312
|
const shouldDeferBuild = path !== undefined && Boolean(options.access) && !options.accessControl;
|
|
281
313
|
if (path !== undefined) {
|
|
282
314
|
if (options.realtime) {
|
|
@@ -336,7 +368,8 @@ const _buildModelRouter = (model, options, routePath) => {
|
|
|
336
368
|
if (routePath) {
|
|
337
369
|
(0, collectionRegistry_1.replaceCollectionOptions)(routePath, options);
|
|
338
370
|
}
|
|
339
|
-
|
|
371
|
+
// A routed router's catalog entry was replaced by routePath above; only pathless ones need this.
|
|
372
|
+
if (options.mcp || (!routePath && (0, actions_1.hasMCPActions)(options))) {
|
|
340
373
|
(0, registry_1.updateMCPRegistryOptions)(model.modelName, options);
|
|
341
374
|
}
|
|
342
375
|
(0, actions_1.assertNoActionCollisions)(model, options);
|
|
@@ -390,6 +423,9 @@ const _buildModelRouter = (model, options, routePath) => {
|
|
|
390
423
|
// Runs before query validation so a field missing from queryFields is always
|
|
391
424
|
// reported with this error, whatever the validator's settings.
|
|
392
425
|
(req, _res, next) => {
|
|
426
|
+
if (req.query.sort !== undefined) {
|
|
427
|
+
checkListSortAllowed(req.query.sort, options, model.modelName);
|
|
428
|
+
}
|
|
393
429
|
for (const queryParam of Object.keys(req.query)) {
|
|
394
430
|
if (PAGINATION_QUERY_PARAMS.includes(queryParam)) {
|
|
395
431
|
continue;
|
|
@@ -752,6 +788,12 @@ const _buildModelRouter = (model, options, routePath) => {
|
|
|
752
788
|
title: "Update not allowed",
|
|
753
789
|
});
|
|
754
790
|
}
|
|
791
|
+
await (0, userWriteGuards_1.assertCanWriteTargetUser)({
|
|
792
|
+
accessControl: options.accessControl,
|
|
793
|
+
actor: req.user,
|
|
794
|
+
modelName: model.modelName,
|
|
795
|
+
target: doc,
|
|
796
|
+
});
|
|
755
797
|
const field = req.params.field;
|
|
756
798
|
const itemId = req.params.itemId;
|
|
757
799
|
// We apply the operation *before* the hooks. As far as the callers are concerned, this should
|
|
@@ -796,9 +838,16 @@ const _buildModelRouter = (model, options, routePath) => {
|
|
|
796
838
|
});
|
|
797
839
|
}
|
|
798
840
|
// For PATCHing an item by ID, we need to merge the objects so we don't override the _id or
|
|
799
|
-
// other parts of the subdocument.
|
|
841
|
+
// other parts of the subdocument. Merge into a detached copy: the array elements are the
|
|
842
|
+
// loaded document's live subdocuments, and only the body that survives the hooks below
|
|
843
|
+
// may change the document.
|
|
800
844
|
if (operation === "PATCH" && (0, utils_1.isValidObjectId)(itemId)) {
|
|
801
|
-
|
|
845
|
+
const current = array[index];
|
|
846
|
+
const detached = typeof current.$clone === "function"
|
|
847
|
+
? current.$clone()
|
|
848
|
+
: { ...current };
|
|
849
|
+
Object.assign(detached, req.body[field]);
|
|
850
|
+
array[index] = detached;
|
|
802
851
|
}
|
|
803
852
|
else if (operation === "PATCH") {
|
|
804
853
|
// For PATCHing a string array, we can replace the whole object.
|
|
@@ -817,6 +866,13 @@ const _buildModelRouter = (model, options, routePath) => {
|
|
|
817
866
|
});
|
|
818
867
|
}
|
|
819
868
|
let body = await applyArrayOperationUpdateHooks({ [field]: array }, req);
|
|
869
|
+
await (0, userWriteGuards_1.assertCanWriteUserIdentity)({
|
|
870
|
+
accessControl: options.accessControl,
|
|
871
|
+
actor: req.user,
|
|
872
|
+
body,
|
|
873
|
+
modelName: model.modelName,
|
|
874
|
+
target: doc,
|
|
875
|
+
});
|
|
820
876
|
body = (0, auth_1.omitUserRolesFromWriteBody)(model.modelName, options.accessControl, body, req.terrenoAllowUserAdminWrite === true);
|
|
821
877
|
if (options.access && options.accessControl && body && typeof body === "object") {
|
|
822
878
|
await (0, modelRouterAccess_1.validateAccessWriteBody)({
|
package/dist/auth.d.ts
CHANGED
|
@@ -40,14 +40,32 @@ export declare const authenticateMiddleware: (anonymous?: boolean) => (req: expr
|
|
|
40
40
|
*/
|
|
41
41
|
export declare const PRIVILEGED_USER_FIELDS: readonly ["admin", "roles", "organizationIds", "emailVerified", "tokenEpoch"];
|
|
42
42
|
/**
|
|
43
|
-
*
|
|
44
|
-
*
|
|
43
|
+
* passport-local-mongoose password and lockout fields. Only the password flows (reset,
|
|
44
|
+
* `setPassword`-gated actions) write them, so RBAC user-model writes through modelRouter, sync,
|
|
45
|
+
* MCP, and the admin panel drop them along with {@link PRIVILEGED_USER_FIELDS}.
|
|
46
|
+
*/
|
|
47
|
+
export declare const USER_CREDENTIAL_FIELDS: readonly ["hash", "salt", "attempts", "last"];
|
|
48
|
+
/**
|
|
49
|
+
* Fields self-service requests (anonymous signup, `PATCH /me`) must never set: the
|
|
50
|
+
* {@link PRIVILEGED_USER_FIELDS} plus the fields that bind an external credential to the row
|
|
51
|
+
* (Better Auth id, GitHub link, OAuth provider), the passport-local-mongoose password and
|
|
52
|
+
* lockout state, and the disabled flag. Only the Better Auth sync, GitHub link, and password
|
|
53
|
+
* flows that own them write these. Kept apart from PRIVILEGED_USER_FIELDS so authorized admin
|
|
54
|
+
* User writes through modelRouter, sync, MCP, and the admin panel can still manage the identity
|
|
55
|
+
* and disabled fields (those writes still drop {@link USER_CREDENTIAL_FIELDS}).
|
|
56
|
+
*/
|
|
57
|
+
export declare const SELF_SERVICE_BLOCKED_USER_FIELDS: readonly ["admin", "roles", "organizationIds", "emailVerified", "tokenEpoch", "betterAuthId", "githubId", "githubUsername", "githubProfileUrl", "githubAvatarUrl", "oauthProvider", "hash", "salt", "attempts", "last", "disabled"];
|
|
58
|
+
/**
|
|
59
|
+
* Removes {@link SELF_SERVICE_BLOCKED_USER_FIELDS} from a self-service body, including dotted
|
|
60
|
+
* paths into them (`roles.0`). Fields are dropped rather than rejected so clients that echo a
|
|
61
|
+
* whole user object back still succeed.
|
|
45
62
|
*/
|
|
46
63
|
export declare const stripPrivilegedUserFields: (body: Record<string, unknown>, context: string) => Record<string, unknown>;
|
|
47
64
|
/**
|
|
48
65
|
* When RBAC is enabled, authority-bearing User fields must not flow through ordinary mongoose
|
|
49
66
|
* writes on `/users`, sync, or MCP. AdminApp captures role assignments before this runs and
|
|
50
|
-
* explicitly marks authorized legacy-admin writes after its additional checks.
|
|
67
|
+
* explicitly marks authorized legacy-admin writes after its additional checks. The user model is
|
|
68
|
+
* recognized by {@link isRbacUserModelName}.
|
|
51
69
|
*/
|
|
52
70
|
export declare const omitUserRolesFromWriteBody: (modelName: string, accessControl: unknown, body: unknown, allowAdminWrite?: boolean) => unknown;
|
|
53
71
|
export declare const signupUser: (userModel: UserModel, email: string, password: string, body?: Record<string, unknown>) => Promise<User & {
|
|
@@ -106,6 +124,12 @@ export declare const generateTokens: (user: unknown, authOptions?: AuthOptions,
|
|
|
106
124
|
sessionId: string;
|
|
107
125
|
token: string;
|
|
108
126
|
}>;
|
|
127
|
+
/**
|
|
128
|
+
* Whether an account has been disabled (`isDisabledPlugin`). Disabled users must not
|
|
129
|
+
* authenticate or receive new tokens on any path.
|
|
130
|
+
* @internal
|
|
131
|
+
*/
|
|
132
|
+
export declare const isUserDisabled: (user: unknown) => boolean;
|
|
109
133
|
export declare const setupAuth: (app: express.Application, userModel: UserModel) => void;
|
|
110
134
|
export declare const addAuthRoutes: (app: express.Application, userModel: UserModel, authOptions?: AuthOptions) => void;
|
|
111
|
-
export declare const addMeRoutes: (app: express.Application, userModel: UserModel,
|
|
135
|
+
export declare const addMeRoutes: (app: express.Application, userModel: UserModel, authOptions?: AuthOptions, accessControl?: import("./rbac/types").AnyTerrenoAccess) => void;
|