@terreno/api 57.2.0 → 57.3.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 (277) hide show
  1. package/README.md +17 -7
  2. package/dist/actions.js +19 -7
  3. package/dist/api.d.ts +4 -0
  4. package/dist/api.js +12 -24
  5. package/dist/auth.d.ts +23 -10
  6. package/dist/auth.js +97 -32
  7. package/dist/authRecovery.d.ts +5 -0
  8. package/dist/authRecovery.js +350 -0
  9. package/dist/authTokens.d.ts +8 -0
  10. package/dist/authTokens.js +162 -0
  11. package/dist/betterAuth.d.ts +33 -0
  12. package/dist/betterAuthApp.d.ts +4 -0
  13. package/dist/betterAuthApp.js +26 -8
  14. package/dist/betterAuthSetup.d.ts +44 -2
  15. package/dist/betterAuthSetup.js +288 -18
  16. package/dist/collectionRegistry.d.ts +38 -0
  17. package/dist/collectionRegistry.js +72 -0
  18. package/dist/configurationApp.d.ts +11 -2
  19. package/dist/configurationApp.js +2 -4
  20. package/dist/docLoader.js +35 -6
  21. package/dist/expressServer.d.ts +26 -3
  22. package/dist/expressServer.js +79 -11
  23. package/dist/index.d.ts +16 -0
  24. package/dist/index.js +38 -2
  25. package/dist/mcp/auth.d.ts +1 -0
  26. package/dist/mcp/auth.js +47 -25
  27. package/dist/mcp/handlers.d.ts +1 -1
  28. package/dist/mcp/handlers.js +67 -233
  29. package/dist/mcp/query.d.ts +2 -2
  30. package/dist/mcp/registry.d.ts +1 -5
  31. package/dist/mcp/registry.js +31 -20
  32. package/dist/mcp/schemaGenerator.d.ts +2 -7
  33. package/dist/mcp/schemaGenerator.js +41 -116
  34. package/dist/mcp/server.d.ts +1 -0
  35. package/dist/mcp/server.js +1 -0
  36. package/dist/mcp/serviceTokens.d.ts +16 -0
  37. package/dist/mcp/serviceTokens.js +345 -0
  38. package/dist/mcp/types.d.ts +2 -2
  39. package/dist/models/mcpServiceToken.d.ts +3 -0
  40. package/dist/models/mcpServiceToken.js +208 -0
  41. package/dist/openApiBuilder.d.ts +5 -4
  42. package/dist/openApiBuilder.js +61 -8
  43. package/dist/openApiCompat.js +1 -1
  44. package/dist/openApiValidator.js +0 -2
  45. package/dist/plugins.d.ts +14 -1
  46. package/dist/plugins.js +17 -6
  47. package/dist/populate.d.ts +2 -2
  48. package/dist/populate.js +47 -42
  49. package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
  50. package/dist/rateLimit/applyTrustProxy.js +17 -0
  51. package/dist/rateLimit/createStore.d.ts +2 -0
  52. package/dist/rateLimit/createStore.js +28 -0
  53. package/dist/rateLimit/memoryStore.d.ts +2 -0
  54. package/dist/rateLimit/memoryStore.js +108 -0
  55. package/dist/rateLimit/middleware.d.ts +11 -0
  56. package/dist/rateLimit/middleware.js +110 -0
  57. package/dist/rateLimit/mongoStore.d.ts +3 -0
  58. package/dist/rateLimit/mongoStore.js +122 -0
  59. package/dist/rateLimit/policies.d.ts +14 -0
  60. package/dist/rateLimit/policies.js +151 -0
  61. package/dist/rateLimit/redisStore.d.ts +3 -0
  62. package/dist/rateLimit/redisStore.js +155 -0
  63. package/dist/rateLimit/types.d.ts +54 -0
  64. package/dist/rateLimit/types.js +9 -0
  65. package/dist/rbac/access.js +5 -1
  66. package/dist/rbac/assertAllowed.d.ts +9 -0
  67. package/dist/rbac/assertAllowed.js +182 -0
  68. package/dist/rbac/modelRouterAccess.d.ts +1 -0
  69. package/dist/rbac/modelRouterAccess.js +8 -4
  70. package/dist/rbac/permissionUtils.js +3 -2
  71. package/dist/rbac/resolve.js +5 -4
  72. package/dist/rbac/routes.js +15 -6
  73. package/dist/realtime/deprecation.d.ts +12 -0
  74. package/dist/realtime/deprecation.js +32 -0
  75. package/dist/realtime/realtimeApp.d.ts +1 -1
  76. package/dist/realtime/realtimeApp.js +10 -11
  77. package/dist/realtime/registry.d.ts +0 -31
  78. package/dist/realtime/registry.js +44 -31
  79. package/dist/realtime/socketAuth.d.ts +5 -5
  80. package/dist/realtime/socketAuth.js +11 -1
  81. package/dist/realtime/socketUser.d.ts +5 -1
  82. package/dist/realtime/types.d.ts +14 -4
  83. package/dist/schemaMetadata.d.ts +56 -0
  84. package/dist/schemaMetadata.js +513 -0
  85. package/dist/seedRunner.d.ts +88 -0
  86. package/dist/seedRunner.js +627 -0
  87. package/dist/sync/executors.d.ts +12 -2
  88. package/dist/sync/executors.js +8 -10
  89. package/dist/sync/loadHarness.js +28 -19
  90. package/dist/sync/models.js +26 -24
  91. package/dist/sync/mutationHandler.d.ts +9 -0
  92. package/dist/sync/mutationHandler.js +11 -6
  93. package/dist/sync/registrationSideEffects.d.ts +35 -0
  94. package/dist/sync/registrationSideEffects.js +151 -0
  95. package/dist/sync/registry.d.ts +2 -52
  96. package/dist/sync/registry.js +38 -187
  97. package/dist/sync/routes.js +3 -2
  98. package/dist/sync/scripts/compactTombstones.js +0 -2
  99. package/dist/sync/syncApp.d.ts +3 -3
  100. package/dist/sync/syncApp.js +4 -4
  101. package/dist/sync/syncBatch.js +3 -2
  102. package/dist/sync/syncSeqPlugin.d.ts +1 -1
  103. package/dist/sync/syncSeqPlugin.js +20 -16
  104. package/dist/terrenoApp.d.ts +19 -5
  105. package/dist/terrenoApp.js +66 -18
  106. package/dist/tests/models.d.ts +2 -0
  107. package/dist/tests/models.js +6 -0
  108. package/dist/types/authToken.d.ts +33 -0
  109. package/dist/types/authToken.js +2 -0
  110. package/dist/types/mcpServiceToken.d.ts +41 -0
  111. package/dist/types/mcpServiceToken.js +2 -0
  112. package/dist/webhooks/headerValue.d.ts +2 -0
  113. package/dist/webhooks/headerValue.js +14 -0
  114. package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
  115. package/dist/webhooks/idempotency/memoryStore.js +65 -0
  116. package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
  117. package/dist/webhooks/idempotency/mongoStore.js +150 -0
  118. package/dist/webhooks/idempotency/webhookReceipt.d.ts +62 -0
  119. package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
  120. package/dist/webhooks/rawBody.d.ts +14 -0
  121. package/dist/webhooks/rawBody.js +22 -0
  122. package/dist/webhooks/timingSafeEqual.d.ts +4 -0
  123. package/dist/webhooks/timingSafeEqual.js +17 -0
  124. package/dist/webhooks/verifiers/hmac.d.ts +15 -0
  125. package/dist/webhooks/verifiers/hmac.js +49 -0
  126. package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
  127. package/dist/webhooks/verifiers/sendgrid.js +56 -0
  128. package/dist/webhooks/verifiers/stripe.d.ts +9 -0
  129. package/dist/webhooks/verifiers/stripe.js +99 -0
  130. package/dist/webhooks/verifiers/twilio.d.ts +9 -0
  131. package/dist/webhooks/verifiers/twilio.js +112 -0
  132. package/dist/webhooks/webhooksApp.d.ts +33 -0
  133. package/dist/webhooks/webhooksApp.js +195 -0
  134. package/package.json +4 -5
  135. package/src/__snapshots__/openApi.test.ts.snap +270 -0
  136. package/src/__snapshots__/openApiBuilder.test.ts.snap +30 -12
  137. package/src/__snapshots__/schemaMetadata.test.ts.snap +197 -0
  138. package/src/actions.ts +20 -13
  139. package/src/adminModelRouter.test.ts +133 -0
  140. package/src/api.arrayOperations.test.ts +43 -31
  141. package/src/api.hooks.test.ts +38 -29
  142. package/src/api.query.test.ts +31 -31
  143. package/src/api.test.ts +95 -96
  144. package/src/api.ts +16 -27
  145. package/src/auth.test.ts +107 -51
  146. package/src/auth.ts +98 -29
  147. package/src/authRecovery.test.ts +281 -0
  148. package/src/authRecovery.ts +279 -0
  149. package/src/authTokens.test.ts +94 -0
  150. package/src/authTokens.ts +118 -0
  151. package/src/authVerification.test.ts +293 -0
  152. package/src/betterAuth.ts +24 -0
  153. package/src/betterAuthApp.test.ts +1 -0
  154. package/src/betterAuthApp.ts +27 -9
  155. package/src/betterAuthSetup.test.ts +568 -38
  156. package/src/betterAuthSetup.ts +260 -5
  157. package/src/collectionRegistry.test.ts +165 -0
  158. package/src/collectionRegistry.ts +115 -0
  159. package/src/configurationApp.ts +13 -7
  160. package/src/docLoader.test.ts +45 -1
  161. package/src/docLoader.ts +37 -6
  162. package/src/express.d.ts +1 -0
  163. package/src/expressServer.test.ts +130 -66
  164. package/src/expressServer.ts +75 -19
  165. package/src/githubAuth.test.ts +60 -55
  166. package/src/index.ts +58 -0
  167. package/src/mcp/auth.test.ts +47 -0
  168. package/src/mcp/auth.ts +32 -11
  169. package/src/mcp/handlers.ts +45 -172
  170. package/src/mcp/integration.test.ts +59 -9
  171. package/src/mcp/query.ts +2 -4
  172. package/src/mcp/registry.ts +29 -20
  173. package/src/mcp/schemaGenerator.test.ts +8 -0
  174. package/src/mcp/schemaGenerator.ts +49 -131
  175. package/src/mcp/server.ts +2 -0
  176. package/src/mcp/serviceTokens.test.ts +330 -0
  177. package/src/mcp/serviceTokens.ts +307 -0
  178. package/src/mcp/toolGenerator.test.ts +1 -1
  179. package/src/mcp/types.ts +2 -6
  180. package/src/models/mcpServiceToken.test.ts +129 -0
  181. package/src/models/mcpServiceToken.ts +158 -0
  182. package/src/openApi.test.ts +80 -64
  183. package/src/openApiBuilder.test.ts +95 -7
  184. package/src/openApiBuilder.ts +46 -9
  185. package/src/openApiCompat.ts +1 -1
  186. package/src/openApiValidator.test.ts +49 -54
  187. package/src/openApiValidator.ts +1 -3
  188. package/src/plugins.test.ts +14 -0
  189. package/src/plugins.ts +34 -9
  190. package/src/populate.test.ts +34 -0
  191. package/src/populate.ts +40 -29
  192. package/src/rateLimit/applyTrustProxy.ts +17 -0
  193. package/src/rateLimit/createStore.ts +25 -0
  194. package/src/rateLimit/memoryStore.ts +40 -0
  195. package/src/rateLimit/middleware.ts +79 -0
  196. package/src/rateLimit/mongoStore.test.ts +80 -0
  197. package/src/rateLimit/mongoStore.ts +76 -0
  198. package/src/rateLimit/policies.ts +130 -0
  199. package/src/rateLimit/rateLimit.test.ts +328 -0
  200. package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
  201. package/src/rateLimit/redisStore.test.ts +114 -0
  202. package/src/rateLimit/redisStore.ts +85 -0
  203. package/src/rateLimit/types.ts +64 -0
  204. package/src/rbac/access.ts +5 -1
  205. package/src/rbac/assertAllowed.test.ts +325 -0
  206. package/src/rbac/assertAllowed.ts +157 -0
  207. package/src/rbac/backfillAdmins.test.ts +124 -0
  208. package/src/rbac/fieldViews.test.ts +89 -0
  209. package/src/rbac/modelRouterAccess.test.ts +126 -0
  210. package/src/rbac/modelRouterAccess.ts +5 -2
  211. package/src/rbac/permissionUtils.ts +3 -2
  212. package/src/rbac/realtimeAccess.test.ts +109 -1
  213. package/src/rbac/resolve.ts +5 -4
  214. package/src/rbac/roleManager.test.ts +169 -0
  215. package/src/rbac/routes.test.ts +233 -0
  216. package/src/rbac/routes.ts +16 -6
  217. package/src/realtime/deprecation.test.ts +60 -0
  218. package/src/realtime/deprecation.ts +32 -0
  219. package/src/realtime/realtime.test.ts +8 -4
  220. package/src/realtime/realtimeApp.ts +10 -11
  221. package/src/realtime/realtimeAppSetup.test.ts +32 -5
  222. package/src/realtime/registry.ts +48 -42
  223. package/src/realtime/sessionRevalidation.test.ts +57 -44
  224. package/src/realtime/socketAuth.test.ts +75 -23
  225. package/src/realtime/socketAuth.ts +17 -6
  226. package/src/realtime/socketUser.ts +5 -3
  227. package/src/realtime/types.ts +14 -4
  228. package/src/schemaMetadata.test.ts +405 -0
  229. package/src/schemaMetadata.ts +593 -0
  230. package/src/scrubAdminFields.test.ts +105 -0
  231. package/src/seedRunner.test.ts +591 -0
  232. package/src/seedRunner.ts +464 -0
  233. package/src/sync/docMatchesMutationData.test.ts +16 -0
  234. package/src/sync/ensureSyncIndexes.test.ts +54 -15
  235. package/src/sync/executors.test.ts +40 -0
  236. package/src/sync/executors.ts +24 -12
  237. package/src/sync/integration.test.ts +15 -7
  238. package/src/sync/loadHarness.ts +28 -19
  239. package/src/sync/models.ts +32 -18
  240. package/src/sync/mutationHandler.test.ts +16 -16
  241. package/src/sync/mutationHandler.ts +9 -7
  242. package/src/sync/registrationSideEffects.test.ts +126 -0
  243. package/src/sync/registrationSideEffects.ts +131 -0
  244. package/src/sync/registry.ts +45 -171
  245. package/src/sync/routes.ts +3 -2
  246. package/src/sync/scripts/compactTombstones.ts +0 -2
  247. package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
  248. package/src/sync/sync.test.ts +25 -23
  249. package/src/sync/syncApp.ts +4 -4
  250. package/src/sync/syncBatch.ts +3 -2
  251. package/src/sync/syncFrontier.test.ts +17 -15
  252. package/src/sync/syncPhaseC.test.ts +54 -43
  253. package/src/sync/syncRoutes.test.ts +51 -36
  254. package/src/sync/syncSeqPlugin.ts +66 -44
  255. package/src/sync/syncSocket.test.ts +112 -81
  256. package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
  257. package/src/terrenoApp.ts +87 -15
  258. package/src/tests/models.ts +14 -1
  259. package/src/types/authToken.ts +43 -0
  260. package/src/types/mcpServiceToken.ts +54 -0
  261. package/src/webhooks/headerValue.test.ts +22 -0
  262. package/src/webhooks/headerValue.ts +12 -0
  263. package/src/webhooks/idempotency/memoryStore.ts +34 -0
  264. package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
  265. package/src/webhooks/idempotency/mongoStore.ts +83 -0
  266. package/src/webhooks/idempotency/webhookReceipt.ts +70 -0
  267. package/src/webhooks/rawBody.test.ts +74 -0
  268. package/src/webhooks/rawBody.ts +23 -0
  269. package/src/webhooks/timingSafeEqual.ts +16 -0
  270. package/src/webhooks/verifiers/hmac.test.ts +110 -0
  271. package/src/webhooks/verifiers/hmac.ts +54 -0
  272. package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
  273. package/src/webhooks/verifiers/sendgrid.ts +59 -0
  274. package/src/webhooks/verifiers/stripe.ts +67 -0
  275. package/src/webhooks/verifiers/twilio.ts +69 -0
  276. package/src/webhooks/webhooksApp.test.ts +221 -0
  277. package/src/webhooks/webhooksApp.ts +144 -0
@@ -10,10 +10,12 @@ import {mongodbAdapter} from "better-auth/adapters/mongodb";
10
10
  import {toNodeHandler} from "better-auth/node";
11
11
  import {bearer} from "better-auth/plugins";
12
12
  import type {Application, NextFunction, Request, Response} from "express";
13
+ import type {Db} from "mongodb";
13
14
  import mongoose from "mongoose";
14
- import type {UserModel} from "./auth";
15
+ import {type HasSetPassword, setPasswordForUser, type UserModel} from "./auth";
15
16
  import type {BetterAuthConfig, BetterAuthSessionData, BetterAuthUser} from "./betterAuth";
16
17
  import {APIError} from "./errors";
18
+ import type {AuthRecoveryMail} from "./expressServer";
17
19
  import {logger} from "./logger";
18
20
  import {findOneOrNoneFor} from "./plugins";
19
21
  import {updateRequestContextFromRequest} from "./requestContext";
@@ -28,9 +30,7 @@ export type BetterAuthInstance = ReturnType<typeof betterAuth>;
28
30
  */
29
31
  // Minimal shape we use from the MongoDB native client returned by mongoose connection
30
32
  export interface MongoClientLike {
31
- // noExplicitAny: the MongoDB driver Db type is opaque to this layer; it is passed straight to better-auth's adapter
32
- // biome-ignore lint/suspicious/noExplicitAny: the MongoDB driver Db type is opaque to this layer; it is passed straight to better-auth's adapter
33
- db: () => any;
33
+ db: () => Db;
34
34
  }
35
35
 
36
36
  export interface CreateBetterAuthOptions {
@@ -39,6 +39,103 @@ export interface CreateBetterAuthOptions {
39
39
  userModel?: UserModel;
40
40
  }
41
41
 
42
+ const FALLBACK_AUTH_MAIL = {
43
+ resetPassword: {
44
+ html: '<p><a href="{{resetUrl}}">Reset your password</a></p>',
45
+ subject: "Reset your password",
46
+ text: "Reset your password using this link: {{resetUrl}}",
47
+ },
48
+ verifyEmail: {
49
+ html: '<p><a href="{{verifyUrl}}">Verify your email</a></p>',
50
+ subject: "Verify your email",
51
+ text: "Verify your email using this link: {{verifyUrl}}",
52
+ },
53
+ } as const;
54
+
55
+ const interpolateMail = (value: string, data: Record<string, string>): string =>
56
+ value.replace(/{{\s*([A-Za-z0-9_]+)\s*}}/g, (_match: string, key: string): string => {
57
+ return data[key] ?? "";
58
+ });
59
+
60
+ const fallbackRenderAuthMail = ({
61
+ publicAppUrl,
62
+ templateId,
63
+ token,
64
+ templates,
65
+ }: {
66
+ publicAppUrl: string;
67
+ templateId: "resetPassword" | "verifyEmail";
68
+ token: string;
69
+ templates?: BetterAuthConfig["authMailTemplates"];
70
+ }): {html?: string; subject: string; text?: string} => {
71
+ const template = templates?.[templateId] ?? FALLBACK_AUTH_MAIL[templateId];
72
+ const base = publicAppUrl.replace(/\/$/, "");
73
+ const resetUrl = `${base}/resetPassword?token=${encodeURIComponent(token)}`;
74
+ const verifyUrl = `${base}/verifyEmail?token=${encodeURIComponent(token)}`;
75
+ const data = {publicAppUrl: base, resetUrl, token, verifyUrl};
76
+ return {
77
+ html: template.html === undefined ? undefined : interpolateMail(template.html, data),
78
+ subject: interpolateMail(template.subject, data),
79
+ text: template.text === undefined ? undefined : interpolateMail(template.text, data),
80
+ };
81
+ };
82
+
83
+ export const createBetterAuthEmailHooks = (config: BetterAuthConfig) => {
84
+ if (!config.sendMail) {
85
+ return undefined;
86
+ }
87
+ const sendMail = config.sendMail;
88
+ const deliver = async (
89
+ templateId: "resetPassword" | "verifyEmail",
90
+ user: {email: string},
91
+ token: string
92
+ ): Promise<void> => {
93
+ const publicAppUrl = config.publicAppUrl ?? "";
94
+ if (!publicAppUrl) {
95
+ logger.error("[auth] publicAppUrl is required to send Better Auth recovery mail");
96
+ throw new APIError({
97
+ status: 501,
98
+ title: "publicAppUrl is required to send recovery mail",
99
+ });
100
+ }
101
+ const rendered = (config.renderAuthMail ?? fallbackRenderAuthMail)({
102
+ publicAppUrl,
103
+ templateId,
104
+ templates: config.authMailTemplates,
105
+ token,
106
+ });
107
+ const message: AuthRecoveryMail = {
108
+ html: rendered.html,
109
+ subject: rendered.subject,
110
+ text: rendered.text ?? "",
111
+ to: user.email,
112
+ };
113
+ await sendMail(message);
114
+ };
115
+ return {
116
+ sendResetPassword: async ({
117
+ token,
118
+ user,
119
+ }: {
120
+ token: string;
121
+ url: string;
122
+ user: {email: string};
123
+ }): Promise<void> => {
124
+ await deliver("resetPassword", user, token);
125
+ },
126
+ sendVerificationEmail: async ({
127
+ token,
128
+ user,
129
+ }: {
130
+ token: string;
131
+ url: string;
132
+ user: {email: string};
133
+ }): Promise<void> => {
134
+ await deliver("verifyEmail", user, token);
135
+ },
136
+ };
137
+ };
138
+
42
139
  /**
43
140
  * Creates a Better Auth instance with MongoDB adapter.
44
141
  */
@@ -86,6 +183,9 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
86
183
  };
87
184
  }
88
185
 
186
+ const emailHooks = createBetterAuthEmailHooks(config);
187
+ const userModel = options.userModel;
188
+
89
189
  const auth = betterAuth({
90
190
  advanced: config.crossDomainCookies
91
191
  ? {
@@ -101,7 +201,27 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
101
201
  database: mongodbAdapter(mongoClient.db()),
102
202
  emailAndPassword: {
103
203
  enabled: true,
204
+ revokeSessionsOnPasswordReset: true,
205
+ ...(emailHooks ? {sendResetPassword: emailHooks.sendResetPassword} : {}),
206
+ ...(userModel
207
+ ? {
208
+ onPasswordReset: async (
209
+ {user}: {user: {email?: string; id?: string}},
210
+ request?: PasswordResetRequestLike
211
+ ): Promise<void> => {
212
+ await applyBetterAuthPasswordResetToJwt(userModel, user, request);
213
+ },
214
+ }
215
+ : {}),
104
216
  },
217
+ ...(emailHooks
218
+ ? {
219
+ emailVerification: {
220
+ sendOnSignUp: true,
221
+ sendVerificationEmail: emailHooks.sendVerificationEmail,
222
+ },
223
+ }
224
+ : {}),
105
225
  // The bearer plugin lets clients authenticate with `Authorization: Bearer <sessionToken>`
106
226
  // instead of the signed session cookie. Required for cross-origin/native clients and for
107
227
  // websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
@@ -125,6 +245,141 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
125
245
  return auth as unknown as BetterAuthInstance;
126
246
  };
127
247
 
248
+ interface BetterAuthCredentialAccount {
249
+ providerId?: string;
250
+ }
251
+
252
+ interface BetterAuthUserLookup {
253
+ user?: {id?: string};
254
+ }
255
+
256
+ interface BetterAuthPasswordResetContext {
257
+ internalAdapter: {
258
+ createAccount: (account: {
259
+ accountId: string;
260
+ password: string;
261
+ providerId: string;
262
+ userId: string;
263
+ }) => Promise<unknown>;
264
+ deleteUserSessions: (userId: string) => Promise<unknown>;
265
+ findAccounts: (userId: string) => Promise<BetterAuthCredentialAccount[]>;
266
+ findUserByEmail: (email: string) => Promise<BetterAuthUserLookup | null>;
267
+ findUserById: (userId: string) => Promise<{id?: string} | null>;
268
+ updatePassword: (userId: string, password: string) => Promise<unknown>;
269
+ };
270
+ password: {hash: (password: string) => Promise<string>};
271
+ }
272
+
273
+ /**
274
+ * After JWT `POST /auth/resetPassword`, update the Better Auth credential hash
275
+ * (when that user exists) and delete Better Auth sessions so a dual-enrolled
276
+ * account cannot keep the old password or stolen sessions.
277
+ */
278
+ export const applyJwtPasswordResetToBetterAuth = async (
279
+ auth: BetterAuthInstance,
280
+ user: {betterAuthId?: string; email?: string},
281
+ password: string
282
+ ): Promise<void> => {
283
+ const ctx = (await auth.$context) as BetterAuthPasswordResetContext;
284
+ let betterAuthUserId = typeof user.betterAuthId === "string" ? user.betterAuthId : "";
285
+ if (!betterAuthUserId && typeof user.email === "string" && user.email.length > 0) {
286
+ const found = await ctx.internalAdapter.findUserByEmail(user.email);
287
+ betterAuthUserId = found?.user?.id ?? "";
288
+ }
289
+ if (!betterAuthUserId) {
290
+ const byId = user.betterAuthId
291
+ ? await ctx.internalAdapter.findUserById(user.betterAuthId)
292
+ : null;
293
+ betterAuthUserId = byId?.id ?? "";
294
+ }
295
+ if (!betterAuthUserId) {
296
+ return;
297
+ }
298
+ const hashedPassword = await ctx.password.hash(password);
299
+ const accounts = await ctx.internalAdapter.findAccounts(betterAuthUserId);
300
+ const hasCredential = accounts.some((account) => account.providerId === "credential");
301
+ if (hasCredential) {
302
+ await ctx.internalAdapter.updatePassword(betterAuthUserId, hashedPassword);
303
+ } else {
304
+ await ctx.internalAdapter.createAccount({
305
+ accountId: betterAuthUserId,
306
+ password: hashedPassword,
307
+ providerId: "credential",
308
+ userId: betterAuthUserId,
309
+ });
310
+ }
311
+ await ctx.internalAdapter.deleteUserSessions(betterAuthUserId);
312
+ };
313
+
314
+ interface PasswordResetRequestLike {
315
+ body?: unknown;
316
+ clone?: () => {json: () => Promise<unknown>};
317
+ }
318
+
319
+ const passwordFromUnknown = (value: unknown): string => {
320
+ if (!value || typeof value !== "object") {
321
+ return "";
322
+ }
323
+ const record = value as Record<string, unknown>;
324
+ const candidate = record.newPassword ?? record.password;
325
+ if (typeof candidate !== "string") {
326
+ return "";
327
+ }
328
+ return candidate;
329
+ };
330
+
331
+ export const readPasswordFromBetterAuthResetRequest = async (
332
+ request: PasswordResetRequestLike | undefined
333
+ ): Promise<string> => {
334
+ if (!request) {
335
+ return "";
336
+ }
337
+ const attached = passwordFromUnknown(request.body);
338
+ if (attached.length > 0) {
339
+ return attached;
340
+ }
341
+ if (typeof request.clone !== "function") {
342
+ return "";
343
+ }
344
+ try {
345
+ return passwordFromUnknown(await request.clone().json());
346
+ } catch {
347
+ return "";
348
+ }
349
+ };
350
+
351
+ /**
352
+ * After Better Auth password reset, update the JWT/passport hash and bump
353
+ * `tokenEpoch` so a dual-enrolled account cannot keep the old password or
354
+ * outstanding refresh tokens.
355
+ */
356
+ export const applyBetterAuthPasswordResetToJwt = async (
357
+ userModel: UserModel,
358
+ betterAuthUser: {email?: string; id?: string},
359
+ request: PasswordResetRequestLike | undefined
360
+ ): Promise<void> => {
361
+ const betterAuthId = typeof betterAuthUser.id === "string" ? betterAuthUser.id : "";
362
+ const email = typeof betterAuthUser.email === "string" ? betterAuthUser.email : "";
363
+ let appUser = betterAuthId ? await findOneOrNoneFor(userModel, {betterAuthId} as never) : null;
364
+ if (!appUser && email.length > 0) {
365
+ appUser = await findOneOrNoneFor(userModel, {email} as never);
366
+ }
367
+ if (!appUser) {
368
+ return;
369
+ }
370
+ const password = await readPasswordFromBetterAuthResetRequest(request);
371
+ if (!password) {
372
+ logger.error("[auth] Better Auth password reset did not include a password to sync to JWT");
373
+ throw new APIError({
374
+ status: 500,
375
+ title: "Password reset could not sync to JWT credentials",
376
+ });
377
+ }
378
+ await setPasswordForUser(appUser as unknown as HasSetPassword, password);
379
+ appUser.tokenEpoch = (appUser.tokenEpoch ?? 0) + 1;
380
+ await appUser.save();
381
+ };
382
+
128
383
  /**
129
384
  * Creates Express middleware that extracts the Better Auth session
130
385
  * and populates req.user with the application User model.
@@ -246,7 +501,7 @@ export const syncBetterAuthUser = async (
246
501
  betterAuthId: betterAuthUser.id,
247
502
  email: betterAuthUser.email,
248
503
  name: betterAuthUser.name || betterAuthUser.email.split("@")[0],
249
- oauthProvider: oauthProvider || null,
504
+ ...(oauthProvider ? {oauthProvider} : {}),
250
505
  });
251
506
  await newUser.save();
252
507
  logger.info(`Created new user from Better Auth: ${newUser.id}`);
@@ -0,0 +1,165 @@
1
+ import {beforeEach, describe, expect, it} from "bun:test";
2
+ import {model, Schema} from "mongoose";
3
+ import {
4
+ clearCollectionRegistry,
5
+ getCollection,
6
+ listCollections,
7
+ registerCollection,
8
+ replaceCollectionOptions,
9
+ } from "./collectionRegistry";
10
+ import {clearMCPRegistry, getMCPRegistry} from "./mcp/registry";
11
+ import {Permissions} from "./permissions";
12
+ import {createdUpdatedPlugin, type IsDeleted, isDeletedPlugin} from "./plugins";
13
+ import {trackSyncIndexCreation} from "./sync/registrationSideEffects";
14
+ import {clearSyncRegistry, getSyncRegistry, registerSync} from "./sync/registry";
15
+ import {syncPlugin} from "./sync/syncSeqPlugin";
16
+ import {FoodModel} from "./tests";
17
+
18
+ interface CatalogTodo extends IsDeleted {
19
+ _id: string;
20
+ ownerId: string;
21
+ title: string;
22
+ _syncSeq?: number;
23
+ }
24
+
25
+ const catalogTodoSchema = new Schema<CatalogTodo>({
26
+ ownerId: {description: "The owner", type: String},
27
+ title: {description: "The title", required: true, type: String},
28
+ });
29
+ catalogTodoSchema.plugin(isDeletedPlugin);
30
+ catalogTodoSchema.plugin(createdUpdatedPlugin);
31
+ catalogTodoSchema.plugin(syncPlugin);
32
+ const CatalogTodoModel = model<CatalogTodo>("CatalogTodo", catalogTodoSchema);
33
+
34
+ const syncOptions = {
35
+ permissions: {
36
+ create: [Permissions.IsAuthenticated],
37
+ delete: [Permissions.IsAuthenticated],
38
+ list: [Permissions.IsAuthenticated],
39
+ read: [Permissions.IsAuthenticated],
40
+ update: [Permissions.IsAuthenticated],
41
+ },
42
+ sync: {scope: {type: "owner"}},
43
+ } as const;
44
+
45
+ const baseOptions = {
46
+ permissions: {
47
+ create: [Permissions.IsAny],
48
+ delete: [Permissions.IsAny],
49
+ list: [Permissions.IsAny],
50
+ read: [Permissions.IsAny],
51
+ update: [Permissions.IsAny],
52
+ },
53
+ };
54
+
55
+ describe("CollectionRegistry", () => {
56
+ beforeEach(() => {
57
+ clearCollectionRegistry();
58
+ });
59
+
60
+ it("stores one catalog record per route path on registerCollection", () => {
61
+ registerCollection({
62
+ model: FoodModel,
63
+ options: baseOptions,
64
+ routePath: "/food",
65
+ });
66
+
67
+ const record = getCollection("/food");
68
+ expect(record?.routePath).toBe("/food");
69
+ expect(record?.model).toBe(FoodModel);
70
+ expect(record?.options).toBe(baseOptions);
71
+ expect(listCollections()).toHaveLength(1);
72
+ });
73
+
74
+ it("replaceCollectionOptions updates options for a registered path", () => {
75
+ registerCollection({
76
+ model: FoodModel,
77
+ options: baseOptions,
78
+ routePath: "/food",
79
+ });
80
+ const updatedOptions = {
81
+ ...baseOptions,
82
+ permissions: {...baseOptions.permissions, list: [Permissions.IsAuthenticated]},
83
+ };
84
+ replaceCollectionOptions("/food", updatedOptions);
85
+
86
+ expect(getCollection("/food")?.options).toBe(updatedOptions);
87
+ });
88
+
89
+ it("replaceCollectionOptions no-ops when the route path is unknown", () => {
90
+ registerCollection({
91
+ model: FoodModel,
92
+ options: baseOptions,
93
+ routePath: "/food",
94
+ });
95
+ const originalOptions = getCollection("/food")?.options;
96
+ replaceCollectionOptions("/missing", {
97
+ permissions: {},
98
+ } as never);
99
+
100
+ expect(getCollection("/food")?.options).toBe(originalOptions);
101
+ });
102
+
103
+ it("replaceCollectionOptions updates MCP registry views with the same options object", () => {
104
+ clearMCPRegistry();
105
+ registerCollection({
106
+ model: FoodModel,
107
+ options: {...baseOptions, mcp: {methods: ["list"]}},
108
+ routePath: "/food",
109
+ });
110
+ const updatedOptions = {
111
+ ...baseOptions,
112
+ mcp: {methods: ["read"]},
113
+ } as typeof baseOptions & {mcp: {methods: ["read"]}};
114
+ replaceCollectionOptions("/food", updatedOptions);
115
+
116
+ expect(getCollection("/food")?.options).toBe(updatedOptions);
117
+ expect(getMCPRegistry()[0]?.options).toBe(updatedOptions);
118
+ });
119
+
120
+ it("replaceCollectionOptions updates sync registry views with the same options object", () => {
121
+ clearSyncRegistry();
122
+ registerSync({
123
+ config: {scope: {type: "owner"}},
124
+ model: CatalogTodoModel,
125
+ options: syncOptions,
126
+ routePath: "/catalogTodos",
127
+ });
128
+ const updatedOptions = {
129
+ ...syncOptions,
130
+ permissions: {...syncOptions.permissions, list: [Permissions.IsAny]},
131
+ };
132
+ replaceCollectionOptions("/catalogTodos", updatedOptions);
133
+
134
+ expect(getCollection("/catalogTodos")?.options).toBe(updatedOptions);
135
+ expect(getSyncRegistry()[0]?.options).toBe(updatedOptions);
136
+ });
137
+
138
+ it("rejects re-registering sync at the same route path", () => {
139
+ clearSyncRegistry();
140
+ registerSync({
141
+ config: {scope: {type: "owner"}},
142
+ model: CatalogTodoModel,
143
+ options: syncOptions,
144
+ routePath: "/catalogTodos",
145
+ });
146
+ expect(() =>
147
+ registerSync({
148
+ config: {scope: {type: "owner"}},
149
+ model: CatalogTodoModel,
150
+ options: syncOptions,
151
+ routePath: "/catalogTodos",
152
+ })
153
+ ).toThrow(/already registered/);
154
+ });
155
+
156
+ it("clearCollectionRegistry resets deferred sync index tasks", async () => {
157
+ clearCollectionRegistry();
158
+ trackSyncIndexCreation(async () => {
159
+ throw new Error("should not run");
160
+ });
161
+ clearCollectionRegistry();
162
+ const {ensureSyncIndexes} = await import("./sync/registrationSideEffects");
163
+ await expect(ensureSyncIndexes()).resolves.toBeUndefined();
164
+ });
165
+ });
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Process-global catalog of modelRouter collections, keyed by routePath
3
+ * (e.g. `/todos`). MCP, realtime, and Sync read this Map instead of each
4
+ * keeping their own list. `modelRouter` is the writer; surface `register*`
5
+ * / `update*` / `clear*` helpers are wrappers around this module.
6
+ *
7
+ * TerrenoApp later injects `accessControl` into options. That patch goes
8
+ * through replaceCollectionOptions so all three surfaces see one options
9
+ * object. Surface flags stay sticky (OR) so a later replace cannot drop
10
+ * mcp/realtime/sync once enabled. First-time sync enable still runs schema
11
+ * and index guards in registrationSideEffects — not here — so catalog
12
+ * writes stay a Map update.
13
+ */
14
+ import type {Model} from "mongoose";
15
+
16
+ import type {ModelRouterOptions} from "./api";
17
+ import {APIError} from "./errors";
18
+ import {
19
+ applySyncRegistrationSideEffects,
20
+ clearSyncIndexCreationTasks,
21
+ } from "./sync/registrationSideEffects";
22
+
23
+ export interface CollectionSurfaces {
24
+ mcp: boolean;
25
+ realtime: boolean;
26
+ sync: boolean;
27
+ }
28
+
29
+ export interface CollectionRecord {
30
+ model: Model<unknown>;
31
+ options: ModelRouterOptions<unknown>;
32
+ routePath: string;
33
+ surfaces: CollectionSurfaces;
34
+ }
35
+
36
+ const collectionRegistry = new Map<string, CollectionRecord>();
37
+
38
+ /** OR new option flags onto existing ones so a patch cannot disable a surface. */
39
+ const deriveSurfaces = (
40
+ options: ModelRouterOptions<unknown>,
41
+ existing?: CollectionSurfaces
42
+ ): CollectionSurfaces => ({
43
+ mcp: Boolean(options.mcp) || (existing?.mcp ?? false),
44
+ realtime: Boolean(options.realtime) || (existing?.realtime ?? false),
45
+ sync: Boolean(options.sync) || (existing?.sync ?? false),
46
+ });
47
+
48
+ /** Insert or merge a collection. First sync enable runs schema/index guards. */
49
+ export const registerCollection = <T>({
50
+ model,
51
+ options,
52
+ routePath,
53
+ }: {
54
+ model: Model<T>;
55
+ options: ModelRouterOptions<T>;
56
+ routePath: string;
57
+ }): void => {
58
+ const existing = collectionRegistry.get(routePath);
59
+ const wasSyncEnabled = existing?.surfaces.sync ?? false;
60
+
61
+ if (options.sync && wasSyncEnabled) {
62
+ const collectionTag = routePath.replace(/^\//, "");
63
+ throw new APIError({
64
+ status: 500,
65
+ title:
66
+ `Sync collection tag "${collectionTag}" is already registered (routePath ${routePath}). ` +
67
+ "Each synced model must have a unique route path.",
68
+ });
69
+ }
70
+
71
+ if (options.sync && !wasSyncEnabled) {
72
+ applySyncRegistrationSideEffects({
73
+ config: options.sync,
74
+ existingSyncEntries: listCollections()
75
+ .filter((record) => record.surfaces.sync)
76
+ .map((record) => ({
77
+ collectionTag: record.routePath.replace(/^\//, ""),
78
+ modelName: record.model.modelName,
79
+ })),
80
+ model,
81
+ options,
82
+ routePath,
83
+ });
84
+ }
85
+
86
+ collectionRegistry.set(routePath, {
87
+ model: model as unknown as Model<unknown>,
88
+ options: options as ModelRouterOptions<unknown>,
89
+ routePath,
90
+ surfaces: deriveSurfaces(options as ModelRouterOptions<unknown>, existing?.surfaces),
91
+ });
92
+ };
93
+
94
+ /** Swap the options pointer after TerrenoApp enriches it. Unknown path is a no-op. */
95
+ export const replaceCollectionOptions = (
96
+ routePath: string,
97
+ options: ModelRouterOptions<unknown>
98
+ ): void => {
99
+ const existing = collectionRegistry.get(routePath);
100
+ if (!existing) {
101
+ return;
102
+ }
103
+ existing.options = options;
104
+ };
105
+
106
+ export const getCollection = (routePath: string): CollectionRecord | undefined =>
107
+ collectionRegistry.get(routePath);
108
+
109
+ export const listCollections = (): CollectionRecord[] => Array.from(collectionRegistry.values());
110
+
111
+ /** Wipe the catalog and queued sync indexes so tests cannot leave a stale surface. */
112
+ export const clearCollectionRegistry = (): void => {
113
+ collectionRegistry.clear();
114
+ clearSyncIndexCreationTasks();
115
+ };
@@ -127,14 +127,22 @@ export type ConfigurationPostUpdateHook = (
127
127
  req: express.Request
128
128
  ) => void | Promise<void>;
129
129
 
130
+ /**
131
+ * The subset of a Mongoose model that ConfigurationApp inspects. Structural (rather than
132
+ * `Model<T>`) so consumers can pass any configuration model without generic invariance
133
+ * issues; the configurationPlugin statics are looked up at registration time.
134
+ */
135
+ export interface ConfigurationModelLike {
136
+ modelName: string;
137
+ schema: Schema;
138
+ }
139
+
130
140
  /**
131
141
  * Options for ConfigurationApp.
132
142
  */
133
143
  export interface ConfigurationAppOptions {
134
144
  /** The Mongoose model with configurationPlugin applied. */
135
- // noExplicitAny: Model<any> required for invariance — consumers pass arbitrary configuration models
136
- // biome-ignore lint/suspicious/noExplicitAny: Model<any> required for invariance — consumers pass arbitrary configuration models
137
- model: Model<any>;
145
+ model: ConfigurationModelLike;
138
146
  /** Base path for configuration routes. Defaults to "/configuration". */
139
147
  basePath?: string;
140
148
  /** Per-field widget overrides (e.g., {"ai.systemPrompt": "markdown"}). */
@@ -357,7 +365,7 @@ export class ConfigurationApp implements TerrenoPlugin {
357
365
  const schema = ConfigModel.schema;
358
366
 
359
367
  // Build metadata by inspecting the schema
360
- const meta = this.buildMetadata(ConfigModel, schema);
368
+ const meta = this.buildMetadata(schema);
361
369
 
362
370
  // GET /configuration/meta — schema metadata for the frontend
363
371
  app.get(
@@ -479,9 +487,7 @@ export class ConfigurationApp implements TerrenoPlugin {
479
487
  * Top-level fields with subschemas become sections.
480
488
  * Top-level scalar fields go into a "General" section.
481
489
  */
482
- // noExplicitAny: Model<any> required for invariance with consumer-supplied configuration models
483
- // biome-ignore lint/suspicious/noExplicitAny: Model<any> required for invariance with consumer-supplied configuration models
484
- private buildMetadata(_model: Model<any>, schema: Schema): ConfigurationMetaResponse {
490
+ private buildMetadata(schema: Schema): ConfigurationMetaResponse {
485
491
  const sections: ConfigSectionMeta[] = [];
486
492
  const generalFields: Record<string, ConfigFieldMeta> = {};
487
493
 
@@ -1,5 +1,5 @@
1
1
  import {describe, expect, it, mock} from "bun:test";
2
- import type {Model} from "mongoose";
2
+ import mongoose, {type Model} from "mongoose";
3
3
  import {loadDocOr404} from "./docLoader";
4
4
  import {APIError} from "./errors";
5
5
 
@@ -38,6 +38,50 @@ describe("loadDocOr404", () => {
38
38
  await expect(loadDocOr404(model, "507f1f77bcf86cd799439011")).rejects.toBe(original);
39
39
  });
40
40
 
41
+ it("maps CastError on a populate path to a GET error, not 404", async () => {
42
+ const model = {
43
+ collection: {findOne: mock(async () => null)},
44
+ findById: mock(() => ({
45
+ exec: mock(async () => {
46
+ throw new mongoose.Error.CastError("ObjectId", "not-an-object-id", "ownerId");
47
+ }),
48
+ })),
49
+ modelName: "MockModel",
50
+ } as unknown as Model<unknown>;
51
+
52
+ try {
53
+ await loadDocOr404(model, "507f1f77bcf86cd799439011");
54
+ expect.unreachable("expected loadDocOr404 to throw");
55
+ } catch (error) {
56
+ expect(error).toBeInstanceOf(APIError);
57
+ const apiError = error as APIError;
58
+ expect(apiError.status).toBe(500);
59
+ expect(apiError.title).toBe("GET error");
60
+ }
61
+ });
62
+
63
+ it("maps CastError from findById to a 404", async () => {
64
+ const model = {
65
+ collection: {findOne: mock(async () => null)},
66
+ findById: mock(() => ({
67
+ exec: mock(async () => {
68
+ throw new mongoose.Error.CastError("ObjectId", "not-an-object-id", "_id");
69
+ }),
70
+ })),
71
+ modelName: "MockModel",
72
+ } as unknown as Model<unknown>;
73
+
74
+ try {
75
+ await loadDocOr404(model, "not-an-object-id");
76
+ expect.unreachable("expected loadDocOr404 to throw");
77
+ } catch (error) {
78
+ expect(error).toBeInstanceOf(APIError);
79
+ const apiError = error as APIError;
80
+ expect(apiError.status).toBe(404);
81
+ expect(apiError.title).toBe("Document not found");
82
+ }
83
+ });
84
+
41
85
  it("returns plain not found when document does not exist", async () => {
42
86
  const model = {
43
87
  collection: {findOne: mock(async () => null)},