@terreno/api 57.21.0 → 58.0.0-beta.2
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/CHANGELOG.md +89 -0
- package/README.md +1 -1
- package/dist/api.d.ts +0 -13
- package/dist/api.js +0 -9
- package/dist/auth.d.ts +3 -2
- package/dist/auth.js +95 -5
- package/dist/authRecovery.d.ts +2 -1
- package/dist/authRecovery.js +35 -17
- package/dist/collectionRegistry.d.ts +3 -4
- package/dist/collectionRegistry.js +0 -1
- package/dist/consentApp.d.ts +1 -1
- package/dist/consentApp.js +58 -2
- package/dist/index.d.ts +4 -5
- package/dist/index.js +8 -20
- package/dist/mcp/adminTracking.js +1 -1
- package/dist/mcp/serviceTokens.d.ts +21 -1
- package/dist/mcp/serviceTokens.js +159 -183
- package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
- package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
- package/dist/models/mcpRequestLog.js +1 -1
- package/dist/models/mcpServiceToken.js +36 -4
- package/dist/openApiBuilder.d.ts +4 -0
- package/dist/openApiBuilder.js +2 -0
- package/dist/rbac/realtimeAccess.d.ts +5 -4
- package/dist/rbac/realtimeAccess.js +17 -64
- package/dist/realtime/changeStreamWatcher.d.ts +8 -63
- package/dist/realtime/changeStreamWatcher.js +32 -391
- package/dist/realtime/realtimeApp.d.ts +14 -27
- package/dist/realtime/realtimeApp.js +14 -220
- package/dist/realtime/types.d.ts +0 -64
- package/dist/sync/entityIds.d.ts +14 -0
- package/dist/sync/entityIds.js +17 -0
- package/dist/sync/executors.js +14 -2
- package/dist/sync/models.d.ts +1 -0
- package/dist/sync/models.js +4 -0
- package/dist/sync/mutationHandler.js +51 -2
- package/dist/sync/routes.js +12 -17
- package/dist/sync/socketHandlers.d.ts +1 -1
- package/dist/sync/socketHandlers.js +1 -1
- package/dist/sync/types.d.ts +8 -0
- package/dist/terrenoApp.d.ts +7 -5
- package/dist/terrenoApp.js +18 -14
- package/dist/tests/openApiResponseSchema.d.ts +39 -0
- package/dist/tests/openApiResponseSchema.js +56 -0
- package/dist/tests.d.ts +1 -0
- package/dist/tests.js +4 -1
- package/dist/types/mcpAdmin.d.ts +1 -1
- package/dist/types/mcpServiceToken.d.ts +7 -4
- package/dist/versionCheckPlugin.d.ts +1 -1
- package/dist/versionCheckPlugin.js +25 -2
- package/package.json +17 -6
- package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
- package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
- package/src/__tests__/openApiResponseSchema.test.ts +148 -0
- package/src/__tests__/versionCheckPlugin.test.ts +72 -0
- package/src/api.test.ts +9 -7
- package/src/api.ts +0 -24
- package/src/auth.ts +116 -5
- package/src/authOpenApi.test.ts +316 -0
- package/src/authRecovery.ts +47 -19
- package/src/betterAuthOAuthHandoff.test.ts +13 -5
- package/src/collectionRegistry.ts +3 -5
- package/src/consentApp.test.ts +98 -0
- package/src/consentApp.ts +67 -2
- package/src/index.ts +6 -28
- package/src/mcp/actionTools.test.ts +2 -2
- package/src/mcp/adminTracking.ts +1 -1
- package/src/mcp/auth.test.ts +7 -3
- package/src/mcp/oauth.test.ts +12 -12
- package/src/mcp/serviceTokens.sync.test.ts +230 -0
- package/src/mcp/serviceTokens.test.ts +112 -61
- package/src/mcp/serviceTokens.ts +193 -212
- package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
- package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
- package/src/models/mcpRequestLog.ts +1 -1
- package/src/models/mcpServiceToken.test.ts +52 -5
- package/src/models/mcpServiceToken.ts +51 -14
- package/src/openApiBuilder.test.ts +34 -1
- package/src/openApiBuilder.ts +5 -0
- package/src/rateLimit/rateLimit.test.ts +25 -10
- package/src/rbac/realtimeAccess.test.ts +20 -172
- package/src/rbac/realtimeAccess.ts +17 -82
- package/src/realtime/changeStreamWatcher.ts +43 -506
- package/src/realtime/realtime.test.ts +205 -2545
- package/src/realtime/realtimeApp.ts +16 -295
- package/src/realtime/types.ts +0 -72
- package/src/sync/entityIds.ts +18 -0
- package/src/sync/executors.test.ts +28 -0
- package/src/sync/executors.ts +23 -2
- package/src/sync/models.ts +6 -0
- package/src/sync/mutationHandler.test.ts +84 -0
- package/src/sync/mutationHandler.ts +57 -2
- package/src/sync/routes.ts +12 -17
- package/src/sync/socketHandlers.ts +1 -1
- package/src/sync/syncRoutes.test.ts +8 -4
- package/src/sync/syncSocket.test.ts +77 -113
- package/src/sync/types.ts +9 -0
- package/src/terrenoApp.mcpServiceTokens.test.ts +14 -6
- package/src/terrenoApp.ts +24 -18
- package/src/tests/openApiResponseSchema.ts +104 -0
- package/src/tests.ts +7 -0
- package/src/types/mcpAdmin.ts +1 -1
- package/src/types/mcpServiceToken.ts +7 -4
- package/src/versionCheckPlugin.ts +41 -2
- package/biome.jsonc +0 -22
- package/bunfig.toml +0 -10
- package/bunfig.unit.toml +0 -3
- package/dist/realtime/deprecation.d.ts +0 -13
- package/dist/realtime/deprecation.js +0 -31
- package/dist/realtime/queryStore.d.ts +0 -37
- package/dist/realtime/queryStore.js +0 -103
- package/dist/realtime/registry.d.ts +0 -15
- package/dist/realtime/registry.js +0 -52
- package/e2e/smoke.ts +0 -193
- package/src/realtime/deprecation.test.ts +0 -60
- package/src/realtime/deprecation.ts +0 -33
- package/src/realtime/queryStore.ts +0 -122
- package/src/realtime/registry.ts +0 -84
- package/tsconfig.json +0 -19
- package/tsconfig.typecheck.json +0 -14
- package/tsconfig.typedoc.json +0 -13
package/src/consentApp.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* endpoints for fetching pending consents and submitting responses.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import {type Application, Router} from "express";
|
|
9
|
+
import {type Application, type RequestHandler, Router} from "express";
|
|
10
10
|
import {DateTime} from "luxon";
|
|
11
11
|
import type mongoose from "mongoose";
|
|
12
12
|
import type {CollectionActionConfig} from "./actions";
|
|
@@ -27,8 +27,9 @@ import {APIError} from "./errors";
|
|
|
27
27
|
import {logger} from "./logger";
|
|
28
28
|
import {ConsentForm} from "./models/consentForm";
|
|
29
29
|
import {ConsentResponse} from "./models/consentResponse";
|
|
30
|
+
import {createOpenApiBuilder, type OpenApiSchemaProperty} from "./openApiBuilder";
|
|
30
31
|
import {type PermissionMethod, Permissions} from "./permissions";
|
|
31
|
-
import type
|
|
32
|
+
import {getOpenApiSpecForModel, type PopulatePath} from "./populate";
|
|
32
33
|
import type {AnyTerrenoAccess} from "./rbac/types";
|
|
33
34
|
import type {TerrenoPlugin} from "./terrenoPlugin";
|
|
34
35
|
import type {ConsentFormDocument} from "./types/consentForm";
|
|
@@ -52,6 +53,67 @@ export const consentResponsePopulatePaths: PopulatePath[] = [
|
|
|
52
53
|
},
|
|
53
54
|
];
|
|
54
55
|
|
|
56
|
+
/** A consent document as `toJSON` serializes it: model fields plus the `id` virtual. */
|
|
57
|
+
const consentDocumentOpenApiSchema = (model: mongoose.Model<unknown>): OpenApiSchemaProperty => {
|
|
58
|
+
const {properties, required} = getOpenApiSpecForModel(model);
|
|
59
|
+
return {
|
|
60
|
+
properties: {
|
|
61
|
+
...(properties as Record<string, OpenApiSchemaProperty>),
|
|
62
|
+
id: {description: "The document id, the same value as _id", type: "string"},
|
|
63
|
+
},
|
|
64
|
+
required: Array.from(new Set([...required, "_id", "id"])),
|
|
65
|
+
type: "object",
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** Documentation only: request validation stays off so the handlers behave as before. */
|
|
70
|
+
const buildConsentOpenApi = (
|
|
71
|
+
openApi: OpenApiMiddleware | undefined
|
|
72
|
+
): {pending: RequestHandler; respond: RequestHandler} => {
|
|
73
|
+
const noop: RequestHandler = (_req, _res, next) => next();
|
|
74
|
+
if (!openApi?.path) {
|
|
75
|
+
return {pending: noop, respond: noop};
|
|
76
|
+
}
|
|
77
|
+
const consentForm = consentDocumentOpenApiSchema(
|
|
78
|
+
ConsentForm as unknown as mongoose.Model<unknown>
|
|
79
|
+
);
|
|
80
|
+
const consentResponse = consentDocumentOpenApiSchema(
|
|
81
|
+
ConsentResponse as unknown as mongoose.Model<unknown>
|
|
82
|
+
);
|
|
83
|
+
return {
|
|
84
|
+
pending: createOpenApiBuilder({openApi})
|
|
85
|
+
.withTags(["consents"])
|
|
86
|
+
.withSummary("List active consent forms the current user still has to answer")
|
|
87
|
+
.withResponse(200, {data: {items: consentForm, type: "array"}}, {required: ["data"]})
|
|
88
|
+
.withValidation({enabled: false})
|
|
89
|
+
.build(),
|
|
90
|
+
respond: createOpenApiBuilder({openApi})
|
|
91
|
+
.withTags(["consents"])
|
|
92
|
+
.withSummary("Submit the current user's response to a consent form")
|
|
93
|
+
.withRequestBody({
|
|
94
|
+
agreed: {description: "Whether the user agreed", required: true, type: "boolean"},
|
|
95
|
+
checkboxValues: {
|
|
96
|
+
additionalProperties: {type: "boolean"},
|
|
97
|
+
description: "Checkbox index (as a string) to whether it was checked",
|
|
98
|
+
type: "object",
|
|
99
|
+
},
|
|
100
|
+
consentFormId: {
|
|
101
|
+
description: "The consent form being answered",
|
|
102
|
+
required: true,
|
|
103
|
+
type: "string",
|
|
104
|
+
},
|
|
105
|
+
locale: {description: "Locale the form was shown in", required: true, type: "string"},
|
|
106
|
+
signature: {
|
|
107
|
+
description: "Signature image data, required when the form captures a signature",
|
|
108
|
+
type: "string",
|
|
109
|
+
},
|
|
110
|
+
})
|
|
111
|
+
.withResponse(200, {data: consentResponse}, {required: ["data"]})
|
|
112
|
+
.withValidation({enabled: false})
|
|
113
|
+
.build(),
|
|
114
|
+
};
|
|
115
|
+
};
|
|
116
|
+
|
|
55
117
|
const PROVISIONAL_NOTE_MAX_LENGTH = 2000;
|
|
56
118
|
|
|
57
119
|
const provisionalSignBody = z
|
|
@@ -356,6 +418,7 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
356
418
|
|
|
357
419
|
register(app: Application, openApi?: unknown): void {
|
|
358
420
|
const {accessControl, auditTrail, resolveConsentForms, aiConfig} = this.options;
|
|
421
|
+
const consentOpenApi = buildConsentOpenApi(openApi as OpenApiMiddleware | undefined);
|
|
359
422
|
|
|
360
423
|
if (!accessControl) {
|
|
361
424
|
logger.warn(
|
|
@@ -682,6 +745,7 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
682
745
|
router.get(
|
|
683
746
|
"/pending",
|
|
684
747
|
authenticateMiddleware(),
|
|
748
|
+
consentOpenApi.pending,
|
|
685
749
|
asyncHandler(async (req, res) => {
|
|
686
750
|
const user = req.user as User | undefined;
|
|
687
751
|
if (!user) {
|
|
@@ -768,6 +832,7 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
768
832
|
router.post(
|
|
769
833
|
"/respond",
|
|
770
834
|
authenticateMiddleware(),
|
|
835
|
+
consentOpenApi.respond,
|
|
771
836
|
asyncHandler(async (req, res) => {
|
|
772
837
|
const user = req.user as User | undefined;
|
|
773
838
|
if (!user) {
|
package/src/index.ts
CHANGED
|
@@ -114,10 +114,14 @@ export {generateInputSchema, generateToolDescription} from "./mcp/schemaGenerato
|
|
|
114
114
|
export {type MCPServerOptions, mountMCPServer} from "./mcp/server";
|
|
115
115
|
export {
|
|
116
116
|
addMcpServiceTokenRoutes,
|
|
117
|
+
createMcpServiceTokenRouter,
|
|
117
118
|
MAX_ACTIVE_MCP_SERVICE_TOKENS,
|
|
119
|
+
MCP_SERVICE_TOKENS_ROUTE_PATH,
|
|
120
|
+
MCP_SERVICE_TOKENS_SYNC_COLLECTION,
|
|
118
121
|
type McpServiceTokenRoutesOptions,
|
|
119
122
|
type McpServiceTokensAppOption,
|
|
120
123
|
resolveMcpServiceTokensOption,
|
|
124
|
+
toPublicMcpServiceToken,
|
|
121
125
|
} from "./mcp/serviceTokens";
|
|
122
126
|
export {
|
|
123
127
|
generateAllTools,
|
|
@@ -134,6 +138,7 @@ export type {
|
|
|
134
138
|
MCPToolResult,
|
|
135
139
|
} from "./mcp/types";
|
|
136
140
|
export * from "./middleware";
|
|
141
|
+
export * from "./migrations/builtin/mcpServiceTokenStringIds";
|
|
137
142
|
export * from "./migrations/generate";
|
|
138
143
|
export * from "./migrations/load";
|
|
139
144
|
export * from "./migrations/lock";
|
|
@@ -253,31 +258,11 @@ export {
|
|
|
253
258
|
stopChangeStreamWatcher,
|
|
254
259
|
} from "./realtime/changeStreamWatcher";
|
|
255
260
|
export {matchesQuery} from "./realtime/queryMatcher";
|
|
256
|
-
export {
|
|
257
|
-
addQuerySubscription,
|
|
258
|
-
clearQueryStore,
|
|
259
|
-
computeQueryId,
|
|
260
|
-
getQuerySubscriptionsForCollection,
|
|
261
|
-
removeAllSocketQueries,
|
|
262
|
-
removeQuerySubscription,
|
|
263
|
-
} from "./realtime/queryStore";
|
|
264
261
|
export {
|
|
265
262
|
installRealtimeSocketHandlers,
|
|
266
|
-
MAX_DOCUMENT_SUBSCRIPTIONS,
|
|
267
|
-
MAX_MODEL_SUBSCRIPTIONS,
|
|
268
|
-
MAX_QUERY_SUBSCRIPTIONS,
|
|
269
263
|
RealtimeApp,
|
|
270
264
|
type RealtimeSocketLike,
|
|
271
265
|
} from "./realtime/realtimeApp";
|
|
272
|
-
export {
|
|
273
|
-
clearRealtimeRegistry,
|
|
274
|
-
findRegistryEntryByCollection,
|
|
275
|
-
findRegistryEntryByRoutePath,
|
|
276
|
-
getRealtimeRegistry,
|
|
277
|
-
type RealtimeRegistryEntry,
|
|
278
|
-
registerRealtime,
|
|
279
|
-
updateRealtimeRegistryOptions,
|
|
280
|
-
} from "./realtime/registry";
|
|
281
266
|
export {
|
|
282
267
|
DEFAULT_SESSION_REVALIDATION_INTERVAL_MS,
|
|
283
268
|
loadFullUserForSocket,
|
|
@@ -304,14 +289,7 @@ export {
|
|
|
304
289
|
type SocketDataBag,
|
|
305
290
|
type SocketWithDecodedToken,
|
|
306
291
|
} from "./realtime/socketUser";
|
|
307
|
-
export type {
|
|
308
|
-
ChangeStreamConfig,
|
|
309
|
-
DocumentSubscription,
|
|
310
|
-
QuerySubscription,
|
|
311
|
-
RealtimeAppOptions,
|
|
312
|
-
RealtimeConfig,
|
|
313
|
-
RealtimeEvent,
|
|
314
|
-
} from "./realtime/types";
|
|
292
|
+
export type {ChangeStreamConfig, RealtimeAppOptions} from "./realtime/types";
|
|
315
293
|
export * from "./requestContext";
|
|
316
294
|
export {
|
|
317
295
|
type DescribeModelForRouterOptions,
|
|
@@ -167,7 +167,7 @@ describe("modelRouter actions as MCP tools", () => {
|
|
|
167
167
|
const [, notAdmin] = await setupDb();
|
|
168
168
|
ownerId = notAdmin._id as mongoose.Types.ObjectId;
|
|
169
169
|
await WidgetModel.deleteMany({});
|
|
170
|
-
await McpServiceToken.deleteMany({});
|
|
170
|
+
await McpServiceToken.collection.deleteMany({});
|
|
171
171
|
clearMCPRegistry();
|
|
172
172
|
app = new TerrenoApp({mcpServiceTokens: true, skipListen: true, userModel: typedUserModel})
|
|
173
173
|
.register(widgetRouter())
|
|
@@ -320,7 +320,7 @@ describe("modelRouter actions as MCP tools", () => {
|
|
|
320
320
|
});
|
|
321
321
|
|
|
322
322
|
it("records the credential type inside the tool handler", async () => {
|
|
323
|
-
const created = await ownerAgent.post("/mcp/service-tokens").send({name: "Agent"});
|
|
323
|
+
const created = await ownerAgent.post("/mcp/service-tokens/create").send({name: "Agent"});
|
|
324
324
|
const serviceToken = created.body.data.token as string;
|
|
325
325
|
|
|
326
326
|
const jwtResult = await callTool(ownerAgent, "widgets_count_mine", {});
|
package/src/mcp/adminTracking.ts
CHANGED
|
@@ -72,7 +72,7 @@ export const recordMcpToolCall = (
|
|
|
72
72
|
oauthClientId: auth?.oauthClientId,
|
|
73
73
|
oauthFamilyId: auth?.oauthFamilyId,
|
|
74
74
|
outcome: record.outcome,
|
|
75
|
-
serviceTokenId:
|
|
75
|
+
serviceTokenId: auth?.serviceTokenId,
|
|
76
76
|
toolName: record.toolName,
|
|
77
77
|
userId: toObjectId(auth?.user?.id ? String(auth.user.id) : undefined),
|
|
78
78
|
}).catch((error: unknown) => {
|
package/src/mcp/auth.test.ts
CHANGED
|
@@ -52,7 +52,7 @@ const signToken = (payload: Record<string, unknown>, secret = "test-token-secret
|
|
|
52
52
|
describe("extractUserFromHeaders", () => {
|
|
53
53
|
beforeEach(async () => {
|
|
54
54
|
await UserTestModel.deleteMany({});
|
|
55
|
-
await McpServiceToken.deleteMany({});
|
|
55
|
+
await McpServiceToken.collection.deleteMany({});
|
|
56
56
|
process.env.TOKEN_SECRET = "test-token-secret";
|
|
57
57
|
});
|
|
58
58
|
|
|
@@ -88,8 +88,12 @@ describe("extractUserFromHeaders", () => {
|
|
|
88
88
|
|
|
89
89
|
assert.equal(String((user as unknown as MCPAuthUserFields)?._id), created._id.toString());
|
|
90
90
|
|
|
91
|
-
|
|
92
|
-
|
|
91
|
+
// lastUsedAt is written without awaiting the request, so poll for it.
|
|
92
|
+
let usedToken = await McpServiceToken.findById(issued.mcpServiceToken._id);
|
|
93
|
+
for (let attempt = 0; attempt < 50 && !usedToken?.lastUsedAt; attempt++) {
|
|
94
|
+
await Bun.sleep(20);
|
|
95
|
+
usedToken = await McpServiceToken.findById(issued.mcpServiceToken._id);
|
|
96
|
+
}
|
|
93
97
|
assert.isDefined(usedToken?.lastUsedAt);
|
|
94
98
|
});
|
|
95
99
|
|
package/src/mcp/oauth.test.ts
CHANGED
|
@@ -177,7 +177,7 @@ describe("MCP OAuth authorization server", () => {
|
|
|
177
177
|
McpOAuthAuthorization.deleteMany({}),
|
|
178
178
|
McpOAuthClient.deleteMany({}),
|
|
179
179
|
McpOAuthToken.deleteMany({}),
|
|
180
|
-
McpServiceToken.deleteMany({}),
|
|
180
|
+
McpServiceToken.collection.deleteMany({}),
|
|
181
181
|
]);
|
|
182
182
|
clearMCPRegistry();
|
|
183
183
|
app = buildApp();
|
|
@@ -849,7 +849,7 @@ describe("MCP OAuth authorization server", () => {
|
|
|
849
849
|
});
|
|
850
850
|
|
|
851
851
|
it("keeps accepting JWT and mcp_ service tokens", async () => {
|
|
852
|
-
const created = await agent.post("/mcp/service-tokens").send({name: "Agent"});
|
|
852
|
+
const created = await agent.post("/mcp/service-tokens/create").send({name: "Agent"});
|
|
853
853
|
|
|
854
854
|
const jwtCall = await agent
|
|
855
855
|
.post("/mcp")
|
|
@@ -872,8 +872,8 @@ describe("MCP OAuth authorization server", () => {
|
|
|
872
872
|
};
|
|
873
873
|
|
|
874
874
|
it("ends service tokens, access tokens, and refresh tokens issued before a password reset", async () => {
|
|
875
|
-
const serviceToken = (await agent.post("/mcp/service-tokens").send({name: "Agent"}))
|
|
876
|
-
.token as string;
|
|
875
|
+
const serviceToken = (await agent.post("/mcp/service-tokens/create").send({name: "Agent"}))
|
|
876
|
+
.body.data.token as string;
|
|
877
877
|
const flow = await approvedCode(app, agent);
|
|
878
878
|
const oauth = (await exchangeCode(app, flow)).body;
|
|
879
879
|
expect((await callMcp(app, serviceToken)).status).toBe(200);
|
|
@@ -891,7 +891,7 @@ describe("MCP OAuth authorization server", () => {
|
|
|
891
891
|
});
|
|
892
892
|
|
|
893
893
|
it("lists service tokens from before a password reset as revoked", async () => {
|
|
894
|
-
await agent.post("/mcp/service-tokens").send({name: "Before reset"});
|
|
894
|
+
await agent.post("/mcp/service-tokens/create").send({name: "Before reset"});
|
|
895
895
|
|
|
896
896
|
await resetPassword();
|
|
897
897
|
|
|
@@ -911,8 +911,8 @@ describe("MCP OAuth authorization server", () => {
|
|
|
911
911
|
});
|
|
912
912
|
|
|
913
913
|
it("ends MCP credentials on any tokenEpoch bump, such as a Better Auth session revocation", async () => {
|
|
914
|
-
const serviceToken = (await agent.post("/mcp/service-tokens").send({name: "Agent"}))
|
|
915
|
-
.token as string;
|
|
914
|
+
const serviceToken = (await agent.post("/mcp/service-tokens/create").send({name: "Agent"}))
|
|
915
|
+
.body.data.token as string;
|
|
916
916
|
const flow = await approvedCode(app, agent);
|
|
917
917
|
const oauth = (await exchangeCode(app, flow)).body;
|
|
918
918
|
|
|
@@ -928,8 +928,8 @@ describe("MCP OAuth authorization server", () => {
|
|
|
928
928
|
it("accepts MCP credentials issued after a password reset", async () => {
|
|
929
929
|
await resetPassword();
|
|
930
930
|
|
|
931
|
-
const serviceToken = (await agent.post("/mcp/service-tokens").send({name: "After"}))
|
|
932
|
-
.token as string;
|
|
931
|
+
const serviceToken = (await agent.post("/mcp/service-tokens/create").send({name: "After"}))
|
|
932
|
+
.body.data.token as string;
|
|
933
933
|
const flow = await approvedCode(app, agent);
|
|
934
934
|
const oauth = (await exchangeCode(app, flow)).body;
|
|
935
935
|
const refreshed = await refresh(app, flow.clientId, oauth.refresh_token);
|
|
@@ -1313,7 +1313,7 @@ describe("MCP OAuth granted scopes", () => {
|
|
|
1313
1313
|
McpOAuthAuthorization.deleteMany({}),
|
|
1314
1314
|
McpOAuthClient.deleteMany({}),
|
|
1315
1315
|
McpOAuthToken.deleteMany({}),
|
|
1316
|
-
McpServiceToken.deleteMany({}),
|
|
1316
|
+
McpServiceToken.collection.deleteMany({}),
|
|
1317
1317
|
]);
|
|
1318
1318
|
clearMCPRegistry();
|
|
1319
1319
|
app = new TerrenoApp({
|
|
@@ -1347,8 +1347,8 @@ describe("MCP OAuth granted scopes", () => {
|
|
|
1347
1347
|
});
|
|
1348
1348
|
|
|
1349
1349
|
it("does not apply OAuth scopes to the user's own JWT or service token", async () => {
|
|
1350
|
-
const serviceToken = (await agent.post("/mcp/service-tokens").send({name: "Agent"})).body
|
|
1351
|
-
.token as string;
|
|
1350
|
+
const serviceToken = (await agent.post("/mcp/service-tokens/create").send({name: "Agent"})).body
|
|
1351
|
+
.data.token as string;
|
|
1352
1352
|
|
|
1353
1353
|
const viaServiceToken = rpcResult((await callTool(serviceToken, "scoped_write")).text);
|
|
1354
1354
|
const viaScopes = rpcResult((await callTool(serviceToken, "scoped_scopes")).text);
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import {afterEach, beforeEach, describe, it} from "bun:test";
|
|
2
|
+
import {assert} from "chai";
|
|
3
|
+
import type express from "express";
|
|
4
|
+
import type mongoose from "mongoose";
|
|
5
|
+
import type {Server} from "socket.io";
|
|
6
|
+
import type TestAgent from "supertest/lib/agent";
|
|
7
|
+
|
|
8
|
+
import type {UserModel as AuthUserModel} from "../auth";
|
|
9
|
+
import {McpServiceToken} from "../models/mcpServiceToken";
|
|
10
|
+
import {emitSyncDeltaForChange} from "../realtime/changeStreamWatcher";
|
|
11
|
+
import {
|
|
12
|
+
clearSyncRegistry,
|
|
13
|
+
findSyncEntryByCollectionTag,
|
|
14
|
+
type SyncRegistryEntry,
|
|
15
|
+
} from "../sync/registry";
|
|
16
|
+
import {syncRoomForStream} from "../sync/socketHandlers";
|
|
17
|
+
import {SyncApp} from "../sync/syncApp";
|
|
18
|
+
import type {SyncDelta, SyncSnapshotResponse} from "../sync/types";
|
|
19
|
+
import {TerrenoApp} from "../terrenoApp";
|
|
20
|
+
import {authAsUser, setupDb, UserModel} from "../tests";
|
|
21
|
+
import {MCP_SERVICE_TOKENS_SYNC_COLLECTION} from "./serviceTokens";
|
|
22
|
+
|
|
23
|
+
interface CreatedToken {
|
|
24
|
+
id: string;
|
|
25
|
+
token: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface TrackedEmission {
|
|
29
|
+
event: string;
|
|
30
|
+
payload: unknown;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const buildApp = (): express.Application => {
|
|
34
|
+
clearSyncRegistry();
|
|
35
|
+
return new TerrenoApp({
|
|
36
|
+
mcpServiceTokens: true,
|
|
37
|
+
skipListen: true,
|
|
38
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
39
|
+
})
|
|
40
|
+
.register(new SyncApp({}))
|
|
41
|
+
.build();
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const ownerStream = (userId: string): string =>
|
|
45
|
+
`${MCP_SERVICE_TOKENS_SYNC_COLLECTION}|owner:${userId}`;
|
|
46
|
+
|
|
47
|
+
/** Socket.io stand-in with one socket for `userId` joined to `room`. */
|
|
48
|
+
const makeTrackedIo = (
|
|
49
|
+
room: string,
|
|
50
|
+
userId: string
|
|
51
|
+
): {emissions: TrackedEmission[]; io: Server} => {
|
|
52
|
+
const emissions: TrackedEmission[] = [];
|
|
53
|
+
const socket = {
|
|
54
|
+
decodedToken: {admin: false, id: userId},
|
|
55
|
+
emit: (event: string, payload: unknown): void => {
|
|
56
|
+
emissions.push({event, payload});
|
|
57
|
+
},
|
|
58
|
+
id: "socket-owner",
|
|
59
|
+
};
|
|
60
|
+
const io = {
|
|
61
|
+
sockets: {
|
|
62
|
+
adapter: {rooms: new Map([[room, new Set([socket.id])]])},
|
|
63
|
+
sockets: new Map([[socket.id, socket]]),
|
|
64
|
+
},
|
|
65
|
+
to: () => ({emit: (): void => undefined}),
|
|
66
|
+
} as unknown as Server;
|
|
67
|
+
return {emissions, io};
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const assertNoTokenSecrets = (value: unknown, plaintext: string): void => {
|
|
71
|
+
const serialized = JSON.stringify(value);
|
|
72
|
+
assert.notInclude(serialized, "tokenHash");
|
|
73
|
+
assert.notInclude(serialized, plaintext);
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
describe("MCP service tokens as a synced collection", () => {
|
|
77
|
+
let agent: TestAgent;
|
|
78
|
+
let otherAgent: TestAgent;
|
|
79
|
+
let ownerId: string;
|
|
80
|
+
let created: CreatedToken;
|
|
81
|
+
|
|
82
|
+
beforeEach(async () => {
|
|
83
|
+
const [admin, notAdmin] = await setupDb();
|
|
84
|
+
ownerId = String((notAdmin as {_id: mongoose.Types.ObjectId})._id);
|
|
85
|
+
await McpServiceToken.collection.deleteMany({});
|
|
86
|
+
const app = buildApp();
|
|
87
|
+
agent = await authAsUser(app, "notAdmin");
|
|
88
|
+
otherAgent = await authAsUser(app, "admin");
|
|
89
|
+
assert.isDefined(admin);
|
|
90
|
+
const res = await agent.post("/mcp/service-tokens/create").send({name: "Synced"});
|
|
91
|
+
assert.equal(res.status, 200);
|
|
92
|
+
created = res.body.data as CreatedToken;
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
afterEach(async () => {
|
|
96
|
+
await McpServiceToken.collection.deleteMany({});
|
|
97
|
+
clearSyncRegistry();
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("serves the owner's snapshot without tokenHash or the plaintext", async () => {
|
|
101
|
+
const res = await agent.get(
|
|
102
|
+
`/sync/snapshot?stream=${encodeURIComponent(ownerStream(ownerId))}`
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
assert.equal(res.status, 200);
|
|
106
|
+
const page = res.body as SyncSnapshotResponse;
|
|
107
|
+
assert.lengthOf(page.entities, 1);
|
|
108
|
+
const [entity] = page.entities;
|
|
109
|
+
assert.equal(entity.id, created.id);
|
|
110
|
+
assert.isAbove(entity.seq, 0);
|
|
111
|
+
const data = entity.data as Record<string, unknown>;
|
|
112
|
+
assert.equal(data.name, "Synced");
|
|
113
|
+
assert.equal(data.id, created.id);
|
|
114
|
+
assert.equal(data.tokenPrefix, created.token.slice(4, 12));
|
|
115
|
+
assert.notProperty(data, "tokenHash");
|
|
116
|
+
assert.notProperty(data, "token");
|
|
117
|
+
assertNoTokenSecrets(res.body, created.token);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it("strips tokenHash from batched snapshots and entity lookups", async () => {
|
|
121
|
+
const batch = await agent
|
|
122
|
+
.post("/sync/snapshot/batch")
|
|
123
|
+
.send({streams: [{stream: ownerStream(ownerId)}]});
|
|
124
|
+
const entities = await agent.get(
|
|
125
|
+
`/sync/entities?collection=${encodeURIComponent(MCP_SERVICE_TOKENS_SYNC_COLLECTION)}&ids=${created.id}`
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
assert.equal(batch.status, 200);
|
|
129
|
+
assert.equal(entities.status, 200);
|
|
130
|
+
assert.lengthOf(batch.body.pages[0].entities, 1);
|
|
131
|
+
assert.lengthOf(entities.body.entities, 1);
|
|
132
|
+
assertNoTokenSecrets(batch.body, created.token);
|
|
133
|
+
assertNoTokenSecrets(entities.body, created.token);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("does not serve another user's stream", async () => {
|
|
137
|
+
const res = await otherAgent.get(
|
|
138
|
+
`/sync/snapshot?stream=${encodeURIComponent(ownerStream(ownerId))}`
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
assert.equal(res.status, 403);
|
|
142
|
+
assertNoTokenSecrets(res.body, created.token);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("emits deltas without tokenHash", async () => {
|
|
146
|
+
const entry = findSyncEntryByCollectionTag(
|
|
147
|
+
MCP_SERVICE_TOKENS_SYNC_COLLECTION
|
|
148
|
+
) as SyncRegistryEntry;
|
|
149
|
+
// The change stream post-image is the raw stored row, tokenHash included.
|
|
150
|
+
const fullDocument = (await McpServiceToken.collection.findOne({
|
|
151
|
+
_id: created.id as never,
|
|
152
|
+
})) as Record<string, unknown>;
|
|
153
|
+
assert.isString(fullDocument.tokenHash);
|
|
154
|
+
const stream = ownerStream(ownerId);
|
|
155
|
+
const {emissions, io} = makeTrackedIo(syncRoomForStream(stream), ownerId);
|
|
156
|
+
|
|
157
|
+
await emitSyncDeltaForChange({
|
|
158
|
+
change: {
|
|
159
|
+
documentKey: {_id: created.id},
|
|
160
|
+
fullDocument,
|
|
161
|
+
ns: {coll: "mcpservicetokens"},
|
|
162
|
+
operationType: "insert",
|
|
163
|
+
} as unknown as Parameters<typeof emitSyncDeltaForChange>[0]["change"],
|
|
164
|
+
docId: created.id,
|
|
165
|
+
entry,
|
|
166
|
+
io,
|
|
167
|
+
logDebug: () => undefined,
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
const delta = emissions.find((emission) => emission.event === "sync:delta")
|
|
171
|
+
?.payload as SyncDelta;
|
|
172
|
+
assert.isDefined(delta);
|
|
173
|
+
assert.equal(delta.stream, stream);
|
|
174
|
+
const data = delta.data as Record<string, unknown>;
|
|
175
|
+
assert.equal(data.name, "Synced");
|
|
176
|
+
assert.notProperty(data, "tokenHash");
|
|
177
|
+
assertNoTokenSecrets(delta, created.token);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it("rejects client sync create, update, and delete", async () => {
|
|
181
|
+
const stored = await McpServiceToken.collection.findOne({_id: created.id as never});
|
|
182
|
+
const baseVersion = stored?._syncSeq as number;
|
|
183
|
+
const attempts = [
|
|
184
|
+
{
|
|
185
|
+
data: {name: "Forged", tokenHash: "forged", tokenPrefix: "forged", userId: ownerId},
|
|
186
|
+
mutationId: "mcp-token-create",
|
|
187
|
+
operation: "create",
|
|
188
|
+
},
|
|
189
|
+
{
|
|
190
|
+
baseVersion,
|
|
191
|
+
data: {name: "Renamed"},
|
|
192
|
+
id: created.id,
|
|
193
|
+
mutationId: "mcp-token-update",
|
|
194
|
+
operation: "update",
|
|
195
|
+
},
|
|
196
|
+
{id: created.id, mutationId: "mcp-token-delete", operation: "delete"},
|
|
197
|
+
];
|
|
198
|
+
|
|
199
|
+
for (const attempt of attempts) {
|
|
200
|
+
const res = await agent
|
|
201
|
+
.post("/sync/mutate")
|
|
202
|
+
.send({...attempt, collection: MCP_SERVICE_TOKENS_SYNC_COLLECTION});
|
|
203
|
+
assert.equal(res.status, 403, attempt.operation);
|
|
204
|
+
assert.equal(res.body.nack?.code, "unauthorized", attempt.operation);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const rows = await McpServiceToken.collection.find({}).toArray();
|
|
208
|
+
assert.lengthOf(rows, 1);
|
|
209
|
+
assert.equal(rows[0].name, "Synced");
|
|
210
|
+
assert.notOk(rows[0].revokedAt);
|
|
211
|
+
assert.isFalse(rows[0].deleted);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it("syncs a revoke as an update that keeps the row", async () => {
|
|
215
|
+
const before = await agent.get(
|
|
216
|
+
`/sync/snapshot?stream=${encodeURIComponent(ownerStream(ownerId))}`
|
|
217
|
+
);
|
|
218
|
+
const revoked = await agent.post(`/mcp/service-tokens/${created.id}/revoke`);
|
|
219
|
+
const after = await agent.get(
|
|
220
|
+
`/sync/snapshot?stream=${encodeURIComponent(ownerStream(ownerId))}&cursor=${before.body.cursor}`
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
assert.equal(revoked.status, 200);
|
|
224
|
+
assert.lengthOf(after.body.entities, 1);
|
|
225
|
+
const [entity] = after.body.entities as SyncSnapshotResponse["entities"];
|
|
226
|
+
assert.isFalse(entity.deleted);
|
|
227
|
+
assert.isString((entity.data as {revokedAt?: unknown}).revokedAt);
|
|
228
|
+
assertNoTokenSecrets(after.body, created.token);
|
|
229
|
+
});
|
|
230
|
+
});
|