@terreno/api 57.20.0 → 58.0.0-beta.1

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 (183) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +1 -1
  3. package/biome.jsonc +3 -2
  4. package/dist/api.d.ts +3 -16
  5. package/dist/api.js +0 -9
  6. package/dist/auth.d.ts +3 -2
  7. package/dist/auth.js +95 -5
  8. package/dist/authRecovery.d.ts +2 -1
  9. package/dist/authRecovery.js +35 -17
  10. package/dist/collectionRegistry.d.ts +3 -4
  11. package/dist/collectionRegistry.js +0 -1
  12. package/dist/consentApp.d.ts +1 -1
  13. package/dist/consentApp.js +58 -2
  14. package/dist/frameworkModelNames.d.ts +4 -0
  15. package/dist/frameworkModelNames.js +4 -0
  16. package/dist/index.d.ts +8 -5
  17. package/dist/index.js +14 -20
  18. package/dist/mcp/adminTracking.d.ts +28 -0
  19. package/dist/mcp/adminTracking.js +80 -0
  20. package/dist/mcp/auth.d.ts +6 -0
  21. package/dist/mcp/auth.js +12 -2
  22. package/dist/mcp/server.d.ts +8 -0
  23. package/dist/mcp/server.js +48 -4
  24. package/dist/mcp/serviceTokens.d.ts +21 -1
  25. package/dist/mcp/serviceTokens.js +159 -183
  26. package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
  27. package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
  28. package/dist/models/mcpOAuthToken.js +27 -0
  29. package/dist/models/mcpRequestLog.d.ts +2 -0
  30. package/dist/models/mcpRequestLog.js +73 -0
  31. package/dist/models/mcpServiceToken.js +40 -4
  32. package/dist/models/mcpToolSetting.d.ts +2 -0
  33. package/dist/models/mcpToolSetting.js +119 -0
  34. package/dist/models/versionConfig.d.ts +2 -0
  35. package/dist/openApiBuilder.d.ts +4 -0
  36. package/dist/openApiBuilder.js +2 -0
  37. package/dist/rbac/auditModel.d.ts +2 -1
  38. package/dist/rbac/realtimeAccess.d.ts +5 -4
  39. package/dist/rbac/realtimeAccess.js +17 -64
  40. package/dist/realtime/changeStreamWatcher.d.ts +8 -63
  41. package/dist/realtime/changeStreamWatcher.js +32 -391
  42. package/dist/realtime/realtimeApp.d.ts +14 -27
  43. package/dist/realtime/realtimeApp.js +14 -220
  44. package/dist/realtime/types.d.ts +0 -64
  45. package/dist/sync/executors.js +14 -2
  46. package/dist/sync/socketHandlers.d.ts +1 -1
  47. package/dist/sync/socketHandlers.js +1 -1
  48. package/dist/terrenoApp.d.ts +19 -5
  49. package/dist/terrenoApp.js +21 -14
  50. package/dist/tests/models.d.ts +17 -22
  51. package/dist/tests/models.js +7 -1
  52. package/dist/tests/openApiResponseSchema.d.ts +39 -0
  53. package/dist/tests/openApiResponseSchema.js +56 -0
  54. package/dist/tests/testHelper.d.ts +6 -12
  55. package/dist/tests.d.ts +2 -0
  56. package/dist/tests.js +6 -1
  57. package/dist/types/mcpAdmin.d.ts +58 -0
  58. package/dist/types/mcpAdmin.js +2 -0
  59. package/dist/types/mcpOAuth.d.ts +2 -0
  60. package/dist/types/mcpServiceToken.d.ts +9 -4
  61. package/dist/versionCheckPlugin.d.ts +1 -1
  62. package/dist/versionCheckPlugin.js +25 -2
  63. package/e2e/smoke.ts +193 -0
  64. package/package.json +14 -8
  65. package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
  66. package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
  67. package/src/__tests__/openApiResponseSchema.test.ts +148 -0
  68. package/src/__tests__/versionCheckPlugin.test.ts +72 -0
  69. package/src/adminModelRouter.test.ts +8 -6
  70. package/src/api.arrayOperations.test.ts +31 -22
  71. package/src/api.hooks.test.ts +12 -11
  72. package/src/api.query.test.ts +2 -2
  73. package/src/api.test.ts +17 -14
  74. package/src/api.ts +3 -27
  75. package/src/audit/auditApp.test.ts +1 -1
  76. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  77. package/src/auth.test.ts +21 -7
  78. package/src/auth.ts +116 -5
  79. package/src/authOpenApi.test.ts +316 -0
  80. package/src/authRecovery.test.ts +10 -10
  81. package/src/authRecovery.ts +47 -19
  82. package/src/authVerification.test.ts +7 -7
  83. package/src/betterAuthFeatures.test.ts +3 -2
  84. package/src/betterAuthLinking.test.ts +3 -1
  85. package/src/betterAuthOAuthHandoff.test.ts +13 -5
  86. package/src/betterAuthSetup.test.ts +77 -51
  87. package/src/collectionRegistry.test.ts +4 -4
  88. package/src/collectionRegistry.ts +3 -5
  89. package/src/consentApp.test.ts +98 -0
  90. package/src/consentApp.ts +67 -2
  91. package/src/frameworkModelNames.test.ts +8 -0
  92. package/src/frameworkModelNames.ts +4 -0
  93. package/src/githubAuth.test.ts +11 -11
  94. package/src/index.ts +14 -28
  95. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  96. package/src/mcp/actionTools.test.ts +13 -7
  97. package/src/mcp/adminTracking.test.ts +272 -0
  98. package/src/mcp/adminTracking.ts +104 -0
  99. package/src/mcp/auth.test.ts +7 -3
  100. package/src/mcp/auth.ts +18 -2
  101. package/src/mcp/oauth.test.ts +13 -13
  102. package/src/mcp/server.ts +67 -4
  103. package/src/mcp/serviceTokens.sync.test.ts +230 -0
  104. package/src/mcp/serviceTokens.test.ts +114 -62
  105. package/src/mcp/serviceTokens.ts +193 -212
  106. package/src/mcp/toolGenerator.test.ts +9 -5
  107. package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
  108. package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
  109. package/src/migrations/cli.test.ts +15 -14
  110. package/src/migrations/cli.ts +1 -1
  111. package/src/migrations/generate.test.ts +2 -2
  112. package/src/migrations/load.test.ts +1 -1
  113. package/src/migrations/lock.test.ts +8 -3
  114. package/src/migrations/runner.test.ts +16 -5
  115. package/src/migrations/schemaCatalog.test.ts +4 -1
  116. package/src/models/mcpOAuthToken.test.ts +42 -0
  117. package/src/models/mcpOAuthToken.ts +32 -0
  118. package/src/models/mcpRequestLog.ts +81 -0
  119. package/src/models/mcpServiceToken.test.ts +75 -5
  120. package/src/models/mcpServiceToken.ts +61 -14
  121. package/src/models/mcpToolSetting.test.ts +69 -0
  122. package/src/models/mcpToolSetting.ts +138 -0
  123. package/src/models/versionConfig.ts +2 -0
  124. package/src/notifications/notificationsApp.test.ts +5 -8
  125. package/src/notifiers/slackWebApi.test.ts +30 -8
  126. package/src/openApi.test.ts +4 -4
  127. package/src/openApiBuilder.test.ts +34 -1
  128. package/src/openApiBuilder.ts +5 -0
  129. package/src/openApiValidator.test.ts +3 -3
  130. package/src/orgs/orgPermissions.test.ts +2 -2
  131. package/src/orgs/orgPlugin.test.ts +4 -3
  132. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  133. package/src/orgs/organizationSettings.test.ts +1 -1
  134. package/src/orgs/orgsApp.test.ts +5 -3
  135. package/src/permissions.test.ts +2 -2
  136. package/src/rateLimit/rateLimit.test.ts +25 -10
  137. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  138. package/src/rbac/assertAllowed.test.ts +1 -1
  139. package/src/rbac/auditModel.ts +10 -2
  140. package/src/rbac/realtimeAccess.test.ts +20 -171
  141. package/src/rbac/realtimeAccess.ts +17 -82
  142. package/src/rbac/routes.test.ts +1 -1
  143. package/src/rbac/userWriteGuards.test.ts +8 -5
  144. package/src/realtime/changeStreamWatcher.ts +43 -506
  145. package/src/realtime/realtime.test.ts +211 -2547
  146. package/src/realtime/realtimeApp.ts +16 -295
  147. package/src/realtime/types.ts +0 -72
  148. package/src/scrubAdminFields.test.ts +1 -1
  149. package/src/sync/adminWindowMutation.test.ts +4 -3
  150. package/src/sync/executors.test.ts +29 -1
  151. package/src/sync/executors.ts +23 -2
  152. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  153. package/src/sync/socketHandlers.ts +1 -1
  154. package/src/sync/sync.test.ts +1 -1
  155. package/src/sync/syncPhaseC.test.ts +14 -11
  156. package/src/sync/syncRoutes.test.ts +8 -8
  157. package/src/sync/syncSeqPlugin.test.ts +1 -2
  158. package/src/sync/syncSocket.test.ts +78 -113
  159. package/src/terrenoApp.mcpServiceTokens.test.ts +16 -8
  160. package/src/terrenoApp.migrations.test.ts +8 -7
  161. package/src/terrenoApp.ts +38 -18
  162. package/src/tests/betterAuthStubs.ts +3 -2
  163. package/src/tests/bunSetup.ts +1 -1
  164. package/src/tests/models.ts +10 -0
  165. package/src/tests/openApiResponseSchema.ts +104 -0
  166. package/src/tests/testEnv.ts +7 -0
  167. package/src/tests.ts +8 -0
  168. package/src/types/mcpAdmin.ts +80 -0
  169. package/src/types/mcpOAuth.ts +5 -0
  170. package/src/types/mcpServiceToken.ts +12 -4
  171. package/src/versionCheckPlugin.ts +41 -2
  172. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  173. package/tsconfig.typecheck.json +14 -0
  174. package/dist/realtime/deprecation.d.ts +0 -13
  175. package/dist/realtime/deprecation.js +0 -31
  176. package/dist/realtime/queryStore.d.ts +0 -37
  177. package/dist/realtime/queryStore.js +0 -103
  178. package/dist/realtime/registry.d.ts +0 -15
  179. package/dist/realtime/registry.js +0 -52
  180. package/src/realtime/deprecation.test.ts +0 -60
  181. package/src/realtime/deprecation.ts +0 -33
  182. package/src/realtime/queryStore.ts +0 -122
  183. package/src/realtime/registry.ts +0 -84
package/src/terrenoApp.ts CHANGED
@@ -30,6 +30,7 @@ import {
30
30
  import {type AddRoutes, type AuthOptions, logRequests} from "./expressServer";
31
31
  import {addGitHubAuthRoutes, type GitHubAuthOptions, setupGitHubAuth} from "./githubAuth";
32
32
  import {type LoggingOptions, logger, setupLogging} from "./logger";
33
+ import {type McpRequestLogAppOption, resolveMcpRequestLogOption} from "./mcp/adminTracking";
33
34
  import {addMcpOAuthRoutes} from "./mcp/oauth";
34
35
  import {type McpOAuthAppOption, resolveMcpOAuthOption} from "./mcp/oauthMetadata";
35
36
  import {mountMCPServer} from "./mcp/server";
@@ -129,11 +130,13 @@ export interface TerrenoAppOptions {
129
130
  */
130
131
  configureApp?: AddRoutes;
131
132
  /**
132
- * Optional HTTP rate limiting. Omitted or `undefined` leaves the limiter off
133
- * (Terreno 58 will default it on). Pass `{}` or `{store, limits, trustProxy}`
134
- * to enable. See [Rate limiting](../how-to/rate-limiting.md).
133
+ * HTTP rate limiting. On by default: omitted or `undefined` mounts the limiter with the
134
+ * memory store and default limits (auth 20 / 15 min, api 600 / 15 min). Pass
135
+ * `{store, limits, trustProxy, skip}` to configure it (`{}` is the same as omitting it).
136
+ * Pass `false` to turn it off. On Cloud Run pass `trustProxy: 1` so unauthenticated
137
+ * traffic keys by client IP. See [Rate limiting](../how-to/rate-limiting.md).
135
138
  */
136
- rateLimit?: RateLimitOptions;
139
+ rateLimit?: RateLimitOptions | false;
137
140
  /**
138
141
  * Opt-in personal MCP service tokens. `true` is `{enabled: true}`. When enabled,
139
142
  * mounts `/mcp/service-tokens` and accepts `Authorization: Bearer mcp_…` on `/mcp`.
@@ -148,6 +151,17 @@ export interface TerrenoAppOptions {
148
151
  * [Enable MCP OAuth](../how-to/enable-mcp-oauth.md).
149
152
  */
150
153
  mcpOAuth?: McpOAuthAppOption;
154
+ /**
155
+ * Opt-in log of MCP tool calls for the admin panel. `true` keeps rows 30 days. Rows hold
156
+ * metadata only (tool, user, credential ids, duration, outcome, error class), never tool
157
+ * arguments, results, or error text. See [Manage MCP from the admin panel](../how-to/manage-mcp-in-admin.md).
158
+ */
159
+ mcpRequestLog?: McpRequestLogAppOption;
160
+ /**
161
+ * Opt-in MCP tool registry. When true, every tool is recorded in `McpToolSetting` at startup,
162
+ * and tools an admin switches off are hidden from `tools/list` and rejected by `tools/call`.
163
+ */
164
+ mcpToolSettings?: boolean;
151
165
  /**
152
166
  * Versioned MongoDB migrations. `runOnStart` defaults to false. When true, wet `up`
153
167
  * runs after listen and `ensureSyncIndexes`. Production still requires
@@ -359,7 +373,7 @@ export class TerrenoApp {
359
373
  * Build the Express application without starting the server.
360
374
  *
361
375
  * Configures the complete middleware stack including:
362
- * - CORS, JSON parsing, JWT decode, optional HTTP rate limiting, auth routes
376
+ * - CORS, JSON parsing, JWT decode, HTTP rate limiting (unless `rateLimit: false`), auth routes
363
377
  * - Better Auth session (when BetterAuthApp is registered) before the limiter
364
378
  * - Logging, Sentry, OpenAPI, model routers and plugins
365
379
  * - Error handling middleware
@@ -434,11 +448,13 @@ export class TerrenoApp {
434
448
  betterAuthForLimiter.markSessionMiddlewareMounted?.();
435
449
  }
436
450
 
437
- if (options.rateLimit) {
451
+ // Rate limiting is on unless the app passes `rateLimit: false`.
452
+ const rateLimitOptions = options.rateLimit === false ? undefined : (options.rateLimit ?? {});
453
+ if (rateLimitOptions) {
438
454
  const betterAuthBasePath =
439
- options.rateLimit.betterAuthBasePath ?? betterAuthForLimiter?.getBetterAuthBasePath?.();
455
+ rateLimitOptions.betterAuthBasePath ?? betterAuthForLimiter?.getBetterAuthBasePath?.();
440
456
  const rateLimit = {
441
- ...options.rateLimit,
457
+ ...rateLimitOptions,
442
458
  ...(betterAuthBasePath ? {betterAuthBasePath} : {}),
443
459
  };
444
460
  applyRateLimitTrustProxy(app, rateLimit);
@@ -452,7 +468,17 @@ export class TerrenoApp {
452
468
  options.authOptions = {};
453
469
  }
454
470
  const authOptions = options.authOptions;
455
- addAuthRoutes(app, options.userModel, authOptions);
471
+ // The OpenAPI generator walks the router stack on each /openapi.json request, so the
472
+ // instance can exist before it is mounted below. Auth routes need it to document themselves.
473
+ const oapi = openapi({
474
+ info: {
475
+ description: "Generated docs from an Express api",
476
+ title: "Express Application",
477
+ version: "1.0.0",
478
+ },
479
+ openapi: "3.0.0",
480
+ });
481
+ addAuthRoutes(app, options.userModel, authOptions, oapi);
456
482
 
457
483
  if (options.logRequests !== false && options.loggingOptions?.logRequests !== false) {
458
484
  app.use(logRequests);
@@ -488,14 +514,6 @@ export class TerrenoApp {
488
514
  app.use(openApiCompatMiddleware);
489
515
  app.use(openApiEtagMiddleware);
490
516
  app.use(jsonResponseRequestIdMiddleware);
491
- const oapi = openapi({
492
- info: {
493
- description: "Generated docs from an Express api",
494
- title: "Express Application",
495
- version: "1.0.0",
496
- },
497
- openapi: "3.0.0",
498
- });
499
517
  app.use(oapi);
500
518
 
501
519
  if (process.env.ENABLE_SWAGGER === "true") {
@@ -556,6 +574,8 @@ export class TerrenoApp {
556
574
  betterAuth,
557
575
  mcpOAuth,
558
576
  mcpServiceTokens: mcpServiceTokens.enabled,
577
+ requestLog: resolveMcpRequestLogOption(options.mcpRequestLog),
578
+ toolSettings: options.mcpToolSettings === true,
559
579
  userModel: options.userModel,
560
580
  });
561
581
 
@@ -565,7 +585,7 @@ export class TerrenoApp {
565
585
 
566
586
  // /auth/me must be registered after plugins so that session middleware
567
587
  // (e.g. Better Auth) has a chance to populate req.user first.
568
- addMeRoutes(app, options.userModel, options.authOptions, options.accessControl);
588
+ addMeRoutes(app, options.userModel, options.authOptions, options.accessControl, oapi);
569
589
 
570
590
  Sentry.setupExpressErrorHandler(app);
571
591
 
@@ -7,6 +7,7 @@ import {expect} from "bun:test";
7
7
  import {createHmac, randomUUID} from "node:crypto";
8
8
  import type {BetterAuthPlugin} from "better-auth";
9
9
  import {genericOAuth} from "better-auth/plugins";
10
+ import type {GoogleProfile} from "better-auth/social-providers";
10
11
  import type express from "express";
11
12
  import {DateTime} from "luxon";
12
13
  import mongoose from "mongoose";
@@ -83,12 +84,12 @@ export const stubOidcPlugin = (identity: StubIdentity): BetterAuthPlugin =>
83
84
  export const stubGoogleIdTokenOptions = (identity: StubIdentity): BetterAuthOptionsOverride => ({
84
85
  socialProviders: {
85
86
  google: {
87
+ // Google keys the account on `profile.sub`; the stub returns only the fields it reads.
86
88
  getUserInfo: async () => ({
87
- data: {sub: identity.id},
89
+ data: {sub: identity.id} as GoogleProfile,
88
90
  user: {
89
91
  email: identity.email,
90
92
  emailVerified: identity.emailVerified ?? true,
91
- id: identity.id,
92
93
  name: "Google User",
93
94
  },
94
95
  }),
@@ -12,7 +12,7 @@ if (useFixtureCache) {
12
12
  registerBackendPreload({
13
13
  connectMongoInBeforeAll: true,
14
14
  loadTestDataFromCache: async () => {
15
- const {loadTestDataFromCache} = await import("./mongoTestSetup");
15
+ const {loadTestDataFromCache} = await import("./mongoTestSetup.js");
16
16
  await loadTestDataFromCache();
17
17
  },
18
18
  mongo: {
@@ -1,6 +1,7 @@
1
1
  import mongoose, {type Model, model, Schema, type StringSchemaDefinition} from "mongoose";
2
2
  import passportLocalMongoose from "passport-local-mongoose";
3
3
 
4
+ import type {UserModel as AuthUserModel} from "../auth";
4
5
  import {
5
6
  createdUpdatedPlugin,
6
7
  DateOnly,
@@ -9,6 +10,8 @@ import {
9
10
  } from "../plugins";
10
11
 
11
12
  export interface User {
13
+ _id: mongoose.Types.ObjectId;
14
+ id: string;
12
15
  admin: boolean;
13
16
  name?: string;
14
17
  username: string;
@@ -113,6 +116,13 @@ userSchema.methods.postCreate = async function (body: {age?: number}) {
113
116
 
114
117
  export const UserModel = model<User>("User", userSchema);
115
118
 
119
+ /**
120
+ * `UserModel` typed as the auth `UserModel` for `setupAuth`, `TerrenoApp({userModel})`, and
121
+ * friends. passport-local-mongoose adds the statics at runtime but ships no types, and the auth
122
+ * `User._id` uses mongoose's schema `ObjectId` type, so the models are not structurally related.
123
+ */
124
+ export const authUserModel = UserModel as unknown as AuthUserModel;
125
+
116
126
  const superUserSchema = new Schema<SuperUser>({
117
127
  superTitle: {description: "The super user's title", required: true, type: String},
118
128
  });
@@ -0,0 +1,104 @@
1
+ import Ajv from "ajv";
2
+ import addFormats from "ajv-formats";
3
+
4
+ /** Raised when a route or response is undocumented, or a body breaks its documented schema. */
5
+ class DocumentedResponseError extends Error {
6
+ name = "DocumentedResponseError";
7
+ }
8
+
9
+ /** The subset of an OpenAPI document needed to look up and validate a response schema. */
10
+ export interface OpenApiResponseSpec {
11
+ components?: Record<string, unknown>;
12
+ paths?: Record<string, Record<string, OpenApiResponseOperation | undefined> | undefined>;
13
+ }
14
+
15
+ interface OpenApiResponseOperation {
16
+ responses?: Record<string, {content?: Record<string, {schema?: unknown}>} | undefined>;
17
+ }
18
+
19
+ export interface DocumentedResponseOptions {
20
+ /** The `/openapi.json` document the app serves. */
21
+ spec: OpenApiResponseSpec;
22
+ /** The OpenAPI path template, e.g. `/announcements/{id}/click`. */
23
+ path: string;
24
+ /** HTTP method, any case. */
25
+ method: string;
26
+ /** The real response: its status picks the documented response, its body is validated. */
27
+ response: {status: number; body: unknown};
28
+ /** Response media type to validate against. Defaults to `application/json`. */
29
+ contentType?: string;
30
+ }
31
+
32
+ export interface DocumentedResponseResult {
33
+ valid: boolean;
34
+ errors: string[];
35
+ }
36
+
37
+ const findResponseSchema = ({
38
+ contentType,
39
+ method,
40
+ path,
41
+ spec,
42
+ status,
43
+ }: {
44
+ contentType: string;
45
+ method: string;
46
+ path: string;
47
+ spec: OpenApiResponseSpec;
48
+ status: number;
49
+ }): unknown => {
50
+ const label = `${method.toUpperCase()} ${path}`;
51
+ const operation = spec.paths?.[path]?.[method.toLowerCase()];
52
+ if (!operation) {
53
+ throw new DocumentedResponseError(`${label} is not documented in the OpenAPI spec`);
54
+ }
55
+ const documented = operation.responses?.[String(status)];
56
+ if (!documented) {
57
+ const statuses = Object.keys(operation.responses ?? {}).join(", ") || "none";
58
+ throw new DocumentedResponseError(
59
+ `${label} has no documented ${status} response (documented: ${statuses})`
60
+ );
61
+ }
62
+ const schema = documented.content?.[contentType]?.schema;
63
+ if (!schema) {
64
+ throw new DocumentedResponseError(`${label} ${status} response has no ${contentType} schema`);
65
+ }
66
+ return schema;
67
+ };
68
+
69
+ /**
70
+ * Validates a real response body against the response schema `/openapi.json` documents for it,
71
+ * resolving `#/components/...` references against the same spec.
72
+ */
73
+ export const validateDocumentedResponse = ({
74
+ contentType = "application/json",
75
+ method,
76
+ path,
77
+ response,
78
+ spec,
79
+ }: DocumentedResponseOptions): DocumentedResponseResult => {
80
+ const schema = findResponseSchema({contentType, method, path, spec, status: response.status});
81
+ const ajv = new Ajv({allErrors: true, strict: false});
82
+ addFormats(ajv as unknown as Parameters<typeof addFormats>[0]);
83
+ // Wrapping keeps `#/components/...` refs resolvable from the root of the compiled schema.
84
+ const validate = ajv.compile({allOf: [schema], components: spec.components ?? {}});
85
+ if (validate(response.body)) {
86
+ return {errors: [], valid: true};
87
+ }
88
+ const errors = (validate.errors ?? []).map(
89
+ (error) => `${error.instancePath || "(root)"} ${error.message ?? "is invalid"}`
90
+ );
91
+ return {errors, valid: false};
92
+ };
93
+
94
+ /** Throws with every schema violation when a response body does not match its documentation. */
95
+ export const expectDocumentedResponse = (options: DocumentedResponseOptions): void => {
96
+ const {errors, valid} = validateDocumentedResponse(options);
97
+ if (valid) {
98
+ return;
99
+ }
100
+ const label = `${options.method.toUpperCase()} ${options.path} ${options.response.status}`;
101
+ throw new DocumentedResponseError(
102
+ `${label} response does not match its OpenAPI schema:\n- ${errors.join("\n- ")}\nBody: ${JSON.stringify(options.response.body)}`
103
+ );
104
+ };
@@ -2,3 +2,10 @@
2
2
  if (!process.env.TERRENO_TEST_MONGODB_URI?.trim()) {
3
3
  process.env.TERRENO_TEST_USE_MEMORY_MONGO = "true";
4
4
  }
5
+
6
+ /**
7
+ * Builds a sparse env for code that accepts an injected `NodeJS.ProcessEnv`. The global
8
+ * augmentation in `src/types.d.ts` marks server settings required, which test inputs omit.
9
+ */
10
+ export const partialEnv = (vars: Partial<NodeJS.ProcessEnv> = {}): NodeJS.ProcessEnv =>
11
+ vars as NodeJS.ProcessEnv;
package/src/tests.ts CHANGED
@@ -25,6 +25,7 @@ import {loadTestDataFromCache, setupTestCache} from "./tests/mongoTestSetup";
25
25
  import {setupDb, setupTestData} from "./tests/testHelper";
26
26
  import type {TestData} from "./tests/types";
27
27
 
28
+ export {authUserModel} from "./tests/models";
28
29
  export type {Food, FoodCategory, RequiredField, StaffUser, SuperUser, TestData, User};
29
30
  export {
30
31
  createTestData,
@@ -55,3 +56,10 @@ export const authAsUser = async (
55
56
  };
56
57
 
57
58
  export {loadTestData} from "./tests/mongoTestSetup";
59
+ export {
60
+ type DocumentedResponseOptions,
61
+ type DocumentedResponseResult,
62
+ expectDocumentedResponse,
63
+ type OpenApiResponseSpec,
64
+ validateDocumentedResponse,
65
+ } from "./tests/openApiResponseSchema";
@@ -0,0 +1,80 @@
1
+ import type mongoose from "mongoose";
2
+ import type {FindExactlyOnePlugin, FindOneOrNonePlugin} from "../plugins";
3
+ import type {RequestCredential} from "../requestContext";
4
+
5
+ /** Outcome of one MCP tool call. */
6
+ export type McpRequestLogOutcome = "ok" | "tool_error" | "exception";
7
+
8
+ /**
9
+ * Metadata for one MCP tool call. Holds no tool arguments, results, or error text, since those
10
+ * can carry personal data.
11
+ */
12
+ export interface McpRequestLogDocument extends mongoose.Document {
13
+ _id: mongoose.Types.ObjectId;
14
+ created: Date;
15
+ credential?: RequestCredential;
16
+ durationMs: number;
17
+ /** Error class name for an `exception` outcome, such as `ForbiddenError`. Never the message. */
18
+ errorName?: string;
19
+ expiresAt: Date;
20
+ oauthClientId?: string;
21
+ oauthFamilyId?: string;
22
+ outcome: McpRequestLogOutcome;
23
+ serviceTokenId?: string;
24
+ toolName: string;
25
+ updated: Date;
26
+ userId?: mongoose.Types.ObjectId;
27
+ }
28
+
29
+ export type McpRequestLogMethods = Record<string, never>;
30
+
31
+ export interface McpRequestLogStatics
32
+ extends FindExactlyOnePlugin<McpRequestLogDocument>,
33
+ FindOneOrNonePlugin<McpRequestLogDocument> {}
34
+
35
+ export type McpRequestLogModel = mongoose.Model<McpRequestLogDocument> & McpRequestLogStatics;
36
+
37
+ export type McpRequestLogSchema = mongoose.Schema<
38
+ McpRequestLogDocument,
39
+ McpRequestLogModel,
40
+ McpRequestLogMethods
41
+ >;
42
+
43
+ /** Where an MCP tool comes from. */
44
+ export type McpToolSource = "model" | "custom";
45
+
46
+ /** Admin switch and registry entry for one MCP tool. A tool with no row is enabled. */
47
+ export interface McpToolSettingDocument extends mongoose.Document {
48
+ _id: mongoose.Types.ObjectId;
49
+ created: Date;
50
+ description?: string;
51
+ enabled: boolean;
52
+ /** False when the running server no longer registers this tool. */
53
+ registered: boolean;
54
+ lastRegisteredAt?: Date;
55
+ name: string;
56
+ source: McpToolSource;
57
+ updated: Date;
58
+ }
59
+
60
+ export type McpToolSettingMethods = Record<string, never>;
61
+
62
+ export interface McpToolSettingStatics
63
+ extends FindExactlyOnePlugin<McpToolSettingDocument>,
64
+ FindOneOrNonePlugin<McpToolSettingDocument> {
65
+ /** Names of tools an admin turned off. */
66
+ disabledNames: (this: McpToolSettingModel) => Promise<Set<string>>;
67
+ /** Upsert one row per registered tool and mark rows for tools that are gone. */
68
+ syncRegistered: (
69
+ this: McpToolSettingModel,
70
+ tools: Array<{description: string; name: string; source: McpToolSource}>
71
+ ) => Promise<void>;
72
+ }
73
+
74
+ export type McpToolSettingModel = mongoose.Model<McpToolSettingDocument> & McpToolSettingStatics;
75
+
76
+ export type McpToolSettingSchema = mongoose.Schema<
77
+ McpToolSettingDocument,
78
+ McpToolSettingModel,
79
+ McpToolSettingMethods
80
+ >;
@@ -154,6 +154,11 @@ interface McpOAuthTokenStatics
154
154
  /** Revoke every family issued to this client. */
155
155
  revokeClient: (this: McpOAuthTokenModel, clientId: string) => Promise<void>;
156
156
  revokeFamily: (this: McpOAuthTokenModel, familyId: string) => Promise<void>;
157
+ /** Revoke every active token family the user holds. Returns how many families were revoked. */
158
+ revokeAllForUser: (
159
+ this: McpOAuthTokenModel,
160
+ userId: mongoose.Types.ObjectId | string
161
+ ) => Promise<number>;
157
162
  verifyAccessToken: (
158
163
  this: McpOAuthTokenModel,
159
164
  token: string
@@ -15,7 +15,7 @@ export interface McpServiceTokenStatics
15
15
  FindOneOrNonePlugin<McpServiceTokenDocument> {
16
16
  countActiveForUser: (
17
17
  this: McpServiceTokenModel,
18
- userId: mongoose.Types.ObjectId
18
+ userId: mongoose.Types.ObjectId | string
19
19
  ) => Promise<number>;
20
20
  issueFor: (
21
21
  this: McpServiceTokenModel,
@@ -26,10 +26,15 @@ export interface McpServiceTokenStatics
26
26
  this: McpServiceTokenModel,
27
27
  user: {_id: {toString(): string}; tokenEpoch?: number}
28
28
  ) => Promise<void>;
29
+ /** Revoke every active service token the user holds. Returns how many were revoked. */
30
+ revokeAllForUser: (
31
+ this: McpServiceTokenModel,
32
+ userId: mongoose.Types.ObjectId | string
33
+ ) => Promise<number>;
29
34
  revokeForUser: (
30
35
  this: McpServiceTokenModel,
31
36
  user: {_id: {toString(): string}},
32
- tokenId: mongoose.Types.ObjectId
37
+ tokenId: string
33
38
  ) => Promise<McpServiceTokenDocument | null>;
34
39
  verify: (this: McpServiceTokenModel, token: string) => Promise<McpServiceTokenDocument | null>;
35
40
  }
@@ -38,9 +43,12 @@ export interface McpServiceTokenModel
38
43
  extends mongoose.Model<McpServiceTokenDocument, object, McpServiceTokenMethods>,
39
44
  McpServiceTokenStatics {}
40
45
 
41
- export interface McpServiceTokenDocument extends mongoose.Document {
42
- _id: mongoose.Types.ObjectId;
46
+ export interface McpServiceTokenDocument extends mongoose.Document<string> {
47
+ /** UUID for new rows; ObjectId hex for rows migrated by mcp-service-token-string-ids. */
48
+ _id: string;
43
49
  created: Date;
50
+ /** Always false: a delete revokes the token instead of tombstoning it. */
51
+ deleted: boolean;
44
52
  expiresAt?: Date;
45
53
  lastUsedAt?: Date;
46
54
  name: string;
@@ -1,7 +1,8 @@
1
1
  import type express from "express";
2
2
 
3
- import {asyncHandler} from "./api";
3
+ import {asyncHandler, type OpenApiMiddleware} from "./api";
4
4
  import {VersionConfig} from "./models/versionConfig";
5
+ import {createOpenApiBuilder} from "./openApiBuilder";
5
6
  import type {TerrenoPlugin} from "./terrenoPlugin";
6
7
 
7
8
  export type VersionCheckStatus = "ok" | "warning" | "required";
@@ -26,9 +27,47 @@ const DEFAULT_POLLING_INTERVAL_MINUTES = 1440;
26
27
  * Compares client build number against admin-configured thresholds per platform.
27
28
  */
28
29
  export class VersionCheckPlugin implements TerrenoPlugin {
29
- register(app: express.Application): void {
30
+ register(app: express.Application, openApi?: unknown): void {
31
+ // Documentation only: request validation stays off so unparseable versions still get "ok".
32
+ const versionCheckOpenApi = createOpenApiBuilder(
33
+ openApi ? {openApi: openApi as OpenApiMiddleware} : {}
34
+ )
35
+ .withTags(["version"])
36
+ .withSummary("Check whether the client build must or should update")
37
+ .withQueryParameter(
38
+ "platform",
39
+ {enum: ["web", "mobile"], type: "string"},
40
+ {description: "Client platform. Any other value is treated as web."}
41
+ )
42
+ .withQueryParameter(
43
+ "version",
44
+ {type: "integer"},
45
+ {description: "Client build number. When missing or not a number, the status is ok."}
46
+ )
47
+ .withResponse(
48
+ 200,
49
+ {
50
+ message: {
51
+ description: "Message to show when status is warning or required",
52
+ type: "string",
53
+ },
54
+ pollingIntervalMs: {
55
+ description: "How often the client should poll for updates, in milliseconds",
56
+ type: "number",
57
+ },
58
+ requiredVersion: {description: "Minimum supported build number", type: "number"},
59
+ status: {enum: ["ok", "warning", "required"], type: "string"},
60
+ updateUrl: {description: "Where the user can get the update", type: "string"},
61
+ warningVersion: {description: "Builds below this number get a warning", type: "number"},
62
+ },
63
+ {required: ["status"]}
64
+ )
65
+ .withValidation({enabled: false})
66
+ .build();
67
+
30
68
  app.get(
31
69
  "/version-check",
70
+ versionCheckOpenApi,
32
71
  asyncHandler(async (req, res) => {
33
72
  const versionParam = req.query.version;
34
73
  const platform = req.query.platform as string | undefined;
@@ -81,7 +81,7 @@ describe("hmacSignature", () => {
81
81
 
82
82
  it("rejects a missing raw body", () => {
83
83
  const verify = hmacSignature({header: "X-Webhook-Signature", secret: SECRET});
84
- const req = {headers: {"x-webhook-signature": VALID_HEX}} as Request;
84
+ const req = {headers: {"x-webhook-signature": VALID_HEX}} as unknown as Request;
85
85
  assert.isFalse(verify(req));
86
86
  });
87
87
 
@@ -0,0 +1,14 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "noEmit": true,
5
+ "composite": false,
6
+ "incremental": false,
7
+ "declaration": false,
8
+ "declarationMap": false
9
+ },
10
+ "exclude": [
11
+ "node_modules",
12
+ "dist"
13
+ ]
14
+ }
@@ -1,13 +0,0 @@
1
- /**
2
- * One-line warning for modelRouter `realtime`. Keep in sync with the
3
- * `@terreno/rtk` helpers and `docs/implementationPlans/remove-legacy-realtime.md`.
4
- */
5
- /** @internal */
6
- export declare const REALTIME_DEPRECATION_MESSAGE = "modelRouter `realtime` is deprecated and will be removed in Terreno 58. Use `sync` with `@terreno/syncdb` instead. See docs/how-to/migrate-rtk-to-syncdb.md. RealtimeApp remains required for sync sockets.";
7
- /**
8
- * Emits a one-time deprecation warning per model/routePath per process when a
9
- * consumer enables the legacy RTK cache-patching `realtime` option.
10
- */
11
- export declare const warnRealtimeDeprecated: (modelName: string, routePath?: string) => void;
12
- /** @internal Test helper — clears one-time realtime deprecation warnings. */
13
- export declare const resetRealtimeDeprecationWarningsForTests: () => void;
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resetRealtimeDeprecationWarningsForTests = exports.warnRealtimeDeprecated = exports.REALTIME_DEPRECATION_MESSAGE = void 0;
4
- const logger_1 = require("../logger");
5
- /**
6
- * One-line warning for modelRouter `realtime`. Keep in sync with the
7
- * `@terreno/rtk` helpers and `docs/implementationPlans/remove-legacy-realtime.md`.
8
- */
9
- /** @internal */
10
- exports.REALTIME_DEPRECATION_MESSAGE = "modelRouter `realtime` is deprecated and will be removed in Terreno 58. Use `sync` with `@terreno/syncdb` instead. See docs/how-to/migrate-rtk-to-syncdb.md. RealtimeApp remains required for sync sockets.";
11
- const warnedKeys = new Set();
12
- const warningKey = (modelName, routePath) => `${modelName}:${routePath ?? ""}`;
13
- /**
14
- * Emits a one-time deprecation warning per model/routePath per process when a
15
- * consumer enables the legacy RTK cache-patching `realtime` option.
16
- */
17
- const warnRealtimeDeprecated = (modelName, routePath) => {
18
- const key = warningKey(modelName, routePath);
19
- if (warnedKeys.has(key)) {
20
- return;
21
- }
22
- warnedKeys.add(key);
23
- const location = routePath ? `${modelName} at ${routePath}` : modelName;
24
- logger_1.logger.warn(`[realtime] ${exports.REALTIME_DEPRECATION_MESSAGE} (${location})`);
25
- };
26
- exports.warnRealtimeDeprecated = warnRealtimeDeprecated;
27
- /** @internal Test helper — clears one-time realtime deprecation warnings. */
28
- const resetRealtimeDeprecationWarningsForTests = () => {
29
- warnedKeys.clear();
30
- };
31
- exports.resetRealtimeDeprecationWarningsForTests = resetRealtimeDeprecationWarningsForTests;
@@ -1,37 +0,0 @@
1
- /**
2
- * Manages query subscriptions for Socket.io clients.
3
- *
4
- * When a client subscribes to a query (e.g., `{completed: false}` on the "todos" collection),
5
- * the query is stored here. The change stream watcher consults this store to determine
6
- * which query rooms should receive a given change event.
7
- */
8
- /**
9
- * Compute a deterministic queryId from collection and query on the server side.
10
- * This prevents clients from hijacking other subscriptions by providing a colliding queryId.
11
- */
12
- export declare const computeQueryId: (collection: string, query: Record<string, unknown>) => string;
13
- /**
14
- * Register a query subscription for a socket.
15
- * The socket joins the `query:{queryId}` room (handled by the caller).
16
- */
17
- export declare const addQuerySubscription: (socketId: string, collection: string, query: Record<string, unknown>, queryId: string) => void;
18
- /**
19
- * Remove a single query subscription for a socket.
20
- */
21
- export declare const removeQuerySubscription: (socketId: string, queryId: string) => void;
22
- /**
23
- * Remove all query subscriptions for a disconnected socket.
24
- */
25
- export declare const removeAllSocketQueries: (socketId: string) => void;
26
- /**
27
- * Get all unique query subscriptions for a given collection.
28
- * Used by the change stream watcher to evaluate which query rooms to emit to.
29
- */
30
- export declare const getQuerySubscriptionsForCollection: (collection: string) => {
31
- queryId: string;
32
- query: Record<string, unknown>;
33
- }[];
34
- /**
35
- * Clear all subscriptions (for testing).
36
- */
37
- export declare const clearQueryStore: () => void;