@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
@@ -1,8 +1,9 @@
1
1
  import {authorize, UnauthorizedError} from "@thream/socketio-jwt";
2
2
  import type {Socket} from "socket.io";
3
3
 
4
- import type {UserModel} from "../auth";
5
- import type {BetterAuthInstance} from "../betterAuthSetup";
4
+ import {isUserDisabled, type UserModel} from "../auth";
5
+ import type {BetterAuthUser} from "../betterAuth";
6
+ import {type BetterAuthInstance, resolveBetterAuthAppUser} from "../betterAuthSetup";
6
7
  import {APIError} from "../errors";
7
8
  import {logger} from "../logger";
8
9
  import {findOneOrNoneFor} from "../plugins";
@@ -45,8 +46,10 @@ export interface BetterAuthSocketOptions {
45
46
  auth: BetterAuthInstance;
46
47
  /**
47
48
  * Optional application user model. When provided, the Better Auth user is resolved to
48
- * the app user (via `betterAuthId`) so `decodedToken.id`/`admin` match the identity the
49
- * REST layer uses. Without it, the Better Auth user id is used and `admin` is false.
49
+ * the app user (via `betterAuthId`, created on first contact) so `decodedToken.id`/`admin`
50
+ * match the identity the REST layer uses, and disabled users are refused. Without it, the
51
+ * Better Auth user id is used and `admin` is false. `RealtimeApp` fills this in from its own
52
+ * `userModel`, else the TerrenoApp's, when it is omitted.
50
53
  */
51
54
  userModel?: UserModel;
52
55
  }
@@ -73,10 +76,15 @@ export interface BetterAuthSocketOptions {
73
76
  * (e.g. test suites that mutate it between fixtures). Pass a thunk to preserve that
74
77
  * per-request freshness; a plain string is still supported for callers who intentionally
75
78
  * want a fixed value.
79
+ *
80
+ * When `userModel` is provided, the token's user is loaded after verification and the
81
+ * handshake is refused when that user is missing or disabled, matching the HTTP JWT
82
+ * middleware and the Better Auth validator. Without it, only the token is checked.
76
83
  */
77
84
  export const createLegacyJwtValidator = (
78
85
  tokenSecret: string,
79
- issuer?: string | (() => string | undefined)
86
+ issuer?: string | (() => string | undefined),
87
+ userModel?: UserModel
80
88
  ): SocketAuthValidator => {
81
89
  const resolveIssuer = (): string | undefined =>
82
90
  typeof issuer === "function" ? issuer() : issuer;
@@ -100,18 +108,60 @@ export const createLegacyJwtValidator = (
100
108
  reject(error);
101
109
  return;
102
110
  }
103
- // D1: stamp which validator authenticated this socket so the periodic
104
- // re-validation sweep knows to re-check local JWT expiry (not a Better Auth
105
- // session lookup) for it. The library already populated decodedToken with the
106
- // full JWT payload (exp/iss included), so this only adds the discriminator.
107
- if (socket.decodedToken) {
108
- socket.decodedToken.authKind = "jwt";
109
- }
110
- resolve();
111
+ rejectUnusableJwtUser(socket, userModel)
112
+ .then(() => {
113
+ // D1: stamp which validator authenticated this socket so the periodic
114
+ // re-validation sweep knows to re-check local JWT expiry (not a Better Auth
115
+ // session lookup) for it. The library already populated decodedToken with the
116
+ // full JWT payload (exp/iss included), so this only adds the discriminator.
117
+ if (socket.decodedToken) {
118
+ socket.decodedToken.authKind = "jwt";
119
+ }
120
+ resolve();
121
+ })
122
+ .catch((userError: unknown) => {
123
+ socket.decodedToken = undefined;
124
+ reject(userError);
125
+ });
111
126
  });
112
127
  });
113
128
  };
114
129
 
130
+ /**
131
+ * Refuse a verified JWT whose user no longer exists or is disabled, so disabling an account
132
+ * blocks new socket handshakes the same way the HTTP JWT middleware blocks requests.
133
+ */
134
+ const rejectUnusableJwtUser = async (
135
+ socket: AuthenticatableSocket,
136
+ userModel?: UserModel
137
+ ): Promise<void> => {
138
+ const userId = socket.decodedToken?.id;
139
+ if (!userModel || !userId) {
140
+ return;
141
+ }
142
+ let user: unknown;
143
+ try {
144
+ user = await findOneOrNoneFor(userModel, {_id: userId});
145
+ } catch (error) {
146
+ // Keep database details out of the client error.
147
+ logger.error(`[socket] Could not load the user for a JWT handshake: ${error}`);
148
+ throw new UnauthorizedError("invalid_token", {
149
+ message: "Unauthorized: could not resolve the application user",
150
+ });
151
+ }
152
+ if (!user) {
153
+ throw new UnauthorizedError("invalid_token", {
154
+ message: "Unauthorized: user not found",
155
+ });
156
+ }
157
+ if (isUserDisabled(user)) {
158
+ logger.warn(`[socket] User ${userId} is disabled, rejecting JWT`);
159
+ throw new UnauthorizedError("invalid_token", {
160
+ message: "Unauthorized: user is disabled",
161
+ });
162
+ }
163
+ };
164
+
115
165
  /** Strip an optional `Bearer ` prefix from the handshake token. */
116
166
  const extractRawToken = (socket: AuthenticatableSocket): string | null => {
117
167
  const {token} = socket.handshake.auth;
@@ -159,14 +209,29 @@ export const createBetterAuthValidator = (
159
209
  let id = String(betterAuthUserId);
160
210
  let admin = false;
161
211
  if (userModel) {
162
- const appUser = (await findOneOrNoneFor(userModel, {
163
- betterAuthId: betterAuthUserId,
164
- })) as unknown as {_id?: unknown; admin?: boolean} | null;
165
- if (!appUser?._id) {
212
+ // Same lookup as the REST session middleware: a user whose first contact after
213
+ // signing up is this handshake gets their app user created here.
214
+ let resolved: Awaited<ReturnType<typeof resolveBetterAuthAppUser>>;
215
+ try {
216
+ resolved = await resolveBetterAuthAppUser({
217
+ betterAuthUser: session.user as BetterAuthUser,
218
+ userModel,
219
+ });
220
+ } catch (error) {
221
+ // Keep database details (model, field, duplicate-key values) out of the client error.
222
+ logger.error(`[socket] Could not resolve the app user for a Better Auth session: ${error}`);
223
+ throw new UnauthorizedError("invalid_token", {
224
+ message: "Unauthorized: could not resolve the application user",
225
+ });
226
+ }
227
+ const {isDisabled, user} = resolved;
228
+ if (isDisabled) {
229
+ logger.warn(`[socket] User ${user.id} is disabled, rejecting Better Auth session`);
166
230
  throw new UnauthorizedError("invalid_token", {
167
- message: "Unauthorized: Better Auth user has no application user",
231
+ message: "Unauthorized: user is disabled",
168
232
  });
169
233
  }
234
+ const appUser = user as unknown as {_id: unknown; admin?: boolean};
170
235
  id = String(appUser._id);
171
236
  admin = appUser.admin === true;
172
237
  }
@@ -187,6 +252,7 @@ export const createSocketAuthMiddleware = ({
187
252
  tokenSecret,
188
253
  issuer,
189
254
  betterAuth,
255
+ userModel,
190
256
  extraValidators = [],
191
257
  }: {
192
258
  /** Secret enabling the legacy JWT validator (same handling as before the refactor). */
@@ -199,12 +265,17 @@ export const createSocketAuthMiddleware = ({
199
265
  issuer?: string | (() => string | undefined);
200
266
  /** Enables the Better Auth session validator after the legacy JWT validator. */
201
267
  betterAuth?: BetterAuthSocketOptions;
268
+ /**
269
+ * Application user model. When set, the legacy JWT validator refuses tokens whose user is
270
+ * missing or disabled.
271
+ */
272
+ userModel?: UserModel;
202
273
  /** Additional validators appended to the chain (after JWT and Better Auth). */
203
274
  extraValidators?: SocketAuthValidator[];
204
275
  }): ((socket: Socket, next: (error?: Error) => void) => void) => {
205
276
  const validators: SocketAuthValidator[] = [];
206
277
  if (tokenSecret) {
207
- validators.push(createLegacyJwtValidator(tokenSecret, issuer));
278
+ validators.push(createLegacyJwtValidator(tokenSecret, issuer, userModel));
208
279
  }
209
280
  if (betterAuth) {
210
281
  validators.push(createBetterAuthValidator(betterAuth));
@@ -102,9 +102,10 @@ export interface RealtimeAppOptions {
102
102
  tokenIssuer?: string;
103
103
  /**
104
104
  * Enables the Better Auth session validator for socket authentication. It is tried after
105
- * the legacy JWT validator when a token secret exists, or used alone otherwise. Pass the
106
- * instance returned by `createBetterAuth` (and optionally the app user model so
107
- * `decodedToken.id`/`admin` match the REST identity).
105
+ * the legacy JWT validator when a token secret exists, or used alone otherwise. Usually
106
+ * omitted: when a BetterAuthApp is registered on the same TerrenoApp, its instance and the
107
+ * RealtimeApp's `userModel` (else the TerrenoApp's) are used automatically. Pass the instance returned by
108
+ * `createBetterAuth` only for a RealtimeApp mounted without TerrenoApp, or to override it.
108
109
  */
109
110
  betterAuth?: BetterAuthSocketOptions;
110
111
  /**
@@ -119,8 +120,10 @@ export interface RealtimeAppOptions {
119
120
  * (D1). Authorization for realtime/sync subscriptions and mutations uses this full
120
121
  * document instead of the synthetic `{_id, admin, id}` shape derived from the token
121
122
  * alone — required for any permission check or `getUserScopes` resolver that reads
122
- * fields beyond `admin` (e.g. `organizationIds` for tenant-scoped sync). Without it,
123
- * socket-side authorization falls back to the synthetic shape (pre-D2 behavior).
123
+ * fields beyond `admin` (e.g. `organizationIds` for tenant-scoped sync). The sweep also
124
+ * disconnects sockets whose user was disabled or deleted. When omitted, the user model of
125
+ * the TerrenoApp this RealtimeApp is registered on is used; without either, socket-side
126
+ * authorization falls back to the synthetic shape (pre-D2 behavior).
124
127
  */
125
128
  userModel?: UserModel;
126
129
  /**
@@ -39,14 +39,37 @@ const TRACE_PARENT_HEADER = "traceparent";
39
39
  const TRACE_SAMPLED_HEADER = "x-trace-sampled";
40
40
  const USER_ID_HEADER = "x-user-id";
41
41
 
42
+ /**
43
+ * How the caller authenticated. Permission functions and hooks read it through
44
+ * {@link getCurrentRequestContext} to tell a user's own session apart from a delegated agent
45
+ * credential (an `mcp_` service token or an MCP OAuth access token).
46
+ *
47
+ * - `jwt`: a Terreno JWT bearer (REST or `/mcp`).
48
+ * - `better-auth-session`: a Better Auth session cookie or bearer.
49
+ * - `mcp-service-token`: a personal `mcp_` service token on `/mcp`.
50
+ * - `oauth`: an MCP OAuth access token on `/mcp`.
51
+ */
52
+ export type RequestCredential = "jwt" | "better-auth-session" | "mcp-service-token" | "oauth";
53
+
42
54
  /**
43
55
  * Correlation fields stored in AsyncLocalStorage for the lifetime of a request or job. Every log
44
56
  * line emitted inside the scope is enriched with these. `requestId` is the only required field; the
45
57
  * rest are populated when headers, trace context, or auth supply them.
46
58
  */
47
59
  export interface RequestContext {
60
+ /**
61
+ * The credential type that authenticated `userId`. Unset for anonymous requests and jobs.
62
+ * See {@link RequestCredential}.
63
+ */
64
+ credential?: RequestCredential;
48
65
  /** Background job identifier (from `x-job-id` or set via {@link runWithRequestContext}). */
49
66
  jobId?: string;
67
+ /**
68
+ * Scopes granted to the MCP OAuth access token that authenticated the request. Set only when
69
+ * `credential` is `oauth`. Terreno does not map scopes to tools; check them in permission code,
70
+ * for example with `requireOAuthScope`.
71
+ */
72
+ oauthScopes?: string[];
50
73
  /** Stable id shared by all log lines for one request/job; echoed to clients as `X-Request-ID`. */
51
74
  requestId: string;
52
75
  /** Auth session id, resolved from the JWT/Better Auth session or `x-session-id`. */
@@ -223,6 +246,7 @@ export const getCurrentLogContext = (): Partial<RequestContext> => {
223
246
  }
224
247
 
225
248
  return {
249
+ credential: context.credential,
226
250
  jobId: context.jobId,
227
251
  requestId: context.requestId,
228
252
  sessionId: context.sessionId,
@@ -260,6 +284,7 @@ export const applyRequestContextToSentry = (
260
284
  ): void => {
261
285
  const scope = Sentry.getCurrentScope();
262
286
  setSentryTag(scope, "request_id", context.requestId);
287
+ setSentryTag(scope, "credential", context.credential);
263
288
  setSentryTag(scope, "session_id", context.sessionId);
264
289
  setSentryTag(scope, "job_id", context.jobId);
265
290
  setSentryTag(scope, "user_id", context.userId);
@@ -273,6 +298,7 @@ export const applyRequestContextToSentry = (
273
298
 
274
299
  const sentryContext: Record<string, string | boolean> = {};
275
300
  setSentryContextValue(sentryContext, "requestId", context.requestId);
301
+ setSentryContextValue(sentryContext, "credential", context.credential);
276
302
  setSentryContextValue(sentryContext, "sessionId", context.sessionId);
277
303
  setSentryContextValue(sentryContext, "jobId", context.jobId);
278
304
  setSentryContextValue(sentryContext, "userId", context.userId);
@@ -369,6 +395,30 @@ export const runWithRequestContextAttributes = <T>(
369
395
  return runWithRequestContext(getRequestContextFromAttributes(attributes), callback);
370
396
  };
371
397
 
398
+ /**
399
+ * The Better Auth session middleware runs after JWT decoding and replaces `req.user` when it
400
+ * finds a session, so a session wins over a decoded JWT payload. A user set some other way (for
401
+ * example by passport inside `authenticateMiddleware`) keeps the credential already recorded.
402
+ */
403
+ const resolveRequestCredential = (
404
+ req: express.Request & {
405
+ authTokenPayload?: JwtSessionPayload;
406
+ betterAuthSession?: {session?: {id?: string}};
407
+ },
408
+ userId: string | undefined
409
+ ): RequestCredential | undefined => {
410
+ if (!userId) {
411
+ return undefined;
412
+ }
413
+ if (req.betterAuthSession) {
414
+ return "better-auth-session";
415
+ }
416
+ if (req.authTokenPayload) {
417
+ return "jwt";
418
+ }
419
+ return getCurrentRequestContext()?.credential;
420
+ };
421
+
372
422
  export const updateRequestContextFromRequest = (
373
423
  req: express.Request,
374
424
  res?: express.Response
@@ -388,8 +438,9 @@ export const updateRequestContextFromRequest = (
388
438
  getHeader(req, SESSION_ID_HEADER);
389
439
  const user = req.user as {_id?: unknown; id?: string} | undefined;
390
440
  const userId = user?.id ?? (user?._id ? String(user._id) : undefined);
441
+ const credential = resolveRequestCredential(reqWithContext, userId);
391
442
 
392
- setRequestContext({jobId, sessionId, userId});
443
+ setRequestContext({credential, jobId, sessionId, userId});
393
444
 
394
445
  if (jobId) {
395
446
  reqWithContext.jobId = jobId;
@@ -0,0 +1,89 @@
1
+ import {beforeEach, describe, expect, it} from "bun:test";
2
+ import type express from "express";
3
+ import mongoose, {model, Schema} from "mongoose";
4
+
5
+ import {modelRouter} from "./api";
6
+ import type {UserModel as UserModelType} from "./auth";
7
+ import {clearMCPRegistry} from "./mcp/registry";
8
+ import {Permissions} from "./permissions";
9
+ import {
10
+ getCurrentRequestContext,
11
+ type RequestCredential,
12
+ runWithRequestContext,
13
+ updateRequestContextFromRequest,
14
+ } from "./requestContext";
15
+ import {TerrenoApp} from "./terrenoApp";
16
+ import {authAsUser, setupDb, UserModel} from "./tests";
17
+
18
+ const typedUserModel = UserModel as unknown as UserModelType;
19
+
20
+ const gadgetSchema = new Schema({name: {description: "Gadget name", type: String}});
21
+ const GadgetModel =
22
+ (mongoose.models.CredentialGadget as mongoose.Model<{name?: string}> | undefined) ??
23
+ model<{name?: string}>("CredentialGadget", gadgetSchema);
24
+
25
+ const fakeRequest = (fields: Record<string, unknown>): express.Request =>
26
+ ({header: () => undefined, ...fields}) as unknown as express.Request;
27
+
28
+ const credentialFor = (fields: Record<string, unknown>): RequestCredential | undefined =>
29
+ runWithRequestContext({}, () => {
30
+ updateRequestContextFromRequest(fakeRequest(fields));
31
+ return getCurrentRequestContext()?.credential;
32
+ });
33
+
34
+ describe("request context credential", () => {
35
+ it("records jwt when a decoded JWT authenticated the user", () => {
36
+ expect(credentialFor({authTokenPayload: {id: "u1"}, user: {id: "u1"}})).toBe("jwt");
37
+ });
38
+
39
+ it("records better-auth-session when a Better Auth session authenticated the user", () => {
40
+ expect(
41
+ credentialFor({
42
+ authTokenPayload: {id: "u1"},
43
+ betterAuthSession: {session: {id: "s1"}},
44
+ user: {id: "u1"},
45
+ })
46
+ ).toBe("better-auth-session");
47
+ });
48
+
49
+ it("leaves the credential unset for anonymous requests", () => {
50
+ expect(credentialFor({authTokenPayload: {id: "u1"}})).toBeUndefined();
51
+ });
52
+
53
+ describe("inside a REST permission function", () => {
54
+ let app: express.Application;
55
+ let seen: Array<RequestCredential | undefined>;
56
+
57
+ beforeEach(async () => {
58
+ await setupDb();
59
+ clearMCPRegistry();
60
+ seen = [];
61
+ const recordCredential = (): boolean => {
62
+ seen.push(getCurrentRequestContext()?.credential);
63
+ return true;
64
+ };
65
+ app = new TerrenoApp({skipListen: true, userModel: typedUserModel})
66
+ .register(
67
+ modelRouter("/credential-gadgets", GadgetModel, {
68
+ permissions: {
69
+ create: [Permissions.IsAuthenticated],
70
+ delete: [],
71
+ list: [Permissions.IsAuthenticated, recordCredential],
72
+ read: [Permissions.IsAuthenticated],
73
+ update: [],
74
+ },
75
+ })
76
+ )
77
+ .build();
78
+ });
79
+
80
+ it("reports jwt for a JWT bearer", async () => {
81
+ const agent = await authAsUser(app, "notAdmin");
82
+
83
+ const res = await agent.get("/credential-gadgets");
84
+
85
+ expect(res.status).toBe(200);
86
+ expect(seen).toEqual(["jwt"]);
87
+ });
88
+ });
89
+ });
@@ -541,6 +541,27 @@ describe("seedBetterAuthUser", () => {
541
541
  assert.equal((user as {betterAuthId?: string}).betterAuthId, authId);
542
542
  });
543
543
 
544
+ it("links an application user that already exists for the seeded email", async () => {
545
+ const existing = await SeedAuthUser.create({email: seedUser.email, name: "Legacy Seed"});
546
+ const authId = new mongoose.Types.ObjectId().toString();
547
+ const auth = {
548
+ api: {
549
+ signUpEmail: async () => ({
550
+ user: {email: seedUser.email, emailVerified: false, id: authId, name: seedUser.name},
551
+ }),
552
+ },
553
+ };
554
+
555
+ const user = await seedBetterAuthUser({
556
+ auth: auth as never,
557
+ user: seedUser,
558
+ userModel: SeedAuthUser as never,
559
+ });
560
+
561
+ assert.equal(String((user as {_id?: unknown})._id), String(existing._id));
562
+ assert.equal((user as {betterAuthId?: string}).betterAuthId, authId);
563
+ });
564
+
544
565
  it("falls back to sign-in when sign-up fails", async () => {
545
566
  const authId = new mongoose.Types.ObjectId().toString();
546
567
  const auth = {
package/src/seedRunner.ts CHANGED
@@ -171,7 +171,9 @@ export const seedBetterAuthUser = async ({
171
171
  title: "Better Auth seed returned no user",
172
172
  });
173
173
  }
174
- return syncBetterAuthUser(userModel, authUser);
174
+ // The seed created or signed in to this Better Auth account itself, so its email is trusted
175
+ // for linking an existing app user (for example one seeded under the legacy JWT flow).
176
+ return syncBetterAuthUser(userModel, authUser, undefined, {trustEmail: true});
175
177
  };
176
178
 
177
179
  const selectSteps = (steps: SeedStep[], only?: string[]): SeedStep[] => {
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Sort-key allowlisting for modelRouter list endpoints and the MCP list tool.
3
+ *
4
+ * Sorting by a field reveals its order (and, combined with a second key, its exact value
5
+ * for booleans and enums) even when the field is hidden from the response. List sorts are
6
+ * therefore limited to fields the router declares sortable, the same way filters are limited
7
+ * to `queryFields`.
8
+ */
9
+
10
+ interface SortFieldOptions {
11
+ /** Fields the router allows filtering on. */
12
+ queryFields?: string[];
13
+ /** The router's default sort; the fields it names stay sortable. */
14
+ sort?: string | {[key: string]: unknown};
15
+ /** Extra fields clients may sort by without being able to filter on them. */
16
+ sortFields?: string[];
17
+ }
18
+
19
+ type ParsedSortFields = {fields: string[]} | {error: "invalid-sort"};
20
+
21
+ /**
22
+ * Field names named by a Mongoose-style sort: a space-separated string with optional
23
+ * `-`/`+` prefixes, or an object keyed by field. Anything else is invalid.
24
+ */
25
+ const parseSortFields = (sort: unknown): ParsedSortFields => {
26
+ if (typeof sort === "string") {
27
+ return {
28
+ fields: sort
29
+ .split(/\s+/)
30
+ .filter((token) => token.length > 0)
31
+ .map((token) => token.replace(/^[-+]/, "")),
32
+ };
33
+ }
34
+ if (sort !== null && typeof sort === "object" && !Array.isArray(sort)) {
35
+ return {fields: Object.keys(sort)};
36
+ }
37
+ return {error: "invalid-sort"};
38
+ };
39
+
40
+ /** Fields a list request may sort by: queryFields, the default sort's fields, and sortFields. */
41
+ export const getAllowedSortFields = (options: SortFieldOptions): string[] => {
42
+ const defaultSort = options.sort === undefined ? undefined : parseSortFields(options.sort);
43
+ const defaultSortFields = defaultSort && "fields" in defaultSort ? defaultSort.fields : [];
44
+ return [
45
+ ...new Set([
46
+ ...(options.queryFields ?? []),
47
+ ...defaultSortFields,
48
+ ...(options.sortFields ?? []),
49
+ ]),
50
+ ];
51
+ };
52
+
53
+ type SortCheckResult =
54
+ | {allowed: true}
55
+ | {allowed: false; error: "invalid-sort"}
56
+ | {allowed: false; error: "sort-field-not-allowed"; field: string};
57
+
58
+ /** Checks every field in a client sort against an allowlist. */
59
+ export const checkSortFields = (sort: unknown, allowedFields: string[]): SortCheckResult => {
60
+ const parsed = parseSortFields(sort);
61
+ if ("error" in parsed) {
62
+ return {allowed: false, error: parsed.error};
63
+ }
64
+ const field = parsed.fields.find((name) => !allowedFields.includes(name));
65
+ if (field !== undefined) {
66
+ return {allowed: false, error: "sort-field-not-allowed", field};
67
+ }
68
+ return {allowed: true};
69
+ };