@terreno/api 57.20.0 → 57.22.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 +81 -0
  2. package/biome.jsonc +3 -2
  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
@@ -103,6 +103,10 @@ mcpServiceTokenSchema.statics = {
103
103
  });
104
104
  return { mcpServiceToken, token };
105
105
  },
106
+ async revokeAllForUser(userId) {
107
+ const result = await this.updateMany({ revokedAt: { $exists: false }, userId: new mongoose_1.default.Types.ObjectId(String(userId)) }, { $set: { revokedAt: luxon_1.DateTime.now().toJSDate() } });
108
+ return result.modifiedCount;
109
+ },
106
110
  async revokeForUser(user, tokenId) {
107
111
  return this.findOneAndUpdate({
108
112
  _id: tokenId,
@@ -0,0 +1,2 @@
1
+ import type { McpToolSettingModel } from "../types/mcpAdmin";
2
+ export declare const McpToolSetting: McpToolSettingModel;
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.McpToolSetting = void 0;
7
+ const luxon_1 = require("luxon");
8
+ const mongoose_1 = __importDefault(require("mongoose"));
9
+ const logger_1 = require("../logger");
10
+ const plugins_1 = require("../plugins");
11
+ /**
12
+ * Registry of MCP tools with an admin on/off switch. Rows are written when the server mounts
13
+ * with `mcpToolSettings` on. A tool with no row, or with `enabled: true`, is served.
14
+ */
15
+ const mcpToolSettingSchema = new mongoose_1.default.Schema({
16
+ description: {
17
+ description: "Tool description as sent to MCP clients",
18
+ type: String,
19
+ },
20
+ enabled: {
21
+ default: true,
22
+ description: "When false, the tool is hidden from tools/list and tools/call rejects it",
23
+ type: Boolean,
24
+ },
25
+ lastRegisteredAt: {
26
+ description: "Last server start that registered this tool",
27
+ type: Date,
28
+ },
29
+ name: {
30
+ description: "MCP tool name",
31
+ required: true,
32
+ type: String,
33
+ unique: true,
34
+ },
35
+ registered: {
36
+ default: true,
37
+ description: "False when the running server no longer registers this tool",
38
+ type: Boolean,
39
+ },
40
+ source: {
41
+ description: "model (generated from a modelRouter) or custom (registerMCPTool)",
42
+ enum: ["model", "custom"],
43
+ required: true,
44
+ type: String,
45
+ },
46
+ }, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
47
+ /** How long one process reuses the disabled-tool set before reading it again. */
48
+ const DISABLED_NAMES_TTL_MS = 5000;
49
+ // Per-process cache so /mcp does not query Mongo on every request. Writes through this model
50
+ // clear it at once; other processes pick up a change within DISABLED_NAMES_TTL_MS.
51
+ const disabledNamesCache = { expiresAt: 0 };
52
+ const clearDisabledNamesCache = () => {
53
+ disabledNamesCache.expiresAt = 0;
54
+ disabledNamesCache.names = undefined;
55
+ };
56
+ for (const hook of [
57
+ "save",
58
+ "updateOne",
59
+ "updateMany",
60
+ "findOneAndUpdate",
61
+ "deleteOne",
62
+ "deleteMany",
63
+ "findOneAndDelete",
64
+ ]) {
65
+ mcpToolSettingSchema.post(hook, clearDisabledNamesCache);
66
+ }
67
+ mcpToolSettingSchema.post("bulkWrite", clearDisabledNamesCache);
68
+ mcpToolSettingSchema.plugin(plugins_1.createdUpdatedPlugin);
69
+ mcpToolSettingSchema.plugin(plugins_1.findOneOrNone);
70
+ mcpToolSettingSchema.plugin(plugins_1.findExactlyOne);
71
+ mcpToolSettingSchema.statics = {
72
+ ...mcpToolSettingSchema.statics,
73
+ async disabledNames() {
74
+ const now = luxon_1.DateTime.now().toMillis();
75
+ if (disabledNamesCache.names && now < disabledNamesCache.expiresAt) {
76
+ return disabledNamesCache.names;
77
+ }
78
+ try {
79
+ const rows = await this.find({ enabled: false }).select({ name: 1 }).lean();
80
+ const names = new Set(rows.map((row) => row.name));
81
+ disabledNamesCache.names = names;
82
+ disabledNamesCache.expiresAt = now + DISABLED_NAMES_TTL_MS;
83
+ return names;
84
+ }
85
+ catch (error) {
86
+ // Keep enforcing the last known switches rather than re-enabling every tool. With no
87
+ // known state, fail the request (closed) instead of serving tools an admin turned off.
88
+ if (disabledNamesCache.names) {
89
+ logger_1.logger.warn(`[mcp] Tool settings read failed; using last known: ${String(error)}`);
90
+ return disabledNamesCache.names;
91
+ }
92
+ throw error;
93
+ }
94
+ },
95
+ async syncRegistered(tools) {
96
+ const now = luxon_1.DateTime.now().toJSDate();
97
+ if (tools.length > 0) {
98
+ // `enabled` is only set on insert so a restart never undoes an admin's switch.
99
+ await this.bulkWrite(tools.map((tool) => ({
100
+ updateOne: {
101
+ filter: { name: tool.name },
102
+ update: {
103
+ $set: {
104
+ description: tool.description,
105
+ lastRegisteredAt: now,
106
+ registered: true,
107
+ source: tool.source,
108
+ },
109
+ $setOnInsert: { enabled: true },
110
+ },
111
+ upsert: true,
112
+ },
113
+ })));
114
+ }
115
+ await this.updateMany({ name: { $nin: tools.map((tool) => tool.name) }, registered: { $ne: false } }, { $set: { registered: false } });
116
+ },
117
+ };
118
+ exports.McpToolSetting = mongoose_1.default.models.TerrenoMcpToolSetting ??
119
+ mongoose_1.default.model("TerrenoMcpToolSetting", mcpToolSettingSchema, "mcptoolsettings");
@@ -10,6 +10,8 @@ export interface VersionConfigDocument extends mongoose.Document {
10
10
  updateUrl?: string;
11
11
  /** How often clients should poll for version updates, in minutes. Defaults to 1440 (24 hours). */
12
12
  pollingIntervalMinutes: number;
13
+ /** Singleton sentinel backing the unique index; not selected by default. */
14
+ _singleton?: "config";
13
15
  created?: Date;
14
16
  updated?: Date;
15
17
  }
@@ -1,4 +1,5 @@
1
1
  import mongoose from "mongoose";
2
+ import { type FindExactlyOnePlugin, type FindOneOrNonePlugin } from "../plugins";
2
3
  import type { PermissionSet } from "./statements";
3
4
  export interface RbacAuditDocument {
4
5
  _id: mongoose.Types.ObjectId;
@@ -14,7 +15,7 @@ export interface RbacAuditDocument {
14
15
  created: Date;
15
16
  updated: Date;
16
17
  }
17
- export type RbacAuditModel = mongoose.Model<RbacAuditDocument>;
18
+ export type RbacAuditModel = mongoose.Model<RbacAuditDocument> & FindExactlyOnePlugin<RbacAuditDocument> & FindOneOrNonePlugin<RbacAuditDocument>;
18
19
  export declare const createRbacAuditModel: (connection: mongoose.Connection) => RbacAuditModel;
19
20
  export interface RbacAuditWrite {
20
21
  action: string;
@@ -8,6 +8,7 @@ import { type ConfigurationAppOptions, type ConfigurationModelLike } from "./con
8
8
  import { type AddRoutes, type AuthOptions } from "./expressServer";
9
9
  import { type GitHubAuthOptions } from "./githubAuth";
10
10
  import { type LoggingOptions } from "./logger";
11
+ import { type McpRequestLogAppOption } from "./mcp/adminTracking";
11
12
  import { type McpOAuthAppOption } from "./mcp/oauthMetadata";
12
13
  import { type McpServiceTokensAppOption } from "./mcp/serviceTokens";
13
14
  import { type StartupMigrationsOption } from "./migrations/runner";
@@ -92,6 +93,17 @@ export interface TerrenoAppOptions {
92
93
  * [Enable MCP OAuth](../how-to/enable-mcp-oauth.md).
93
94
  */
94
95
  mcpOAuth?: McpOAuthAppOption;
96
+ /**
97
+ * Opt-in log of MCP tool calls for the admin panel. `true` keeps rows 30 days. Rows hold
98
+ * metadata only (tool, user, credential ids, duration, outcome, error class), never tool
99
+ * arguments, results, or error text. See [Manage MCP from the admin panel](../how-to/manage-mcp-in-admin.md).
100
+ */
101
+ mcpRequestLog?: McpRequestLogAppOption;
102
+ /**
103
+ * Opt-in MCP tool registry. When true, every tool is recorded in `McpToolSetting` at startup,
104
+ * and tools an admin switches off are hidden from `tools/list` and rejected by `tools/call`.
105
+ */
106
+ mcpToolSettings?: boolean;
95
107
  /**
96
108
  * Versioned MongoDB migrations. `runOnStart` defaults to false. When true, wet `up`
97
109
  * runs after listen and `ensureSyncIndexes`. Production still requires
@@ -54,6 +54,7 @@ const errors_1 = require("./errors");
54
54
  const expressServer_1 = require("./expressServer");
55
55
  const githubAuth_1 = require("./githubAuth");
56
56
  const logger_1 = require("./logger");
57
+ const adminTracking_1 = require("./mcp/adminTracking");
57
58
  const oauth_1 = require("./mcp/oauth");
58
59
  const oauthMetadata_1 = require("./mcp/oauthMetadata");
59
60
  const server_1 = require("./mcp/server");
@@ -430,6 +431,8 @@ class TerrenoApp {
430
431
  betterAuth,
431
432
  mcpOAuth,
432
433
  mcpServiceTokens: mcpServiceTokens.enabled,
434
+ requestLog: (0, adminTracking_1.resolveMcpRequestLogOption)(options.mcpRequestLog),
435
+ toolSettings: options.mcpToolSettings === true,
433
436
  userModel: options.userModel,
434
437
  });
435
438
  if (options.configureApp) {
@@ -1,5 +1,8 @@
1
1
  import mongoose, { type Model } from "mongoose";
2
+ import type { UserModel as AuthUserModel } from "../auth";
2
3
  export interface User {
4
+ _id: mongoose.Types.ObjectId;
5
+ id: string;
3
6
  admin: boolean;
4
7
  name?: string;
5
8
  username: string;
@@ -56,35 +59,27 @@ export interface RequiredField {
56
59
  name: string;
57
60
  about?: string;
58
61
  }
59
- export declare const UserModel: mongoose.Model<User, {}, {}, {}, mongoose.Document<unknown, {}, User, {}, mongoose.DefaultSchemaOptions> & User & {
62
+ export declare const UserModel: mongoose.Model<User, {}, {}, {}, mongoose.Document<unknown, {}, User, {}, mongoose.DefaultSchemaOptions> & User & Required<{
60
63
  _id: mongoose.Types.ObjectId;
61
- } & {
64
+ }> & {
62
65
  __v: number;
63
- } & {
64
- id: string;
65
66
  }, any, User>;
66
- export declare const SuperUserModel: mongoose.Model<User & SuperUser, {}, {}, {
67
- id: string;
68
- }, mongoose.Document<unknown, {}, User & SuperUser, {
69
- id: string;
70
- }, mongoose.DefaultSchemaOptions> & Omit<User & SuperUser & {
67
+ /**
68
+ * `UserModel` typed as the auth `UserModel` for `setupAuth`, `TerrenoApp({userModel})`, and
69
+ * friends. passport-local-mongoose adds the statics at runtime but ships no types, and the auth
70
+ * `User._id` uses mongoose's schema `ObjectId` type, so the models are not structurally related.
71
+ */
72
+ export declare const authUserModel: AuthUserModel;
73
+ export declare const SuperUserModel: mongoose.Model<User & SuperUser, {}, {}, {}, mongoose.Document<unknown, {}, User & SuperUser, {}, mongoose.DefaultSchemaOptions> & User & SuperUser & Required<{
71
74
  _id: mongoose.Types.ObjectId;
72
- } & {
75
+ }> & {
73
76
  __v: number;
74
- }, "id"> & mongoose.HydratedDocumentOverrides<{
75
- id: string;
76
- }>, any, User & SuperUser>;
77
- export declare const StaffUserModel: mongoose.Model<User & StaffUser, {}, {}, {
78
- id: string;
79
- }, mongoose.Document<unknown, {}, User & StaffUser, {
80
- id: string;
81
- }, mongoose.DefaultSchemaOptions> & Omit<User & StaffUser & {
77
+ }, any, User & SuperUser>;
78
+ export declare const StaffUserModel: mongoose.Model<User & StaffUser, {}, {}, {}, mongoose.Document<unknown, {}, User & StaffUser, {}, mongoose.DefaultSchemaOptions> & User & StaffUser & Required<{
82
79
  _id: mongoose.Types.ObjectId;
83
- } & {
80
+ }> & {
84
81
  __v: number;
85
- }, "id"> & mongoose.HydratedDocumentOverrides<{
86
- id: string;
87
- }>, any, User & StaffUser>;
82
+ }, any, User & StaffUser>;
88
83
  export declare const FoodModel: Model<Food>;
89
84
  export declare const RequiredModel: mongoose.Model<RequiredField, {}, {}, {}, mongoose.Document<unknown, {}, RequiredField, {}, mongoose.DefaultSchemaOptions> & RequiredField & {
90
85
  _id: mongoose.Types.ObjectId;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.RequiredModel = exports.FoodModel = exports.StaffUserModel = exports.SuperUserModel = exports.UserModel = void 0;
6
+ exports.RequiredModel = exports.FoodModel = exports.StaffUserModel = exports.SuperUserModel = exports.authUserModel = exports.UserModel = void 0;
7
7
  const mongoose_1 = require("mongoose");
8
8
  const passport_local_mongoose_1 = __importDefault(require("passport-local-mongoose"));
9
9
  const plugins_1 = require("../plugins");
@@ -47,6 +47,12 @@ userSchema.methods.postCreate = async function (body) {
47
47
  return this.save();
48
48
  };
49
49
  exports.UserModel = (0, mongoose_1.model)("User", userSchema);
50
+ /**
51
+ * `UserModel` typed as the auth `UserModel` for `setupAuth`, `TerrenoApp({userModel})`, and
52
+ * friends. passport-local-mongoose adds the statics at runtime but ships no types, and the auth
53
+ * `User._id` uses mongoose's schema `ObjectId` type, so the models are not structurally related.
54
+ */
55
+ exports.authUserModel = exports.UserModel;
50
56
  const superUserSchema = new mongoose_1.Schema({
51
57
  superTitle: { description: "The super user's title", required: true, type: String },
52
58
  });
@@ -1,23 +1,17 @@
1
1
  import type { TestData } from "./types";
2
2
  /** Seeds only the standard users (legacy helper). */
3
- export declare const setupDb: () => Promise<readonly [import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & {
3
+ export declare const setupDb: () => Promise<readonly [import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & Required<{
4
4
  _id: import("mongoose").Types.ObjectId;
5
- } & {
5
+ }> & {
6
6
  __v: number;
7
- } & {
8
- id: string;
9
- }, import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & {
7
+ }, import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & Required<{
10
8
  _id: import("mongoose").Types.ObjectId;
11
- } & {
9
+ }> & {
12
10
  __v: number;
13
- } & {
14
- id: string;
15
- }, import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & {
11
+ }, import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & Required<{
16
12
  _id: import("mongoose").Types.ObjectId;
17
- } & {
13
+ }> & {
18
14
  __v: number;
19
- } & {
20
- id: string;
21
15
  }]>;
22
16
  /** Seeds users, foods, and required docs — the recommended API test baseline. */
23
17
  export declare const setupTestData: () => Promise<TestData>;
package/dist/tests.d.ts CHANGED
@@ -6,6 +6,7 @@ import { type Food, type FoodCategory, FoodModel, type RequiredField, RequiredMo
6
6
  import { loadTestDataFromCache, setupTestCache } from "./tests/mongoTestSetup";
7
7
  import { setupDb, setupTestData } from "./tests/testHelper";
8
8
  import type { TestData } from "./tests/types";
9
+ export { authUserModel } from "./tests/models";
9
10
  export type { Food, FoodCategory, RequiredField, StaffUser, SuperUser, TestData, User };
10
11
  export { createTestData, FoodModel, loadTestDataFromCache, RequiredModel, StaffUserModel, SuperUserModel, setupDb, setupTestCache, setupTestData, UserModel, };
11
12
  export declare const getBaseServer: () => Express;
package/dist/tests.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.loadTestData = exports.authAsUser = exports.getBaseServer = exports.UserModel = exports.setupTestData = exports.setupTestCache = exports.setupDb = exports.SuperUserModel = exports.StaffUserModel = exports.RequiredModel = exports.loadTestDataFromCache = exports.FoodModel = exports.createTestData = void 0;
3
+ exports.loadTestData = exports.authAsUser = exports.getBaseServer = exports.UserModel = exports.setupTestData = exports.setupTestCache = exports.setupDb = exports.SuperUserModel = exports.StaffUserModel = exports.RequiredModel = exports.loadTestDataFromCache = exports.FoodModel = exports.createTestData = exports.authUserModel = void 0;
4
4
  const test_1 = require("@terreno/test");
5
5
  const openApiCompat_1 = require("./openApiCompat");
6
6
  const createTestData_1 = require("./tests/createTestData");
@@ -17,6 +17,8 @@ Object.defineProperty(exports, "setupTestCache", { enumerable: true, get: functi
17
17
  const testHelper_1 = require("./tests/testHelper");
18
18
  Object.defineProperty(exports, "setupDb", { enumerable: true, get: function () { return testHelper_1.setupDb; } });
19
19
  Object.defineProperty(exports, "setupTestData", { enumerable: true, get: function () { return testHelper_1.setupTestData; } });
20
+ var models_2 = require("./tests/models");
21
+ Object.defineProperty(exports, "authUserModel", { enumerable: true, get: function () { return models_2.authUserModel; } });
20
22
  const getBaseServer = () => {
21
23
  return (0, test_1.getBaseServer)({
22
24
  patchOpenApiCompat: openApiCompat_1.patchAppUse,
@@ -0,0 +1,58 @@
1
+ import type mongoose from "mongoose";
2
+ import type { FindExactlyOnePlugin, FindOneOrNonePlugin } from "../plugins";
3
+ import type { RequestCredential } from "../requestContext";
4
+ /** Outcome of one MCP tool call. */
5
+ export type McpRequestLogOutcome = "ok" | "tool_error" | "exception";
6
+ /**
7
+ * Metadata for one MCP tool call. Holds no tool arguments, results, or error text, since those
8
+ * can carry personal data.
9
+ */
10
+ export interface McpRequestLogDocument extends mongoose.Document {
11
+ _id: mongoose.Types.ObjectId;
12
+ created: Date;
13
+ credential?: RequestCredential;
14
+ durationMs: number;
15
+ /** Error class name for an `exception` outcome, such as `ForbiddenError`. Never the message. */
16
+ errorName?: string;
17
+ expiresAt: Date;
18
+ oauthClientId?: string;
19
+ oauthFamilyId?: string;
20
+ outcome: McpRequestLogOutcome;
21
+ serviceTokenId?: mongoose.Types.ObjectId;
22
+ toolName: string;
23
+ updated: Date;
24
+ userId?: mongoose.Types.ObjectId;
25
+ }
26
+ export type McpRequestLogMethods = Record<string, never>;
27
+ export interface McpRequestLogStatics extends FindExactlyOnePlugin<McpRequestLogDocument>, FindOneOrNonePlugin<McpRequestLogDocument> {
28
+ }
29
+ export type McpRequestLogModel = mongoose.Model<McpRequestLogDocument> & McpRequestLogStatics;
30
+ export type McpRequestLogSchema = mongoose.Schema<McpRequestLogDocument, McpRequestLogModel, McpRequestLogMethods>;
31
+ /** Where an MCP tool comes from. */
32
+ export type McpToolSource = "model" | "custom";
33
+ /** Admin switch and registry entry for one MCP tool. A tool with no row is enabled. */
34
+ export interface McpToolSettingDocument extends mongoose.Document {
35
+ _id: mongoose.Types.ObjectId;
36
+ created: Date;
37
+ description?: string;
38
+ enabled: boolean;
39
+ /** False when the running server no longer registers this tool. */
40
+ registered: boolean;
41
+ lastRegisteredAt?: Date;
42
+ name: string;
43
+ source: McpToolSource;
44
+ updated: Date;
45
+ }
46
+ export type McpToolSettingMethods = Record<string, never>;
47
+ export interface McpToolSettingStatics extends FindExactlyOnePlugin<McpToolSettingDocument>, FindOneOrNonePlugin<McpToolSettingDocument> {
48
+ /** Names of tools an admin turned off. */
49
+ disabledNames: (this: McpToolSettingModel) => Promise<Set<string>>;
50
+ /** Upsert one row per registered tool and mark rows for tools that are gone. */
51
+ syncRegistered: (this: McpToolSettingModel, tools: Array<{
52
+ description: string;
53
+ name: string;
54
+ source: McpToolSource;
55
+ }>) => Promise<void>;
56
+ }
57
+ export type McpToolSettingModel = mongoose.Model<McpToolSettingDocument> & McpToolSettingStatics;
58
+ export type McpToolSettingSchema = mongoose.Schema<McpToolSettingDocument, McpToolSettingModel, McpToolSettingMethods>;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -127,6 +127,8 @@ interface McpOAuthTokenStatics extends FindExactlyOnePlugin<McpOAuthTokenDocumen
127
127
  /** Revoke every family issued to this client. */
128
128
  revokeClient: (this: McpOAuthTokenModel, clientId: string) => Promise<void>;
129
129
  revokeFamily: (this: McpOAuthTokenModel, familyId: string) => Promise<void>;
130
+ /** Revoke every active token family the user holds. Returns how many families were revoked. */
131
+ revokeAllForUser: (this: McpOAuthTokenModel, userId: mongoose.Types.ObjectId | string) => Promise<number>;
130
132
  verifyAccessToken: (this: McpOAuthTokenModel, token: string) => Promise<McpOAuthTokenDocument | null>;
131
133
  }
132
134
  export interface McpOAuthTokenModel extends mongoose.Model<McpOAuthTokenDocument>, McpOAuthTokenStatics {
@@ -24,6 +24,8 @@ export interface McpServiceTokenStatics extends FindExactlyOnePlugin<McpServiceT
24
24
  };
25
25
  tokenEpoch?: number;
26
26
  }) => Promise<void>;
27
+ /** Revoke every active service token the user holds. Returns how many were revoked. */
28
+ revokeAllForUser: (this: McpServiceTokenModel, userId: mongoose.Types.ObjectId | string) => Promise<number>;
27
29
  revokeForUser: (this: McpServiceTokenModel, user: {
28
30
  _id: {
29
31
  toString(): string;
package/e2e/smoke.ts ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Real-process smoke for @terreno/api. Run `bun e2e/smoke.ts` after `bun run compile`.
3
+ *
4
+ * The smoke re-runs this file with `serve` as a child process: a minimal TerrenoApp built from
5
+ * the compiled package with one modelRouter model, on a free port, against `smokeMongoUri()`.
6
+ * The parent then checks over real HTTP that `/health` answers, a user can sign up, and that
7
+ * user can create and list a document. Exits non-zero on the first failed check.
8
+ */
9
+ import {
10
+ freePort,
11
+ type SpawnedProcess,
12
+ smokeMongoUri,
13
+ spawnUntilReady,
14
+ stopSmokeMongo,
15
+ } from "@terreno/test";
16
+ import type express from "express";
17
+ import {DateTime} from "luxon";
18
+ import type {Schema} from "mongoose";
19
+
20
+ const SERVE_ARG = "serve";
21
+
22
+ interface SmokeWidget {
23
+ _id: string;
24
+ name: string;
25
+ ownerId: string;
26
+ }
27
+
28
+ /**
29
+ * Child: the compiled API with auth, one owner-scoped model, and a health plugin. The API is
30
+ * imported here, not at the top, so the parent process never loads it.
31
+ */
32
+ const serve = async (): Promise<void> => {
33
+ const {createdUpdatedPlugin, logger, modelRouter, OwnerQueryFilter, Permissions, TerrenoApp} =
34
+ await import("@terreno/api");
35
+ const {default: mongoose} = await import("mongoose");
36
+ const {default: passportLocalMongoose} = await import("passport-local-mongoose");
37
+
38
+ const userSchema = new mongoose.Schema({
39
+ admin: {default: false, description: "Whether the user is an admin", type: Boolean},
40
+ email: {description: "Sign-in email", type: String},
41
+ name: {description: "Display name", type: String},
42
+ });
43
+ userSchema.plugin(passportLocalMongoose as unknown as (schema: Schema, options: object) => void, {
44
+ usernameCaseInsensitive: true,
45
+ usernameField: "email",
46
+ });
47
+ userSchema.plugin(createdUpdatedPlugin);
48
+ const User = mongoose.model("User", userSchema);
49
+
50
+ const widgetSchema = new mongoose.Schema({
51
+ name: {description: "Widget name", required: true, type: String},
52
+ ownerId: {description: "User who owns the widget", ref: "User", type: String},
53
+ });
54
+ widgetSchema.plugin(createdUpdatedPlugin);
55
+ const Widget = mongoose.model("Widget", widgetSchema);
56
+
57
+ const widgetRouter = modelRouter("/widgets", Widget, {
58
+ permissions: {
59
+ create: [Permissions.IsAuthenticated],
60
+ delete: [],
61
+ list: [Permissions.IsAuthenticated],
62
+ read: [Permissions.IsOwner],
63
+ update: [],
64
+ },
65
+ preCreate: (body, req) => {
66
+ const user = req.user as unknown as {_id: string};
67
+ return {...(body as {name: string}), ownerId: String(user._id)};
68
+ },
69
+ queryFilter: OwnerQueryFilter,
70
+ });
71
+
72
+ const healthPlugin = {
73
+ register: (app: express.Application): void => {
74
+ app.get("/health", (_req, res) => {
75
+ res.json({healthy: mongoose.connection.readyState === 1});
76
+ });
77
+ },
78
+ };
79
+
80
+ await mongoose.connect(process.env.MONGO_URI as string);
81
+ const app = new TerrenoApp({
82
+ loggingOptions: {logRequests: false},
83
+ userModel: User as unknown as ConstructorParameters<typeof TerrenoApp>[0]["userModel"],
84
+ })
85
+ .register(widgetRouter)
86
+ .register(healthPlugin);
87
+ app.start();
88
+ await app.whenReady();
89
+ logger.info(`[apiSmoke] serving on port ${process.env.PORT}`);
90
+ };
91
+
92
+ const expectStatus = async (res: Response, status: number, step: string): Promise<unknown> => {
93
+ const body = await res.text();
94
+ if (res.status !== status) {
95
+ throw new Error(`${step}: expected ${status}, got ${res.status}: ${body}`);
96
+ }
97
+ return body ? JSON.parse(body) : undefined;
98
+ };
99
+
100
+ /** Parent: boots the child and walks the happy path over HTTP. */
101
+ const run = async (): Promise<void> => {
102
+ const startedAt = DateTime.now();
103
+ const port = await freePort();
104
+ const baseUrl = `http://127.0.0.1:${port}`;
105
+ let server: SpawnedProcess | undefined;
106
+
107
+ try {
108
+ server = await spawnUntilReady({
109
+ cmd: [process.execPath, __filename, SERVE_ARG],
110
+ env: {
111
+ MONGO_URI: await smokeMongoUri({databaseName: "apiSmoke"}),
112
+ PORT: String(port),
113
+ REFRESH_TOKEN_SECRET: "api-smoke-refresh-secret",
114
+ SESSION_SECRET: "api-smoke-session-secret",
115
+ TOKEN_ISSUER: "api-smoke",
116
+ TOKEN_SECRET: "api-smoke-token-secret",
117
+ },
118
+ timeoutMs: 20000,
119
+ url: `${baseUrl}/health`,
120
+ });
121
+
122
+ const health = (await expectStatus(await fetch(`${baseUrl}/health`), 200, "GET /health")) as {
123
+ healthy: boolean;
124
+ };
125
+ if (!health.healthy) {
126
+ throw new Error("GET /health: server reports unhealthy");
127
+ }
128
+ console.info("✅ GET /health is healthy");
129
+
130
+ const email = `api-smoke-${startedAt.toMillis()}@example.com`;
131
+ const signup = (await expectStatus(
132
+ await fetch(`${baseUrl}/auth/signup`, {
133
+ body: JSON.stringify({email, password: "api-smoke-password-1"}),
134
+ headers: {"Content-Type": "application/json"},
135
+ method: "POST",
136
+ }),
137
+ 200,
138
+ "POST /auth/signup"
139
+ )) as {data: {token: string; userId: string}};
140
+ const headers = {
141
+ Authorization: `Bearer ${signup.data.token}`,
142
+ "Content-Type": "application/json",
143
+ };
144
+ console.info("✅ POST /auth/signup returns a token");
145
+
146
+ const created = (await expectStatus(
147
+ await fetch(`${baseUrl}/widgets`, {
148
+ body: JSON.stringify({name: "Smoke widget"}),
149
+ headers,
150
+ method: "POST",
151
+ }),
152
+ 201,
153
+ "POST /widgets"
154
+ )) as {data: SmokeWidget};
155
+ if (created.data.ownerId !== String(signup.data.userId)) {
156
+ throw new Error(`POST /widgets: ownerId ${created.data.ownerId} is not the new user`);
157
+ }
158
+ console.info("✅ POST /widgets creates an owned widget");
159
+
160
+ const listed = (await expectStatus(
161
+ await fetch(`${baseUrl}/widgets`, {headers}),
162
+ 200,
163
+ "GET /widgets"
164
+ )) as {data: SmokeWidget[]};
165
+ if (!listed.data.some((widget) => widget._id === created.data._id)) {
166
+ throw new Error("GET /widgets: the created widget is missing from the list");
167
+ }
168
+ console.info("✅ GET /widgets lists it");
169
+ } catch (error: unknown) {
170
+ if (server) {
171
+ console.error(`--- server output ---\n${server.output()}`);
172
+ }
173
+ throw error;
174
+ } finally {
175
+ await server?.stop();
176
+ await stopSmokeMongo();
177
+ }
178
+
179
+ console.info(`api smoke passed in ${DateTime.now().diff(startedAt).toMillis()} ms`);
180
+ };
181
+
182
+ const main = process.argv[2] === SERVE_ARG ? serve : run;
183
+ main().then(
184
+ () => {
185
+ if (main === run) {
186
+ process.exit(0);
187
+ }
188
+ },
189
+ (error: unknown) => {
190
+ console.error(`❌ ${error instanceof Error ? error.message : String(error)}`);
191
+ process.exit(1);
192
+ }
193
+ );
package/package.json CHANGED
@@ -13,7 +13,7 @@
13
13
  "@modelcontextprotocol/node": "^2.0.0",
14
14
  "@modelcontextprotocol/server": "^2.0.0",
15
15
  "@sentry/bun": "^10.39.0",
16
- "@terreno/test": "57.20.0",
16
+ "@terreno/test": "57.22.0",
17
17
  "@thream/socketio-jwt": "^3.1.4",
18
18
  "@types/qs": "^6.14.0",
19
19
  "ajv": "8.20.0",
@@ -51,7 +51,7 @@
51
51
  "devDependencies": {
52
52
  "@biomejs/biome": "^2.3.6",
53
53
  "@modelcontextprotocol/client": "^2.0.0",
54
- "@terreno/syncdb": "57.20.0",
54
+ "@terreno/syncdb": "57.22.0",
55
55
  "@types/bun": "^1.4.0",
56
56
  "@types/cors": "^2.8.17",
57
57
  "@types/express": "^5.0.6",
@@ -121,10 +121,11 @@
121
121
  "compile:watch": "bun tsc -w",
122
122
  "dev": "bun tsc -w",
123
123
  "docs": "bunx typedoc@0.28.19 --out docs src/index.ts",
124
- "lint": "biome check ./src",
125
- "lint:fix": "biome check --write ./src",
124
+ "lint": "biome check ./src ./e2e",
125
+ "lint:fix": "biome check --write ./src ./e2e",
126
126
  "lint:unsafefix": "biome check --fix --unsafe ./src",
127
127
  "load": "bun src/sync/loadHarness.ts",
128
+ "smoke": "bun e2e/smoke.ts",
128
129
  "test": "bun test --update-snapshots",
129
130
  "test:agent": "AGENT=1 bun test --only-failures",
130
131
  "test:cache:clean": "bun ./src/tests/mongoTestSetup.ts clean",
@@ -132,8 +133,9 @@
132
133
  "test:cache:status": "bun ./src/tests/mongoTestSetup.ts status",
133
134
  "test:ci": "bun test",
134
135
  "test:coverage": "bun run ../scripts/check-coverage.ts",
136
+ "typecheck": "tsc -p tsconfig.typecheck.json",
135
137
  "updateSnapshot": "bun test --update-snapshots"
136
138
  },
137
139
  "types": "dist/index.d.ts",
138
- "version": "57.20.0"
140
+ "version": "57.22.0"
139
141
  }