@terreno/api 57.16.1 → 57.17.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 (184) hide show
  1. package/dist/actions.d.ts +26 -3
  2. package/dist/actions.js +102 -16
  3. package/dist/api.d.ts +7 -0
  4. package/dist/api.js +59 -3
  5. package/dist/auth.d.ts +28 -4
  6. package/dist/auth.js +140 -15
  7. package/dist/authRecovery.d.ts +31 -0
  8. package/dist/authRecovery.js +86 -6
  9. package/dist/betterAuth.d.ts +86 -0
  10. package/dist/betterAuthApp.d.ts +17 -0
  11. package/dist/betterAuthApp.js +12 -1
  12. package/dist/betterAuthOAuthHandoff.d.ts +24 -0
  13. package/dist/betterAuthOAuthHandoff.js +305 -0
  14. package/dist/betterAuthSetup.d.ts +37 -2
  15. package/dist/betterAuthSetup.js +304 -24
  16. package/dist/expressServer.d.ts +16 -0
  17. package/dist/expressServer.js +61 -14
  18. package/dist/githubAuth.d.ts +9 -0
  19. package/dist/githubAuth.js +230 -31
  20. package/dist/index.d.ts +9 -1
  21. package/dist/index.js +27 -3
  22. package/dist/mcp/actionTools.d.ts +4 -0
  23. package/dist/mcp/actionTools.js +158 -0
  24. package/dist/mcp/auth.d.ts +30 -0
  25. package/dist/mcp/auth.js +83 -28
  26. package/dist/mcp/createMCPRequest.d.ts +5 -1
  27. package/dist/mcp/createMCPRequest.js +3 -3
  28. package/dist/mcp/handlers.d.ts +3 -0
  29. package/dist/mcp/handlers.js +43 -27
  30. package/dist/mcp/oauth.d.ts +14 -0
  31. package/dist/mcp/oauth.js +618 -0
  32. package/dist/mcp/oauthMetadata.d.ts +89 -0
  33. package/dist/mcp/oauthMetadata.js +137 -0
  34. package/dist/mcp/registry.d.ts +5 -0
  35. package/dist/mcp/registry.js +9 -1
  36. package/dist/mcp/server.d.ts +6 -0
  37. package/dist/mcp/server.js +44 -7
  38. package/dist/mcp/serviceTokens.js +12 -2
  39. package/dist/mcp/toolExecution.d.ts +12 -0
  40. package/dist/mcp/toolExecution.js +60 -0
  41. package/dist/mcp/toolGenerator.d.ts +4 -1
  42. package/dist/mcp/toolGenerator.js +26 -60
  43. package/dist/mcp/types.d.ts +4 -4
  44. package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
  45. package/dist/models/mcpOAuthAuthorization.js +86 -0
  46. package/dist/models/mcpOAuthClient.d.ts +2 -0
  47. package/dist/models/mcpOAuthClient.js +42 -0
  48. package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
  49. package/dist/models/mcpOAuthRevokedFamily.js +36 -0
  50. package/dist/models/mcpOAuthToken.d.ts +12 -0
  51. package/dist/models/mcpOAuthToken.js +159 -0
  52. package/dist/models/mcpServiceToken.d.ts +1 -0
  53. package/dist/models/mcpServiceToken.js +21 -4
  54. package/dist/permissions.d.ts +7 -0
  55. package/dist/permissions.js +18 -1
  56. package/dist/rateLimit/policies.d.ts +4 -0
  57. package/dist/rateLimit/policies.js +46 -7
  58. package/dist/rbac/access.js +1 -0
  59. package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
  60. package/dist/rbac/membershipOrgAdminSource.js +5 -0
  61. package/dist/rbac/modelRouterAccess.d.ts +7 -1
  62. package/dist/rbac/modelRouterAccess.js +37 -24
  63. package/dist/rbac/realtimeAccess.js +17 -3
  64. package/dist/rbac/resolve.js +66 -9
  65. package/dist/rbac/roleManager.js +60 -5
  66. package/dist/rbac/roleModel.js +1 -1
  67. package/dist/rbac/statements.d.ts +1 -1
  68. package/dist/rbac/statements.js +13 -1
  69. package/dist/rbac/types.d.ts +12 -0
  70. package/dist/rbac/userWriteGuards.d.ts +50 -0
  71. package/dist/rbac/userWriteGuards.js +156 -0
  72. package/dist/realtime/changeStreamWatcher.d.ts +4 -1
  73. package/dist/realtime/changeStreamWatcher.js +157 -73
  74. package/dist/realtime/queryMatcher.d.ts +3 -0
  75. package/dist/realtime/queryMatcher.js +25 -10
  76. package/dist/realtime/realtimeApp.d.ts +16 -1
  77. package/dist/realtime/realtimeApp.js +76 -8
  78. package/dist/realtime/socketAuth.d.ts +17 -6
  79. package/dist/realtime/socketAuth.js +77 -16
  80. package/dist/realtime/types.d.ts +8 -5
  81. package/dist/requestContext.d.ts +22 -0
  82. package/dist/requestContext.js +22 -1
  83. package/dist/seedRunner.js +3 -1
  84. package/dist/sortFields.d.ts +33 -0
  85. package/dist/sortFields.js +55 -0
  86. package/dist/sync/executors.js +140 -2
  87. package/dist/sync/models.d.ts +2 -0
  88. package/dist/sync/models.js +5 -0
  89. package/dist/sync/mutationHandler.js +70 -7
  90. package/dist/sync/routes.js +4 -2
  91. package/dist/sync/syncSeqPlugin.js +6 -5
  92. package/dist/terrenoApp.d.ts +14 -0
  93. package/dist/terrenoApp.js +21 -6
  94. package/dist/types/mcpOAuth.d.ts +101 -0
  95. package/dist/types/mcpOAuth.js +2 -0
  96. package/dist/types/mcpServiceToken.d.ts +8 -0
  97. package/package.json +3 -3
  98. package/src/actions.test.ts +118 -0
  99. package/src/actions.ts +139 -17
  100. package/src/api.arrayOperations.test.ts +78 -0
  101. package/src/api.test.ts +36 -0
  102. package/src/api.ts +76 -4
  103. package/src/auth.test.ts +521 -3
  104. package/src/auth.ts +171 -17
  105. package/src/authRecovery.test.ts +99 -0
  106. package/src/authRecovery.ts +117 -5
  107. package/src/authVerification.test.ts +3 -3
  108. package/src/betterAuth.ts +104 -1
  109. package/src/betterAuthApp.test.ts +634 -1
  110. package/src/betterAuthApp.ts +28 -0
  111. package/src/betterAuthOAuthHandoff.test.ts +946 -0
  112. package/src/betterAuthOAuthHandoff.ts +375 -0
  113. package/src/betterAuthSetup.test.ts +393 -4
  114. package/src/betterAuthSetup.ts +402 -29
  115. package/src/expressServer.test.ts +93 -0
  116. package/src/expressServer.ts +81 -14
  117. package/src/githubAuth.test.ts +448 -6
  118. package/src/githubAuth.ts +276 -34
  119. package/src/index.ts +35 -1
  120. package/src/mcp/actionTools.test.ts +498 -0
  121. package/src/mcp/actionTools.ts +220 -0
  122. package/src/mcp/auth.test.ts +114 -1
  123. package/src/mcp/auth.ts +122 -35
  124. package/src/mcp/createMCPRequest.ts +8 -2
  125. package/src/mcp/handlers.test.ts +27 -0
  126. package/src/mcp/handlers.ts +21 -6
  127. package/src/mcp/oauth.test.ts +1026 -0
  128. package/src/mcp/oauth.ts +798 -0
  129. package/src/mcp/oauthMetadata.ts +234 -0
  130. package/src/mcp/registry.ts +11 -0
  131. package/src/mcp/server.ts +54 -14
  132. package/src/mcp/serviceTokens.ts +16 -3
  133. package/src/mcp/toolExecution.ts +67 -0
  134. package/src/mcp/toolGenerator.ts +27 -83
  135. package/src/mcp/types.ts +4 -4
  136. package/src/models/mcpOAuthAuthorization.ts +97 -0
  137. package/src/models/mcpOAuthClient.ts +49 -0
  138. package/src/models/mcpOAuthRevokedFamily.ts +47 -0
  139. package/src/models/mcpOAuthToken.test.ts +82 -0
  140. package/src/models/mcpOAuthToken.ts +195 -0
  141. package/src/models/mcpServiceToken.ts +26 -2
  142. package/src/permissions.ts +17 -0
  143. package/src/rateLimit/policies.ts +54 -10
  144. package/src/rateLimit/rateLimit.test.ts +41 -0
  145. package/src/rbac/access.ts +1 -0
  146. package/src/rbac/membershipOrgAdminSource.ts +5 -0
  147. package/src/rbac/modelRouterAccess.ts +40 -23
  148. package/src/rbac/realtimeAccess.test.ts +43 -0
  149. package/src/rbac/realtimeAccess.ts +23 -3
  150. package/src/rbac/resolve.test.ts +179 -1
  151. package/src/rbac/resolve.ts +78 -9
  152. package/src/rbac/roleManager.test.ts +132 -0
  153. package/src/rbac/roleManager.ts +69 -5
  154. package/src/rbac/roleModel.ts +1 -1
  155. package/src/rbac/statements.ts +14 -1
  156. package/src/rbac/types.ts +12 -0
  157. package/src/rbac/userWriteGuards.test.ts +407 -0
  158. package/src/rbac/userWriteGuards.ts +185 -0
  159. package/src/realtime/changeStreamWatcher.ts +203 -75
  160. package/src/realtime/queryMatcher.ts +30 -13
  161. package/src/realtime/realtime.test.ts +132 -0
  162. package/src/realtime/realtimeApp.ts +94 -10
  163. package/src/realtime/realtimeAppSetup.test.ts +282 -1
  164. package/src/realtime/socketAuth.test.ts +140 -8
  165. package/src/realtime/socketAuth.ts +90 -19
  166. package/src/realtime/types.ts +8 -5
  167. package/src/requestContext.ts +52 -1
  168. package/src/requestCredential.test.ts +89 -0
  169. package/src/seedRunner.test.ts +21 -0
  170. package/src/seedRunner.ts +3 -1
  171. package/src/sortFields.ts +69 -0
  172. package/src/sync/executors.test.ts +382 -3
  173. package/src/sync/executors.ts +179 -4
  174. package/src/sync/models.ts +8 -0
  175. package/src/sync/mutationHandler.test.ts +166 -2
  176. package/src/sync/mutationHandler.ts +97 -5
  177. package/src/sync/routes.ts +4 -2
  178. package/src/sync/syncFrontier.test.ts +11 -0
  179. package/src/sync/syncPhaseC.test.ts +18 -0
  180. package/src/sync/syncSeqPlugin.ts +6 -5
  181. package/src/sync/syncSocket.test.ts +92 -0
  182. package/src/terrenoApp.ts +36 -21
  183. package/src/types/mcpOAuth.ts +129 -0
  184. package/src/types/mcpServiceToken.ts +6 -1
@@ -9,7 +9,9 @@ const mongoose_1 = __importDefault(require("mongoose"));
9
9
  const errors_1 = require("../errors");
10
10
  const logger_1 = require("../logger");
11
11
  const orgContext_1 = require("../orgs/orgContext");
12
+ const permissions_1 = require("../permissions");
12
13
  const plugins_1 = require("../plugins");
14
+ const adminBroadcastScope_1 = require("./adminBroadcastScope");
13
15
  const adminWindowMutation_1 = require("./adminWindowMutation");
14
16
  const executors_1 = require("./executors");
15
17
  const models_1 = require("./models");
@@ -90,13 +92,45 @@ const makeNack = (nack) => {
90
92
  logger_1.logger.info("[sync] Mutation nacked", { code: nack.code, mutationId: nack.mutationId });
91
93
  return { nack, type: "nack" };
92
94
  };
95
+ /**
96
+ * A replayed conflict hands back the LIVE document, so the caller must still be allowed to
97
+ * read it now: the admin broadcast scope for an admin-window replay, otherwise the
98
+ * collection's read permission plus membership in the document's sync stream (the checks a
99
+ * snapshot applies).
100
+ */
101
+ const canReadReplayedDoc = async ({ doc, entry, mutation, scopeResolver, user, }) => {
102
+ const plain = doc.toObject();
103
+ if (mutation.mutationMode === "adminWindow") {
104
+ const decision = await (0, adminBroadcastScope_1.authorizeAdminBroadcastDocument)({
105
+ doc: plain,
106
+ modelName: entry.modelName,
107
+ user,
108
+ });
109
+ return decision === "allow";
110
+ }
111
+ if (!(await (0, permissions_1.checkPermissions)("read", entry.options.permissions.read, user, doc))) {
112
+ return false;
113
+ }
114
+ const stream = (0, streams_1.resolveStreamForDoc)({
115
+ collectionTag: entry.collectionTag,
116
+ doc: plain,
117
+ scope: entry.config.scope,
118
+ });
119
+ const userStreams = await (0, streams_1.resolveUserStreamsForEntry)({
120
+ entry,
121
+ getUserScopes: scopeResolver,
122
+ user,
123
+ });
124
+ return userStreams.includes(stream);
125
+ };
93
126
  /**
94
127
  * Load a document by id INCLUDING tombstones (`isDeletedPlugin` would otherwise filter a
95
128
  * soft-deleted doc out) and serialize it for a sync payload. Returns undefined when the
96
- * document is gone, the id does not cast, or the consumer's serializer throws — callers
97
- * treat a missing `serverDoc` as "seq only", which is what the client needs to re-base.
129
+ * document is gone, the id does not cast, the caller may no longer read it, or the
130
+ * consumer's serializer throws — callers treat a missing `serverDoc` as "seq only", which
131
+ * is what the client needs to re-base.
98
132
  */
99
- const serializeLiveDoc = async ({ entry, id, request, }) => {
133
+ const serializeLiveDoc = async ({ entry, id, mutation, request, scopeResolver, user, }) => {
100
134
  if (!id) {
101
135
  return undefined;
102
136
  }
@@ -107,6 +141,9 @@ const serializeLiveDoc = async ({ entry, id, request, }) => {
107
141
  if (!doc) {
108
142
  return undefined;
109
143
  }
144
+ if (!(await canReadReplayedDoc({ doc, entry, mutation, scopeResolver, user }))) {
145
+ return undefined;
146
+ }
110
147
  return await (0, routes_1.serializeSyncDoc)({ doc, entry, req: request });
111
148
  }
112
149
  catch (error) {
@@ -126,7 +163,7 @@ const serializeLiveDoc = async ({ entry, id, request, }) => {
126
163
  * `syncmutations` for the ledger's 30-day TTL, this hands the client current server
127
164
  * state rather than a snapshot frozen at first-conflict time.
128
165
  */
129
- const outcomeFromLedgerRow = async ({ entry, request, row, }) => {
166
+ const outcomeFromLedgerRow = async ({ entry, mutation, request, row, scopeResolver, user, }) => {
130
167
  if (row.status === "applied") {
131
168
  return {
132
169
  ack: { id: row.resultId ?? "", mutationId: row.mutationId, seq: row.resultSeq ?? 0 },
@@ -138,7 +175,14 @@ const outcomeFromLedgerRow = async ({ entry, request, row, }) => {
138
175
  code: "conflict",
139
176
  message: row.error,
140
177
  mutationId: row.mutationId,
141
- serverDoc: await serializeLiveDoc({ entry, id: row.resultId, request }),
178
+ serverDoc: await serializeLiveDoc({
179
+ entry,
180
+ id: row.resultId,
181
+ mutation,
182
+ request,
183
+ scopeResolver,
184
+ user,
185
+ }),
142
186
  serverSeq: row.resultSeq,
143
187
  });
144
188
  }
@@ -173,7 +217,7 @@ const takeoverStaleLease = async (mutationId) => {
173
217
  * pending and un-stale past the timeout, nack `error` without modifying the row — the
174
218
  * owning delivery will still finalize it.
175
219
  */
176
- const waitForRecordedOutcome = async ({ entry, mutationId, request, user, onTakeover, }) => {
220
+ const waitForRecordedOutcome = async ({ entry, mutation, mutationId, request, scopeResolver, user, onTakeover, }) => {
177
221
  for (let attempt = 0; attempt < PENDING_POLL_ATTEMPTS; attempt++) {
178
222
  const row = await (0, plugins_1.findOneOrNoneFor)(models_1.SyncMutation, { mutationId });
179
223
  if (row) {
@@ -184,7 +228,23 @@ const waitForRecordedOutcome = async ({ entry, mutationId, request, user, onTake
184
228
  mutationId,
185
229
  });
186
230
  }
187
- const outcome = await outcomeFromLedgerRow({ entry, request, row });
231
+ // Rows recorded before collectionTag existed carry none; their replays still pass
232
+ // the live read check in serializeLiveDoc.
233
+ if (row.collectionTag !== undefined && row.collectionTag !== entry.collectionTag) {
234
+ return makeNack({
235
+ code: "unauthorized",
236
+ message: `Mutation ${mutationId} was submitted for another collection`,
237
+ mutationId,
238
+ });
239
+ }
240
+ const outcome = await outcomeFromLedgerRow({
241
+ entry,
242
+ mutation,
243
+ request,
244
+ row,
245
+ scopeResolver,
246
+ user,
247
+ });
188
248
  if (outcome) {
189
249
  return outcome;
190
250
  }
@@ -634,6 +694,7 @@ const applySyncMutation = async ({ user, mutation, req, scopeResolver, syncOptio
634
694
  try {
635
695
  claimed = await models_1.SyncMutation.create({
636
696
  claimedAt: luxon_1.DateTime.now().toJSDate(),
697
+ collectionTag: entry.collectionTag,
637
698
  mutationId,
638
699
  status: "pending",
639
700
  userId: String(user.id),
@@ -645,6 +706,7 @@ const applySyncMutation = async ({ user, mutation, req, scopeResolver, syncOptio
645
706
  }
646
707
  return waitForRecordedOutcome({
647
708
  entry,
709
+ mutation,
648
710
  mutationId,
649
711
  onTakeover: (takenOver) => applyClaimedMutation({
650
712
  claimed: takenOver,
@@ -657,6 +719,7 @@ const applySyncMutation = async ({ user, mutation, req, scopeResolver, syncOptio
657
719
  user,
658
720
  }),
659
721
  request,
722
+ scopeResolver,
660
723
  user,
661
724
  });
662
725
  }
@@ -212,9 +212,11 @@ const pageLegacyStratum = async ({ model, scopeFilter, legacyCursorIn, limit, en
212
212
  if (!(await (0, permissions_1.checkPermissions)("read", entry.options.permissions.read, user, doc))) {
213
213
  continue;
214
214
  }
215
+ const isTombstone = Boolean(doc.deleted);
215
216
  entities.push({
216
- data: await (0, exports.serializeSyncDoc)({ doc, entry, req }),
217
- deleted: Boolean(doc.deleted),
217
+ // C7: tombstones carry no data, the same as the seq stratum and /sync/entities.
218
+ data: isTombstone ? null : await (0, exports.serializeSyncDoc)({ doc, entry, req }),
219
+ deleted: isTombstone,
218
220
  id: String(doc._id),
219
221
  seq: 0,
220
222
  });
@@ -270,12 +270,13 @@ const syncPlugin = (schema) => {
270
270
  // behind; drop it so this save's post hook never acts on the earlier attempt's claim.
271
271
  this.$locals[PENDING_COMMIT_KEY] = undefined;
272
272
  // m10: a save that changes nothing meaningful must not burn a seq or emit a delta.
273
- // Excluded from the "meaningful" set: the sync stamps this hook writes (`_syncSeq`,
274
- // `_syncPrevStream`) and auto-managed timestamp metadata (`updated`, which
275
- // createdUpdatedPlugin bumps on EVERY save — otherwise no save would ever be a
276
- // no-op). A save whose only modified paths are these is a no-op: skip the claim.
273
+ // Excluded from the "meaningful" set: auto-managed timestamp metadata (`updated`, which
274
+ // createdUpdatedPlugin bumps on EVERY save — otherwise no save would ever be a no-op).
275
+ // A save whose only modified path is that is a no-op: skip the claim. The sync stamps
276
+ // (`_syncSeq`, `_syncPrevStream`) still count: this hook has not written them yet, so a
277
+ // change to them came from the caller, and it must be restamped rather than persisted.
277
278
  if (!this.isNew) {
278
- const ignored = new Set(["_syncSeq", "_syncPrevStream", "updated"]);
279
+ const ignored = new Set(["updated"]);
279
280
  const meaningful = this.modifiedPaths().filter((p) => !ignored.has(p));
280
281
  if (meaningful.length === 0) {
281
282
  return;
@@ -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 McpOAuthAppOption } from "./mcp/oauthMetadata";
11
12
  import { type McpServiceTokensAppOption } from "./mcp/serviceTokens";
12
13
  import { type StartupMigrationsOption } from "./migrations/runner";
13
14
  import { type OrgsAppOptions } from "./orgs/orgsApp";
@@ -82,6 +83,15 @@ export interface TerrenoAppOptions {
82
83
  * mounts `/mcp/service-tokens` and accepts `Authorization: Bearer mcp_…` on `/mcp`.
83
84
  */
84
85
  mcpServiceTokens?: McpServiceTokensAppOption;
86
+ /**
87
+ * Opt-in OAuth 2.1 authorization server for `/mcp`, so remote MCP clients (Claude.ai
88
+ * connectors, ChatGPT apps) can connect to a JWT-auth app. Off unless `enabled: true`. Mounts
89
+ * RFC 9728 / RFC 8414 discovery, authorize + consent, token, and revocation endpoints, and makes
90
+ * `/mcp` answer credential-less requests with a 401 challenge. Dynamic client registration is a
91
+ * second opt-in (`dynamicClientRegistration: true`). See
92
+ * [Enable MCP OAuth](../how-to/enable-mcp-oauth.md).
93
+ */
94
+ mcpOAuth?: McpOAuthAppOption;
85
95
  /**
86
96
  * Versioned MongoDB migrations. `runOnStart` defaults to false. When true, wet `up`
87
97
  * runs after listen and `ensureSyncIndexes`. Production still requires
@@ -189,6 +199,10 @@ export declare class TerrenoApp {
189
199
  * Returns registered model routers and plugins in mount order.
190
200
  */
191
201
  getRegistrations(): readonly (ModelRouterRegistration | TerrenoPlugin)[];
202
+ /**
203
+ * The application user model this app authenticates against.
204
+ */
205
+ getUserModel(): TerrenoAppOptions["userModel"];
192
206
  /**
193
207
  * Returns only TerrenoPlugin registrations (excludes model routers).
194
208
  */
@@ -45,6 +45,7 @@ const express_1 = __importDefault(require("express"));
45
45
  const mongoose_1 = __importDefault(require("mongoose"));
46
46
  const qs_1 = __importDefault(require("qs"));
47
47
  const auth_1 = require("./auth");
48
+ const betterAuthApp_1 = require("./betterAuthApp");
48
49
  const betterAuthSetup_1 = require("./betterAuthSetup");
49
50
  const browserLogsRoute_1 = require("./browserLogsRoute");
50
51
  const configurationApp_1 = require("./configurationApp");
@@ -52,6 +53,8 @@ const errors_1 = require("./errors");
52
53
  const expressServer_1 = require("./expressServer");
53
54
  const githubAuth_1 = require("./githubAuth");
54
55
  const logger_1 = require("./logger");
56
+ const oauth_1 = require("./mcp/oauth");
57
+ const oauthMetadata_1 = require("./mcp/oauthMetadata");
55
58
  const server_1 = require("./mcp/server");
56
59
  const serviceTokens_1 = require("./mcp/serviceTokens");
57
60
  const middleware_1 = require("./middleware");
@@ -175,6 +178,12 @@ class TerrenoApp {
175
178
  getRegistrations() {
176
179
  return this.registrations;
177
180
  }
181
+ /**
182
+ * The application user model this app authenticates against.
183
+ */
184
+ getUserModel() {
185
+ return this.options.userModel;
186
+ }
178
187
  /**
179
188
  * Returns only TerrenoPlugin registrations (excludes model routers).
180
189
  */
@@ -268,6 +277,8 @@ class TerrenoApp {
268
277
  (0, logger_1.setupLogging)(this.options.loggingOptions);
269
278
  const app = (0, express_1.default)();
270
279
  const options = this.options;
280
+ // Resolve first so a misconfigured issuer or consent URL fails at boot.
281
+ const mcpOAuth = (0, oauthMetadata_1.resolveMcpOAuthOption)(options.mcpOAuth);
271
282
  // Record mount paths on layers for Express 5 → OpenAPI compat
272
283
  (0, openApiCompat_1.patchAppUse)(app);
273
284
  app.set("query parser", (str) => qs_1.default.parse(str, { arrayLimit: options.arrayLimit ?? 200 }));
@@ -296,8 +307,7 @@ class TerrenoApp {
296
307
  (0, requestContext_1.updateRequestContextFromRequest)(req, res);
297
308
  next();
298
309
  });
299
- const betterAuthForLimiter = this.registrations.find((registration) => "getAuth" in registration &&
300
- typeof registration.getAuth === "function");
310
+ const betterAuthForLimiter = (0, betterAuthApp_1.findBetterAuthProvider)(this.registrations);
301
311
  if (betterAuthForLimiter?.ensureAuth) {
302
312
  const auth = betterAuthForLimiter.ensureAuth();
303
313
  app.use((0, betterAuthSetup_1.createBetterAuthSessionMiddleware)(auth, options.userModel));
@@ -319,7 +329,7 @@ class TerrenoApp {
319
329
  }
320
330
  const authOptions = options.authOptions;
321
331
  (0, auth_1.addAuthRoutes)(app, options.userModel, authOptions);
322
- if (options.logRequests !== false) {
332
+ if (options.logRequests !== false && options.loggingOptions?.logRequests !== false) {
323
333
  app.use(expressServer_1.logRequests);
324
334
  }
325
335
  // Store logging options on the response locals
@@ -387,13 +397,14 @@ class TerrenoApp {
387
397
  }
388
398
  }
389
399
  // Mount MCP at POST /mcp when any model opted in or a custom tool was registered.
390
- const betterAuthPlugin = this.registrations.find((registration) => "getAuth" in registration &&
391
- typeof registration.getAuth === "function");
392
- const betterAuth = betterAuthPlugin?.ensureAuth?.() ?? betterAuthPlugin?.getAuth();
400
+ const betterAuth = (0, betterAuthApp_1.getProvidedBetterAuth)((0, betterAuthApp_1.findBetterAuthProvider)(this.registrations));
393
401
  if (betterAuth) {
394
402
  authOptions.syncPasswordResetToBetterAuth = async (user, password) => {
395
403
  await (0, betterAuthSetup_1.applyJwtPasswordResetToBetterAuth)(betterAuth, user, password);
396
404
  };
405
+ authOptions.verifyBetterAuthPassword = async (user, password) => {
406
+ return (0, betterAuthSetup_1.verifyBetterAuthCredentialPassword)(betterAuth, user, password);
407
+ };
397
408
  }
398
409
  const mcpServiceTokens = (0, serviceTokens_1.resolveMcpServiceTokensOption)(options.mcpServiceTokens);
399
410
  if (mcpServiceTokens.enabled) {
@@ -402,8 +413,12 @@ class TerrenoApp {
402
413
  publicMcpUrl: mcpServiceTokens.publicMcpUrl,
403
414
  });
404
415
  }
416
+ if (mcpOAuth) {
417
+ (0, oauth_1.addMcpOAuthRoutes)(app, { oauth: mcpOAuth, openApi: oapi, userModel: options.userModel });
418
+ }
405
419
  (0, server_1.mountMCPServer)(app, {
406
420
  betterAuth,
421
+ mcpOAuth,
407
422
  mcpServiceTokens: mcpServiceTokens.enabled,
408
423
  userModel: options.userModel,
409
424
  });
@@ -0,0 +1,101 @@
1
+ import type mongoose from "mongoose";
2
+ import type { FindExactlyOnePlugin, FindOneOrNonePlugin } from "../plugins";
3
+ /** A client registered through dynamic client registration (RFC 7591). Public clients only. */
4
+ export interface McpOAuthClientDocument extends mongoose.Document {
5
+ _id: mongoose.Types.ObjectId;
6
+ clientId: string;
7
+ clientName?: string;
8
+ created: Date;
9
+ grantTypes: string[];
10
+ redirectUris: string[];
11
+ responseTypes: string[];
12
+ scope?: string;
13
+ updated: Date;
14
+ }
15
+ interface McpOAuthClientStatics extends FindExactlyOnePlugin<McpOAuthClientDocument>, FindOneOrNonePlugin<McpOAuthClientDocument> {
16
+ }
17
+ export interface McpOAuthClientModel extends mongoose.Model<McpOAuthClientDocument>, McpOAuthClientStatics {
18
+ }
19
+ /**
20
+ * Lifecycle of one authorization request: `pending` until the signed-in user decides, then
21
+ * `approved` (a code is outstanding) or `denied`, then `used` once the code is exchanged.
22
+ */
23
+ export type McpOAuthAuthorizationStatus = "pending" | "approved" | "denied" | "used";
24
+ export interface McpOAuthAuthorizationDocument extends mongoose.Document {
25
+ _id: mongoose.Types.ObjectId;
26
+ clientId: string;
27
+ codeChallenge: string;
28
+ codeExpiresAt?: Date;
29
+ codeHash?: string;
30
+ created: Date;
31
+ expiresAt: Date;
32
+ familyId?: string;
33
+ redirectUri: string;
34
+ requestId: string;
35
+ resource?: string;
36
+ scope?: string;
37
+ state?: string;
38
+ status: McpOAuthAuthorizationStatus;
39
+ tokenEpoch?: number;
40
+ updated: Date;
41
+ usedAt?: Date;
42
+ userId?: mongoose.Types.ObjectId;
43
+ }
44
+ interface McpOAuthAuthorizationStatics extends FindExactlyOnePlugin<McpOAuthAuthorizationDocument>, FindOneOrNonePlugin<McpOAuthAuthorizationDocument> {
45
+ }
46
+ export interface McpOAuthAuthorizationModel extends mongoose.Model<McpOAuthAuthorizationDocument>, McpOAuthAuthorizationStatics {
47
+ }
48
+ /** Tombstone written when a token family is revoked; blocks any later issue into it. */
49
+ export interface McpOAuthRevokedFamilyDocument extends mongoose.Document {
50
+ _id: mongoose.Types.ObjectId;
51
+ created: Date;
52
+ expiresAt: Date;
53
+ familyId: string;
54
+ revokedAt: Date;
55
+ updated: Date;
56
+ }
57
+ interface McpOAuthRevokedFamilyStatics extends FindExactlyOnePlugin<McpOAuthRevokedFamilyDocument>, FindOneOrNonePlugin<McpOAuthRevokedFamilyDocument> {
58
+ }
59
+ export interface McpOAuthRevokedFamilyModel extends mongoose.Model<McpOAuthRevokedFamilyDocument>, McpOAuthRevokedFamilyStatics {
60
+ }
61
+ /** One issued access/refresh token pair. Rotation chains pairs together by `familyId`. */
62
+ export interface McpOAuthTokenDocument extends mongoose.Document {
63
+ _id: mongoose.Types.ObjectId;
64
+ accessExpiresAt: Date;
65
+ accessTokenHash: string;
66
+ clientId: string;
67
+ created: Date;
68
+ familyId: string;
69
+ refreshExpiresAt: Date;
70
+ refreshTokenHash: string;
71
+ resource?: string;
72
+ revokedAt?: Date;
73
+ rotatedAt?: Date;
74
+ scope?: string;
75
+ tokenEpoch?: number;
76
+ updated: Date;
77
+ userId: mongoose.Types.ObjectId;
78
+ }
79
+ export interface McpOAuthTokenIssueOptions {
80
+ accessTokenTtlSeconds: number;
81
+ clientId: string;
82
+ familyId?: string;
83
+ refreshTokenTtlSeconds: number;
84
+ resource?: string;
85
+ scope?: string;
86
+ /** The user's tokenEpoch when the grant was approved (default 0); a later bump ends the family. */
87
+ tokenEpoch?: number;
88
+ userId: mongoose.Types.ObjectId;
89
+ }
90
+ interface McpOAuthTokenStatics extends FindExactlyOnePlugin<McpOAuthTokenDocument>, FindOneOrNonePlugin<McpOAuthTokenDocument> {
91
+ issue: (this: McpOAuthTokenModel, options: McpOAuthTokenIssueOptions) => Promise<{
92
+ accessToken: string;
93
+ mcpOAuthToken: McpOAuthTokenDocument;
94
+ refreshToken: string;
95
+ }>;
96
+ revokeFamily: (this: McpOAuthTokenModel, familyId: string) => Promise<void>;
97
+ verifyAccessToken: (this: McpOAuthTokenModel, token: string) => Promise<McpOAuthTokenDocument | null>;
98
+ }
99
+ export interface McpOAuthTokenModel extends mongoose.Model<McpOAuthTokenDocument>, McpOAuthTokenStatics {
100
+ }
101
+ export {};
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -13,10 +13,17 @@ export interface McpServiceTokenStatics extends FindExactlyOnePlugin<McpServiceT
13
13
  _id: {
14
14
  toString(): string;
15
15
  };
16
+ tokenEpoch?: number;
16
17
  }, options: McpServiceTokenIssueOptions) => Promise<{
17
18
  mcpServiceToken: McpServiceTokenDocument;
18
19
  token: string;
19
20
  }>;
21
+ revokeOutdatedForUser: (this: McpServiceTokenModel, user: {
22
+ _id: {
23
+ toString(): string;
24
+ };
25
+ tokenEpoch?: number;
26
+ }) => Promise<void>;
20
27
  revokeForUser: (this: McpServiceTokenModel, user: {
21
28
  _id: {
22
29
  toString(): string;
@@ -33,6 +40,7 @@ export interface McpServiceTokenDocument extends mongoose.Document {
33
40
  lastUsedAt?: Date;
34
41
  name: string;
35
42
  revokedAt?: Date;
43
+ tokenEpoch?: number;
36
44
  tokenHash: string;
37
45
  tokenPrefix: string;
38
46
  updated: Date;
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "@modelcontextprotocol/node": "^2.0.0",
12
12
  "@modelcontextprotocol/server": "^2.0.0",
13
13
  "@sentry/bun": "^10.39.0",
14
- "@terreno/test": "57.16.1",
14
+ "@terreno/test": "57.17.0",
15
15
  "@thream/socketio-jwt": "^3.1.4",
16
16
  "@types/qs": "^6.14.0",
17
17
  "ajv": "8.20.0",
@@ -48,7 +48,7 @@
48
48
  "devDependencies": {
49
49
  "@biomejs/biome": "^2.3.6",
50
50
  "@modelcontextprotocol/client": "^2.0.0",
51
- "@terreno/syncdb": "57.16.1",
51
+ "@terreno/syncdb": "57.17.0",
52
52
  "@types/bun": "^1.4.0",
53
53
  "@types/cors": "^2.8.17",
54
54
  "@types/express": "^5.0.6",
@@ -132,5 +132,5 @@
132
132
  "updateSnapshot": "bun test --update-snapshots"
133
133
  },
134
134
  "types": "dist/index.d.ts",
135
- "version": "57.16.1"
135
+ "version": "57.17.0"
136
136
  }
@@ -1005,5 +1005,123 @@ describe("modelRouter actions", () => {
1005
1005
  )
1006
1006
  ).rejects.toMatchObject({status: 405, title: "Access denied"});
1007
1007
  });
1008
+
1009
+ const setupEditor = async (): Promise<{
1010
+ access: ReturnType<typeof createAccess>;
1011
+ editor: User & {roles: string[]};
1012
+ }> => {
1013
+ await setupDb();
1014
+ const access = createAccess({
1015
+ connection: mongoose.connection,
1016
+ defaultRoles: [
1017
+ {
1018
+ displayName: "Editor",
1019
+ name: "editor",
1020
+ permissions: {todo: ["read", "update", "list"]},
1021
+ },
1022
+ ],
1023
+ statements: {
1024
+ ...terrenoStatements,
1025
+ todo: ["create", "read", "update", "delete", "list"],
1026
+ },
1027
+ });
1028
+ await access.roles.seedDefaults();
1029
+ const id = new mongoose.Types.ObjectId();
1030
+ const editor = {
1031
+ _id: id as unknown as User["_id"],
1032
+ admin: false,
1033
+ id: id.toString(),
1034
+ roles: ["editor"],
1035
+ } as unknown as User & {roles: string[]};
1036
+ return {access, editor};
1037
+ };
1038
+
1039
+ const ownerOnlyScope = {
1040
+ check: ({doc, user}: {doc?: unknown; user?: {id?: string}}): boolean =>
1041
+ !doc || String((doc as {ownerId?: string}).ownerId) === String(user?.id),
1042
+ };
1043
+
1044
+ it("applies the inherited router access.scope to the loaded document", async () => {
1045
+ const {access, editor} = await setupEditor();
1046
+ const req = {params: {}, user: editor} as unknown as Request;
1047
+ const action = {method: "POST" as const, permissions: [Permissions.IsAuthenticated]};
1048
+ const routerAccess = {resource: "todo", scope: ownerOnlyScope};
1049
+
1050
+ await runActionPermissions(
1051
+ action,
1052
+ "instance",
1053
+ FoodModel,
1054
+ req,
1055
+ undefined,
1056
+ access,
1057
+ routerAccess
1058
+ );
1059
+ await expect(
1060
+ runActionPermissions(
1061
+ action,
1062
+ "instance",
1063
+ FoodModel,
1064
+ req,
1065
+ {name: "victim's", ownerId: new mongoose.Types.ObjectId().toString()} as never,
1066
+ access,
1067
+ routerAccess
1068
+ )
1069
+ ).rejects.toMatchObject({status: 403});
1070
+ await runActionPermissions(
1071
+ action,
1072
+ "instance",
1073
+ FoodModel,
1074
+ req,
1075
+ {name: "mine", ownerId: editor.id} as never,
1076
+ access,
1077
+ routerAccess
1078
+ );
1079
+ });
1080
+
1081
+ it("applies the inherited router access.also for the mapped method", async () => {
1082
+ const {access, editor} = await setupEditor();
1083
+ const req = {params: {}, user: editor} as unknown as Request;
1084
+ const action = {method: "POST" as const, permissions: [Permissions.IsAuthenticated]};
1085
+ const routerAccess = {also: {update: [Permissions.IsOwner]}, resource: "todo"};
1086
+
1087
+ await expect(
1088
+ runActionPermissions(
1089
+ action,
1090
+ "instance",
1091
+ FoodModel,
1092
+ req,
1093
+ {name: "victim's", ownerId: new mongoose.Types.ObjectId().toString()} as never,
1094
+ access,
1095
+ routerAccess
1096
+ )
1097
+ ).rejects.toMatchObject({status: 403});
1098
+ await runActionPermissions(
1099
+ action,
1100
+ "instance",
1101
+ FoodModel,
1102
+ req,
1103
+ {name: "mine", ownerId: editor.id} as never,
1104
+ access,
1105
+ routerAccess
1106
+ );
1107
+ });
1108
+
1109
+ it("does not apply router scope to an action that overrides access with another resource", async () => {
1110
+ const {access, editor} = await setupEditor();
1111
+ const req = {params: {}, user: editor} as unknown as Request;
1112
+ await runActionPermissions(
1113
+ {
1114
+ access: {action: "read", resource: "todo"},
1115
+ method: "POST",
1116
+ permissions: [Permissions.IsAuthenticated],
1117
+ },
1118
+ "instance",
1119
+ FoodModel,
1120
+ req,
1121
+ {name: "other resource", ownerId: new mongoose.Types.ObjectId().toString()} as never,
1122
+ access,
1123
+ {resource: "food", scope: ownerOnlyScope}
1124
+ );
1125
+ });
1008
1126
  });
1009
1127
  });