@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
@@ -6,7 +6,8 @@
6
6
  */
7
7
  import { betterAuth } from "better-auth";
8
8
  import type { Application, NextFunction, Request, Response } from "express";
9
- import type { UserModel } from "./auth";
9
+ import type { Db } from "mongodb";
10
+ import { type UserModel } from "./auth";
10
11
  import type { BetterAuthConfig, BetterAuthSessionData, BetterAuthUser } from "./betterAuth";
11
12
  /**
12
13
  * The Better Auth instance type.
@@ -16,17 +17,58 @@ export type BetterAuthInstance = ReturnType<typeof betterAuth>;
16
17
  * Options for creating a Better Auth instance.
17
18
  */
18
19
  export interface MongoClientLike {
19
- db: () => any;
20
+ db: () => Db;
20
21
  }
21
22
  export interface CreateBetterAuthOptions {
22
23
  config: BetterAuthConfig;
23
24
  mongoClient: MongoClientLike;
24
25
  userModel?: UserModel;
25
26
  }
27
+ export declare const createBetterAuthEmailHooks: (config: BetterAuthConfig) => {
28
+ sendResetPassword: ({ token, user, }: {
29
+ token: string;
30
+ url: string;
31
+ user: {
32
+ email: string;
33
+ };
34
+ }) => Promise<void>;
35
+ sendVerificationEmail: ({ token, user, }: {
36
+ token: string;
37
+ url: string;
38
+ user: {
39
+ email: string;
40
+ };
41
+ }) => Promise<void>;
42
+ } | undefined;
26
43
  /**
27
44
  * Creates a Better Auth instance with MongoDB adapter.
28
45
  */
29
46
  export declare const createBetterAuth: (options: CreateBetterAuthOptions) => BetterAuthInstance;
47
+ /**
48
+ * After JWT `POST /auth/resetPassword`, update the Better Auth credential hash
49
+ * (when that user exists) and delete Better Auth sessions so a dual-enrolled
50
+ * account cannot keep the old password or stolen sessions.
51
+ */
52
+ export declare const applyJwtPasswordResetToBetterAuth: (auth: BetterAuthInstance, user: {
53
+ betterAuthId?: string;
54
+ email?: string;
55
+ }, password: string) => Promise<void>;
56
+ interface PasswordResetRequestLike {
57
+ body?: unknown;
58
+ clone?: () => {
59
+ json: () => Promise<unknown>;
60
+ };
61
+ }
62
+ export declare const readPasswordFromBetterAuthResetRequest: (request: PasswordResetRequestLike | undefined) => Promise<string>;
63
+ /**
64
+ * After Better Auth password reset, update the JWT/passport hash and bump
65
+ * `tokenEpoch` so a dual-enrolled account cannot keep the old password or
66
+ * outstanding refresh tokens.
67
+ */
68
+ export declare const applyBetterAuthPasswordResetToJwt: (userModel: UserModel, betterAuthUser: {
69
+ email?: string;
70
+ id?: string;
71
+ }, request: PasswordResetRequestLike | undefined) => Promise<void>;
30
72
  /**
31
73
  * Creates Express middleware that extracts the Better Auth session
32
74
  * and populates req.user with the application User model.
@@ -56,16 +56,113 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
56
56
  return (mod && mod.__esModule) ? mod : { "default": mod };
57
57
  };
58
58
  Object.defineProperty(exports, "__esModule", { value: true });
59
- exports.hasBetterAuthSession = exports.getBetterAuthSession = exports.setupBetterAuthUserSync = exports.getMongoClientFromMongoose = exports.mountBetterAuthRoutes = exports.syncBetterAuthUser = exports.createBetterAuthSessionMiddleware = exports.createBetterAuth = void 0;
59
+ exports.hasBetterAuthSession = exports.getBetterAuthSession = exports.setupBetterAuthUserSync = exports.getMongoClientFromMongoose = exports.mountBetterAuthRoutes = exports.syncBetterAuthUser = exports.createBetterAuthSessionMiddleware = exports.applyBetterAuthPasswordResetToJwt = exports.readPasswordFromBetterAuthResetRequest = exports.applyJwtPasswordResetToBetterAuth = exports.createBetterAuth = exports.createBetterAuthEmailHooks = void 0;
60
60
  var better_auth_1 = require("better-auth");
61
61
  var mongodb_1 = require("better-auth/adapters/mongodb");
62
62
  var node_1 = require("better-auth/node");
63
63
  var plugins_1 = require("better-auth/plugins");
64
64
  var mongoose_1 = __importDefault(require("mongoose"));
65
+ var auth_1 = require("./auth");
65
66
  var errors_1 = require("./errors");
66
67
  var logger_1 = require("./logger");
67
68
  var plugins_2 = require("./plugins");
68
69
  var requestContext_1 = require("./requestContext");
70
+ var FALLBACK_AUTH_MAIL = {
71
+ resetPassword: {
72
+ html: '<p><a href="{{resetUrl}}">Reset your password</a></p>',
73
+ subject: "Reset your password",
74
+ text: "Reset your password using this link: {{resetUrl}}",
75
+ },
76
+ verifyEmail: {
77
+ html: '<p><a href="{{verifyUrl}}">Verify your email</a></p>',
78
+ subject: "Verify your email",
79
+ text: "Verify your email using this link: {{verifyUrl}}",
80
+ },
81
+ };
82
+ var interpolateMail = function (value, data) {
83
+ return value.replace(/{{\s*([A-Za-z0-9_]+)\s*}}/g, function (_match, key) {
84
+ var _a;
85
+ return (_a = data[key]) !== null && _a !== void 0 ? _a : "";
86
+ });
87
+ };
88
+ var fallbackRenderAuthMail = function (_a) {
89
+ var _b;
90
+ var publicAppUrl = _a.publicAppUrl, templateId = _a.templateId, token = _a.token, templates = _a.templates;
91
+ var template = (_b = templates === null || templates === void 0 ? void 0 : templates[templateId]) !== null && _b !== void 0 ? _b : FALLBACK_AUTH_MAIL[templateId];
92
+ var base = publicAppUrl.replace(/\/$/, "");
93
+ var resetUrl = "".concat(base, "/resetPassword?token=").concat(encodeURIComponent(token));
94
+ var verifyUrl = "".concat(base, "/verifyEmail?token=").concat(encodeURIComponent(token));
95
+ var data = { publicAppUrl: base, resetUrl: resetUrl, token: token, verifyUrl: verifyUrl };
96
+ return {
97
+ html: template.html === undefined ? undefined : interpolateMail(template.html, data),
98
+ subject: interpolateMail(template.subject, data),
99
+ text: template.text === undefined ? undefined : interpolateMail(template.text, data),
100
+ };
101
+ };
102
+ var createBetterAuthEmailHooks = function (config) {
103
+ if (!config.sendMail) {
104
+ return undefined;
105
+ }
106
+ var sendMail = config.sendMail;
107
+ var deliver = function (templateId, user, token) { return __awaiter(void 0, void 0, void 0, function () {
108
+ var publicAppUrl, rendered, message;
109
+ var _a, _b, _c;
110
+ return __generator(this, function (_d) {
111
+ switch (_d.label) {
112
+ case 0:
113
+ publicAppUrl = (_a = config.publicAppUrl) !== null && _a !== void 0 ? _a : "";
114
+ if (!publicAppUrl) {
115
+ logger_1.logger.error("[auth] publicAppUrl is required to send Better Auth recovery mail");
116
+ throw new errors_1.APIError({
117
+ status: 501,
118
+ title: "publicAppUrl is required to send recovery mail",
119
+ });
120
+ }
121
+ rendered = ((_b = config.renderAuthMail) !== null && _b !== void 0 ? _b : fallbackRenderAuthMail)({
122
+ publicAppUrl: publicAppUrl,
123
+ templateId: templateId,
124
+ templates: config.authMailTemplates,
125
+ token: token,
126
+ });
127
+ message = {
128
+ html: rendered.html,
129
+ subject: rendered.subject,
130
+ text: (_c = rendered.text) !== null && _c !== void 0 ? _c : "",
131
+ to: user.email,
132
+ };
133
+ return [4 /*yield*/, sendMail(message)];
134
+ case 1:
135
+ _d.sent();
136
+ return [2 /*return*/];
137
+ }
138
+ });
139
+ }); };
140
+ return {
141
+ sendResetPassword: function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
142
+ var token = _b.token, user = _b.user;
143
+ return __generator(this, function (_c) {
144
+ switch (_c.label) {
145
+ case 0: return [4 /*yield*/, deliver("resetPassword", user, token)];
146
+ case 1:
147
+ _c.sent();
148
+ return [2 /*return*/];
149
+ }
150
+ });
151
+ }); },
152
+ sendVerificationEmail: function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
153
+ var token = _b.token, user = _b.user;
154
+ return __generator(this, function (_c) {
155
+ switch (_c.label) {
156
+ case 0: return [4 /*yield*/, deliver("verifyEmail", user, token)];
157
+ case 1:
158
+ _c.sent();
159
+ return [2 /*return*/];
160
+ }
161
+ });
162
+ }); },
163
+ };
164
+ };
165
+ exports.createBetterAuthEmailHooks = createBetterAuthEmailHooks;
69
166
  /**
70
167
  * Creates a Better Auth instance with MongoDB adapter.
71
168
  */
@@ -106,8 +203,9 @@ var createBetterAuth = function (options) {
106
203
  clientSecret: config.githubOAuth.clientSecret,
107
204
  };
108
205
  }
109
- var auth = (0, better_auth_1.betterAuth)({
110
- advanced: config.crossDomainCookies
206
+ var emailHooks = (0, exports.createBetterAuthEmailHooks)(config);
207
+ var userModel = options.userModel;
208
+ var auth = (0, better_auth_1.betterAuth)(__assign(__assign({ advanced: config.crossDomainCookies
111
209
  ? {
112
210
  defaultCookieAttributes: {
113
211
  httpOnly: true,
@@ -115,35 +213,207 @@ var createBetterAuth = function (options) {
115
213
  secure: true,
116
214
  },
117
215
  }
118
- : undefined,
119
- basePath: basePath,
120
- baseURL: baseURL,
121
- database: (0, mongodb_1.mongodbAdapter)(mongoClient.db()),
122
- emailAndPassword: {
123
- enabled: true,
124
- },
216
+ : undefined, basePath: basePath, baseURL: baseURL, database: (0, mongodb_1.mongodbAdapter)(mongoClient.db()), emailAndPassword: __assign(__assign({ enabled: true, revokeSessionsOnPasswordReset: true }, (emailHooks ? { sendResetPassword: emailHooks.sendResetPassword } : {})), (userModel
217
+ ? {
218
+ onPasswordReset: function (_a, request_1) { return __awaiter(void 0, [_a, request_1], void 0, function (_b, request) {
219
+ var user = _b.user;
220
+ return __generator(this, function (_c) {
221
+ switch (_c.label) {
222
+ case 0: return [4 /*yield*/, (0, exports.applyBetterAuthPasswordResetToJwt)(userModel, user, request)];
223
+ case 1:
224
+ _c.sent();
225
+ return [2 /*return*/];
226
+ }
227
+ });
228
+ }); },
229
+ }
230
+ : {})) }, (emailHooks
231
+ ? {
232
+ emailVerification: {
233
+ sendOnSignUp: true,
234
+ sendVerificationEmail: emailHooks.sendVerificationEmail,
235
+ },
236
+ }
237
+ : {})), {
125
238
  // The bearer plugin lets clients authenticate with `Authorization: Bearer <sessionToken>`
126
239
  // instead of the signed session cookie. Required for cross-origin/native clients and for
127
240
  // websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
128
241
  // token as a bearer header) — without it, a raw session token cannot be validated and
129
242
  // socket auth silently fails (the sync client shows perpetually "offline").
130
- plugins: [(0, plugins_1.bearer)()],
131
- secret: secret,
132
- session: {
243
+ plugins: [(0, plugins_1.bearer)()], secret: secret, session: {
133
244
  cookieCache: {
134
245
  enabled: true,
135
246
  maxAge: 5 * 60, // 5 minutes
136
247
  },
137
- },
138
- socialProviders: Object.keys(socialProviders).length > 0 ? socialProviders : undefined,
139
- trustedOrigins: (_b = config.trustedOrigins) !== null && _b !== void 0 ? _b : [],
140
- });
248
+ }, socialProviders: Object.keys(socialProviders).length > 0 ? socialProviders : undefined, trustedOrigins: (_b = config.trustedOrigins) !== null && _b !== void 0 ? _b : [] }));
141
249
  // Cast through unknown: enabling the bearer plugin narrows betterAuth()'s inferred
142
250
  // return type to a plugin-specific tuple that no longer matches the plugin-agnostic
143
251
  // BetterAuthInstance alias, though the runtime instance is a valid better-auth instance.
144
252
  return auth;
145
253
  };
146
254
  exports.createBetterAuth = createBetterAuth;
255
+ /**
256
+ * After JWT `POST /auth/resetPassword`, update the Better Auth credential hash
257
+ * (when that user exists) and delete Better Auth sessions so a dual-enrolled
258
+ * account cannot keep the old password or stolen sessions.
259
+ */
260
+ var applyJwtPasswordResetToBetterAuth = function (auth, user, password) { return __awaiter(void 0, void 0, void 0, function () {
261
+ var ctx, betterAuthUserId, found, byId, _a, hashedPassword, accounts, hasCredential;
262
+ var _b, _c, _d;
263
+ return __generator(this, function (_e) {
264
+ switch (_e.label) {
265
+ case 0: return [4 /*yield*/, auth.$context];
266
+ case 1:
267
+ ctx = (_e.sent());
268
+ betterAuthUserId = typeof user.betterAuthId === "string" ? user.betterAuthId : "";
269
+ if (!(!betterAuthUserId && typeof user.email === "string" && user.email.length > 0)) return [3 /*break*/, 3];
270
+ return [4 /*yield*/, ctx.internalAdapter.findUserByEmail(user.email)];
271
+ case 2:
272
+ found = _e.sent();
273
+ betterAuthUserId = (_c = (_b = found === null || found === void 0 ? void 0 : found.user) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : "";
274
+ _e.label = 3;
275
+ case 3:
276
+ if (!!betterAuthUserId) return [3 /*break*/, 7];
277
+ if (!user.betterAuthId) return [3 /*break*/, 5];
278
+ return [4 /*yield*/, ctx.internalAdapter.findUserById(user.betterAuthId)];
279
+ case 4:
280
+ _a = _e.sent();
281
+ return [3 /*break*/, 6];
282
+ case 5:
283
+ _a = null;
284
+ _e.label = 6;
285
+ case 6:
286
+ byId = _a;
287
+ betterAuthUserId = (_d = byId === null || byId === void 0 ? void 0 : byId.id) !== null && _d !== void 0 ? _d : "";
288
+ _e.label = 7;
289
+ case 7:
290
+ if (!betterAuthUserId) {
291
+ return [2 /*return*/];
292
+ }
293
+ return [4 /*yield*/, ctx.password.hash(password)];
294
+ case 8:
295
+ hashedPassword = _e.sent();
296
+ return [4 /*yield*/, ctx.internalAdapter.findAccounts(betterAuthUserId)];
297
+ case 9:
298
+ accounts = _e.sent();
299
+ hasCredential = accounts.some(function (account) { return account.providerId === "credential"; });
300
+ if (!hasCredential) return [3 /*break*/, 11];
301
+ return [4 /*yield*/, ctx.internalAdapter.updatePassword(betterAuthUserId, hashedPassword)];
302
+ case 10:
303
+ _e.sent();
304
+ return [3 /*break*/, 13];
305
+ case 11: return [4 /*yield*/, ctx.internalAdapter.createAccount({
306
+ accountId: betterAuthUserId,
307
+ password: hashedPassword,
308
+ providerId: "credential",
309
+ userId: betterAuthUserId,
310
+ })];
311
+ case 12:
312
+ _e.sent();
313
+ _e.label = 13;
314
+ case 13: return [4 /*yield*/, ctx.internalAdapter.deleteUserSessions(betterAuthUserId)];
315
+ case 14:
316
+ _e.sent();
317
+ return [2 /*return*/];
318
+ }
319
+ });
320
+ }); };
321
+ exports.applyJwtPasswordResetToBetterAuth = applyJwtPasswordResetToBetterAuth;
322
+ var passwordFromUnknown = function (value) {
323
+ var _a;
324
+ if (!value || typeof value !== "object") {
325
+ return "";
326
+ }
327
+ var record = value;
328
+ var candidate = (_a = record.newPassword) !== null && _a !== void 0 ? _a : record.password;
329
+ if (typeof candidate !== "string") {
330
+ return "";
331
+ }
332
+ return candidate;
333
+ };
334
+ var readPasswordFromBetterAuthResetRequest = function (request) { return __awaiter(void 0, void 0, void 0, function () {
335
+ var attached, _a, _b;
336
+ return __generator(this, function (_c) {
337
+ switch (_c.label) {
338
+ case 0:
339
+ if (!request) {
340
+ return [2 /*return*/, ""];
341
+ }
342
+ attached = passwordFromUnknown(request.body);
343
+ if (attached.length > 0) {
344
+ return [2 /*return*/, attached];
345
+ }
346
+ if (typeof request.clone !== "function") {
347
+ return [2 /*return*/, ""];
348
+ }
349
+ _c.label = 1;
350
+ case 1:
351
+ _c.trys.push([1, 3, , 4]);
352
+ _a = passwordFromUnknown;
353
+ return [4 /*yield*/, request.clone().json()];
354
+ case 2: return [2 /*return*/, _a.apply(void 0, [_c.sent()])];
355
+ case 3:
356
+ _b = _c.sent();
357
+ return [2 /*return*/, ""];
358
+ case 4: return [2 /*return*/];
359
+ }
360
+ });
361
+ }); };
362
+ exports.readPasswordFromBetterAuthResetRequest = readPasswordFromBetterAuthResetRequest;
363
+ /**
364
+ * After Better Auth password reset, update the JWT/passport hash and bump
365
+ * `tokenEpoch` so a dual-enrolled account cannot keep the old password or
366
+ * outstanding refresh tokens.
367
+ */
368
+ var applyBetterAuthPasswordResetToJwt = function (userModel, betterAuthUser, request) { return __awaiter(void 0, void 0, void 0, function () {
369
+ var betterAuthId, email, appUser, _a, password;
370
+ var _b;
371
+ return __generator(this, function (_c) {
372
+ switch (_c.label) {
373
+ case 0:
374
+ betterAuthId = typeof betterAuthUser.id === "string" ? betterAuthUser.id : "";
375
+ email = typeof betterAuthUser.email === "string" ? betterAuthUser.email : "";
376
+ if (!betterAuthId) return [3 /*break*/, 2];
377
+ return [4 /*yield*/, (0, plugins_2.findOneOrNoneFor)(userModel, { betterAuthId: betterAuthId })];
378
+ case 1:
379
+ _a = _c.sent();
380
+ return [3 /*break*/, 3];
381
+ case 2:
382
+ _a = null;
383
+ _c.label = 3;
384
+ case 3:
385
+ appUser = _a;
386
+ if (!(!appUser && email.length > 0)) return [3 /*break*/, 5];
387
+ return [4 /*yield*/, (0, plugins_2.findOneOrNoneFor)(userModel, { email: email })];
388
+ case 4:
389
+ appUser = _c.sent();
390
+ _c.label = 5;
391
+ case 5:
392
+ if (!appUser) {
393
+ return [2 /*return*/];
394
+ }
395
+ return [4 /*yield*/, (0, exports.readPasswordFromBetterAuthResetRequest)(request)];
396
+ case 6:
397
+ password = _c.sent();
398
+ if (!password) {
399
+ logger_1.logger.error("[auth] Better Auth password reset did not include a password to sync to JWT");
400
+ throw new errors_1.APIError({
401
+ status: 500,
402
+ title: "Password reset could not sync to JWT credentials",
403
+ });
404
+ }
405
+ return [4 /*yield*/, (0, auth_1.setPasswordForUser)(appUser, password)];
406
+ case 7:
407
+ _c.sent();
408
+ appUser.tokenEpoch = ((_b = appUser.tokenEpoch) !== null && _b !== void 0 ? _b : 0) + 1;
409
+ return [4 /*yield*/, appUser.save()];
410
+ case 8:
411
+ _c.sent();
412
+ return [2 /*return*/];
413
+ }
414
+ });
415
+ }); };
416
+ exports.applyBetterAuthPasswordResetToJwt = applyBetterAuthPasswordResetToJwt;
147
417
  /**
148
418
  * Creates Express middleware that extracts the Better Auth session
149
419
  * and populates req.user with the application User model.
@@ -248,7 +518,7 @@ var syncBetterAuthUser = function (userModel, betterAuthUser, oauthProvider) { r
248
518
  case 6:
249
519
  useAsId = mongoose_1.default.isValidObjectId(betterAuthUser.id) ? { _id: betterAuthUser.id } : {};
250
520
  UserDocumentConstructor = userModel;
251
- newUser = new UserDocumentConstructor(__assign(__assign({}, useAsId), { admin: false, betterAuthId: betterAuthUser.id, email: betterAuthUser.email, name: betterAuthUser.name || betterAuthUser.email.split("@")[0], oauthProvider: oauthProvider || null }));
521
+ newUser = new UserDocumentConstructor(__assign(__assign(__assign({}, useAsId), { admin: false, betterAuthId: betterAuthUser.id, email: betterAuthUser.email, name: betterAuthUser.name || betterAuthUser.email.split("@")[0] }), (oauthProvider ? { oauthProvider: oauthProvider } : {})));
252
522
  return [4 /*yield*/, newUser.save()];
253
523
  case 7:
254
524
  _a.sent();
@@ -0,0 +1,38 @@
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
+ import type { ModelRouterOptions } from "./api";
16
+ export interface CollectionSurfaces {
17
+ mcp: boolean;
18
+ realtime: boolean;
19
+ sync: boolean;
20
+ }
21
+ export interface CollectionRecord {
22
+ model: Model<unknown>;
23
+ options: ModelRouterOptions<unknown>;
24
+ routePath: string;
25
+ surfaces: CollectionSurfaces;
26
+ }
27
+ /** Insert or merge a collection. First sync enable runs schema/index guards. */
28
+ export declare const registerCollection: <T>({ model, options, routePath, }: {
29
+ model: Model<T>;
30
+ options: ModelRouterOptions<T>;
31
+ routePath: string;
32
+ }) => void;
33
+ /** Swap the options pointer after TerrenoApp enriches it. Unknown path is a no-op. */
34
+ export declare const replaceCollectionOptions: (routePath: string, options: ModelRouterOptions<unknown>) => void;
35
+ export declare const getCollection: (routePath: string) => CollectionRecord | undefined;
36
+ export declare const listCollections: () => CollectionRecord[];
37
+ /** Wipe the catalog and queued sync indexes so tests cannot leave a stale surface. */
38
+ export declare const clearCollectionRegistry: () => void;
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.clearCollectionRegistry = exports.listCollections = exports.getCollection = exports.replaceCollectionOptions = exports.registerCollection = void 0;
4
+ var errors_1 = require("./errors");
5
+ var registrationSideEffects_1 = require("./sync/registrationSideEffects");
6
+ var collectionRegistry = new Map();
7
+ /** OR new option flags onto existing ones so a patch cannot disable a surface. */
8
+ var deriveSurfaces = function (options, existing) {
9
+ var _a, _b, _c;
10
+ return ({
11
+ mcp: Boolean(options.mcp) || ((_a = existing === null || existing === void 0 ? void 0 : existing.mcp) !== null && _a !== void 0 ? _a : false),
12
+ realtime: Boolean(options.realtime) || ((_b = existing === null || existing === void 0 ? void 0 : existing.realtime) !== null && _b !== void 0 ? _b : false),
13
+ sync: Boolean(options.sync) || ((_c = existing === null || existing === void 0 ? void 0 : existing.sync) !== null && _c !== void 0 ? _c : false),
14
+ });
15
+ };
16
+ /** Insert or merge a collection. First sync enable runs schema/index guards. */
17
+ var registerCollection = function (_a) {
18
+ var _b;
19
+ var model = _a.model, options = _a.options, routePath = _a.routePath;
20
+ var existing = collectionRegistry.get(routePath);
21
+ var wasSyncEnabled = (_b = existing === null || existing === void 0 ? void 0 : existing.surfaces.sync) !== null && _b !== void 0 ? _b : false;
22
+ if (options.sync && wasSyncEnabled) {
23
+ var collectionTag = routePath.replace(/^\//, "");
24
+ throw new errors_1.APIError({
25
+ status: 500,
26
+ title: "Sync collection tag \"".concat(collectionTag, "\" is already registered (routePath ").concat(routePath, "). ") +
27
+ "Each synced model must have a unique route path.",
28
+ });
29
+ }
30
+ if (options.sync && !wasSyncEnabled) {
31
+ (0, registrationSideEffects_1.applySyncRegistrationSideEffects)({
32
+ config: options.sync,
33
+ existingSyncEntries: (0, exports.listCollections)()
34
+ .filter(function (record) { return record.surfaces.sync; })
35
+ .map(function (record) { return ({
36
+ collectionTag: record.routePath.replace(/^\//, ""),
37
+ modelName: record.model.modelName,
38
+ }); }),
39
+ model: model,
40
+ options: options,
41
+ routePath: routePath,
42
+ });
43
+ }
44
+ collectionRegistry.set(routePath, {
45
+ model: model,
46
+ options: options,
47
+ routePath: routePath,
48
+ surfaces: deriveSurfaces(options, existing === null || existing === void 0 ? void 0 : existing.surfaces),
49
+ });
50
+ };
51
+ exports.registerCollection = registerCollection;
52
+ /** Swap the options pointer after TerrenoApp enriches it. Unknown path is a no-op. */
53
+ var replaceCollectionOptions = function (routePath, options) {
54
+ var existing = collectionRegistry.get(routePath);
55
+ if (!existing) {
56
+ return;
57
+ }
58
+ existing.options = options;
59
+ };
60
+ exports.replaceCollectionOptions = replaceCollectionOptions;
61
+ var getCollection = function (routePath) {
62
+ return collectionRegistry.get(routePath);
63
+ };
64
+ exports.getCollection = getCollection;
65
+ var listCollections = function () { return Array.from(collectionRegistry.values()); };
66
+ exports.listCollections = listCollections;
67
+ /** Wipe the catalog and queued sync indexes so tests cannot leave a stale surface. */
68
+ var clearCollectionRegistry = function () {
69
+ collectionRegistry.clear();
70
+ (0, registrationSideEffects_1.clearSyncIndexCreationTasks)();
71
+ };
72
+ exports.clearCollectionRegistry = clearCollectionRegistry;
@@ -1,5 +1,5 @@
1
1
  import type express from "express";
2
- import type { Model } from "mongoose";
2
+ import type { Schema } from "mongoose";
3
3
  import { type PermissionMethod } from "./permissions";
4
4
  import type { TerrenoPlugin } from "./terrenoPlugin";
5
5
  /**
@@ -67,12 +67,21 @@ export type ConfigurationPreUpdateHook = (body: Record<string, unknown>, req: ex
67
67
  * never included.
68
68
  */
69
69
  export type ConfigurationPostUpdateHook = (config: Record<string, unknown>, prevValue: Record<string, unknown>, req: express.Request) => void | Promise<void>;
70
+ /**
71
+ * The subset of a Mongoose model that ConfigurationApp inspects. Structural (rather than
72
+ * `Model<T>`) so consumers can pass any configuration model without generic invariance
73
+ * issues; the configurationPlugin statics are looked up at registration time.
74
+ */
75
+ export interface ConfigurationModelLike {
76
+ modelName: string;
77
+ schema: Schema;
78
+ }
70
79
  /**
71
80
  * Options for ConfigurationApp.
72
81
  */
73
82
  export interface ConfigurationAppOptions {
74
83
  /** The Mongoose model with configurationPlugin applied. */
75
- model: Model<any>;
84
+ model: ConfigurationModelLike;
76
85
  /** Base path for configuration routes. Defaults to "/configuration". */
77
86
  basePath?: string;
78
87
  /** Per-field widget overrides (e.g., {"ai.systemPrompt": "markdown"}). */
@@ -345,7 +345,7 @@ var ConfigurationApp = /** @class */ (function () {
345
345
  var ConfigModel = this.options.model;
346
346
  var schema = ConfigModel.schema;
347
347
  // Build metadata by inspecting the schema
348
- var meta = this.buildMetadata(ConfigModel, schema);
348
+ var meta = this.buildMetadata(schema);
349
349
  // GET /configuration/meta — schema metadata for the frontend
350
350
  app.get("".concat(basePath, "/meta"), (0, auth_1.authenticateMiddleware)(), this.guardFor("meta", "read"), function (_req, res) {
351
351
  return res.json(meta);
@@ -441,9 +441,7 @@ var ConfigurationApp = /** @class */ (function () {
441
441
  * Top-level fields with subschemas become sections.
442
442
  * Top-level scalar fields go into a "General" section.
443
443
  */
444
- // noExplicitAny: Model<any> required for invariance with consumer-supplied configuration models
445
- // biome-ignore lint/suspicious/noExplicitAny: Model<any> required for invariance with consumer-supplied configuration models
446
- ConfigurationApp.prototype.buildMetadata = function (_model, schema) {
444
+ ConfigurationApp.prototype.buildMetadata = function (schema) {
447
445
  var _this = this;
448
446
  var sections = [];
449
447
  var generalFields = {};
package/dist/docLoader.js CHANGED
@@ -43,6 +43,27 @@ exports.loadDocOr404 = void 0;
43
43
  var mongoose_1 = __importDefault(require("mongoose"));
44
44
  var api_1 = require("./api");
45
45
  var errors_1 = require("./errors");
46
+ var isCastErrorOnDocumentId = function (error) {
47
+ if (error instanceof mongoose_1.default.Error.CastError) {
48
+ return error.path === "_id";
49
+ }
50
+ var maybe = error;
51
+ return (maybe === null || maybe === void 0 ? void 0 : maybe.name) === "CastError" && maybe.path === "_id";
52
+ };
53
+ var isInvalidIdError = function (error) {
54
+ if (isCastErrorOnDocumentId(error)) {
55
+ return true;
56
+ }
57
+ var name = error === null || error === void 0 ? void 0 : error.name;
58
+ return name === "BSONError" || name === "BSONTypeError";
59
+ };
60
+ var documentNotFound = function (modelName, id) {
61
+ return new errors_1.NotFoundError({
62
+ code: "document-not-found",
63
+ detail: "Document ".concat(id, " not found for model ").concat(modelName),
64
+ title: "Document not found",
65
+ });
66
+ };
46
67
  /**
47
68
  * Loads a document by id or throws a 404 APIError.
48
69
  * Matches permission middleware behavior including soft-delete metadata.
@@ -67,6 +88,9 @@ var loadDocOr404 = function (model, id, populatePaths) { return __awaiter(void 0
67
88
  if ((0, errors_1.isAPIError)(error_1)) {
68
89
  throw error_1;
69
90
  }
91
+ if (isInvalidIdError(error_1)) {
92
+ throw documentNotFound(model.modelName, id);
93
+ }
70
94
  throw new errors_1.APIError({
71
95
  cause: error_1,
72
96
  code: "get-error",
@@ -78,7 +102,16 @@ var loadDocOr404 = function (model, id, populatePaths) { return __awaiter(void 0
78
102
  case 4:
79
103
  if (!!data) return [3 /*break*/, 6];
80
104
  idSchemaType = (_a = model.schema) === null || _a === void 0 ? void 0 : _a.path("_id");
81
- hiddenId = (idSchemaType === null || idSchemaType === void 0 ? void 0 : idSchemaType.instance) === "String" ? id : new mongoose_1.default.Types.ObjectId(id);
105
+ hiddenId = void 0;
106
+ try {
107
+ hiddenId = (idSchemaType === null || idSchemaType === void 0 ? void 0 : idSchemaType.instance) === "String" ? id : new mongoose_1.default.Types.ObjectId(id);
108
+ }
109
+ catch (error) {
110
+ if (isInvalidIdError(error)) {
111
+ throw documentNotFound(model.modelName, id);
112
+ }
113
+ throw error;
114
+ }
82
115
  return [4 /*yield*/, model.collection.findOne({
83
116
  _id: hiddenId,
84
117
  })];
@@ -86,11 +119,7 @@ var loadDocOr404 = function (model, id, populatePaths) { return __awaiter(void 0
86
119
  hiddenDoc = _b.sent();
87
120
  notFoundDetail = "Document ".concat(id, " not found for model ").concat(model.modelName);
88
121
  if (!hiddenDoc) {
89
- throw new errors_1.NotFoundError({
90
- code: "document-not-found",
91
- detail: notFoundDetail,
92
- title: "Document not found",
93
- });
122
+ throw documentNotFound(model.modelName, id);
94
123
  }
95
124
  reason = null;
96
125
  if (hiddenDoc.deleted) {