@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
package/src/docLoader.ts CHANGED
@@ -4,6 +4,30 @@ import {addPopulateToQuery} from "./api";
4
4
  import {APIError, errorDetail, isAPIError, NotFoundError} from "./errors";
5
5
  import type {PopulatePath} from "./populate";
6
6
 
7
+ const isCastErrorOnDocumentId = (error: unknown): boolean => {
8
+ if (error instanceof mongoose.Error.CastError) {
9
+ return error.path === "_id";
10
+ }
11
+ const maybe = error as {name?: string; path?: string} | undefined;
12
+ return maybe?.name === "CastError" && maybe.path === "_id";
13
+ };
14
+
15
+ const isInvalidIdError = (error: unknown): boolean => {
16
+ if (isCastErrorOnDocumentId(error)) {
17
+ return true;
18
+ }
19
+ const name = (error as {name?: string} | undefined)?.name;
20
+ return name === "BSONError" || name === "BSONTypeError";
21
+ };
22
+
23
+ const documentNotFound = (modelName: string, id: string): NotFoundError => {
24
+ return new NotFoundError({
25
+ code: "document-not-found",
26
+ detail: `Document ${id} not found for model ${modelName}`,
27
+ title: "Document not found",
28
+ });
29
+ };
30
+
7
31
  /**
8
32
  * Loads a document by id or throws a 404 APIError.
9
33
  * Matches permission middleware behavior including soft-delete metadata.
@@ -25,6 +49,9 @@ export const loadDocOr404 = async <T>(
25
49
  if (isAPIError(error)) {
26
50
  throw error;
27
51
  }
52
+ if (isInvalidIdError(error)) {
53
+ throw documentNotFound(model.modelName, id);
54
+ }
28
55
  throw new APIError({
29
56
  cause: error,
30
57
  code: "get-error",
@@ -36,7 +63,15 @@ export const loadDocOr404 = async <T>(
36
63
  }
37
64
  if (!data) {
38
65
  const idSchemaType = model.schema?.path("_id");
39
- const hiddenId = idSchemaType?.instance === "String" ? id : new mongoose.Types.ObjectId(id);
66
+ let hiddenId: unknown;
67
+ try {
68
+ hiddenId = idSchemaType?.instance === "String" ? id : new mongoose.Types.ObjectId(id);
69
+ } catch (error: unknown) {
70
+ if (isInvalidIdError(error)) {
71
+ throw documentNotFound(model.modelName, id);
72
+ }
73
+ throw error;
74
+ }
40
75
  const hiddenDoc = await model.collection.findOne({
41
76
  _id: hiddenId as never,
42
77
  });
@@ -44,11 +79,7 @@ export const loadDocOr404 = async <T>(
44
79
  const notFoundDetail = `Document ${id} not found for model ${model.modelName}`;
45
80
 
46
81
  if (!hiddenDoc) {
47
- throw new NotFoundError({
48
- code: "document-not-found",
49
- detail: notFoundDetail,
50
- title: "Document not found",
51
- });
82
+ throw documentNotFound(model.modelName, id);
52
83
  }
53
84
 
54
85
  let reason: {[key: string]: string} | null = null;
package/src/express.d.ts CHANGED
@@ -6,6 +6,7 @@ declare namespace Express {
6
6
  [key: string]: unknown;
7
7
  };
8
8
  jobId?: string;
9
+ rawBody?: Buffer;
9
10
  requestId?: string;
10
11
  sessionId?: string;
11
12
  user?: {
@@ -1,8 +1,6 @@
1
- // noExplicitAny: test mock typing
2
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
1
  import {afterEach, beforeEach, describe, expect, it, mock} from "bun:test";
4
2
  import {Writable} from "node:stream";
5
- import express from "express";
3
+ import express, {type Router} from "express";
6
4
  import supertest from "supertest";
7
5
  import winston from "winston";
8
6
 
@@ -21,6 +19,12 @@ import {UserModel} from "./tests";
21
19
 
22
20
  const typedUserModel = UserModel as unknown as UserModelType;
23
21
 
22
+ // `routeMount` is set by createRouter's internal middleware and is not part of the
23
+ // Express request types.
24
+ interface RouteMountRequest extends express.Request {
25
+ routeMount?: string[] | string;
26
+ }
27
+
24
28
  describe("expressServer", () => {
25
29
  describe("setupEnvironment", () => {
26
30
  const originalEnv = process.env;
@@ -88,7 +92,7 @@ describe("expressServer", () => {
88
92
  },
89
93
  logRequests: false,
90
94
  skipListen: true,
91
- userModel: UserModel as any,
95
+ userModel: typedUserModel,
92
96
  }).build();
93
97
  winstonLogger.add(transport);
94
98
 
@@ -193,12 +197,64 @@ describe("expressServer", () => {
193
197
  expect(req.body.password).toBe("secret123");
194
198
  });
195
199
 
200
+ it("redacts token and newPassword in logged request bodies", () => {
201
+ const logged: string[] = [];
202
+ const originalDebug = logger.debug;
203
+ logger.debug = ((message: string) => {
204
+ logged.push(message);
205
+ }) as typeof logger.debug;
206
+ try {
207
+ const req = {
208
+ body: {newPassword: "fresh-secret", token: "one-time-token", username: "testuser"},
209
+ method: "POST",
210
+ url: "/auth/resetPassword",
211
+ };
212
+ const res = {
213
+ locals: {},
214
+ on: () => {},
215
+ };
216
+ logRequests(req as never, res as never, () => {});
217
+ const combined = logged.join("\n");
218
+ expect(combined).toContain("<REDACTED>");
219
+ expect(combined).not.toContain("fresh-secret");
220
+ expect(combined).not.toContain("one-time-token");
221
+ expect(req.body.token).toBe("one-time-token");
222
+ expect(req.body.newPassword).toBe("fresh-secret");
223
+ } finally {
224
+ logger.debug = originalDebug;
225
+ }
226
+ });
227
+
228
+ it("redacts token query params in request URLs", () => {
229
+ const logged: string[] = [];
230
+ const originalDebug = logger.debug;
231
+ logger.debug = ((message: string) => {
232
+ logged.push(message);
233
+ }) as typeof logger.debug;
234
+ try {
235
+ const req = {
236
+ body: {},
237
+ method: "GET",
238
+ url: "/api/auth/verify-email?token=one-time-token",
239
+ };
240
+ const res = {
241
+ locals: {},
242
+ on: () => {},
243
+ };
244
+ logRequests(req as never, res as never, () => {});
245
+ const combined = logged.join("\n");
246
+ expect(combined).toContain("token=%3CREDACTED%3E");
247
+ expect(combined).not.toContain("one-time-token");
248
+ } finally {
249
+ logger.debug = originalDebug;
250
+ }
251
+ });
252
+
196
253
  it("triggers onFinished callback with route info", async () => {
197
254
  const app = express();
198
255
  app.use(logRequests);
199
- app.get("/test", (req: any, res) => {
200
- req.route = {path: "/test"};
201
- req.routeMount = "/api";
256
+ app.get("/test", (req, res) => {
257
+ (req as RouteMountRequest).routeMount = "/api";
202
258
  res.json({ok: true});
203
259
  });
204
260
 
@@ -255,8 +311,7 @@ describe("expressServer", () => {
255
311
  it("handles request with route path only (no routeMount)", async () => {
256
312
  const app = express();
257
313
  app.use(logRequests);
258
- app.get("/test", (req: any, res) => {
259
- req.route = {path: "/test"};
314
+ app.get("/test", (_req, res) => {
260
315
  // No routeMount set
261
316
  res.json({ok: true});
262
317
  });
@@ -268,9 +323,9 @@ describe("expressServer", () => {
268
323
  describe("createRouter", () => {
269
324
  it("creates router with root path and adds routes", () => {
270
325
  let routesCalled = false;
271
- const addRoutes = (router: any) => {
326
+ const addRoutes = (router: Router) => {
272
327
  routesCalled = true;
273
- router.get("/test", (_req: any, res: any) => res.send("ok"));
328
+ router.get("/test", (_req, res) => res.send("ok"));
274
329
  };
275
330
 
276
331
  const result = createRouter("/api", addRoutes);
@@ -281,8 +336,8 @@ describe("expressServer", () => {
281
336
  });
282
337
 
283
338
  it("creates router with middleware", () => {
284
- const middleware1 = (_req: any, _res: any, next: any) => next();
285
- const middleware2 = (_req: any, _res: any, next: any) => next();
339
+ const middleware1: express.RequestHandler = (_req, _res, next) => next();
340
+ const middleware2: express.RequestHandler = (_req, _res, next) => next();
286
341
  const addRoutes = () => {};
287
342
 
288
343
  const result = createRouter("/api", addRoutes, [middleware1, middleware2]);
@@ -292,15 +347,15 @@ describe("expressServer", () => {
292
347
  });
293
348
 
294
349
  it("routePathMiddleware sets routeMount on request", () => {
295
- const addRoutes = (router: any) => {
296
- router.get("/test", (req: any, res: any) => {
297
- res.json({routeMount: req.routeMount});
350
+ const addRoutes = (router: Router) => {
351
+ router.get("/test", (req, res) => {
352
+ res.json({routeMount: (req as RouteMountRequest).routeMount});
298
353
  });
299
354
  };
300
355
 
301
356
  const result = createRouter("/api", addRoutes);
302
357
  const app = express();
303
- app.use(...(result as [string, ...any[]]));
358
+ app.use(...(result as [string, ...express.RequestHandler[]]));
304
359
 
305
360
  // The routePathMiddleware is internal, but we can verify the router works
306
361
  expect(result[0]).toBe("/api");
@@ -310,9 +365,9 @@ describe("expressServer", () => {
310
365
  describe("createRouterWithAuth", () => {
311
366
  it("creates router with passport authentication middleware", () => {
312
367
  let routesCalled = false;
313
- const addRoutes = (router: any) => {
368
+ const addRoutes = (router: Router) => {
314
369
  routesCalled = true;
315
- router.get("/protected", (_req: any, res: any) => res.send("ok"));
370
+ router.get("/protected", (_req, res) => res.send("ok"));
316
371
  };
317
372
 
318
373
  const result = createRouterWithAuth("/secure", addRoutes);
@@ -324,7 +379,7 @@ describe("expressServer", () => {
324
379
  });
325
380
 
326
381
  it("includes additional middleware", () => {
327
- const customMiddleware = (_req: any, _res: any, next: any) => next();
382
+ const customMiddleware: express.RequestHandler = (_req, _res, next) => next();
328
383
  const addRoutes = () => {};
329
384
 
330
385
  const result = createRouterWithAuth("/secure", addRoutes, [customMiddleware]);
@@ -378,36 +433,36 @@ describe("expressServer", () => {
378
433
 
379
434
  describe("createRouter routePathMiddleware", () => {
380
435
  it("initializes routeMount array when not present", async () => {
381
- const addRoutes = (router: any) => {
382
- router.get("/test", (req: any, res: any) => {
383
- res.json({routeMount: req.routeMount});
436
+ const addRoutes = (router: Router) => {
437
+ router.get("/test", (req, res) => {
438
+ res.json({routeMount: (req as RouteMountRequest).routeMount});
384
439
  });
385
440
  };
386
441
 
387
442
  const result = createRouter("/api", addRoutes);
388
443
  const app = express();
389
- app.use(...(result as [string, ...any[]]));
444
+ app.use(...(result as [string, ...express.RequestHandler[]]));
390
445
 
391
446
  const response = await supertest(app).get("/api/test").expect(200);
392
447
  expect(response.body.routeMount).toEqual(["/api"]);
393
448
  });
394
449
 
395
450
  it("appends to existing routeMount array", async () => {
396
- const addRoutes = (router: any) => {
397
- router.get("/test", (req: any, res: any) => {
398
- res.json({routeMount: req.routeMount});
451
+ const addRoutes = (router: Router) => {
452
+ router.get("/test", (req, res) => {
453
+ res.json({routeMount: (req as RouteMountRequest).routeMount});
399
454
  });
400
455
  };
401
456
 
402
457
  // Create nested routers
403
458
  const innerResult = createRouter("/inner", addRoutes);
404
- const outerAddRoutes = (router: any) => {
405
- router.use(...(innerResult as [string, ...any[]]));
459
+ const outerAddRoutes = (router: Router) => {
460
+ router.use(...(innerResult as [string, ...express.RequestHandler[]]));
406
461
  };
407
462
  const outerResult = createRouter("/outer", outerAddRoutes);
408
463
 
409
464
  const app = express();
410
- app.use(...(outerResult as [string, ...any[]]));
465
+ app.use(...(outerResult as [string, ...express.RequestHandler[]]));
411
466
 
412
467
  const response = await supertest(app).get("/outer/inner/test").expect(200);
413
468
  expect(response.body.routeMount).toEqual(["/outer", "/inner"]);
@@ -438,7 +493,7 @@ describe("expressServer", () => {
438
493
  const app = new TerrenoApp({
439
494
  configureApp,
440
495
  skipListen: true,
441
- userModel: UserModel as any,
496
+ userModel: typedUserModel,
442
497
  }).build();
443
498
 
444
499
  expect(app).toBeDefined();
@@ -449,13 +504,14 @@ describe("expressServer", () => {
449
504
  const configureApp = (): void => {};
450
505
 
451
506
  const app = new TerrenoApp({
452
- beforeJsonSetup: (httpApp: any) => {
507
+ beforeJsonSetup: (httpApp: express.Application) => {
453
508
  middlewareCalled = true;
454
- httpApp.use((_req: any, _res: any, next: any) => next());
509
+ const passthrough: express.RequestHandler = (_req, _res, next) => next();
510
+ httpApp.use(passthrough);
455
511
  },
456
512
  configureApp,
457
513
  skipListen: true,
458
- userModel: UserModel as any,
514
+ userModel: typedUserModel,
459
515
  }).build();
460
516
 
461
517
  expect(app).toBeDefined();
@@ -469,7 +525,7 @@ describe("expressServer", () => {
469
525
  configureApp,
470
526
  corsOrigin: "https://example.com",
471
527
  skipListen: true,
472
- userModel: UserModel as any,
528
+ userModel: typedUserModel,
473
529
  }).build();
474
530
 
475
531
  expect(app).toBeDefined();
@@ -485,7 +541,7 @@ describe("expressServer", () => {
485
541
  },
486
542
  configureApp,
487
543
  skipListen: true,
488
- userModel: UserModel as any,
544
+ userModel: typedUserModel,
489
545
  }).build();
490
546
 
491
547
  expect(app).toBeDefined();
@@ -497,7 +553,7 @@ describe("expressServer", () => {
497
553
  const app = express();
498
554
  app.use(logRequests);
499
555
  // Middleware that sets statusCode < 400 but doesn't define route
500
- app.use((_req: any, res) => {
556
+ app.use((_req, res) => {
501
557
  res.status(200).json({ok: true});
502
558
  });
503
559
 
@@ -507,9 +563,8 @@ describe("expressServer", () => {
507
563
  it("handles request with routeMount as string (legacy)", async () => {
508
564
  const app = express();
509
565
  app.use(logRequests);
510
- app.get("/test", (req: any, res) => {
511
- req.route = {path: "/test"};
512
- req.routeMount = "/api"; // String instead of array
566
+ app.get("/test", (req, res) => {
567
+ (req as RouteMountRequest).routeMount = "/api"; // String instead of array
513
568
  res.json({ok: true});
514
569
  });
515
570
 
@@ -536,8 +591,8 @@ describe("expressServer", () => {
536
591
  });
537
592
 
538
593
  it("sets Sentry transaction ID tag from header", async () => {
539
- const configureApp = (httpApp: any) => {
540
- httpApp.get("/test", (_req: any, res: any) => {
594
+ const configureApp = (httpApp: Router) => {
595
+ httpApp.get("/test", (_req, res) => {
541
596
  res.json({ok: true});
542
597
  });
543
598
  };
@@ -545,15 +600,15 @@ describe("expressServer", () => {
545
600
  const app = new TerrenoApp({
546
601
  configureApp,
547
602
  skipListen: true,
548
- userModel: UserModel as any,
603
+ userModel: typedUserModel,
549
604
  }).build();
550
605
 
551
606
  await supertest(app).get("/test").set("X-Transaction-ID", "txn-123").expect(200);
552
607
  });
553
608
 
554
609
  it("sets Sentry session ID tag from header", async () => {
555
- const configureApp = (httpApp: any) => {
556
- httpApp.get("/test", (_req: any, res: any) => {
610
+ const configureApp = (httpApp: Router) => {
611
+ httpApp.get("/test", (_req, res) => {
557
612
  res.json({ok: true});
558
613
  });
559
614
  };
@@ -561,15 +616,15 @@ describe("expressServer", () => {
561
616
  const app = new TerrenoApp({
562
617
  configureApp,
563
618
  skipListen: true,
564
- userModel: UserModel as any,
619
+ userModel: typedUserModel,
565
620
  }).build();
566
621
 
567
622
  await supertest(app).get("/test").set("X-Session-ID", "session-456").expect(200);
568
623
  });
569
624
 
570
625
  it("sets both transaction and session ID tags", async () => {
571
- const configureApp = (httpApp: any) => {
572
- httpApp.get("/test", (_req: any, res: any) => {
626
+ const configureApp = (httpApp: Router) => {
627
+ httpApp.get("/test", (_req, res) => {
573
628
  res.json({ok: true});
574
629
  });
575
630
  };
@@ -577,7 +632,7 @@ describe("expressServer", () => {
577
632
  const app = new TerrenoApp({
578
633
  configureApp,
579
634
  skipListen: true,
580
- userModel: UserModel as any,
635
+ userModel: typedUserModel,
581
636
  }).build();
582
637
 
583
638
  await supertest(app)
@@ -588,8 +643,8 @@ describe("expressServer", () => {
588
643
  });
589
644
 
590
645
  it("handles fallthrough error handler", async () => {
591
- const configureApp = (httpApp: any) => {
592
- httpApp.get("/error", (_req: any, _res: any) => {
646
+ const configureApp = (httpApp: Router) => {
647
+ httpApp.get("/error", () => {
593
648
  throw new Error("Unexpected error");
594
649
  });
595
650
  };
@@ -597,15 +652,15 @@ describe("expressServer", () => {
597
652
  const app = new TerrenoApp({
598
653
  configureApp,
599
654
  skipListen: true,
600
- userModel: UserModel as any,
655
+ userModel: typedUserModel,
601
656
  }).build();
602
657
 
603
658
  await supertest(app).get("/error").expect(500);
604
659
  });
605
660
 
606
661
  it("handles loggingOptions passed to TerrenoApp", async () => {
607
- const configureApp = (httpApp: any) => {
608
- httpApp.get("/test", (_req: any, res: any) => {
662
+ const configureApp = (httpApp: Router) => {
663
+ httpApp.get("/test", (_req, res) => {
609
664
  res.json({ok: true});
610
665
  });
611
666
  };
@@ -617,7 +672,7 @@ describe("expressServer", () => {
617
672
  logSlowRequestsReadMs: 100,
618
673
  },
619
674
  skipListen: true,
620
- userModel: UserModel as any,
675
+ userModel: typedUserModel,
621
676
  }).build();
622
677
 
623
678
  await supertest(app).get("/test").expect(200);
@@ -632,7 +687,7 @@ describe("expressServer", () => {
632
687
  new TerrenoApp({
633
688
  configureApp,
634
689
  skipListen: true,
635
- userModel: UserModel as any,
690
+ userModel: typedUserModel,
636
691
  }).build()
637
692
  ).toThrow("Route init boom");
638
693
  });
@@ -865,9 +920,9 @@ describe("expressServer", () => {
865
920
 
866
921
  describe("TerrenoApp with listen", () => {
867
922
  const originalEnv = process.env;
868
- const http = require("node:http");
869
- let activeServer: any = null;
870
- let originalListen: any = null;
923
+ const http = require("node:http") as typeof import("node:http");
924
+ let activeServer: import("node:http").Server | null = null;
925
+ let originalListen: typeof http.Server.prototype.listen | null = null;
871
926
 
872
927
  beforeEach(() => {
873
928
  process.env = {
@@ -881,17 +936,26 @@ describe("expressServer", () => {
881
936
  };
882
937
 
883
938
  originalListen = http.Server.prototype.listen;
884
- http.Server.prototype.listen = function (...args: any[]) {
939
+ http.Server.prototype.listen = function (
940
+ this: import("node:http").Server,
941
+ ...args: unknown[]
942
+ ) {
885
943
  activeServer = this;
886
- return originalListen.apply(this, args);
887
- };
944
+ return (originalListen as (...listenArgs: unknown[]) => import("node:http").Server).apply(
945
+ this,
946
+ args
947
+ );
948
+ } as typeof http.Server.prototype.listen;
888
949
  });
889
950
 
890
951
  afterEach(async () => {
891
952
  process.env = originalEnv;
892
- http.Server.prototype.listen = originalListen;
953
+ if (originalListen) {
954
+ http.Server.prototype.listen = originalListen;
955
+ }
893
956
  if (activeServer) {
894
- await new Promise<void>((resolve) => activeServer.close(() => resolve()));
957
+ const server = activeServer;
958
+ await new Promise<void>((resolve) => server.close(() => resolve()));
895
959
  activeServer = null;
896
960
  }
897
961
  });
@@ -902,7 +966,7 @@ describe("expressServer", () => {
902
966
  const app = new TerrenoApp({
903
967
  configureApp,
904
968
  skipListen: false,
905
- userModel: UserModel as any,
969
+ userModel: typedUserModel,
906
970
  }).start();
907
971
 
908
972
  expect(app).toBeDefined();
@@ -999,7 +1063,7 @@ describe("expressServer", () => {
999
1063
  new TerrenoApp({
1000
1064
  configureApp,
1001
1065
  skipListen: true,
1002
- userModel: UserModel as any,
1066
+ userModel: typedUserModel,
1003
1067
  }).build()
1004
1068
  ).toThrow("route initialization failed");
1005
1069
  });
@@ -7,6 +7,7 @@ import cloneDeep from "lodash/cloneDeep";
7
7
  import onFinished from "on-finished";
8
8
  import passport from "passport";
9
9
  import type {ModelRouterOptions} from "./api";
10
+ import type {User} from "./auth";
10
11
  import {APIError} from "./errors";
11
12
  import {type LoggingOptions, logger} from "./logger";
12
13
  import {sendToSlack} from "./notifiers/slackNotifier";
@@ -14,6 +15,47 @@ import {sendToSlack} from "./notifiers/slackNotifier";
14
15
  const SLOW_READ_MAX = 200;
15
16
  const SLOW_WRITE_MAX = 500;
16
17
  const IS_JEST = process.env.JEST_WORKER_ID !== undefined;
18
+ const SENSITIVE_REQUEST_BODY_KEYS = [
19
+ "newPassword",
20
+ "oldPassword",
21
+ "password",
22
+ "refreshToken",
23
+ "token",
24
+ ] as const;
25
+
26
+ const redactSensitiveRequestBody = (body: Record<string, unknown>): Record<string, unknown> => {
27
+ const bodyCopy = cloneDeep(body);
28
+ for (const key of SENSITIVE_REQUEST_BODY_KEYS) {
29
+ if (key in bodyCopy && bodyCopy[key] !== undefined) {
30
+ bodyCopy[key] = "<REDACTED>";
31
+ }
32
+ }
33
+ return bodyCopy;
34
+ };
35
+
36
+ const sensitiveQueryKeySet = new Set<string>(SENSITIVE_REQUEST_BODY_KEYS);
37
+
38
+ export const redactSensitiveRequestUrl = (url: string | undefined): string => {
39
+ if (!url) {
40
+ return "";
41
+ }
42
+ const isAbsolute = /^[a-z][a-z0-9+.-]*:/i.test(url);
43
+ const parsed = new URL(url, "http://terreno.invalid");
44
+ let didRedact = false;
45
+ for (const key of parsed.searchParams.keys()) {
46
+ if (sensitiveQueryKeySet.has(key)) {
47
+ parsed.searchParams.set(key, "<REDACTED>");
48
+ didRedact = true;
49
+ }
50
+ }
51
+ if (!didRedact) {
52
+ return url;
53
+ }
54
+ if (isAbsolute) {
55
+ return parsed.toString();
56
+ }
57
+ return `${parsed.pathname}${parsed.search}${parsed.hash}`;
58
+ };
17
59
 
18
60
  export const setupEnvironment = (): void => {
19
61
  if (!process.env.TOKEN_ISSUER) {
@@ -72,10 +114,12 @@ const logRequestsFinished = (req: LoggableRequest, res: LoggableResponse, startT
72
114
  } else if (req.route) {
73
115
  pathName = req.route.path;
74
116
  } else if (res.statusCode != null && res.statusCode < 400) {
75
- logger.warn(`Request without route: ${req.originalUrl}`);
117
+ logger.warn(`Request without route: ${redactSensitiveRequestUrl(req.originalUrl)}`);
76
118
  }
77
119
  if (process.env.DISABLE_LOG_ALL_REQUESTS !== "true") {
78
- logger.debug(`${req.method} -> ${req.originalUrl} ${res.statusCode} ${`${diffInMs}ms`}`);
120
+ logger.debug(
121
+ `${req.method} -> ${redactSensitiveRequestUrl(req.originalUrl)} ${res.statusCode} ${`${diffInMs}ms`}`
122
+ );
79
123
  }
80
124
  if (options.logSlowRequests) {
81
125
  if (diffInMs > slowReadMs && req.method === "GET") {
@@ -83,7 +127,7 @@ const logRequestsFinished = (req: LoggableRequest, res: LoggableResponse, startT
83
127
  `Slow GET request, ${JSON.stringify({
84
128
  pathName,
85
129
  requestTime: diffInMs,
86
- url: req.originalUrl,
130
+ url: redactSensitiveRequestUrl(req.originalUrl),
87
131
  })}`
88
132
  );
89
133
  } else if (diffInMs > slowWriteMs) {
@@ -91,7 +135,7 @@ const logRequestsFinished = (req: LoggableRequest, res: LoggableResponse, startT
91
135
  `Slow write request ${JSON.stringify({
92
136
  pathName,
93
137
  requestTime: diffInMs,
94
- url: req.originalUrl,
138
+ url: redactSensitiveRequestUrl(req.originalUrl),
95
139
  })}`
96
140
  );
97
141
  }
@@ -120,15 +164,11 @@ export const logRequests = (
120
164
 
121
165
  let body = "";
122
166
  if (req.body && Object.keys(req.body).length > 0) {
123
- const bodyCopy = cloneDeep(req.body);
124
- if (bodyCopy.password) {
125
- bodyCopy.password = "<PASSWORD>";
126
- }
127
- body = ` Body: ${JSON.stringify(bodyCopy)}`;
167
+ body = ` Body: ${JSON.stringify(redactSensitiveRequestBody(req.body))}`;
128
168
  }
129
169
 
130
170
  if (process.env.DISABLE_LOG_ALL_REQUESTS !== "true") {
131
- logger.debug(`${req.method} <- ${req.url}${userString}${body}`);
171
+ logger.debug(`${req.method} <- ${redactSensitiveRequestUrl(req.url)}${userString}${body}`);
132
172
  }
133
173
  onFinished(res as unknown as OutgoingMessage, () => logRequestsFinished(req, res, startTime));
134
174
  next();
@@ -168,16 +208,32 @@ export const createRouterWithAuth = (
168
208
  ]);
169
209
  };
170
210
 
211
+ export interface AuthRecoveryMail {
212
+ html?: string;
213
+ subject: string;
214
+ text: string;
215
+ to: string;
216
+ }
217
+
171
218
  export interface AuthOptions {
172
- // noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
173
- // biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
174
- generateJWTPayload?: (user: any) => Record<string, unknown>;
175
- // noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
176
- // biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
177
- generateTokenExpiration?: (user: any) => number | jwt.SignOptions["expiresIn"];
178
- // noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
179
- // biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
180
- generateRefreshTokenExpiration?: (user: any) => number | jwt.SignOptions["expiresIn"];
219
+ generateJWTPayload?: (user: User) => Record<string, unknown>;
220
+ generateTokenExpiration?: (user: User) => number | jwt.SignOptions["expiresIn"];
221
+ generateRefreshTokenExpiration?: (user: User) => number | jwt.SignOptions["expiresIn"];
222
+ /** Public web/app origin used in password-reset and verification links. */
223
+ publicAppUrl?: string;
224
+ /**
225
+ * Deliver recovery mail (forgot password / verify email). Wire to
226
+ * `getCommsService().sendMail` when `@terreno/comms` is registered.
227
+ */
228
+ sendMail?: (message: AuthRecoveryMail) => Promise<void>;
229
+ /** When true, unverified users receive 403 `email-not-verified` on login. Default false. */
230
+ requireEmailVerification?: boolean;
231
+ /**
232
+ * After a successful JWT password reset, update the Better Auth credential hash
233
+ * and delete that user's Better Auth sessions. TerrenoApp wires this when
234
+ * BetterAuthApp is registered.
235
+ */
236
+ syncPasswordResetToBetterAuth?: (user: User, password: string) => Promise<void>;
181
237
  }
182
238
 
183
239
  export const cronjob = (