@terreno/api 57.20.0 → 57.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/biome.jsonc +1 -0
  3. package/dist/api.d.ts +3 -3
  4. package/dist/frameworkModelNames.d.ts +4 -0
  5. package/dist/frameworkModelNames.js +4 -0
  6. package/dist/index.d.ts +4 -0
  7. package/dist/index.js +9 -3
  8. package/dist/mcp/adminTracking.d.ts +28 -0
  9. package/dist/mcp/adminTracking.js +80 -0
  10. package/dist/mcp/auth.d.ts +6 -0
  11. package/dist/mcp/auth.js +12 -2
  12. package/dist/mcp/server.d.ts +8 -0
  13. package/dist/mcp/server.js +48 -4
  14. package/dist/models/mcpOAuthToken.js +27 -0
  15. package/dist/models/mcpRequestLog.d.ts +2 -0
  16. package/dist/models/mcpRequestLog.js +73 -0
  17. package/dist/models/mcpServiceToken.js +4 -0
  18. package/dist/models/mcpToolSetting.d.ts +2 -0
  19. package/dist/models/mcpToolSetting.js +119 -0
  20. package/dist/models/versionConfig.d.ts +2 -0
  21. package/dist/rbac/auditModel.d.ts +2 -1
  22. package/dist/terrenoApp.d.ts +12 -0
  23. package/dist/terrenoApp.js +3 -0
  24. package/dist/tests/models.d.ts +17 -22
  25. package/dist/tests/models.js +7 -1
  26. package/dist/tests/testHelper.d.ts +6 -12
  27. package/dist/tests.d.ts +1 -0
  28. package/dist/tests.js +3 -1
  29. package/dist/types/mcpAdmin.d.ts +58 -0
  30. package/dist/types/mcpAdmin.js +2 -0
  31. package/dist/types/mcpOAuth.d.ts +2 -0
  32. package/dist/types/mcpServiceToken.d.ts +2 -0
  33. package/e2e/smoke.ts +193 -0
  34. package/package.json +7 -5
  35. package/src/adminModelRouter.test.ts +8 -6
  36. package/src/api.arrayOperations.test.ts +31 -22
  37. package/src/api.hooks.test.ts +12 -11
  38. package/src/api.query.test.ts +2 -2
  39. package/src/api.test.ts +8 -7
  40. package/src/api.ts +3 -3
  41. package/src/audit/auditApp.test.ts +1 -1
  42. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  43. package/src/auth.test.ts +21 -7
  44. package/src/authRecovery.test.ts +10 -10
  45. package/src/authVerification.test.ts +7 -7
  46. package/src/betterAuthFeatures.test.ts +3 -2
  47. package/src/betterAuthLinking.test.ts +3 -1
  48. package/src/betterAuthSetup.test.ts +77 -51
  49. package/src/collectionRegistry.test.ts +4 -4
  50. package/src/frameworkModelNames.test.ts +8 -0
  51. package/src/frameworkModelNames.ts +4 -0
  52. package/src/githubAuth.test.ts +11 -11
  53. package/src/index.ts +8 -0
  54. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  55. package/src/mcp/actionTools.test.ts +11 -5
  56. package/src/mcp/adminTracking.test.ts +272 -0
  57. package/src/mcp/adminTracking.ts +104 -0
  58. package/src/mcp/auth.ts +18 -2
  59. package/src/mcp/oauth.test.ts +1 -1
  60. package/src/mcp/server.ts +67 -4
  61. package/src/mcp/serviceTokens.test.ts +2 -1
  62. package/src/mcp/toolGenerator.test.ts +9 -5
  63. package/src/migrations/cli.test.ts +15 -14
  64. package/src/migrations/cli.ts +1 -1
  65. package/src/migrations/generate.test.ts +2 -2
  66. package/src/migrations/load.test.ts +1 -1
  67. package/src/migrations/lock.test.ts +8 -3
  68. package/src/migrations/runner.test.ts +16 -5
  69. package/src/migrations/schemaCatalog.test.ts +4 -1
  70. package/src/models/mcpOAuthToken.test.ts +42 -0
  71. package/src/models/mcpOAuthToken.ts +32 -0
  72. package/src/models/mcpRequestLog.ts +81 -0
  73. package/src/models/mcpServiceToken.test.ts +23 -0
  74. package/src/models/mcpServiceToken.ts +10 -0
  75. package/src/models/mcpToolSetting.test.ts +69 -0
  76. package/src/models/mcpToolSetting.ts +138 -0
  77. package/src/models/versionConfig.ts +2 -0
  78. package/src/notifications/notificationsApp.test.ts +5 -8
  79. package/src/notifiers/slackWebApi.test.ts +30 -8
  80. package/src/openApi.test.ts +4 -4
  81. package/src/openApiValidator.test.ts +3 -3
  82. package/src/orgs/orgPermissions.test.ts +2 -2
  83. package/src/orgs/orgPlugin.test.ts +4 -3
  84. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  85. package/src/orgs/organizationSettings.test.ts +1 -1
  86. package/src/orgs/orgsApp.test.ts +5 -3
  87. package/src/permissions.test.ts +2 -2
  88. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  89. package/src/rbac/assertAllowed.test.ts +1 -1
  90. package/src/rbac/auditModel.ts +10 -2
  91. package/src/rbac/realtimeAccess.test.ts +3 -2
  92. package/src/rbac/routes.test.ts +1 -1
  93. package/src/rbac/userWriteGuards.test.ts +8 -5
  94. package/src/realtime/realtime.test.ts +35 -31
  95. package/src/scrubAdminFields.test.ts +1 -1
  96. package/src/sync/adminWindowMutation.test.ts +4 -3
  97. package/src/sync/executors.test.ts +1 -1
  98. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  99. package/src/sync/sync.test.ts +1 -1
  100. package/src/sync/syncPhaseC.test.ts +14 -11
  101. package/src/sync/syncRoutes.test.ts +8 -8
  102. package/src/sync/syncSeqPlugin.test.ts +1 -2
  103. package/src/sync/syncSocket.test.ts +5 -4
  104. package/src/terrenoApp.mcpServiceTokens.test.ts +2 -2
  105. package/src/terrenoApp.migrations.test.ts +8 -7
  106. package/src/terrenoApp.ts +14 -0
  107. package/src/tests/betterAuthStubs.ts +3 -2
  108. package/src/tests/bunSetup.ts +1 -1
  109. package/src/tests/models.ts +10 -0
  110. package/src/tests/testEnv.ts +7 -0
  111. package/src/tests.ts +1 -0
  112. package/src/types/mcpAdmin.ts +80 -0
  113. package/src/types/mcpOAuth.ts +5 -0
  114. package/src/types/mcpServiceToken.ts +5 -0
  115. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  116. package/tsconfig.typecheck.json +14 -0
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";
@@ -148,6 +149,17 @@ export interface TerrenoAppOptions {
148
149
  * [Enable MCP OAuth](../how-to/enable-mcp-oauth.md).
149
150
  */
150
151
  mcpOAuth?: McpOAuthAppOption;
152
+ /**
153
+ * Opt-in log of MCP tool calls for the admin panel. `true` keeps rows 30 days. Rows hold
154
+ * metadata only (tool, user, credential ids, duration, outcome, error class), never tool
155
+ * arguments, results, or error text. See [Manage MCP from the admin panel](../how-to/manage-mcp-in-admin.md).
156
+ */
157
+ mcpRequestLog?: McpRequestLogAppOption;
158
+ /**
159
+ * Opt-in MCP tool registry. When true, every tool is recorded in `McpToolSetting` at startup,
160
+ * and tools an admin switches off are hidden from `tools/list` and rejected by `tools/call`.
161
+ */
162
+ mcpToolSettings?: boolean;
151
163
  /**
152
164
  * Versioned MongoDB migrations. `runOnStart` defaults to false. When true, wet `up`
153
165
  * runs after listen and `ensureSyncIndexes`. Production still requires
@@ -556,6 +568,8 @@ export class TerrenoApp {
556
568
  betterAuth,
557
569
  mcpOAuth,
558
570
  mcpServiceTokens: mcpServiceTokens.enabled,
571
+ requestLog: resolveMcpRequestLogOption(options.mcpRequestLog),
572
+ toolSettings: options.mcpToolSettings === true,
559
573
  userModel: options.userModel,
560
574
  });
561
575
 
@@ -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
  });
@@ -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,
@@ -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?: mongoose.Types.ObjectId;
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
@@ -26,6 +26,11 @@ 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}},
@@ -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
+ }