@terreno/api 57.3.0 → 57.6.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 (412) hide show
  1. package/.ai/skills/mongoose-schema-safety/SKILL.md +23 -10
  2. package/README.md +11 -5
  3. package/bunfig.toml +1 -1
  4. package/dist/actions.js +197 -368
  5. package/dist/adminModelRouter.js +88 -173
  6. package/dist/adminTypes.d.ts +7 -0
  7. package/dist/adminTypes.js +6 -1
  8. package/dist/api.d.ts +10 -0
  9. package/dist/api.js +601 -792
  10. package/dist/audit/auditApp.d.ts +30 -0
  11. package/dist/audit/auditApp.js +114 -0
  12. package/dist/audit/auditEventModel.d.ts +29 -0
  13. package/dist/audit/auditEventModel.js +101 -0
  14. package/dist/audit/cloudTasksEnqueue.d.ts +32 -0
  15. package/dist/audit/cloudTasksEnqueue.js +69 -0
  16. package/dist/audit/diff.d.ts +10 -0
  17. package/dist/audit/diff.js +140 -0
  18. package/dist/audit/processQueue.d.ts +6 -0
  19. package/dist/audit/processQueue.js +56 -0
  20. package/dist/audit/rbacSink.d.ts +2 -0
  21. package/dist/audit/rbacSink.js +41 -0
  22. package/dist/audit/record.d.ts +56 -0
  23. package/dist/audit/record.js +251 -0
  24. package/dist/auth.js +432 -681
  25. package/dist/authRecovery.js +155 -269
  26. package/dist/authTokens.js +43 -118
  27. package/dist/betterAuth.d.ts +6 -0
  28. package/dist/betterAuthApp.js +25 -26
  29. package/dist/betterAuthSetup.js +258 -413
  30. package/dist/browserLogsRoute.d.ts +6 -0
  31. package/dist/browserLogsRoute.js +97 -0
  32. package/dist/collectionRegistry.d.ts +3 -1
  33. package/dist/collectionRegistry.js +43 -33
  34. package/dist/config.js +53 -122
  35. package/dist/configurationApp.js +180 -361
  36. package/dist/configurationPlugin.js +130 -302
  37. package/dist/consentApp.js +276 -421
  38. package/dist/docLoader.js +78 -126
  39. package/dist/envConfigurationPlugin.js +25 -147
  40. package/dist/errors.js +151 -247
  41. package/dist/example.js +28 -34
  42. package/dist/expressServer.d.ts +10 -0
  43. package/dist/expressServer.js +109 -255
  44. package/dist/frameworkModelNames.d.ts +24 -0
  45. package/dist/frameworkModelNames.js +31 -0
  46. package/dist/githubAuth.js +152 -216
  47. package/dist/httpClient.js +176 -264
  48. package/dist/index.d.ts +28 -1
  49. package/dist/index.js +53 -2
  50. package/dist/logger.js +145 -278
  51. package/dist/mcp/auth.js +76 -128
  52. package/dist/mcp/createMCPRequest.js +4 -5
  53. package/dist/mcp/handlers.js +268 -480
  54. package/dist/mcp/query.d.ts +0 -13
  55. package/dist/mcp/query.js +57 -151
  56. package/dist/mcp/registry.js +17 -30
  57. package/dist/mcp/schemaGenerator.js +95 -181
  58. package/dist/mcp/server.js +28 -100
  59. package/dist/mcp/serviceTokens.js +102 -191
  60. package/dist/mcp/toolGenerator.js +78 -191
  61. package/dist/middleware.js +15 -27
  62. package/dist/migrations/fixtures/all-down/20260910120000-one.d.ts +4 -0
  63. package/dist/migrations/fixtures/all-down/20260910120000-one.js +9 -0
  64. package/dist/migrations/fixtures/all-down/20260910120001-two.d.ts +4 -0
  65. package/dist/migrations/fixtures/all-down/20260910120001-two.js +9 -0
  66. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.d.ts +3 -0
  67. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +7 -0
  68. package/dist/migrations/fixtures/bad-name/not-a-migration.d.ts +3 -0
  69. package/dist/migrations/fixtures/bad-name/not-a-migration.js +7 -0
  70. package/dist/migrations/fixtures/missing-up/20260910120000-noup.d.ts +2 -0
  71. package/dist/migrations/fixtures/missing-up/20260910120000-noup.js +5 -0
  72. package/dist/migrations/fixtures/valid/20260910120000-alpha.d.ts +3 -0
  73. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +7 -0
  74. package/dist/migrations/fixtures/valid/20260910120001-beta.d.ts +4 -0
  75. package/dist/migrations/fixtures/valid/20260910120001-beta.js +9 -0
  76. package/dist/migrations/generate.d.ts +17 -0
  77. package/dist/migrations/generate.js +155 -0
  78. package/dist/migrations/load.d.ts +20 -0
  79. package/dist/migrations/load.js +110 -0
  80. package/dist/migrations/lock.d.ts +13 -0
  81. package/dist/migrations/lock.js +73 -0
  82. package/dist/migrations/runner.d.ts +42 -0
  83. package/dist/migrations/runner.js +249 -0
  84. package/dist/migrations/schemaCatalog.d.ts +44 -0
  85. package/dist/migrations/schemaCatalog.js +185 -0
  86. package/dist/migrations/types.d.ts +87 -0
  87. package/dist/migrations/types.js +7 -0
  88. package/dist/models/consentForm.js +6 -6
  89. package/dist/models/consentResponse.js +5 -5
  90. package/dist/models/mcpServiceToken.js +66 -156
  91. package/dist/models/notification.d.ts +2 -0
  92. package/dist/models/notification.js +62 -0
  93. package/dist/models/notificationPreference.d.ts +2 -0
  94. package/dist/models/notificationPreference.js +49 -0
  95. package/dist/models/versionConfig.js +5 -5
  96. package/dist/notifications/notificationService.d.ts +40 -0
  97. package/dist/notifications/notificationService.js +183 -0
  98. package/dist/notifications/notificationsApp.d.ts +18 -0
  99. package/dist/notifications/notificationsApp.js +156 -0
  100. package/dist/notifications/notificationsBeforeSend.d.ts +14 -0
  101. package/dist/notifications/notificationsBeforeSend.js +32 -0
  102. package/dist/notifiers/googleChatNotifier.js +36 -117
  103. package/dist/notifiers/slackNotifier.d.ts +31 -2
  104. package/dist/notifiers/slackNotifier.js +170 -119
  105. package/dist/notifiers/zoomNotifier.js +60 -111
  106. package/dist/openApi.d.ts +1 -7
  107. package/dist/openApi.js +113 -127
  108. package/dist/openApiBuilder.d.ts +14 -3
  109. package/dist/openApiBuilder.js +117 -159
  110. package/dist/openApiCompat.js +81 -148
  111. package/dist/openApiEtag.js +7 -7
  112. package/dist/openApiValidator.d.ts +13 -1
  113. package/dist/openApiValidator.js +301 -246
  114. package/dist/orgs/orgContext.d.ts +23 -0
  115. package/dist/orgs/orgContext.js +128 -0
  116. package/dist/orgs/orgPermissions.d.ts +4 -0
  117. package/dist/orgs/orgPermissions.js +38 -0
  118. package/dist/orgs/orgPlugin.d.ts +13 -0
  119. package/dist/orgs/orgPlugin.js +66 -0
  120. package/dist/orgs/organizationModel.d.ts +13 -0
  121. package/dist/orgs/organizationModel.js +200 -0
  122. package/dist/orgs/organizationSettings.d.ts +19 -0
  123. package/dist/orgs/organizationSettings.js +113 -0
  124. package/dist/orgs/orgsApp.d.ts +28 -0
  125. package/dist/orgs/orgsApp.js +416 -0
  126. package/dist/permissions.d.ts +7 -13
  127. package/dist/permissions.js +95 -211
  128. package/dist/plugins.js +125 -218
  129. package/dist/populate.js +130 -240
  130. package/dist/rateLimit/applyTrustProxy.js +1 -1
  131. package/dist/rateLimit/createStore.js +7 -8
  132. package/dist/rateLimit/memoryStore.js +22 -100
  133. package/dist/rateLimit/middleware.d.ts +0 -8
  134. package/dist/rateLimit/middleware.js +49 -101
  135. package/dist/rateLimit/mongoStore.d.ts +1 -0
  136. package/dist/rateLimit/mongoStore.js +55 -112
  137. package/dist/rateLimit/policies.d.ts +0 -4
  138. package/dist/rateLimit/policies.js +44 -80
  139. package/dist/rateLimit/redisStore.d.ts +1 -0
  140. package/dist/rateLimit/redisStore.js +40 -133
  141. package/dist/rbac/access.js +122 -253
  142. package/dist/rbac/assertAllowed.js +95 -171
  143. package/dist/rbac/auditModel.js +14 -58
  144. package/dist/rbac/backfillAdmins.js +24 -130
  145. package/dist/rbac/fieldViews.js +46 -141
  146. package/dist/rbac/membershipOrgAdminSource.d.ts +6 -0
  147. package/dist/rbac/membershipOrgAdminSource.js +51 -0
  148. package/dist/rbac/middleware.js +30 -96
  149. package/dist/rbac/modelRouterAccess.d.ts +3 -0
  150. package/dist/rbac/modelRouterAccess.js +133 -307
  151. package/dist/rbac/permissionUtils.js +40 -179
  152. package/dist/rbac/realtimeAccess.js +81 -147
  153. package/dist/rbac/resolve.d.ts +1 -1
  154. package/dist/rbac/resolve.js +154 -319
  155. package/dist/rbac/roleManager.js +318 -700
  156. package/dist/rbac/roleModel.d.ts +2 -5
  157. package/dist/rbac/roleModel.js +60 -173
  158. package/dist/rbac/routes.js +93 -196
  159. package/dist/rbac/scopes.js +39 -133
  160. package/dist/rbac/statements.d.ts +10 -1
  161. package/dist/rbac/statements.js +42 -93
  162. package/dist/rbac/types.d.ts +5 -0
  163. package/dist/rbac/userPlugin.js +3 -29
  164. package/dist/realtime/changeStreamWatcher.d.ts +10 -4
  165. package/dist/realtime/changeStreamWatcher.js +499 -764
  166. package/dist/realtime/deprecation.d.ts +1 -0
  167. package/dist/realtime/deprecation.js +9 -10
  168. package/dist/realtime/queryMatcher.js +110 -191
  169. package/dist/realtime/queryStore.js +35 -118
  170. package/dist/realtime/realtimeApp.d.ts +1 -0
  171. package/dist/realtime/realtimeApp.js +248 -401
  172. package/dist/realtime/registry.js +19 -30
  173. package/dist/realtime/sessionRevalidation.js +132 -358
  174. package/dist/realtime/socketAuth.js +89 -208
  175. package/dist/realtime/socketUser.js +10 -56
  176. package/dist/requestContext.js +93 -139
  177. package/dist/schemaMetadata.js +181 -265
  178. package/dist/scriptRunner.js +96 -266
  179. package/dist/scrubAdminFields.js +36 -108
  180. package/dist/secretProviders.js +130 -299
  181. package/dist/seedRunner.js +221 -514
  182. package/dist/sync/adminBroadcastScope.d.ts +40 -0
  183. package/dist/sync/adminBroadcastScope.js +82 -0
  184. package/dist/sync/adminWindowAccess.d.ts +13 -0
  185. package/dist/sync/adminWindowAccess.js +25 -0
  186. package/dist/sync/adminWindowMutation.d.ts +88 -0
  187. package/dist/sync/adminWindowMutation.js +176 -0
  188. package/dist/sync/executors.d.ts +9 -3
  189. package/dist/sync/executors.js +425 -598
  190. package/dist/sync/loadHarness.js +392 -689
  191. package/dist/sync/models.js +181 -341
  192. package/dist/sync/mutationHandler.d.ts +5 -2
  193. package/dist/sync/mutationHandler.js +549 -697
  194. package/dist/sync/registrationSideEffects.js +41 -95
  195. package/dist/sync/registry.js +31 -47
  196. package/dist/sync/routes.d.ts +13 -0
  197. package/dist/sync/routes.js +484 -760
  198. package/dist/sync/scripts/compactTombstones.js +83 -228
  199. package/dist/sync/serialize.js +18 -58
  200. package/dist/sync/socketHandlers.d.ts +8 -2
  201. package/dist/sync/socketHandlers.js +271 -402
  202. package/dist/sync/streams.d.ts +2 -0
  203. package/dist/sync/streams.js +54 -116
  204. package/dist/sync/syncApp.d.ts +2 -1
  205. package/dist/sync/syncApp.js +14 -16
  206. package/dist/sync/syncBatch.d.ts +5 -2
  207. package/dist/sync/syncBatch.js +63 -168
  208. package/dist/sync/syncSeqPlugin.js +430 -702
  209. package/dist/sync/types.d.ts +18 -0
  210. package/dist/syncConsents.js +113 -253
  211. package/dist/terrenoApp.d.ts +29 -0
  212. package/dist/terrenoApp.js +184 -257
  213. package/dist/tests/createTestData.d.ts +1 -3
  214. package/dist/tests/createTestData.js +147 -259
  215. package/dist/tests/models.d.ts +1 -0
  216. package/dist/tests/models.js +23 -56
  217. package/dist/tests/mongoTestSetup.js +42 -103
  218. package/dist/tests/testHelper.d.ts +0 -5
  219. package/dist/tests/testHelper.js +32 -101
  220. package/dist/tests.js +12 -51
  221. package/dist/transformers.js +61 -164
  222. package/dist/types/authToken.d.ts +3 -3
  223. package/dist/types/mcpServiceToken.d.ts +2 -2
  224. package/dist/types/membership.d.ts +23 -0
  225. package/dist/types/membership.js +2 -0
  226. package/dist/types/notification.d.ts +28 -0
  227. package/dist/types/notification.js +2 -0
  228. package/dist/types/notificationPreference.d.ts +20 -0
  229. package/dist/types/notificationPreference.js +2 -0
  230. package/dist/types/organization.d.ts +36 -0
  231. package/dist/types/organization.js +2 -0
  232. package/dist/utils.js +31 -93
  233. package/dist/vendor/wesleytodd-openapi/index.js +37 -51
  234. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
  235. package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
  236. package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
  237. package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
  238. package/dist/versionCheckPlugin.js +52 -100
  239. package/dist/webhooks/headerValue.js +2 -2
  240. package/dist/webhooks/idempotency/memoryStore.js +16 -59
  241. package/dist/webhooks/idempotency/mongoStore.js +55 -130
  242. package/dist/webhooks/idempotency/webhookReceipt.d.ts +4 -49
  243. package/dist/webhooks/idempotency/webhookReceipt.js +14 -14
  244. package/dist/webhooks/rawBody.d.ts +1 -0
  245. package/dist/webhooks/rawBody.js +2 -1
  246. package/dist/webhooks/timingSafeEqual.js +4 -5
  247. package/dist/webhooks/verifiers/hmac.js +17 -18
  248. package/dist/webhooks/verifiers/sendgrid.js +20 -22
  249. package/dist/webhooks/verifiers/stripe.js +31 -65
  250. package/dist/webhooks/verifiers/twilio.js +23 -73
  251. package/dist/webhooks/webhooksApp.js +78 -177
  252. package/dist/zodOpenApi.js +2 -2
  253. package/package.json +34 -28
  254. package/src/__snapshots__/openApi.test.ts.snap +192 -54
  255. package/src/__snapshots__/openApiBuilder.test.ts.snap +0 -18
  256. package/src/__snapshots__/schemaMetadata.test.ts.snap +0 -1
  257. package/src/__tests__/browserLogsRoute.test.ts +165 -0
  258. package/src/adminTypes.ts +8 -0
  259. package/src/api.test.ts +39 -2
  260. package/src/api.ts +68 -0
  261. package/src/audit/auditApp.test.ts +243 -0
  262. package/src/audit/auditApp.ts +139 -0
  263. package/src/audit/auditEventModel.ts +160 -0
  264. package/src/audit/auditRouter.test.ts +456 -0
  265. package/src/audit/cloudTasksEnqueue.test.ts +124 -0
  266. package/src/audit/cloudTasksEnqueue.ts +104 -0
  267. package/src/audit/diff.ts +163 -0
  268. package/src/audit/processQueue.ts +69 -0
  269. package/src/audit/rbacSink.test.ts +86 -0
  270. package/src/audit/rbacSink.ts +42 -0
  271. package/src/audit/record.test.ts +402 -0
  272. package/src/audit/record.ts +329 -0
  273. package/src/auth.test.ts +1 -1
  274. package/src/auth.ts +1 -1
  275. package/src/authRecovery.test.ts +43 -0
  276. package/src/authRecovery.ts +16 -10
  277. package/src/authTokens.ts +6 -2
  278. package/src/authVerification.test.ts +22 -0
  279. package/src/betterAuth.ts +7 -0
  280. package/src/betterAuthSetup.test.ts +27 -0
  281. package/src/betterAuthSetup.ts +1 -0
  282. package/src/browserLogsRoute.ts +110 -0
  283. package/src/collectionRegistry.test.ts +8 -9
  284. package/src/collectionRegistry.ts +21 -1
  285. package/src/configurationPlugin.test.ts +1 -11
  286. package/src/express.d.ts +2 -0
  287. package/src/expressServer.test.ts +50 -2
  288. package/src/expressServer.ts +10 -0
  289. package/src/frameworkModelNames.test.ts +62 -0
  290. package/src/frameworkModelNames.ts +33 -0
  291. package/src/index.ts +76 -0
  292. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  293. package/src/mcp/auth.test.ts +34 -1
  294. package/src/mcp/handlers.test.ts +275 -0
  295. package/src/mcp/query.ts +3 -3
  296. package/src/mcp/toolGenerator.test.ts +81 -0
  297. package/src/migrations/cli.test.ts +353 -0
  298. package/src/migrations/cli.ts +283 -0
  299. package/src/migrations/fixtures/all-down/20260910120000-one.ts +6 -0
  300. package/src/migrations/fixtures/all-down/20260910120001-two.ts +6 -0
  301. package/src/migrations/fixtures/bad-id/20260910120000-mismatch.ts +4 -0
  302. package/src/migrations/fixtures/bad-name/not-a-migration.ts +4 -0
  303. package/src/migrations/fixtures/missing-up/20260910120000-noup.ts +2 -0
  304. package/src/migrations/fixtures/valid/20260910120000-alpha.ts +4 -0
  305. package/src/migrations/fixtures/valid/20260910120001-beta.ts +6 -0
  306. package/src/migrations/generate.test.ts +333 -0
  307. package/src/migrations/generate.ts +216 -0
  308. package/src/migrations/load.test.ts +103 -0
  309. package/src/migrations/load.ts +124 -0
  310. package/src/migrations/lock.test.ts +133 -0
  311. package/src/migrations/lock.ts +118 -0
  312. package/src/migrations/runner.test.ts +504 -0
  313. package/src/migrations/runner.ts +358 -0
  314. package/src/migrations/schemaCatalog.test.ts +159 -0
  315. package/src/migrations/schemaCatalog.ts +262 -0
  316. package/src/migrations/types.ts +94 -0
  317. package/src/models/mcpServiceToken.ts +4 -3
  318. package/src/models/notification.ts +69 -0
  319. package/src/models/notificationPreference.ts +62 -0
  320. package/src/notifications/notificationService.ts +254 -0
  321. package/src/notifications/notificationsApp.test.ts +528 -0
  322. package/src/notifications/notificationsApp.ts +200 -0
  323. package/src/notifications/notificationsBeforeSend.ts +51 -0
  324. package/src/notifiers/slackNotifier.test.ts +186 -1
  325. package/src/notifiers/slackNotifier.ts +167 -8
  326. package/src/openApi.test.ts +0 -1
  327. package/src/openApi.ts +2 -1
  328. package/src/openApiBuilder.ts +14 -3
  329. package/src/openApiValidator.test.ts +221 -2
  330. package/src/openApiValidator.ts +218 -33
  331. package/src/orgs/orgAccessOptIn.test.ts +87 -0
  332. package/src/orgs/orgContext.test.ts +259 -0
  333. package/src/orgs/orgContext.ts +151 -0
  334. package/src/orgs/orgPermissions.test.ts +105 -0
  335. package/src/orgs/orgPermissions.ts +40 -0
  336. package/src/orgs/orgPlugin.test.ts +130 -0
  337. package/src/orgs/orgPlugin.ts +70 -0
  338. package/src/orgs/orgRbac.test.ts +267 -0
  339. package/src/orgs/orgSecurityDefects.test.ts +415 -0
  340. package/src/orgs/organizationModel.test.ts +205 -0
  341. package/src/orgs/organizationModel.ts +262 -0
  342. package/src/orgs/organizationSettings.test.ts +113 -0
  343. package/src/orgs/organizationSettings.ts +126 -0
  344. package/src/orgs/orgsApp.test.ts +382 -0
  345. package/src/orgs/orgsApp.ts +563 -0
  346. package/src/permissions.test.ts +62 -36
  347. package/src/permissions.ts +8 -30
  348. package/src/plugins.test.ts +5 -0
  349. package/src/plugins.ts +3 -0
  350. package/src/rateLimit/middleware.ts +1 -1
  351. package/src/rateLimit/mongoStore.ts +1 -0
  352. package/src/rateLimit/policies.ts +2 -2
  353. package/src/rateLimit/redisStore.ts +1 -0
  354. package/src/rbac/access.ts +11 -3
  355. package/src/rbac/membershipOrgAdminSource.ts +59 -0
  356. package/src/rbac/modelRouterAccess.ts +3 -0
  357. package/src/rbac/permissionUtils.test.ts +26 -5
  358. package/src/rbac/resolve.test.ts +34 -2
  359. package/src/rbac/resolve.ts +26 -7
  360. package/src/rbac/roleModel.test.ts +34 -1
  361. package/src/rbac/roleModel.ts +17 -1
  362. package/src/rbac/statements.test.ts +19 -0
  363. package/src/rbac/statements.ts +19 -1
  364. package/src/rbac/types.ts +5 -0
  365. package/src/realtime/changeStreamWatcher.ts +73 -33
  366. package/src/realtime/deprecation.ts +1 -0
  367. package/src/realtime/realtime.test.ts +357 -185
  368. package/src/realtime/realtimeApp.ts +2 -1
  369. package/src/schemaMetadata.test.ts +14 -0
  370. package/src/schemaMetadata.ts +5 -5
  371. package/src/sync/adminBroadcastConfig.test.ts +96 -0
  372. package/src/sync/adminBroadcastScope.test.ts +155 -0
  373. package/src/sync/adminBroadcastScope.ts +123 -0
  374. package/src/sync/adminWindowAccess.test.ts +57 -0
  375. package/src/sync/adminWindowAccess.ts +32 -0
  376. package/src/sync/adminWindowMutation.test.ts +450 -0
  377. package/src/sync/adminWindowMutation.ts +283 -0
  378. package/src/sync/executors.ts +33 -6
  379. package/src/sync/integration.test.ts +2 -2
  380. package/src/sync/mutationHandler.test.ts +277 -1
  381. package/src/sync/mutationHandler.ts +171 -29
  382. package/src/sync/registry.ts +4 -0
  383. package/src/sync/routes.ts +52 -8
  384. package/src/sync/socketHandlers.ts +154 -58
  385. package/src/sync/streams.ts +6 -0
  386. package/src/sync/sync.test.ts +3 -2
  387. package/src/sync/syncApp.ts +2 -1
  388. package/src/sync/syncBatch.ts +7 -2
  389. package/src/sync/syncRoutes.test.ts +297 -3
  390. package/src/sync/syncSocket.test.ts +229 -0
  391. package/src/sync/types.ts +20 -0
  392. package/src/terrenoApp.migrations.test.ts +114 -0
  393. package/src/terrenoApp.test.ts +41 -0
  394. package/src/terrenoApp.ts +97 -31
  395. package/src/tests/createTestData.ts +2 -2
  396. package/src/tests/models.ts +10 -2
  397. package/src/tests/testHelper.ts +1 -7
  398. package/src/types/authToken.ts +2 -4
  399. package/src/types/mcpServiceToken.ts +1 -7
  400. package/src/types/membership.ts +48 -0
  401. package/src/types/notification.ts +34 -0
  402. package/src/types/notificationPreference.ts +28 -0
  403. package/src/types/organization.ts +49 -0
  404. package/src/types.d.ts +1 -0
  405. package/src/webhooks/idempotency/webhookReceipt.ts +8 -10
  406. package/src/webhooks/rawBody.test.ts +33 -0
  407. package/src/webhooks/rawBody.ts +1 -0
  408. package/tsconfig.json +13 -54
  409. package/tsconfig.typedoc.json +4 -1
  410. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.d.ts +0 -2
  411. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
  412. package/src/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
package/dist/auth.js CHANGED
@@ -1,125 +1,30 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
- var __rest = (this && this.__rest) || function (s, e) {
50
- var t = {};
51
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
52
- t[p] = s[p];
53
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
54
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
55
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
56
- t[p[i]] = s[p[i]];
57
- }
58
- return t;
59
- };
60
- var __values = (this && this.__values) || function(o) {
61
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
62
- if (m) return m.call(o);
63
- if (o && typeof o.length === "number") return {
64
- next: function () {
65
- if (o && i >= o.length) o = void 0;
66
- return { value: o && o[i++], done: !o };
67
- }
68
- };
69
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
70
- };
71
- var __read = (this && this.__read) || function (o, n) {
72
- var m = typeof Symbol === "function" && o[Symbol.iterator];
73
- if (!m) return o;
74
- var i = m.call(o), r, ar = [], e;
75
- try {
76
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
77
- }
78
- catch (error) { e = { error: error }; }
79
- finally {
80
- try {
81
- if (r && !r.done && (m = i["return"])) m.call(i);
82
- }
83
- finally { if (e) throw e.error; }
84
- }
85
- return ar;
86
- };
87
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
88
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
89
- if (ar || !(i in from)) {
90
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
91
- ar[i] = from[i];
92
- }
93
- }
94
- return to.concat(ar || Array.prototype.slice.call(from));
95
- };
96
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
97
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
98
4
  };
99
5
  Object.defineProperty(exports, "__esModule", { value: true });
100
6
  exports.addMeRoutes = exports.addAuthRoutes = exports.setupAuth = exports.generateTokens = exports.setPasswordForUser = exports.MAX_PASSWORD_LENGTH = exports.signupUser = exports.omitUserRolesFromWriteBody = exports.stripPrivilegedUserFields = exports.PRIVILEGED_USER_FIELDS = exports.authenticateMiddleware = void 0;
101
- var node_crypto_1 = require("node:crypto");
102
- var express_1 = __importDefault(require("express"));
103
- var jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
104
- var luxon_1 = require("luxon");
105
- var ms_1 = __importDefault(require("ms"));
106
- var passport_1 = __importDefault(require("passport"));
107
- var passport_anonymous_1 = require("passport-anonymous");
108
- var passport_jwt_1 = require("passport-jwt");
109
- var passport_local_1 = require("passport-local");
110
- var authRecovery_1 = require("./authRecovery");
111
- var authTokens_1 = require("./authTokens");
112
- var errors_1 = require("./errors");
113
- var logger_1 = require("./logger");
114
- var policies_1 = require("./rateLimit/policies");
115
- var requestContext_1 = require("./requestContext");
116
- var authenticateMiddleware = function (anonymous) {
117
- if (anonymous === void 0) { anonymous = false; }
118
- var strategies = ["jwt"];
7
+ const node_crypto_1 = require("node:crypto");
8
+ const express_1 = __importDefault(require("express"));
9
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
10
+ const luxon_1 = require("luxon");
11
+ const ms_1 = __importDefault(require("ms"));
12
+ const passport_1 = __importDefault(require("passport"));
13
+ const passport_anonymous_1 = require("passport-anonymous");
14
+ const passport_jwt_1 = require("passport-jwt");
15
+ const passport_local_1 = require("passport-local");
16
+ const authRecovery_1 = require("./authRecovery");
17
+ const authTokens_1 = require("./authTokens");
18
+ const errors_1 = require("./errors");
19
+ const logger_1 = require("./logger");
20
+ const policies_1 = require("./rateLimit/policies");
21
+ const requestContext_1 = require("./requestContext");
22
+ const authenticateMiddleware = (anonymous = false) => {
23
+ const strategies = ["jwt"];
119
24
  if (anonymous) {
120
25
  strategies.push("anonymous");
121
26
  }
122
- return function (req, res, next) {
27
+ return (req, res, next) => {
123
28
  if (req.user) {
124
29
  return next();
125
30
  }
@@ -131,7 +36,7 @@ var authenticateMiddleware = function (anonymous) {
131
36
  // matches on, so the response contract is unchanged.
132
37
  // (The anonymous strategy calls pass(), which skips this callback and
133
38
  // continues the chain with no user — same as before.)
134
- return passport_1.default.authenticate(strategies, { session: false }, function (err, user, info) {
39
+ return passport_1.default.authenticate(strategies, { session: false }, (err, user, info) => {
135
40
  if (err) {
136
41
  return next(err);
137
42
  }
@@ -141,7 +46,7 @@ var authenticateMiddleware = function (anonymous) {
141
46
  req.user = user;
142
47
  // req.logIn used to populate authInfo; keep that passport-public API
143
48
  // intact for downstream consumers.
144
- req.authInfo = (info !== null && info !== void 0 ? info : {});
49
+ req.authInfo = (info ?? {});
145
50
  return next();
146
51
  })(req, res, next);
147
52
  };
@@ -164,64 +69,42 @@ exports.PRIVILEGED_USER_FIELDS = [
164
69
  * Removes {@link PRIVILEGED_USER_FIELDS} from a self-service body. Fields are dropped rather
165
70
  * than rejected so clients that echo a whole user object back still succeed.
166
71
  */
167
- var stripPrivilegedUserFields = function (body, context) {
168
- var e_1, _a;
169
- var sanitized = {};
170
- var dropped = [];
171
- try {
172
- for (var _b = __values(Object.entries(body)), _c = _b.next(); !_c.done; _c = _b.next()) {
173
- var _d = __read(_c.value, 2), key = _d[0], value = _d[1];
174
- if (exports.PRIVILEGED_USER_FIELDS.includes(key)) {
175
- dropped.push(key);
176
- continue;
177
- }
178
- sanitized[key] = value;
179
- }
180
- }
181
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
182
- finally {
183
- try {
184
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
72
+ const stripPrivilegedUserFields = (body, context) => {
73
+ const sanitized = {};
74
+ const dropped = [];
75
+ for (const [key, value] of Object.entries(body)) {
76
+ if (exports.PRIVILEGED_USER_FIELDS.includes(key)) {
77
+ dropped.push(key);
78
+ continue;
185
79
  }
186
- finally { if (e_1) throw e_1.error; }
80
+ sanitized[key] = value;
187
81
  }
188
82
  if (dropped.length > 0) {
189
- logger_1.logger.warn("Ignored privileged user fields on ".concat(context, ": ").concat(dropped.join(", ")));
83
+ logger_1.logger.warn(`Ignored privileged user fields on ${context}: ${dropped.join(", ")}`);
190
84
  }
191
85
  return sanitized;
192
86
  };
193
87
  exports.stripPrivilegedUserFields = stripPrivilegedUserFields;
194
- var isEmailUpdateChangingMailbox = function (currentEmail, nextEmail) {
88
+ const isEmailUpdateChangingMailbox = (currentEmail, nextEmail) => {
195
89
  if (typeof currentEmail !== "string" || typeof nextEmail !== "string") {
196
90
  return false;
197
91
  }
198
92
  return currentEmail.trim().toLowerCase() !== nextEmail.trim().toLowerCase();
199
93
  };
200
- var omitPrivilegedFieldsFromObject = function (item, allowAdminWrite) {
201
- var e_2, _a;
94
+ const omitPrivilegedFieldsFromObject = (item, allowAdminWrite) => {
202
95
  if (!item || typeof item !== "object" || Array.isArray(item)) {
203
96
  return item;
204
97
  }
205
- var record = item;
206
- var fieldsToDrop = exports.PRIVILEGED_USER_FIELDS.filter(function (field) { return field in record && !(field === "admin" && allowAdminWrite); });
98
+ const record = item;
99
+ const fieldsToDrop = exports.PRIVILEGED_USER_FIELDS.filter((field) => field in record && !(field === "admin" && allowAdminWrite));
207
100
  if (fieldsToDrop.length === 0) {
208
101
  return item;
209
102
  }
210
- var next = __assign({}, record);
211
- try {
212
- for (var fieldsToDrop_1 = __values(fieldsToDrop), fieldsToDrop_1_1 = fieldsToDrop_1.next(); !fieldsToDrop_1_1.done; fieldsToDrop_1_1 = fieldsToDrop_1.next()) {
213
- var field = fieldsToDrop_1_1.value;
214
- Reflect.deleteProperty(next, field);
215
- }
103
+ const next = { ...record };
104
+ for (const field of fieldsToDrop) {
105
+ Reflect.deleteProperty(next, field);
216
106
  }
217
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
218
- finally {
219
- try {
220
- if (fieldsToDrop_1_1 && !fieldsToDrop_1_1.done && (_a = fieldsToDrop_1.return)) _a.call(fieldsToDrop_1);
221
- }
222
- finally { if (e_2) throw e_2.error; }
223
- }
224
- logger_1.logger.warn("Ignored privileged User fields on a modelRouter write: ".concat(fieldsToDrop.join(", ")));
107
+ logger_1.logger.warn(`Ignored privileged User fields on a modelRouter write: ${fieldsToDrop.join(", ")}`);
225
108
  return next;
226
109
  };
227
110
  /**
@@ -229,55 +112,41 @@ var omitPrivilegedFieldsFromObject = function (item, allowAdminWrite) {
229
112
  * writes on `/users`, sync, or MCP. AdminApp captures role assignments before this runs and
230
113
  * explicitly marks authorized legacy-admin writes after its additional checks.
231
114
  */
232
- var omitUserRolesFromWriteBody = function (modelName, accessControl, body, allowAdminWrite) {
233
- if (allowAdminWrite === void 0) { allowAdminWrite = false; }
115
+ const omitUserRolesFromWriteBody = (modelName, accessControl, body, allowAdminWrite = false) => {
234
116
  if (modelName !== "User" || !accessControl || body == null) {
235
117
  return body;
236
118
  }
237
119
  if (Array.isArray(body)) {
238
- return body.map(function (item) { return omitPrivilegedFieldsFromObject(item, allowAdminWrite); });
120
+ return body.map((item) => omitPrivilegedFieldsFromObject(item, allowAdminWrite));
239
121
  }
240
122
  return omitPrivilegedFieldsFromObject(body, allowAdminWrite);
241
123
  };
242
124
  exports.omitUserRolesFromWriteBody = omitUserRolesFromWriteBody;
243
- var signupUser = function (userModel, email, password, body) { return __awaiter(void 0, void 0, void 0, function () {
244
- var _a, _email, _password, rawBody, bodyRest, registrableModel, user, error_1, error_2, message;
245
- return __generator(this, function (_b) {
246
- switch (_b.label) {
247
- case 0:
248
- _a = body !== null && body !== void 0 ? body : {}, _email = _a.email, _password = _a.password, rawBody = __rest(_a, ["email", "password"]);
249
- bodyRest = (0, exports.stripPrivilegedUserFields)(rawBody, "signup");
250
- _b.label = 1;
251
- case 1:
252
- _b.trys.push([1, 8, , 9]);
253
- registrableModel = userModel;
254
- return [4 /*yield*/, registrableModel.register(__assign({ email: email }, bodyRest), password)];
255
- case 2:
256
- user = _b.sent();
257
- if (!user.postCreate) return [3 /*break*/, 6];
258
- _b.label = 3;
259
- case 3:
260
- _b.trys.push([3, 5, , 6]);
261
- return [4 /*yield*/, user.postCreate(bodyRest)];
262
- case 4:
263
- _b.sent();
264
- return [3 /*break*/, 6];
265
- case 5:
266
- error_1 = _b.sent();
267
- logger_1.logger.error("Error in user.postCreate: ".concat(error_1));
268
- throw error_1;
269
- case 6: return [4 /*yield*/, user.save()];
270
- case 7:
271
- _b.sent();
272
- return [2 /*return*/, user];
273
- case 8:
274
- error_2 = _b.sent();
275
- message = (0, errors_1.errorMessage)(error_2);
276
- throw new errors_1.APIError({ title: message });
277
- case 9: return [2 /*return*/];
125
+ const signupUser = async (userModel, email, password, body) => {
126
+ // Strip email and password from the body. They can cause mongoose to throw an error if strict is
127
+ // set.
128
+ const { email: _email, password: _password, ...rawBody } = body ?? {};
129
+ const bodyRest = (0, exports.stripPrivilegedUserFields)(rawBody, "signup");
130
+ try {
131
+ const registrableModel = userModel;
132
+ const user = await registrableModel.register({ email, ...bodyRest }, password);
133
+ if (user.postCreate) {
134
+ try {
135
+ await user.postCreate(bodyRest);
136
+ }
137
+ catch (error) {
138
+ logger_1.logger.error(`Error in user.postCreate: ${error}`);
139
+ throw error;
140
+ }
278
141
  }
279
- });
280
- }); };
142
+ await user.save();
143
+ return user;
144
+ }
145
+ catch (error) {
146
+ const message = (0, errors_1.errorMessage)(error);
147
+ throw new errors_1.APIError({ title: message });
148
+ }
149
+ };
281
150
  exports.signupUser = signupUser;
282
151
  /** Upper bound on password length accepted by {@link setPasswordForUser} (D5). */
283
152
  exports.MAX_PASSWORD_LENGTH = 256;
@@ -293,75 +162,58 @@ exports.MAX_PASSWORD_LENGTH = 256;
293
162
  * password change), logs a `logger.info` audit line with the admin id, target user id, and
294
163
  * timestamp — NEVER the password itself.
295
164
  */
296
- var setPasswordForUser = function (user_1, password_1) {
297
- var args_1 = [];
298
- for (var _i = 2; _i < arguments.length; _i++) {
299
- args_1[_i - 2] = arguments[_i];
165
+ const setPasswordForUser = async (user, password, timeoutMs = 15_000, audit) => {
166
+ if (password.length > exports.MAX_PASSWORD_LENGTH) {
167
+ throw new errors_1.APIError({
168
+ status: 400,
169
+ title: `Password must be at most ${exports.MAX_PASSWORD_LENGTH} characters`,
170
+ });
300
171
  }
301
- return __awaiter(void 0, __spreadArray([user_1, password_1], __read(args_1), false), void 0, function (user, password, timeoutMs, audit) {
302
- var targetUserId;
303
- var _a, _b;
304
- if (timeoutMs === void 0) { timeoutMs = 15000; }
305
- return __generator(this, function (_c) {
306
- switch (_c.label) {
307
- case 0:
308
- if (password.length > exports.MAX_PASSWORD_LENGTH) {
309
- throw new errors_1.APIError({
310
- status: 400,
311
- title: "Password must be at most ".concat(exports.MAX_PASSWORD_LENGTH, " characters"),
312
- });
313
- }
314
- if ((audit === null || audit === void 0 ? void 0 : audit.adminId) !== undefined) {
315
- targetUserId = (_b = (_a = user._id) !== null && _a !== void 0 ? _a : user.id) !== null && _b !== void 0 ? _b : "unknown";
316
- logger_1.logger.info("[auth] Admin ".concat(String(audit.adminId), " set password for user ").concat(String(targetUserId), " ") +
317
- "at ".concat(luxon_1.DateTime.now().toISO()));
318
- }
319
- return [4 /*yield*/, new Promise(function (resolve, reject) {
320
- var isSettled = false;
321
- var timeout = setTimeout(function () {
322
- if (isSettled) {
323
- return;
324
- }
325
- isSettled = true;
326
- reject(new Error("Timed out while setting password"));
327
- }, timeoutMs);
328
- var resolveOnce = function () {
329
- if (isSettled) {
330
- return;
331
- }
332
- isSettled = true;
333
- clearTimeout(timeout);
334
- resolve();
335
- };
336
- var rejectOnce = function (error) {
337
- if (isSettled) {
338
- return;
339
- }
340
- isSettled = true;
341
- clearTimeout(timeout);
342
- reject(error);
343
- };
344
- try {
345
- var maybePromise = user.setPassword(password, function (error) {
346
- if (error) {
347
- rejectOnce(error);
348
- return;
349
- }
350
- resolveOnce();
351
- });
352
- if (maybePromise && typeof maybePromise.then === "function") {
353
- maybePromise.then(resolveOnce).catch(rejectOnce);
354
- }
355
- }
356
- catch (error) {
357
- rejectOnce(error);
358
- }
359
- })];
360
- case 1:
361
- _c.sent();
362
- return [2 /*return*/];
172
+ if (audit?.adminId !== undefined) {
173
+ const targetUserId = user._id ?? user.id ?? "unknown";
174
+ logger_1.logger.info(`[auth] Admin ${String(audit.adminId)} set password for user ${String(targetUserId)} ` +
175
+ `at ${luxon_1.DateTime.now().toISO()}`);
176
+ }
177
+ await new Promise((resolve, reject) => {
178
+ let isSettled = false;
179
+ const timeout = setTimeout(() => {
180
+ if (isSettled) {
181
+ return;
363
182
  }
364
- });
183
+ isSettled = true;
184
+ reject(new Error("Timed out while setting password"));
185
+ }, timeoutMs);
186
+ const resolveOnce = () => {
187
+ if (isSettled) {
188
+ return;
189
+ }
190
+ isSettled = true;
191
+ clearTimeout(timeout);
192
+ resolve();
193
+ };
194
+ const rejectOnce = (error) => {
195
+ if (isSettled) {
196
+ return;
197
+ }
198
+ isSettled = true;
199
+ clearTimeout(timeout);
200
+ reject(error);
201
+ };
202
+ try {
203
+ const maybePromise = user.setPassword(password, (error) => {
204
+ if (error) {
205
+ rejectOnce(error);
206
+ return;
207
+ }
208
+ resolveOnce();
209
+ });
210
+ if (maybePromise && typeof maybePromise.then === "function") {
211
+ maybePromise.then(resolveOnce).catch(rejectOnce);
212
+ }
213
+ }
214
+ catch (error) {
215
+ rejectOnce(error);
216
+ }
365
217
  });
366
218
  };
367
219
  exports.setPasswordForUser = setPasswordForUser;
@@ -369,9 +221,9 @@ exports.setPasswordForUser = setPasswordForUser;
369
221
  * Returns the duration when `ms` can parse it, otherwise logs and returns undefined so the caller
370
222
  * keeps its default. Signing a token with an unparseable duration throws instead.
371
223
  */
372
- var validateDuration = function (envName, value) {
224
+ const validateDuration = (envName, value) => {
373
225
  if ((0, ms_1.default)(value) === undefined) {
374
- logger_1.logger.error("".concat(envName, " is not a valid duration: \"").concat(value, "\". Using the default instead."));
226
+ logger_1.logger.error(`${envName} is not a valid duration: "${value}". Using the default instead.`);
375
227
  return undefined;
376
228
  }
377
229
  return value;
@@ -393,76 +245,66 @@ var validateDuration = function (envName, value) {
393
245
  * authentication providers) to reuse and customize the same token generation logic.
394
246
  * This ensures consistent and secure token issuance across different authentication flows.
395
247
  */
396
- var generateTokens = function (user_1, authOptions_1) {
397
- var args_1 = [];
398
- for (var _i = 2; _i < arguments.length; _i++) {
399
- args_1[_i - 2] = arguments[_i];
248
+ const generateTokens = async (user, authOptions, options = {}) => {
249
+ const tokenSecretOrKey = process.env.TOKEN_SECRET;
250
+ if (!tokenSecretOrKey) {
251
+ throw new errors_1.APIError({ status: 500, title: "TOKEN_SECRET must be set in env." });
400
252
  }
401
- return __awaiter(void 0, __spreadArray([user_1, authOptions_1], __read(args_1), false), void 0, function (user, authOptions, options) {
402
- var tokenSecretOrKey, tokenUser, sessionId, authUser, payload, tokenOptions, expiresIn, token, refreshTokenSecretOrKey, refreshToken, refreshTokenOptions, expiresIn;
403
- var _a, _b;
404
- if (options === void 0) { options = {}; }
405
- return __generator(this, function (_c) {
406
- tokenSecretOrKey = process.env.TOKEN_SECRET;
407
- if (!tokenSecretOrKey) {
408
- throw new errors_1.APIError({ status: 500, title: "TOKEN_SECRET must be set in env." });
409
- }
410
- tokenUser = user;
411
- if (!(tokenUser === null || tokenUser === void 0 ? void 0 : tokenUser._id)) {
412
- logger_1.logger.warn("No user found for token generation");
413
- return [2 /*return*/, { refreshToken: null, token: null }];
414
- }
415
- sessionId = (_a = options.sessionId) !== null && _a !== void 0 ? _a : (0, node_crypto_1.randomUUID)();
416
- authUser = user;
417
- payload = {
418
- id: String(tokenUser._id),
419
- sid: sessionId,
420
- te: (_b = authUser.tokenEpoch) !== null && _b !== void 0 ? _b : 0,
421
- };
422
- if (authOptions === null || authOptions === void 0 ? void 0 : authOptions.generateJWTPayload) {
423
- payload = __assign(__assign({}, authOptions.generateJWTPayload(authUser)), payload);
424
- }
425
- tokenOptions = {
426
- expiresIn: "15m",
427
- };
428
- if (authOptions === null || authOptions === void 0 ? void 0 : authOptions.generateTokenExpiration) {
429
- tokenOptions.expiresIn = authOptions.generateTokenExpiration(authUser);
430
- }
431
- else if (process.env.TOKEN_EXPIRES_IN) {
432
- expiresIn = validateDuration("TOKEN_EXPIRES_IN", process.env.TOKEN_EXPIRES_IN);
433
- if (expiresIn) {
434
- tokenOptions.expiresIn = expiresIn;
435
- }
436
- }
437
- if (process.env.TOKEN_ISSUER) {
438
- tokenOptions.issuer = process.env.TOKEN_ISSUER;
439
- }
440
- token = jsonwebtoken_1.default.sign(payload, tokenSecretOrKey, tokenOptions);
441
- refreshTokenSecretOrKey = process.env.REFRESH_TOKEN_SECRET;
442
- if (refreshTokenSecretOrKey) {
443
- refreshTokenOptions = {
444
- expiresIn: "30d",
445
- };
446
- if (authOptions === null || authOptions === void 0 ? void 0 : authOptions.generateRefreshTokenExpiration) {
447
- refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(authUser);
448
- }
449
- else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
450
- expiresIn = validateDuration("REFRESH_TOKEN_EXPIRES_IN", process.env.REFRESH_TOKEN_EXPIRES_IN);
451
- if (expiresIn) {
452
- refreshTokenOptions.expiresIn = expiresIn;
453
- }
454
- }
455
- refreshToken = jsonwebtoken_1.default.sign(payload, refreshTokenSecretOrKey, refreshTokenOptions);
456
- }
457
- else {
458
- logger_1.logger.info("REFRESH_TOKEN_SECRET not set so refresh tokens will not be issued");
253
+ const tokenUser = user;
254
+ if (!tokenUser?._id) {
255
+ logger_1.logger.warn("No user found for token generation");
256
+ return { refreshToken: null, token: null };
257
+ }
258
+ const sessionId = options.sessionId ?? (0, node_crypto_1.randomUUID)();
259
+ const authUser = user;
260
+ let payload = {
261
+ id: String(tokenUser._id),
262
+ sid: sessionId,
263
+ te: authUser.tokenEpoch ?? 0,
264
+ };
265
+ if (authOptions?.generateJWTPayload) {
266
+ payload = { ...authOptions.generateJWTPayload(authUser), ...payload };
267
+ }
268
+ const tokenOptions = {
269
+ expiresIn: "15m",
270
+ };
271
+ if (authOptions?.generateTokenExpiration) {
272
+ tokenOptions.expiresIn = authOptions.generateTokenExpiration(authUser);
273
+ }
274
+ else if (process.env.TOKEN_EXPIRES_IN) {
275
+ const expiresIn = validateDuration("TOKEN_EXPIRES_IN", process.env.TOKEN_EXPIRES_IN);
276
+ if (expiresIn) {
277
+ tokenOptions.expiresIn = expiresIn;
278
+ }
279
+ }
280
+ if (process.env.TOKEN_ISSUER) {
281
+ tokenOptions.issuer = process.env.TOKEN_ISSUER;
282
+ }
283
+ const token = jsonwebtoken_1.default.sign(payload, tokenSecretOrKey, tokenOptions);
284
+ const refreshTokenSecretOrKey = process.env.REFRESH_TOKEN_SECRET;
285
+ let refreshToken;
286
+ if (refreshTokenSecretOrKey) {
287
+ const refreshTokenOptions = {
288
+ expiresIn: "30d",
289
+ };
290
+ if (authOptions?.generateRefreshTokenExpiration) {
291
+ refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(authUser);
292
+ }
293
+ else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
294
+ const expiresIn = validateDuration("REFRESH_TOKEN_EXPIRES_IN", process.env.REFRESH_TOKEN_EXPIRES_IN);
295
+ if (expiresIn) {
296
+ refreshTokenOptions.expiresIn = expiresIn;
459
297
  }
460
- return [2 /*return*/, { refreshToken: refreshToken, sessionId: sessionId, token: token }];
461
- });
462
- });
298
+ }
299
+ refreshToken = jsonwebtoken_1.default.sign(payload, refreshTokenSecretOrKey, refreshTokenOptions);
300
+ }
301
+ else {
302
+ logger_1.logger.info("REFRESH_TOKEN_SECRET not set so refresh tokens will not be issued");
303
+ }
304
+ return { refreshToken, sessionId, token };
463
305
  };
464
306
  exports.generateTokens = generateTokens;
465
- var setupAuth = function (app, userModel) {
307
+ const setupAuth = (app, userModel) => {
466
308
  if (!userModel.createStrategy) {
467
309
  throw new errors_1.APIError({ status: 500, title: "setupAuth userModel must have .createStrategy()" });
468
310
  }
@@ -472,33 +314,21 @@ var setupAuth = function (app, userModel) {
472
314
  passReqToCallback: true,
473
315
  passwordField: "password",
474
316
  usernameField: "email",
475
- }, function (req, email, password, done) { return __awaiter(void 0, void 0, void 0, function () {
476
- var _a, _b, error_3;
477
- return __generator(this, function (_c) {
478
- switch (_c.label) {
479
- case 0:
480
- _c.trys.push([0, 2, , 3]);
481
- _a = done;
482
- _b = [undefined];
483
- return [4 /*yield*/, (0, exports.signupUser)(userModel, email, password, req.body)];
484
- case 1:
485
- _a.apply(void 0, _b.concat([_c.sent()]));
486
- return [3 /*break*/, 3];
487
- case 2:
488
- error_3 = _c.sent();
489
- return [2 /*return*/, done(error_3)];
490
- case 3: return [2 /*return*/];
491
- }
492
- });
493
- }); }));
494
- var customTokenExtractor = function (req) {
495
- var _a, _b, _c;
496
- var token = null;
497
- if ((_a = req === null || req === void 0 ? void 0 : req.cookies) === null || _a === void 0 ? void 0 : _a.jwt) {
317
+ }, async (req, email, password, done) => {
318
+ try {
319
+ done(undefined, await (0, exports.signupUser)(userModel, email, password, req.body));
320
+ }
321
+ catch (error) {
322
+ return done(error);
323
+ }
324
+ }));
325
+ const customTokenExtractor = (req) => {
326
+ let token = null;
327
+ if (req?.cookies?.jwt) {
498
328
  token = req.cookies.jwt;
499
329
  }
500
- else if ((_b = req === null || req === void 0 ? void 0 : req.headers) === null || _b === void 0 ? void 0 : _b.authorization) {
501
- token = (_c = req === null || req === void 0 ? void 0 : req.headers) === null || _c === void 0 ? void 0 : _c.authorization.split(" ")[1];
330
+ else if (req?.headers?.authorization) {
331
+ token = req?.headers?.authorization.split(" ")[1];
502
332
  }
503
333
  return token;
504
334
  };
@@ -506,243 +336,199 @@ var setupAuth = function (app, userModel) {
506
336
  if (process.env.NODE_ENV !== "test") {
507
337
  logger_1.logger.debug("Setting up JWT Authentication");
508
338
  }
509
- var secretOrKey = process.env.TOKEN_SECRET;
510
- var jwtOpts = {
339
+ const secretOrKey = process.env.TOKEN_SECRET;
340
+ const jwtOpts = {
511
341
  issuer: process.env.TOKEN_ISSUER,
512
342
  jwtFromRequest: customTokenExtractor,
513
- secretOrKey: secretOrKey,
343
+ secretOrKey,
514
344
  };
515
- passport_1.default.use("jwt", new passport_jwt_1.Strategy(jwtOpts, function (jwtPayload, done) { return __awaiter(void 0, void 0, void 0, function () {
516
- var user, error_4;
517
- return __generator(this, function (_a) {
518
- switch (_a.label) {
519
- case 0:
520
- user = null;
521
- if (!jwtPayload) {
522
- return [2 /*return*/, done(null, false)];
523
- }
524
- _a.label = 1;
525
- case 1:
526
- _a.trys.push([1, 3, , 4]);
527
- return [4 /*yield*/, userModel.findById(jwtPayload.id)];
528
- case 2:
529
- user = _a.sent();
530
- return [3 /*break*/, 4];
531
- case 3:
532
- error_4 = _a.sent();
533
- logger_1.logger.warn("[jwt] Error finding user from id: ".concat(error_4));
534
- return [2 /*return*/, done(error_4, false)];
535
- case 4:
536
- if (user) {
537
- return [2 /*return*/, done(null, user)];
538
- }
539
- if (!userModel.createAnonymousUser) return [3 /*break*/, 6];
540
- logger_1.logger.info("[jwt] Creating anonymous user");
541
- return [4 /*yield*/, userModel.createAnonymousUser()];
542
- case 5:
543
- user = _a.sent();
544
- return [2 /*return*/, done(null, user)];
545
- case 6:
546
- logger_1.logger.info("[jwt] No user found from token");
547
- return [2 /*return*/, done(null, false)];
548
- }
549
- });
550
- }); }));
345
+ passport_1.default.use("jwt", new passport_jwt_1.Strategy(jwtOpts, async (jwtPayload, done) => {
346
+ let user = null;
347
+ if (!jwtPayload) {
348
+ return done(null, false);
349
+ }
350
+ try {
351
+ user = await userModel.findById(jwtPayload.id);
352
+ }
353
+ catch (error) {
354
+ logger_1.logger.warn(`[jwt] Error finding user from id: ${error}`);
355
+ return done(error, false);
356
+ }
357
+ if (user) {
358
+ return done(null, user);
359
+ }
360
+ if (userModel.createAnonymousUser) {
361
+ logger_1.logger.info("[jwt] Creating anonymous user");
362
+ user = await userModel.createAnonymousUser();
363
+ return done(null, user);
364
+ }
365
+ logger_1.logger.info("[jwt] No user found from token");
366
+ return done(null, false);
367
+ }));
551
368
  }
552
369
  // Adds req.user to the request. This may wind up duplicating requests with passport,
553
370
  // but passport doesn't give us req.user early enough.
554
- var decodeJWTMiddleware = function (req, res, next) { return __awaiter(void 0, void 0, void 0, function () {
555
- var token, decoded, userText, expiredAt, message, details, sessionId, user, error_5;
556
- var _a, _b, _c, _d;
557
- return __generator(this, function (_e) {
558
- switch (_e.label) {
559
- case 0:
560
- if (!process.env.TOKEN_SECRET) {
561
- return [2 /*return*/, next()];
562
- }
563
- // Login, signup, and refresh exchange credentials. A stale access JWT in
564
- // Authorization / the jwt cookie must not 401 before those handlers run.
565
- if ((0, policies_1.isJwtCredentialExchangePath)(req)) {
566
- return [2 /*return*/, next()];
567
- }
568
- // Allow requests with a "Secret" prefix to pass through since this is a string value,
569
- // not a jwt that needs to be decoded
570
- if (((_b = (_a = req === null || req === void 0 ? void 0 : req.headers) === null || _a === void 0 ? void 0 : _a.authorization) === null || _b === void 0 ? void 0 : _b.split(" ")[0]) === "Secret") {
571
- return [2 /*return*/, next()];
572
- }
573
- token = customTokenExtractor(req);
574
- // For some reason, our app will happily put null into the authorization header when logging
575
- // out then back in.
576
- if (!token || token === "null" || token === "undefined") {
577
- return [2 /*return*/, next()];
578
- }
579
- try {
580
- decoded = jsonwebtoken_1.default.verify(token, process.env.TOKEN_SECRET, {
581
- issuer: process.env.TOKEN_ISSUER,
582
- });
583
- }
584
- catch (error) {
585
- // A bearer token that is not a JWT at all (e.g. a Better Auth opaque session
586
- // token) is not ours to reject — fall through so a later auth layer (Better
587
- // Auth session middleware) or the route's own permissions can handle it.
588
- // Detect this by decoding the token's header/payload structure (D1) rather
589
- // than counting dot-delimited segments: an opaque token can coincidentally
590
- // contain exactly two dots, and a malformed-but-JWT-shaped string can fail
591
- // this same check for the wrong reason — `jwt.decode` parses the actual
592
- // base64url JSON structure of each segment, which dot-counting cannot.
593
- // Genuine JWTs that fail verification (malformed/expired) still return 401 so the
594
- // client's token-refresh flow is preserved.
595
- if (jsonwebtoken_1.default.decode(token, { complete: true }) === null) {
596
- return [2 /*return*/, next()];
597
- }
598
- userText = ((_c = req.user) === null || _c === void 0 ? void 0 : _c._id) ? " for user ".concat(req.user._id, " ") : "";
599
- expiredAt = error && typeof error === "object" && "expiredAt" in error
600
- ? error.expiredAt
601
- : undefined;
602
- message = (0, errors_1.errorMessage)(error);
603
- details = "[jwt] Error decoding token".concat(userText, ": ").concat(error, ", expired at ").concat(expiredAt, ", current time: ").concat(luxon_1.DateTime.now().toMillis());
604
- logger_1.logger.debug(details);
605
- return [2 /*return*/, res.status(401).json({ details: details, message: message })];
606
- }
607
- if (!(decoded === null || decoded === void 0 ? void 0 : decoded.id)) return [3 /*break*/, 4];
608
- sessionId = (0, requestContext_1.getSessionIdFromJwtPayload)(decoded);
609
- req.authTokenPayload = decoded;
610
- if (sessionId) {
611
- req.sessionId = sessionId;
612
- (0, requestContext_1.setRequestContext)({ sessionId: sessionId });
613
- }
614
- _e.label = 1;
615
- case 1:
616
- _e.trys.push([1, 3, , 4]);
617
- return [4 /*yield*/, userModel.findById(decoded.id)];
618
- case 2:
619
- user = _e.sent();
620
- req.user = user;
621
- (0, requestContext_1.updateRequestContextFromRequest)(req, res);
622
- if ((_d = req.user) === null || _d === void 0 ? void 0 : _d.disabled) {
623
- logger_1.logger.warn("[jwt] User ".concat(req.user.id, " is disabled"));
624
- return [2 /*return*/, res.status(401).json({ status: 401, title: "User is disabled" })];
625
- }
626
- return [3 /*break*/, 4];
627
- case 3:
628
- error_5 = _e.sent();
629
- logger_1.logger.warn("[jwt] Error finding user from id: ".concat(error_5));
630
- return [3 /*break*/, 4];
631
- case 4: return [2 /*return*/, next()];
371
+ const decodeJWTMiddleware = async (req, res, next) => {
372
+ if (!process.env.TOKEN_SECRET) {
373
+ return next();
374
+ }
375
+ // Login, signup, and refresh exchange credentials. A stale access JWT in
376
+ // Authorization / the jwt cookie must not 401 before those handlers run.
377
+ if ((0, policies_1.isJwtCredentialExchangePath)(req)) {
378
+ return next();
379
+ }
380
+ // Allow requests with a "Secret" prefix to pass through since this is a string value,
381
+ // not a jwt that needs to be decoded
382
+ if (req?.headers?.authorization?.split(" ")[0] === "Secret") {
383
+ return next();
384
+ }
385
+ const token = customTokenExtractor(req);
386
+ // For some reason, our app will happily put null into the authorization header when logging
387
+ // out then back in.
388
+ if (!token || token === "null" || token === "undefined") {
389
+ return next();
390
+ }
391
+ let decoded;
392
+ try {
393
+ decoded = jsonwebtoken_1.default.verify(token, process.env.TOKEN_SECRET, {
394
+ issuer: process.env.TOKEN_ISSUER,
395
+ });
396
+ }
397
+ catch (error) {
398
+ // A bearer token that is not a JWT at all (e.g. a Better Auth opaque session
399
+ // token) is not ours to reject — fall through so a later auth layer (Better
400
+ // Auth session middleware) or the route's own permissions can handle it.
401
+ // Detect this by decoding the token's header/payload structure (D1) rather
402
+ // than counting dot-delimited segments: an opaque token can coincidentally
403
+ // contain exactly two dots, and a malformed-but-JWT-shaped string can fail
404
+ // this same check for the wrong reason — `jwt.decode` parses the actual
405
+ // base64url JSON structure of each segment, which dot-counting cannot.
406
+ // Genuine JWTs that fail verification (malformed/expired) still return 401 so the
407
+ // client's token-refresh flow is preserved.
408
+ if (jsonwebtoken_1.default.decode(token, { complete: true }) === null) {
409
+ return next();
632
410
  }
633
- });
634
- }); };
411
+ const userText = req.user?._id ? ` for user ${req.user._id} ` : "";
412
+ const expiredAt = error && typeof error === "object" && "expiredAt" in error
413
+ ? error.expiredAt
414
+ : undefined;
415
+ const message = (0, errors_1.errorMessage)(error);
416
+ const details = `[jwt] Error decoding token${userText}: ${error}, expired at ${expiredAt}, current time: ${luxon_1.DateTime.now().toMillis()}`;
417
+ logger_1.logger.debug(details);
418
+ return res.status(401).json({ details, message });
419
+ }
420
+ if (decoded?.id) {
421
+ const sessionId = (0, requestContext_1.getSessionIdFromJwtPayload)(decoded);
422
+ req.authTokenPayload = decoded;
423
+ if (sessionId) {
424
+ req.sessionId = sessionId;
425
+ (0, requestContext_1.setRequestContext)({ sessionId });
426
+ }
427
+ try {
428
+ const user = await userModel.findById(decoded.id);
429
+ req.user = user;
430
+ (0, requestContext_1.updateRequestContextFromRequest)(req, res);
431
+ if (req.user?.disabled) {
432
+ logger_1.logger.warn(`[jwt] User ${req.user.id} is disabled`);
433
+ return res.status(401).json({ status: 401, title: "User is disabled" });
434
+ }
435
+ }
436
+ catch (error) {
437
+ logger_1.logger.warn(`[jwt] Error finding user from id: ${error}`);
438
+ }
439
+ }
440
+ return next();
441
+ };
635
442
  app.use(decodeJWTMiddleware);
636
443
  // express 5's urlencoded() handler type doesn't match RequestHandler directly
637
444
  app.use(express_1.default.urlencoded({ extended: false }));
638
445
  };
639
446
  exports.setupAuth = setupAuth;
640
- var addAuthRoutes = function (app, userModel, authOptions) {
641
- var router = express_1.default.Router();
642
- router.post("/login", function (req, res, next) { return __awaiter(void 0, void 0, void 0, function () {
643
- return __generator(this, function (_a) {
644
- passport_1.default.authenticate("local", { session: false }, function (err, user, info) { return __awaiter(void 0, void 0, void 0, function () {
645
- var tokens;
646
- return __generator(this, function (_a) {
647
- switch (_a.label) {
648
- case 0:
649
- if (err) {
650
- logger_1.logger.error("Error logging in: ".concat(err));
651
- return [2 /*return*/, next(err)];
652
- }
653
- if (!user) {
654
- logger_1.logger.warn("Invalid login: ".concat(info));
655
- return [2 /*return*/, res.status(401).json({ message: info === null || info === void 0 ? void 0 : info.message })];
656
- }
657
- if ((authOptions === null || authOptions === void 0 ? void 0 : authOptions.requireEmailVerification) && user.emailVerified !== true) {
658
- return [2 /*return*/, next(new errors_1.APIError({
659
- code: "email-not-verified",
660
- status: 403,
661
- title: "Email is not verified",
662
- }))];
663
- }
664
- if (process.env.NODE_ENV !== "test") {
665
- logger_1.logger.info("User logged in: ".concat(user._id, ", type: ").concat(user.type || "N/A"));
666
- }
667
- return [4 /*yield*/, (0, exports.generateTokens)(user, authOptions)];
668
- case 1:
669
- tokens = _a.sent();
670
- if (tokens.sessionId) {
671
- (0, requestContext_1.setRequestContext)({ sessionId: tokens.sessionId, userId: String(user._id) });
672
- res.setHeader("X-Session-ID", tokens.sessionId);
673
- }
674
- return [2 /*return*/, res.json({
675
- data: { refreshToken: tokens.refreshToken, token: tokens.token, userId: user === null || user === void 0 ? void 0 : user._id },
676
- })];
677
- }
447
+ const addAuthRoutes = (app, userModel, authOptions) => {
448
+ const router = express_1.default.Router();
449
+ router.post("/login", async (req, res, next) => {
450
+ passport_1.default.authenticate("local", { session: false }, async (err, user, info) => {
451
+ if (err) {
452
+ logger_1.logger.error(`Error logging in: ${err}`);
453
+ return next(err);
454
+ }
455
+ if (!user) {
456
+ logger_1.logger.warn(`Invalid login: ${info}`);
457
+ return res.status(401).json({ message: info?.message });
458
+ }
459
+ if (authOptions?.requireEmailVerification && user.emailVerified !== true) {
460
+ return next(new errors_1.APIError({
461
+ code: "email-not-verified",
462
+ status: 403,
463
+ title: "Email is not verified",
464
+ }));
465
+ }
466
+ if (process.env.NODE_ENV !== "test") {
467
+ logger_1.logger.info(`User logged in: ${user._id}, type: ${user.type || "N/A"}`);
468
+ }
469
+ const tokens = await (0, exports.generateTokens)(user, authOptions);
470
+ if (tokens.sessionId) {
471
+ (0, requestContext_1.setRequestContext)({ sessionId: tokens.sessionId, userId: String(user._id) });
472
+ res.setHeader("X-Session-ID", tokens.sessionId);
473
+ }
474
+ return res.json({
475
+ data: { refreshToken: tokens.refreshToken, token: tokens.token, userId: user?._id },
476
+ });
477
+ })(req, res, next);
478
+ });
479
+ router.post("/refresh_token", async (req, res) => {
480
+ if (!req.body.refreshToken) {
481
+ logger_1.logger.error(`No refresh token provided, must provide refreshToken in body, user id: ${req.user?.id}`);
482
+ return res
483
+ .status(401)
484
+ .json({ message: "No refresh token provided, must provide refreshToken in body" });
485
+ }
486
+ if (!process.env.REFRESH_TOKEN_SECRET) {
487
+ logger_1.logger.error(`No REFRESH_TOKEN_SECRET set, cannot refresh token, user id: ${req.user?.id}`);
488
+ return res.status(401).json({ message: "No REFRESH_TOKEN_SECRET set, cannot refresh token" });
489
+ }
490
+ const refreshTokenSecretOrKey = process.env.REFRESH_TOKEN_SECRET;
491
+ let decoded;
492
+ try {
493
+ decoded = jsonwebtoken_1.default.verify(req.body.refreshToken, refreshTokenSecretOrKey);
494
+ }
495
+ catch (error) {
496
+ logger_1.logger.error(`Error refreshing token for user ${req.user?.id}: ${error}`);
497
+ const message = (0, errors_1.errorMessage)(error);
498
+ return res.status(401).json({ message });
499
+ }
500
+ if (decoded?.id) {
501
+ const user = await userModel.findById(decoded.id);
502
+ const tokenEpoch = typeof decoded.te === "number" ? decoded.te : 0;
503
+ const userEpoch = user?.tokenEpoch ?? 0;
504
+ if (!user || tokenEpoch !== userEpoch) {
505
+ logger_1.logger.error(`Invalid refresh token, user id: ${req.user?.id}`);
506
+ return res.status(401).json({ message: "Invalid refresh token" });
507
+ }
508
+ const sessionId = (0, requestContext_1.getSessionIdFromJwtPayload)(decoded);
509
+ const tokens = await (0, exports.generateTokens)(user, authOptions, { sessionId });
510
+ if (tokens.sessionId) {
511
+ (0, requestContext_1.setRequestContext)({
512
+ sessionId: tokens.sessionId,
513
+ userId: user?._id ? String(user._id) : undefined,
678
514
  });
679
- }); })(req, res, next);
680
- return [2 /*return*/];
681
- });
682
- }); });
683
- router.post("/refresh_token", function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
684
- var refreshTokenSecretOrKey, decoded, message, user, tokenEpoch, userEpoch, sessionId, tokens;
685
- var _a, _b, _c, _d, _e, _f;
686
- return __generator(this, function (_g) {
687
- switch (_g.label) {
688
- case 0:
689
- if (!req.body.refreshToken) {
690
- logger_1.logger.error("No refresh token provided, must provide refreshToken in body, user id: ".concat((_a = req.user) === null || _a === void 0 ? void 0 : _a.id));
691
- return [2 /*return*/, res
692
- .status(401)
693
- .json({ message: "No refresh token provided, must provide refreshToken in body" })];
694
- }
695
- if (!process.env.REFRESH_TOKEN_SECRET) {
696
- logger_1.logger.error("No REFRESH_TOKEN_SECRET set, cannot refresh token, user id: ".concat((_b = req.user) === null || _b === void 0 ? void 0 : _b.id));
697
- return [2 /*return*/, res.status(401).json({ message: "No REFRESH_TOKEN_SECRET set, cannot refresh token" })];
698
- }
699
- refreshTokenSecretOrKey = process.env.REFRESH_TOKEN_SECRET;
700
- try {
701
- decoded = jsonwebtoken_1.default.verify(req.body.refreshToken, refreshTokenSecretOrKey);
702
- }
703
- catch (error) {
704
- logger_1.logger.error("Error refreshing token for user ".concat((_c = req.user) === null || _c === void 0 ? void 0 : _c.id, ": ").concat(error));
705
- message = (0, errors_1.errorMessage)(error);
706
- return [2 /*return*/, res.status(401).json({ message: message })];
707
- }
708
- if (!(decoded === null || decoded === void 0 ? void 0 : decoded.id)) return [3 /*break*/, 3];
709
- return [4 /*yield*/, userModel.findById(decoded.id)];
710
- case 1:
711
- user = _g.sent();
712
- tokenEpoch = typeof decoded.te === "number" ? decoded.te : 0;
713
- userEpoch = (_d = user === null || user === void 0 ? void 0 : user.tokenEpoch) !== null && _d !== void 0 ? _d : 0;
714
- if (!user || tokenEpoch !== userEpoch) {
715
- logger_1.logger.error("Invalid refresh token, user id: ".concat((_e = req.user) === null || _e === void 0 ? void 0 : _e.id));
716
- return [2 /*return*/, res.status(401).json({ message: "Invalid refresh token" })];
717
- }
718
- sessionId = (0, requestContext_1.getSessionIdFromJwtPayload)(decoded);
719
- return [4 /*yield*/, (0, exports.generateTokens)(user, authOptions, { sessionId: sessionId })];
720
- case 2:
721
- tokens = _g.sent();
722
- if (tokens.sessionId) {
723
- (0, requestContext_1.setRequestContext)({
724
- sessionId: tokens.sessionId,
725
- userId: (user === null || user === void 0 ? void 0 : user._id) ? String(user._id) : undefined,
726
- });
727
- res.setHeader("X-Session-ID", tokens.sessionId);
728
- }
729
- logger_1.logger.debug("Refreshed token for ".concat(user === null || user === void 0 ? void 0 : user.id));
730
- return [2 /*return*/, res.json({ data: { refreshToken: tokens.refreshToken, token: tokens.token } })];
731
- case 3:
732
- logger_1.logger.error("Invalid refresh token, user id: ".concat((_f = req.user) === null || _f === void 0 ? void 0 : _f.id));
733
- return [2 /*return*/, res.status(401).json({ message: "Invalid refresh token" })];
515
+ res.setHeader("X-Session-ID", tokens.sessionId);
734
516
  }
735
- });
736
- }); });
737
- var signupDisabled = process.env.SIGNUP_DISABLED === "true";
517
+ logger_1.logger.debug(`Refreshed token for ${user?.id}`);
518
+ return res.json({ data: { refreshToken: tokens.refreshToken, token: tokens.token } });
519
+ }
520
+ logger_1.logger.error(`Invalid refresh token, user id: ${req.user?.id}`);
521
+ return res.status(401).json({ message: "Invalid refresh token" });
522
+ });
523
+ const signupDisabled = process.env.SIGNUP_DISABLED === "true";
738
524
  if (!signupDisabled) {
739
525
  router.post("/signup",
740
526
  // Custom callback instead of `failWithError` — passport's internal
741
527
  // AuthenticationError is unusable in strict-mode bundles (see
742
528
  // authenticateMiddleware). Strategy errors (e.g. duplicate email) pass
743
529
  // through unchanged; a bare failure (missing credentials) is a 400.
744
- function (req, res, next) {
745
- passport_1.default.authenticate("signup", { session: false }, function (err, user) {
530
+ (req, res, next) => {
531
+ passport_1.default.authenticate("signup", { session: false }, (err, user) => {
746
532
  if (err) {
747
533
  return next(err);
748
534
  }
@@ -752,126 +538,91 @@ var addAuthRoutes = function (app, userModel, authOptions) {
752
538
  req.user = user;
753
539
  return next();
754
540
  })(req, res, next);
755
- }, function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
756
- var error_6, tokens;
757
- var _a, _b;
758
- return __generator(this, function (_c) {
759
- switch (_c.label) {
760
- case 0:
761
- if (!req.user) return [3 /*break*/, 4];
762
- _c.label = 1;
763
- case 1:
764
- _c.trys.push([1, 3, , 4]);
765
- return [4 /*yield*/, (0, authRecovery_1.sendVerificationEmail)(req.user, authOptions)];
766
- case 2:
767
- _c.sent();
768
- return [3 /*break*/, 4];
769
- case 3:
770
- error_6 = _c.sent();
771
- logger_1.logger.error("[auth] Failed to send verification mail after signup", { error: error_6 });
772
- return [3 /*break*/, 4];
773
- case 4: return [4 /*yield*/, (0, exports.generateTokens)(req.user, authOptions)];
774
- case 5:
775
- tokens = _c.sent();
776
- if (tokens.sessionId) {
777
- (0, requestContext_1.setRequestContext)({
778
- sessionId: tokens.sessionId,
779
- userId: ((_a = req.user) === null || _a === void 0 ? void 0 : _a._id) ? String(req.user._id) : undefined,
780
- });
781
- res.setHeader("X-Session-ID", tokens.sessionId);
782
- }
783
- return [2 /*return*/, res.json({
784
- data: { refreshToken: tokens.refreshToken, token: tokens.token, userId: (_b = req.user) === null || _b === void 0 ? void 0 : _b._id },
785
- })];
541
+ }, async (req, res) => {
542
+ if (req.user && authOptions?.emailVerification !== false) {
543
+ try {
544
+ await (0, authRecovery_1.sendVerificationEmail)(req.user, authOptions);
786
545
  }
546
+ catch (error) {
547
+ logger_1.logger.error("[auth] Failed to send verification mail after signup", { error });
548
+ }
549
+ }
550
+ const tokens = await (0, exports.generateTokens)(req.user, authOptions);
551
+ if (tokens.sessionId) {
552
+ (0, requestContext_1.setRequestContext)({
553
+ sessionId: tokens.sessionId,
554
+ userId: req.user?._id ? String(req.user._id) : undefined,
555
+ });
556
+ res.setHeader("X-Session-ID", tokens.sessionId);
557
+ }
558
+ return res.json({
559
+ data: { refreshToken: tokens.refreshToken, token: tokens.token, userId: req.user?._id },
787
560
  });
788
- }); });
561
+ });
789
562
  }
790
563
  app.set("etag", false);
791
564
  app.use("/auth", router);
792
565
  (0, authRecovery_1.addAuthRecoveryRoutes)(app, userModel, authOptions);
793
566
  };
794
567
  exports.addAuthRoutes = addAuthRoutes;
795
- var addMeRoutes = function (app, userModel, _authOptions, accessControl) {
796
- var router = express_1.default.Router();
797
- router.get("/me", (0, exports.authenticateMiddleware)(), function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
798
- var data, dataObject, withRoles, _a;
799
- var _b, _c;
800
- return __generator(this, function (_d) {
801
- switch (_d.label) {
802
- case 0:
803
- if (!((_b = req.user) === null || _b === void 0 ? void 0 : _b.id)) {
804
- logger_1.logger.debug("Not user found for /me");
805
- return [2 /*return*/, res.sendStatus(401)];
806
- }
807
- return [4 /*yield*/, userModel.findById(req.user.id)];
808
- case 1:
809
- data = _d.sent();
810
- if (!data) {
811
- logger_1.logger.debug("Not user data found for /me");
812
- return [2 /*return*/, res.sendStatus(404)];
813
- }
814
- dataObject = data.toObject();
815
- dataObject.id = data._id;
816
- if (!accessControl) return [3 /*break*/, 3];
817
- withRoles = data;
818
- dataObject.roles = (_c = withRoles.roles) !== null && _c !== void 0 ? _c : [];
819
- _a = dataObject;
820
- return [4 /*yield*/, accessControl.getPermissions({
821
- user: data,
822
- })];
823
- case 2:
824
- _a.permissions = _d.sent();
825
- _d.label = 3;
826
- case 3: return [2 /*return*/, res.json({ data: dataObject })];
827
- }
828
- });
829
- }); });
830
- router.patch("/me", (0, exports.authenticateMiddleware)(), function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
831
- var doc, update, isMailboxChange, dataObject, error_7, message;
832
- var _a, _b;
833
- return __generator(this, function (_c) {
834
- switch (_c.label) {
835
- case 0:
836
- if (!((_a = req.user) === null || _a === void 0 ? void 0 : _a.id)) {
837
- return [2 /*return*/, res.sendStatus(401)];
838
- }
839
- return [4 /*yield*/, userModel.findById(req.user.id)];
840
- case 1:
841
- doc = _c.sent();
842
- if (!doc) {
843
- return [2 /*return*/, res.sendStatus(404)];
844
- }
845
- _c.label = 2;
846
- case 2:
847
- _c.trys.push([2, 7, , 8]);
848
- update = (0, exports.stripPrivilegedUserFields)((_b = req.body) !== null && _b !== void 0 ? _b : {}, "PATCH /auth/me");
849
- isMailboxChange = isEmailUpdateChangingMailbox(doc.email, update.email);
850
- Object.assign(doc, update);
851
- if (!isMailboxChange) return [3 /*break*/, 5];
852
- return [4 /*yield*/, authTokens_1.AuthToken.invalidateUnusedFor({ _id: String(doc._id) }, "passwordReset")];
853
- case 3:
854
- _c.sent();
855
- if (!(userModel.schema.path("emailVerified") !== undefined)) return [3 /*break*/, 5];
568
+ const addMeRoutes = (app, userModel, _authOptions, accessControl) => {
569
+ const router = express_1.default.Router();
570
+ router.get("/me", (0, exports.authenticateMiddleware)(), async (req, res) => {
571
+ if (!req.user?.id) {
572
+ logger_1.logger.debug("Not user found for /me");
573
+ return res.sendStatus(401);
574
+ }
575
+ const data = await userModel.findById(req.user.id);
576
+ if (!data) {
577
+ logger_1.logger.debug("Not user data found for /me");
578
+ return res.sendStatus(404);
579
+ }
580
+ const dataObject = data.toObject();
581
+ dataObject.id = data._id;
582
+ if (accessControl) {
583
+ const withRoles = data;
584
+ dataObject.roles = withRoles.roles ?? [];
585
+ dataObject.permissions = await accessControl.getPermissions({
586
+ user: data,
587
+ });
588
+ }
589
+ return res.json({ data: dataObject });
590
+ });
591
+ router.patch("/me", (0, exports.authenticateMiddleware)(), async (req, res) => {
592
+ if (!req.user?.id) {
593
+ return res.sendStatus(401);
594
+ }
595
+ const doc = await userModel.findById(req.user.id);
596
+ if (!doc) {
597
+ return res.sendStatus(404);
598
+ }
599
+ // TODO support limited updates for profile.
600
+ // try {
601
+ // body = transform(req.body, "update", req.user);
602
+ // } catch (e) {
603
+ // return res.status(403).send({message: (e as Error).message});
604
+ // }
605
+ try {
606
+ const update = (0, exports.stripPrivilegedUserFields)(req.body ?? {}, "PATCH /auth/me");
607
+ const isMailboxChange = isEmailUpdateChangingMailbox(doc.email, update.email);
608
+ Object.assign(doc, update);
609
+ if (isMailboxChange) {
610
+ await authTokens_1.AuthToken.invalidateUnusedFor({ _id: String(doc._id) }, "passwordReset");
611
+ if (userModel.schema.path("emailVerified") !== undefined) {
856
612
  doc.emailVerified = false;
857
- return [4 /*yield*/, authTokens_1.AuthToken.invalidateUnusedFor({ _id: String(doc._id) }, "emailVerification")];
858
- case 4:
859
- _c.sent();
860
- _c.label = 5;
861
- case 5: return [4 /*yield*/, doc.save()];
862
- case 6:
863
- _c.sent();
864
- dataObject = doc.toObject();
865
- dataObject.id = doc._id;
866
- return [2 /*return*/, res.json({ data: dataObject })];
867
- case 7:
868
- error_7 = _c.sent();
869
- message = (0, errors_1.errorMessage)(error_7);
870
- return [2 /*return*/, res.status(403).send({ message: message })];
871
- case 8: return [2 /*return*/];
613
+ await authTokens_1.AuthToken.invalidateUnusedFor({ _id: String(doc._id) }, "emailVerification");
614
+ }
872
615
  }
873
- });
874
- }); });
616
+ await doc.save();
617
+ const dataObject = doc.toObject();
618
+ dataObject.id = doc._id;
619
+ return res.json({ data: dataObject });
620
+ }
621
+ catch (error) {
622
+ const message = (0, errors_1.errorMessage)(error);
623
+ return res.status(403).send({ message });
624
+ }
625
+ });
875
626
  app.set("etag", false);
876
627
  app.use("/auth", router);
877
628
  app.use(errors_1.apiErrorMiddleware);