@terreno/api 57.16.2 → 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
@@ -2,6 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createSocketAuthMiddleware = exports.createBetterAuthValidator = exports.createLegacyJwtValidator = void 0;
4
4
  const socketio_jwt_1 = require("@thream/socketio-jwt");
5
+ const auth_1 = require("../auth");
6
+ const betterAuthSetup_1 = require("../betterAuthSetup");
5
7
  const errors_1 = require("../errors");
6
8
  const logger_1 = require("../logger");
7
9
  const plugins_1 = require("../plugins");
@@ -27,8 +29,12 @@ const plugins_1 = require("../plugins");
27
29
  * (e.g. test suites that mutate it between fixtures). Pass a thunk to preserve that
28
30
  * per-request freshness; a plain string is still supported for callers who intentionally
29
31
  * want a fixed value.
32
+ *
33
+ * When `userModel` is provided, the token's user is loaded after verification and the
34
+ * handshake is refused when that user is missing or disabled, matching the HTTP JWT
35
+ * middleware and the Better Auth validator. Without it, only the token is checked.
30
36
  */
31
- const createLegacyJwtValidator = (tokenSecret, issuer) => {
37
+ const createLegacyJwtValidator = (tokenSecret, issuer, userModel) => {
32
38
  const resolveIssuer = () => typeof issuer === "function" ? issuer() : issuer;
33
39
  const middleware = (0, socketio_jwt_1.authorize)({
34
40
  onAuthentication: (decodedToken) => {
@@ -49,18 +55,57 @@ const createLegacyJwtValidator = (tokenSecret, issuer) => {
49
55
  reject(error);
50
56
  return;
51
57
  }
52
- // D1: stamp which validator authenticated this socket so the periodic
53
- // re-validation sweep knows to re-check local JWT expiry (not a Better Auth
54
- // session lookup) for it. The library already populated decodedToken with the
55
- // full JWT payload (exp/iss included), so this only adds the discriminator.
56
- if (socket.decodedToken) {
57
- socket.decodedToken.authKind = "jwt";
58
- }
59
- resolve();
58
+ rejectUnusableJwtUser(socket, userModel)
59
+ .then(() => {
60
+ // D1: stamp which validator authenticated this socket so the periodic
61
+ // re-validation sweep knows to re-check local JWT expiry (not a Better Auth
62
+ // session lookup) for it. The library already populated decodedToken with the
63
+ // full JWT payload (exp/iss included), so this only adds the discriminator.
64
+ if (socket.decodedToken) {
65
+ socket.decodedToken.authKind = "jwt";
66
+ }
67
+ resolve();
68
+ })
69
+ .catch((userError) => {
70
+ socket.decodedToken = undefined;
71
+ reject(userError);
72
+ });
60
73
  });
61
74
  });
62
75
  };
63
76
  exports.createLegacyJwtValidator = createLegacyJwtValidator;
77
+ /**
78
+ * Refuse a verified JWT whose user no longer exists or is disabled, so disabling an account
79
+ * blocks new socket handshakes the same way the HTTP JWT middleware blocks requests.
80
+ */
81
+ const rejectUnusableJwtUser = async (socket, userModel) => {
82
+ const userId = socket.decodedToken?.id;
83
+ if (!userModel || !userId) {
84
+ return;
85
+ }
86
+ let user;
87
+ try {
88
+ user = await (0, plugins_1.findOneOrNoneFor)(userModel, { _id: userId });
89
+ }
90
+ catch (error) {
91
+ // Keep database details out of the client error.
92
+ logger_1.logger.error(`[socket] Could not load the user for a JWT handshake: ${error}`);
93
+ throw new socketio_jwt_1.UnauthorizedError("invalid_token", {
94
+ message: "Unauthorized: could not resolve the application user",
95
+ });
96
+ }
97
+ if (!user) {
98
+ throw new socketio_jwt_1.UnauthorizedError("invalid_token", {
99
+ message: "Unauthorized: user not found",
100
+ });
101
+ }
102
+ if ((0, auth_1.isUserDisabled)(user)) {
103
+ logger_1.logger.warn(`[socket] User ${userId} is disabled, rejecting JWT`);
104
+ throw new socketio_jwt_1.UnauthorizedError("invalid_token", {
105
+ message: "Unauthorized: user is disabled",
106
+ });
107
+ }
108
+ };
64
109
  /** Strip an optional `Bearer ` prefix from the handshake token. */
65
110
  const extractRawToken = (socket) => {
66
111
  const { token } = socket.handshake.auth;
@@ -102,14 +147,30 @@ const createBetterAuthValidator = (options) => {
102
147
  let id = String(betterAuthUserId);
103
148
  let admin = false;
104
149
  if (userModel) {
105
- const appUser = (await (0, plugins_1.findOneOrNoneFor)(userModel, {
106
- betterAuthId: betterAuthUserId,
107
- }));
108
- if (!appUser?._id) {
150
+ // Same lookup as the REST session middleware: a user whose first contact after
151
+ // signing up is this handshake gets their app user created here.
152
+ let resolved;
153
+ try {
154
+ resolved = await (0, betterAuthSetup_1.resolveBetterAuthAppUser)({
155
+ betterAuthUser: session.user,
156
+ userModel,
157
+ });
158
+ }
159
+ catch (error) {
160
+ // Keep database details (model, field, duplicate-key values) out of the client error.
161
+ logger_1.logger.error(`[socket] Could not resolve the app user for a Better Auth session: ${error}`);
162
+ throw new socketio_jwt_1.UnauthorizedError("invalid_token", {
163
+ message: "Unauthorized: could not resolve the application user",
164
+ });
165
+ }
166
+ const { isDisabled, user } = resolved;
167
+ if (isDisabled) {
168
+ logger_1.logger.warn(`[socket] User ${user.id} is disabled, rejecting Better Auth session`);
109
169
  throw new socketio_jwt_1.UnauthorizedError("invalid_token", {
110
- message: "Unauthorized: Better Auth user has no application user",
170
+ message: "Unauthorized: user is disabled",
111
171
  });
112
172
  }
173
+ const appUser = user;
113
174
  id = String(appUser._id);
114
175
  admin = appUser.admin === true;
115
176
  }
@@ -125,10 +186,10 @@ exports.createBetterAuthValidator = createBetterAuthValidator;
125
186
  * Build the Socket.io auth middleware from a validator chain: validators run in order and
126
187
  * the first success wins; when all fail the connection is rejected with the last error.
127
188
  */
128
- const createSocketAuthMiddleware = ({ tokenSecret, issuer, betterAuth, extraValidators = [], }) => {
189
+ const createSocketAuthMiddleware = ({ tokenSecret, issuer, betterAuth, userModel, extraValidators = [], }) => {
129
190
  const validators = [];
130
191
  if (tokenSecret) {
131
- validators.push((0, exports.createLegacyJwtValidator)(tokenSecret, issuer));
192
+ validators.push((0, exports.createLegacyJwtValidator)(tokenSecret, issuer, userModel));
132
193
  }
133
194
  if (betterAuth) {
134
195
  validators.push((0, exports.createBetterAuthValidator)(betterAuth));
@@ -97,9 +97,10 @@ export interface RealtimeAppOptions {
97
97
  tokenIssuer?: string;
98
98
  /**
99
99
  * Enables the Better Auth session validator for socket authentication. It is tried after
100
- * the legacy JWT validator when a token secret exists, or used alone otherwise. Pass the
101
- * instance returned by `createBetterAuth` (and optionally the app user model so
102
- * `decodedToken.id`/`admin` match the REST identity).
100
+ * the legacy JWT validator when a token secret exists, or used alone otherwise. Usually
101
+ * omitted: when a BetterAuthApp is registered on the same TerrenoApp, its instance and the
102
+ * RealtimeApp's `userModel` (else the TerrenoApp's) are used automatically. Pass the instance returned by
103
+ * `createBetterAuth` only for a RealtimeApp mounted without TerrenoApp, or to override it.
103
104
  */
104
105
  betterAuth?: BetterAuthSocketOptions;
105
106
  /**
@@ -114,8 +115,10 @@ export interface RealtimeAppOptions {
114
115
  * (D1). Authorization for realtime/sync subscriptions and mutations uses this full
115
116
  * document instead of the synthetic `{_id, admin, id}` shape derived from the token
116
117
  * alone — required for any permission check or `getUserScopes` resolver that reads
117
- * fields beyond `admin` (e.g. `organizationIds` for tenant-scoped sync). Without it,
118
- * socket-side authorization falls back to the synthetic shape (pre-D2 behavior).
118
+ * fields beyond `admin` (e.g. `organizationIds` for tenant-scoped sync). The sweep also
119
+ * disconnects sockets whose user was disabled or deleted. When omitted, the user model of
120
+ * the TerrenoApp this RealtimeApp is registered on is used; without either, socket-side
121
+ * authorization falls back to the synthetic shape (pre-D2 behavior).
119
122
  */
120
123
  userModel?: UserModel;
121
124
  /**
@@ -1,13 +1,35 @@
1
1
  import type express from "express";
2
2
  import type { JwtPayload } from "jsonwebtoken";
3
+ /**
4
+ * How the caller authenticated. Permission functions and hooks read it through
5
+ * {@link getCurrentRequestContext} to tell a user's own session apart from a delegated agent
6
+ * credential (an `mcp_` service token or an MCP OAuth access token).
7
+ *
8
+ * - `jwt`: a Terreno JWT bearer (REST or `/mcp`).
9
+ * - `better-auth-session`: a Better Auth session cookie or bearer.
10
+ * - `mcp-service-token`: a personal `mcp_` service token on `/mcp`.
11
+ * - `oauth`: an MCP OAuth access token on `/mcp`.
12
+ */
13
+ export type RequestCredential = "jwt" | "better-auth-session" | "mcp-service-token" | "oauth";
3
14
  /**
4
15
  * Correlation fields stored in AsyncLocalStorage for the lifetime of a request or job. Every log
5
16
  * line emitted inside the scope is enriched with these. `requestId` is the only required field; the
6
17
  * rest are populated when headers, trace context, or auth supply them.
7
18
  */
8
19
  export interface RequestContext {
20
+ /**
21
+ * The credential type that authenticated `userId`. Unset for anonymous requests and jobs.
22
+ * See {@link RequestCredential}.
23
+ */
24
+ credential?: RequestCredential;
9
25
  /** Background job identifier (from `x-job-id` or set via {@link runWithRequestContext}). */
10
26
  jobId?: string;
27
+ /**
28
+ * Scopes granted to the MCP OAuth access token that authenticated the request. Set only when
29
+ * `credential` is `oauth`. Terreno does not map scopes to tools; check them in permission code,
30
+ * for example with `requireOAuthScope`.
31
+ */
32
+ oauthScopes?: string[];
11
33
  /** Stable id shared by all log lines for one request/job; echoed to clients as `X-Request-ID`. */
12
34
  requestId: string;
13
35
  /** Auth session id, resolved from the JWT/Better Auth session or `x-session-id`. */
@@ -195,6 +195,7 @@ const getCurrentLogContext = () => {
195
195
  return {};
196
196
  }
197
197
  return {
198
+ credential: context.credential,
198
199
  jobId: context.jobId,
199
200
  requestId: context.requestId,
200
201
  sessionId: context.sessionId,
@@ -220,6 +221,7 @@ const setSentryContextValue = (context, name, value) => {
220
221
  const applyRequestContextToSentry = (context = (0, exports.getCurrentLogContext)()) => {
221
222
  const scope = Sentry.getCurrentScope();
222
223
  setSentryTag(scope, "request_id", context.requestId);
224
+ setSentryTag(scope, "credential", context.credential);
223
225
  setSentryTag(scope, "session_id", context.sessionId);
224
226
  setSentryTag(scope, "job_id", context.jobId);
225
227
  setSentryTag(scope, "user_id", context.userId);
@@ -231,6 +233,7 @@ const applyRequestContextToSentry = (context = (0, exports.getCurrentLogContext)
231
233
  }
232
234
  const sentryContext = {};
233
235
  setSentryContextValue(sentryContext, "requestId", context.requestId);
236
+ setSentryContextValue(sentryContext, "credential", context.credential);
234
237
  setSentryContextValue(sentryContext, "sessionId", context.sessionId);
235
238
  setSentryContextValue(sentryContext, "jobId", context.jobId);
236
239
  setSentryContextValue(sentryContext, "userId", context.userId);
@@ -312,6 +315,23 @@ const runWithRequestContextAttributes = (attributes = {}, callback) => {
312
315
  return (0, exports.runWithRequestContext)((0, exports.getRequestContextFromAttributes)(attributes), callback);
313
316
  };
314
317
  exports.runWithRequestContextAttributes = runWithRequestContextAttributes;
318
+ /**
319
+ * The Better Auth session middleware runs after JWT decoding and replaces `req.user` when it
320
+ * finds a session, so a session wins over a decoded JWT payload. A user set some other way (for
321
+ * example by passport inside `authenticateMiddleware`) keeps the credential already recorded.
322
+ */
323
+ const resolveRequestCredential = (req, userId) => {
324
+ if (!userId) {
325
+ return undefined;
326
+ }
327
+ if (req.betterAuthSession) {
328
+ return "better-auth-session";
329
+ }
330
+ if (req.authTokenPayload) {
331
+ return "jwt";
332
+ }
333
+ return (0, exports.getCurrentRequestContext)()?.credential;
334
+ };
315
335
  const updateRequestContextFromRequest = (req, res) => {
316
336
  const reqWithContext = req;
317
337
  const jobId = reqWithContext.jobId ?? getHeader(req, JOB_ID_HEADER);
@@ -321,7 +341,8 @@ const updateRequestContextFromRequest = (req, res) => {
321
341
  getHeader(req, SESSION_ID_HEADER);
322
342
  const user = req.user;
323
343
  const userId = user?.id ?? (user?._id ? String(user._id) : undefined);
324
- (0, exports.setRequestContext)({ jobId, sessionId, userId });
344
+ const credential = resolveRequestCredential(reqWithContext, userId);
345
+ (0, exports.setRequestContext)({ credential, jobId, sessionId, userId });
325
346
  if (jobId) {
326
347
  reqWithContext.jobId = jobId;
327
348
  res?.setHeader("X-Job-ID", jobId);
@@ -74,7 +74,9 @@ const seedBetterAuthUser = async ({ auth, user, userModel, }) => {
74
74
  title: "Better Auth seed returned no user",
75
75
  });
76
76
  }
77
- return (0, betterAuthSetup_1.syncBetterAuthUser)(userModel, authUser);
77
+ // The seed created or signed in to this Better Auth account itself, so its email is trusted
78
+ // for linking an existing app user (for example one seeded under the legacy JWT flow).
79
+ return (0, betterAuthSetup_1.syncBetterAuthUser)(userModel, authUser, undefined, { trustEmail: true });
78
80
  };
79
81
  exports.seedBetterAuthUser = seedBetterAuthUser;
80
82
  const selectSteps = (steps, only) => {
@@ -0,0 +1,33 @@
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
+ interface SortFieldOptions {
10
+ /** Fields the router allows filtering on. */
11
+ queryFields?: string[];
12
+ /** The router's default sort; the fields it names stay sortable. */
13
+ sort?: string | {
14
+ [key: string]: unknown;
15
+ };
16
+ /** Extra fields clients may sort by without being able to filter on them. */
17
+ sortFields?: string[];
18
+ }
19
+ /** Fields a list request may sort by: queryFields, the default sort's fields, and sortFields. */
20
+ export declare const getAllowedSortFields: (options: SortFieldOptions) => string[];
21
+ type SortCheckResult = {
22
+ allowed: true;
23
+ } | {
24
+ allowed: false;
25
+ error: "invalid-sort";
26
+ } | {
27
+ allowed: false;
28
+ error: "sort-field-not-allowed";
29
+ field: string;
30
+ };
31
+ /** Checks every field in a client sort against an allowlist. */
32
+ export declare const checkSortFields: (sort: unknown, allowedFields: string[]) => SortCheckResult;
33
+ export {};
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ /**
3
+ * Sort-key allowlisting for modelRouter list endpoints and the MCP list tool.
4
+ *
5
+ * Sorting by a field reveals its order (and, combined with a second key, its exact value
6
+ * for booleans and enums) even when the field is hidden from the response. List sorts are
7
+ * therefore limited to fields the router declares sortable, the same way filters are limited
8
+ * to `queryFields`.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.checkSortFields = exports.getAllowedSortFields = void 0;
12
+ /**
13
+ * Field names named by a Mongoose-style sort: a space-separated string with optional
14
+ * `-`/`+` prefixes, or an object keyed by field. Anything else is invalid.
15
+ */
16
+ const parseSortFields = (sort) => {
17
+ if (typeof sort === "string") {
18
+ return {
19
+ fields: sort
20
+ .split(/\s+/)
21
+ .filter((token) => token.length > 0)
22
+ .map((token) => token.replace(/^[-+]/, "")),
23
+ };
24
+ }
25
+ if (sort !== null && typeof sort === "object" && !Array.isArray(sort)) {
26
+ return { fields: Object.keys(sort) };
27
+ }
28
+ return { error: "invalid-sort" };
29
+ };
30
+ /** Fields a list request may sort by: queryFields, the default sort's fields, and sortFields. */
31
+ const getAllowedSortFields = (options) => {
32
+ const defaultSort = options.sort === undefined ? undefined : parseSortFields(options.sort);
33
+ const defaultSortFields = defaultSort && "fields" in defaultSort ? defaultSort.fields : [];
34
+ return [
35
+ ...new Set([
36
+ ...(options.queryFields ?? []),
37
+ ...defaultSortFields,
38
+ ...(options.sortFields ?? []),
39
+ ]),
40
+ ];
41
+ };
42
+ exports.getAllowedSortFields = getAllowedSortFields;
43
+ /** Checks every field in a client sort against an allowlist. */
44
+ const checkSortFields = (sort, allowedFields) => {
45
+ const parsed = parseSortFields(sort);
46
+ if ("error" in parsed) {
47
+ return { allowed: false, error: parsed.error };
48
+ }
49
+ const field = parsed.fields.find((name) => !allowedFields.includes(name));
50
+ if (field !== undefined) {
51
+ return { allowed: false, error: "sort-field-not-allowed", field };
52
+ }
53
+ return { allowed: true };
54
+ };
55
+ exports.checkSortFields = checkSortFields;
@@ -12,6 +12,7 @@ const docLoader_1 = require("../docLoader");
12
12
  const errors_1 = require("../errors");
13
13
  const permissions_1 = require("../permissions");
14
14
  const modelRouterAccess_1 = require("../rbac/modelRouterAccess");
15
+ const userWriteGuards_1 = require("../rbac/userWriteGuards");
15
16
  const transformers_1 = require("../transformers");
16
17
  /**
17
18
  * Thrown by executeUpdate when a concurrency check fails. Carries the current server document
@@ -81,6 +82,109 @@ const reloadDocForConflict = async (model, id) => {
81
82
  return undefined;
82
83
  }
83
84
  };
85
+ /**
86
+ * True for legacy permissions whose object check binds a document to its owner. Read lazily:
87
+ * `permissions` and this module import each other.
88
+ */
89
+ const isOwnerIdentityPermission = (permission) => permission === permissions_1.Permissions.IsOwner || permission === permissions_1.Permissions.IsOwnerOrReadOnly;
90
+ /**
91
+ * Owner and scope checks that must hold for the document as written, not only as loaded.
92
+ *
93
+ * - RBAC routers (`access` + `accessControl`): the framework-built role and scope checks for
94
+ * the method (the role grant evaluated against the document, plus the router `access.scope`),
95
+ * and any owner-identity entries in `access.also`. Other `also` entries are left out so
96
+ * state-dependent consumer checks keep running only against the pre-write document.
97
+ * - Legacy routers: `IsOwner` when the method's permissions use an owner-identity check.
98
+ */
99
+ const getWriteScopeChecks = (options, method) => {
100
+ if (options.access && options.accessControl) {
101
+ const scoped = (0, modelRouterAccess_1.buildAccessPermissions)(options.accessControl, {
102
+ ...options.access,
103
+ also: undefined,
104
+ })[method];
105
+ const alsoOwner = (options.access.also?.[method] ?? []).filter(isOwnerIdentityPermission);
106
+ return [...scoped, ...alsoOwner];
107
+ }
108
+ if (method === "update") {
109
+ return (options.permissions?.update ?? []).some(isOwnerIdentityPermission)
110
+ ? [permissions_1.Permissions.IsOwner]
111
+ : [];
112
+ }
113
+ // A create is owner-scoped when any method on the router binds documents to their owner.
114
+ const lists = [
115
+ options.permissions?.create,
116
+ options.permissions?.read,
117
+ options.permissions?.update,
118
+ options.permissions?.delete,
119
+ ];
120
+ if (!lists.some((list) => (list ?? []).some(isOwnerIdentityPermission))) {
121
+ return [];
122
+ }
123
+ // Only a named owner is checked, so a create that leaves the owner for a hook or default
124
+ // to fill keeps working.
125
+ return [
126
+ (method_, user, obj) => obj?.ownerId == null ||
127
+ permissions_1.Permissions.IsOwner(method_, user, obj),
128
+ ];
129
+ };
130
+ /**
131
+ * Reject a write whose resulting document would fall outside the caller's owner or RBAC scope,
132
+ * for example a create naming another user as owner or an update that moves the owner field.
133
+ * Runs on REST, MCP and sync writes alike because they share these executors.
134
+ */
135
+ const assertWriteStaysInScope = async ({ doc, method, model, options, user, }) => {
136
+ const checks = getWriteScopeChecks(options, method);
137
+ for (const check of checks) {
138
+ if (!(await check(method, user, doc))) {
139
+ throw new errors_1.APIError({
140
+ status: 403,
141
+ title: `Write scope violation on ${model.modelName}`,
142
+ });
143
+ }
144
+ }
145
+ };
146
+ /**
147
+ * Hydrate a create body item without saving it, so owner checks see defaults and virtuals the
148
+ * way they see a loaded document. Returns undefined when the item cannot be cast; `create`
149
+ * then reports the same validation error.
150
+ */
151
+ const hydrateCreateCandidate = (model, item) => {
152
+ try {
153
+ return new model(item);
154
+ }
155
+ catch {
156
+ return undefined;
157
+ }
158
+ };
159
+ /** Sync bookkeeping that `syncPlugin` stamps on every write; clients never set it. */
160
+ const SYNC_STAMP_FIELDS = ["_syncSeq", "_syncPrevStream"];
161
+ /**
162
+ * Remove fields that only the server may set from a client write body:
163
+ * - `deleted` on a soft-delete model is set only by the delete operation, so update authority
164
+ * cannot soft-delete a record without delete permission, `preDelete` / `postDelete`, and the
165
+ * delete audit.
166
+ * - `_syncSeq` / `_syncPrevStream` order the sync streams, so a client cannot pin a document's
167
+ * seq and hide it from other members' snapshots and deltas.
168
+ * Server hooks (`preCreate` / `preUpdate`) run after this and may still set `deleted`.
169
+ */
170
+ const stripServerOwnedFields = (model, body) => {
171
+ if (Array.isArray(body)) {
172
+ return body.map((item) => stripServerOwnedFields(model, item));
173
+ }
174
+ if (!body || typeof body !== "object") {
175
+ return body;
176
+ }
177
+ const isSoftDeleteModel = model.schema.path("deleted")?.instance === "Boolean";
178
+ const fields = isSoftDeleteModel ? [...SYNC_STAMP_FIELDS, "deleted"] : SYNC_STAMP_FIELDS;
179
+ if (!fields.some((field) => Object.hasOwn(body, field))) {
180
+ return body;
181
+ }
182
+ const rest = { ...body };
183
+ for (const field of fields) {
184
+ delete rest[field];
185
+ }
186
+ return rest;
187
+ };
84
188
  /**
85
189
  * Create a document through the same pipeline as `POST /`: method-level permissions,
86
190
  * `transformer.transform`, `preCreate`, `Model.create` (Mongoose validation), population,
@@ -97,7 +201,7 @@ const executeCreate = async ({ model, options, user, body, req, skipPermissionCh
97
201
  }
98
202
  let cleanedBody;
99
203
  try {
100
- cleanedBody = (0, transformers_1.transform)(options, body, "create", user);
204
+ cleanedBody = (0, transformers_1.transform)(options, stripServerOwnedFields(model, body), "create", user);
101
205
  }
102
206
  catch (error) {
103
207
  throw (0, errors_1.passthroughOrWrap)(error, {
@@ -147,6 +251,15 @@ const executeCreate = async ({ model, options, user, body, req, skipPermissionCh
147
251
  phase: "create",
148
252
  user,
149
253
  });
254
+ if (!skipPermissionChecks) {
255
+ const items = Array.isArray(cleanedBody) ? cleanedBody : [cleanedBody];
256
+ for (const item of items) {
257
+ const candidate = item ? hydrateCreateCandidate(model, item) : undefined;
258
+ if (candidate) {
259
+ await assertWriteStaysInScope({ doc: candidate, method: "create", model, options, user });
260
+ }
261
+ }
262
+ }
150
263
  let data;
151
264
  try {
152
265
  data = (await model.create(cleanedBody));
@@ -223,9 +336,16 @@ const executeUpdate = async ({ model, options, user, id, body, concurrencyCheck,
223
336
  title: `Access to GET on ${model.modelName}:${id} denied for ${user?.id}`,
224
337
  });
225
338
  }
339
+ // Runs even for admin-window writes that skip modelRouter permissions.
340
+ await (0, userWriteGuards_1.assertCanWriteTargetUser)({
341
+ accessControl: options.accessControl,
342
+ actor: user,
343
+ modelName: writeModelName ?? model.modelName,
344
+ target: doc,
345
+ });
226
346
  let cleanedBody;
227
347
  try {
228
- cleanedBody = (0, transformers_1.transform)(options, body, "update", user);
348
+ cleanedBody = (0, transformers_1.transform)(options, stripServerOwnedFields(model, body), "update", user);
229
349
  }
230
350
  catch (error) {
231
351
  throw (0, errors_1.passthroughOrWrap)(error, {
@@ -270,6 +390,14 @@ const executeUpdate = async ({ model, options, user, id, body, concurrencyCheck,
270
390
  });
271
391
  }
272
392
  }
393
+ // Checked before the privileged-field strip so identity writes are rejected, not dropped.
394
+ await (0, userWriteGuards_1.assertCanWriteUserIdentity)({
395
+ accessControl: options.accessControl,
396
+ actor: user,
397
+ body: cleanedBody,
398
+ modelName: writeModelName ?? model.modelName,
399
+ target: doc,
400
+ });
273
401
  cleanedBody = (0, auth_1.omitUserRolesFromWriteBody)(writeModelName ?? model.modelName, options.accessControl, cleanedBody, request
274
402
  .terrenoAllowUserAdminWrite === true);
275
403
  await (0, modelRouterAccess_1.validateAccessWritePayload)({
@@ -338,6 +466,10 @@ const executeUpdate = async ({ model, options, user, id, body, concurrencyCheck,
338
466
  // updates. We won't wind up with corrupted data, just an API error.
339
467
  try {
340
468
  doc.set(cleanedBody);
469
+ // The pre-write document passed the update checks; the written state must stay in scope too.
470
+ if (!skipPermissionChecks) {
471
+ await assertWriteStaysInScope({ doc, method: "update", model, options, user });
472
+ }
341
473
  await doc.save();
342
474
  }
343
475
  catch (error) {
@@ -447,6 +579,12 @@ const executeDelete = async ({ model, options, user, id, existingDoc, req, skipP
447
579
  title: `Access to GET on ${model.modelName}:${id} denied for ${user?.id}`,
448
580
  });
449
581
  }
582
+ await (0, userWriteGuards_1.assertCanWriteTargetUser)({
583
+ accessControl: options.accessControl,
584
+ actor: user,
585
+ modelName: model.modelName,
586
+ target: doc,
587
+ });
450
588
  if (options.preDelete) {
451
589
  let body;
452
590
  try {
@@ -165,6 +165,8 @@ export interface SyncMutationDocument {
165
165
  _id: mongoose.Types.ObjectId;
166
166
  mutationId: string;
167
167
  userId: string;
168
+ /** Sync collection the mutation was claimed for; absent on rows recorded before it existed. */
169
+ collectionTag?: string;
168
170
  status: SyncMutationStatus;
169
171
  nackCode?: string;
170
172
  resultId?: string;
@@ -338,6 +338,11 @@ const syncMutationSchema = new mongoose_1.Schema({
338
338
  "SYNC_MUTATION_LEASE_MS may be taken over by a fresh delivery via findOneAndUpdate",
339
339
  type: Date,
340
340
  },
341
+ collectionTag: {
342
+ description: "Sync collection the mutation was claimed for; a replay naming another collection is " +
343
+ "rejected",
344
+ type: String,
345
+ },
341
346
  created: {
342
347
  default: () => luxon_1.DateTime.now().toJSDate(),
343
348
  description: "When the mutation was first claimed; TTL-indexed so rows expire after 30 days",