@axiumine/koa-utils 5.6.1 → 5.7.1

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 (220) hide show
  1. package/README.md +33 -5
  2. package/dist/graphQL/schema/mutations/emailChangeHashVerify.d.mts +7 -0
  3. package/dist/graphQL/schema/mutations/emailChangeHashVerify.mjs +38 -35
  4. package/dist/lib/access/accessPaths.d.mts +18 -0
  5. package/dist/lib/access/createMailThrottle.d.mts +34 -0
  6. package/dist/lib/access/createMailThrottle.mjs +45 -0
  7. package/dist/lib/access/createVerifyEmailFlow.d.mts +37 -4
  8. package/dist/lib/access/createVerifyEmailFlow.mjs +33 -10
  9. package/dist/lib/access/verifyEmailMailer.d.mts +54 -0
  10. package/dist/lib/access/verifyEmailMailer.mjs +48 -0
  11. package/dist/private/lib/access/assertVerifyEmailAllowed.d.mts +13 -1
  12. package/dist/private/lib/access/assertVerifyEmailAllowed.mjs +7 -4
  13. package/dist/private/lib/access/db/abandonUser.d.mts +25 -0
  14. package/dist/private/lib/access/db/abandonUser.mjs +26 -0
  15. package/dist/private/lib/access/db/deleteUserByEmail.d.mts +7 -0
  16. package/dist/private/lib/access/db/deleteUserByEmail.mjs +15 -4
  17. package/dist/private/lib/access/db/enableEmailAccess.d.mts +9 -1
  18. package/dist/private/lib/access/db/enableEmailAccess.mjs +11 -5
  19. package/dist/private/lib/access/handleBadDB.d.mts +11 -0
  20. package/dist/private/lib/access/handleBadDB.mjs +13 -1
  21. package/dist/private/lib/access/handleIfAccountDeleted.d.mts +16 -1
  22. package/dist/private/lib/access/handleIfAccountDeleted.mjs +16 -5
  23. package/dist/private/lib/access/handleIfAccountDisabled.d.mts +15 -1
  24. package/dist/private/lib/access/handleIfAccountDisabled.mjs +15 -5
  25. package/dist/private/lib/access/handleIfEmailAlreadyValid.d.mts +18 -1
  26. package/dist/private/lib/access/handleIfEmailAlreadyValid.mjs +18 -5
  27. package/dist/private/lib/access/handleIfHashBad.d.mts +5 -1
  28. package/dist/private/lib/access/handleIfHashBad.mjs +7 -5
  29. package/dist/private/lib/access/handleIfMoreThan3DaysPassed.d.mts +8 -4
  30. package/dist/private/lib/access/handleIfMoreThan3DaysPassed.mjs +10 -8
  31. package/dist/private/lib/access/handleIfTooMuchRequestsTimes.d.mts +7 -4
  32. package/dist/private/lib/access/handleIfTooMuchRequestsTimes.mjs +9 -8
  33. package/package.json +68 -18
  34. package/dist/dataSources/MariaDB.mjs.map +0 -1
  35. package/dist/dataSources/MongoDB.mjs.map +0 -1
  36. package/dist/dataSources/PostgreSQL.mjs.map +0 -1
  37. package/dist/dataSources/Redis.mjs.map +0 -1
  38. package/dist/email/SocketLabsLib.mjs.map +0 -1
  39. package/dist/files/IUploadTemp.mjs.map +0 -1
  40. package/dist/files/checkForNSFW.mjs.map +0 -1
  41. package/dist/files/fileConst.mjs.map +0 -1
  42. package/dist/files/moveFileStaticDomain.mjs.map +0 -1
  43. package/dist/files/moveImageFile.mjs.map +0 -1
  44. package/dist/files/moveTempFile.mjs.map +0 -1
  45. package/dist/files/reEncodeToJpeg.mjs.map +0 -1
  46. package/dist/files/reEncodeToPng.mjs.map +0 -1
  47. package/dist/files/reEncodeToWebp.mjs.map +0 -1
  48. package/dist/files/scanVirus.mjs.map +0 -1
  49. package/dist/files/storeUploadAsTemp.mjs.map +0 -1
  50. package/dist/files/uploadTempImage.mjs.map +0 -1
  51. package/dist/files/uploadTempPdf.mjs.map +0 -1
  52. package/dist/files/validateExtension.mjs.map +0 -1
  53. package/dist/files/validateJpgPngExtension.mjs.map +0 -1
  54. package/dist/files/validateMimeType.mjs.map +0 -1
  55. package/dist/files/validateMimeTypeImages.mjs.map +0 -1
  56. package/dist/files/validateMimeTypePdf.mjs.map +0 -1
  57. package/dist/files/validatePdfExtension.mjs.map +0 -1
  58. package/dist/graphQL/models/MongoDB/UserBase.mjs.map +0 -1
  59. package/dist/graphQL/models/MongoDB/log/DevStatsGraphQLCalls.mjs.map +0 -1
  60. package/dist/graphQL/models/MongoDB/log/LogGlobalError.mjs.map +0 -1
  61. package/dist/graphQL/models/MongoDB/log/LogStatsGraphql.mjs.map +0 -1
  62. package/dist/graphQL/models/MongoDB/log/LogThrow.mjs.map +0 -1
  63. package/dist/graphQL/schema/GraphQLInput/GraphQLInputLogin.mjs.map +0 -1
  64. package/dist/graphQL/schema/context/IContextAuthenticatedResource.mjs.map +0 -1
  65. package/dist/graphQL/schema/context/IContextKoaErrorHandler.mjs.map +0 -1
  66. package/dist/graphQL/schema/context/IContextLogin.mjs.map +0 -1
  67. package/dist/graphQL/schema/context/IContextLogout.mjs.map +0 -1
  68. package/dist/graphQL/schema/context/IContextRefresh.mjs.map +0 -1
  69. package/dist/graphQL/schema/context/TCommonHeaders.mjs.map +0 -1
  70. package/dist/graphQL/schema/interfaces/IFindAndUpdate.mjs.map +0 -1
  71. package/dist/graphQL/schema/mutations/emailChangeHashVerify.mjs.map +0 -1
  72. package/dist/graphQL/schema/mutations/login4Ever.mjs.map +0 -1
  73. package/dist/graphQL/schema/mutations/loginAdmin.mjs.map +0 -1
  74. package/dist/graphQL/schema/mutations/loginRememberme.mjs.map +0 -1
  75. package/dist/graphQL/schema/mutations/logout.mjs.map +0 -1
  76. package/dist/graphQL/schema/mutations/refresh.mjs.map +0 -1
  77. package/dist/graphQL/schema/mutations/resetPwd.mjs.map +0 -1
  78. package/dist/graphQL/schema/mutations/signUp.mjs.map +0 -1
  79. package/dist/graphQL/schema/mutations/updatePassword.mjs.map +0 -1
  80. package/dist/graphQL/schema/types/DeleteType.mjs.map +0 -1
  81. package/dist/graphQL/schema/types/DoneType.mjs.map +0 -1
  82. package/dist/graphQL/schema/types/FindOneAndUpdateType.mjs.map +0 -1
  83. package/dist/graphQL/schema/types/LoginAppType.mjs.map +0 -1
  84. package/dist/graphQL/schema/types/LoginType.mjs.map +0 -1
  85. package/dist/graphQL/schema/types/MidNameType.mjs.map +0 -1
  86. package/dist/graphQL/schema/types/OnlyIdType.mjs.map +0 -1
  87. package/dist/graphQL/schema/types/RefreshType.mjs.map +0 -1
  88. package/dist/graphQL/schema/types/RetStatusMexType.mjs.map +0 -1
  89. package/dist/graphQL/schema/types/RetStatusType.mjs.map +0 -1
  90. package/dist/graphQL/schema/types/SaveType.mjs.map +0 -1
  91. package/dist/graphQL/schema/types/SidNameType.mjs.map +0 -1
  92. package/dist/graphQL/schema/types/SidNomeType.mjs.map +0 -1
  93. package/dist/graphQL/schema/types/UpdateResultType.mjs.map +0 -1
  94. package/dist/graphQL/status.mjs.map +0 -1
  95. package/dist/graphQL/throw/throwAccessTokenExpiredOrDeleted.mjs.map +0 -1
  96. package/dist/graphQL/throw/throwAccessTokenRequired.mjs.map +0 -1
  97. package/dist/graphQL/throw/throwAlreadyDone.mjs.map +0 -1
  98. package/dist/graphQL/throw/throwAlreadyTakenError.mjs.map +0 -1
  99. package/dist/graphQL/throw/throwConflictError.mjs.map +0 -1
  100. package/dist/graphQL/throw/throwErrorWrongUserInput.mjs.map +0 -1
  101. package/dist/graphQL/throw/throwForbiddenError.mjs.map +0 -1
  102. package/dist/graphQL/throw/throwGoneError.mjs.map +0 -1
  103. package/dist/graphQL/throw/throwGraphQLError.mjs.map +0 -1
  104. package/dist/graphQL/throw/throwInternalError.mjs.map +0 -1
  105. package/dist/graphQL/throw/throwMethodNotAllowedError.mjs.map +0 -1
  106. package/dist/graphQL/throw/throwMissingMalformedInvalidToken.mjs.map +0 -1
  107. package/dist/graphQL/throw/throwNotAcceptableError.mjs.map +0 -1
  108. package/dist/graphQL/throw/throwNotFoundError.mjs.map +0 -1
  109. package/dist/graphQL/throw/throwNotImplementedError.mjs.map +0 -1
  110. package/dist/graphQL/throw/throwPaymentRequiredError.mjs.map +0 -1
  111. package/dist/graphQL/throw/throwPreconditionFailedNoAuthCookie.mjs.map +0 -1
  112. package/dist/graphQL/throw/throwPreconditionFailedNoAuthHeader.mjs.map +0 -1
  113. package/dist/graphQL/throw/throwRefreshTokenExpiredOrDeleted.mjs.map +0 -1
  114. package/dist/graphQL/throw/throwRefreshTokenRequired.mjs.map +0 -1
  115. package/dist/graphQL/throw/throwRefreshTokenSignatureRequired.mjs.map +0 -1
  116. package/dist/graphQL/throw/throwTooManyRequestsError.mjs.map +0 -1
  117. package/dist/graphQL/throw/throwUnauthorizedError.mjs.map +0 -1
  118. package/dist/graphQL/throw/throwUnprocessableContentError.mjs.map +0 -1
  119. package/dist/graphQL/throw/throwUnsupportedMediaTypeError.mjs.map +0 -1
  120. package/dist/koa/IFileUpload.mjs.map +0 -1
  121. package/dist/koa/IKoaError.mjs.map +0 -1
  122. package/dist/koa/customFormatErrorFn.mjs.map +0 -1
  123. package/dist/koa/logRequestToDb.mjs.map +0 -1
  124. package/dist/koa/middleware/authenticatedAuthorizationHandler/TCookieRefreshToken.mjs.map +0 -1
  125. package/dist/koa/middleware/authenticatedAuthorizationHandler/index.mjs.map +0 -1
  126. package/dist/koa/middleware/authenticatedAuthorizationHandler/verifySignedRefreshToken.mjs.map +0 -1
  127. package/dist/koa/middleware/authenticatedLogoutHandler/index.mjs.map +0 -1
  128. package/dist/koa/middleware/authenticatedResourceHandler/index.mjs.map +0 -1
  129. package/dist/koa/middleware/debug/index.mjs.map +0 -1
  130. package/dist/koa/router/verifyEmail.mjs.map +0 -1
  131. package/dist/koa/tdwKoaErrorHandler.mjs.map +0 -1
  132. package/dist/lib/ArrayLib.mjs.map +0 -1
  133. package/dist/lib/Constants.mjs.map +0 -1
  134. package/dist/lib/DateLib.mjs.map +0 -1
  135. package/dist/lib/IAuthorizationDisDel.mjs.map +0 -1
  136. package/dist/lib/ICookies.mjs.map +0 -1
  137. package/dist/lib/MariaDB/IMariaDBErr.mjs.map +0 -1
  138. package/dist/lib/MariaDB/MariaDBErrType.mjs.map +0 -1
  139. package/dist/lib/MariaDB/throwSqlErrors.mjs.map +0 -1
  140. package/dist/lib/MongoDB/IMongoDBError.mjs.map +0 -1
  141. package/dist/lib/MongoDB/IOnboarding.mjs.map +0 -1
  142. package/dist/lib/MongoDB/MongoDBErrType.mjs.map +0 -1
  143. package/dist/lib/MongoDB/throwIfMongoErr.mjs.map +0 -1
  144. package/dist/lib/MongoDB/throwMongoErrors.mjs.map +0 -1
  145. package/dist/lib/NumLib.mjs.map +0 -1
  146. package/dist/lib/PostgreSQL/IPostgresError.mjs.map +0 -1
  147. package/dist/lib/PostgreSQL/IPostgresErrorCodes.mjs.map +0 -1
  148. package/dist/lib/PostgreSQL/makePostgreSqlLogError.mjs.map +0 -1
  149. package/dist/lib/Redis/RedisBoolean.mjs.map +0 -1
  150. package/dist/lib/Redis/buildPrefixedRedisKey.mjs.map +0 -1
  151. package/dist/lib/Redis/fromRedisBooleanValue.mjs.map +0 -1
  152. package/dist/lib/Redis/toRedisBooleanValue.mjs.map +0 -1
  153. package/dist/lib/StringLib.mjs.map +0 -1
  154. package/dist/lib/access/accessPaths.mjs.map +0 -1
  155. package/dist/lib/access/createResetPwdFlow.mjs.map +0 -1
  156. package/dist/lib/access/createVerifyEmailFlow.mjs.map +0 -1
  157. package/dist/lib/checkEmailLen.mjs.map +0 -1
  158. package/dist/lib/checkPwdLen.mjs.map +0 -1
  159. package/dist/lib/db/log/hitStat.mjs.map +0 -1
  160. package/dist/lib/db/log/logGlobalError.mjs.map +0 -1
  161. package/dist/lib/db/log/logGraphql.mjs.map +0 -1
  162. package/dist/lib/db/log/logThrow.mjs.map +0 -1
  163. package/dist/lib/db/login/ILoginSet.mjs.map +0 -1
  164. package/dist/lib/db/login/ILoginUnset.mjs.map +0 -1
  165. package/dist/lib/db/registerNewUser.mjs.map +0 -1
  166. package/dist/lib/db/userExist.mjs.map +0 -1
  167. package/dist/lib/emailHash.mjs.map +0 -1
  168. package/dist/lib/encryptPassword.mjs.map +0 -1
  169. package/dist/lib/hash.mjs.map +0 -1
  170. package/dist/lib/isSafeRedirectTarget.mjs.map +0 -1
  171. package/dist/lib/isSessionBlocked.mjs.map +0 -1
  172. package/dist/lib/isValidUuidV4.mjs.map +0 -1
  173. package/dist/lib/makeOnboardingData.mjs.map +0 -1
  174. package/dist/lib/setLoginCookies.mjs.map +0 -1
  175. package/dist/lib/sleepMs.mjs.map +0 -1
  176. package/dist/lib/throwIfNotValidEnumValue.mjs.map +0 -1
  177. package/dist/lib/tokenOptions.mjs.map +0 -1
  178. package/dist/lib/tokens.mjs.map +0 -1
  179. package/dist/lib/tryCatchRethrow.mjs.map +0 -1
  180. package/dist/private/files/_validateMimeType.mjs.map +0 -1
  181. package/dist/private/files/assertNoTraversal.mjs.map +0 -1
  182. package/dist/private/files/reEncode.mjs.map +0 -1
  183. package/dist/private/graphQL/Consts.mjs.map +0 -1
  184. package/dist/private/graphQL/models/MongoDB/private/UserAdminKoaUtils.mjs.map +0 -1
  185. package/dist/private/graphQL/schema/context/IContextLog.mjs.map +0 -1
  186. package/dist/private/graphQL/schema/context/IContextVerifyEmail.mjs.map +0 -1
  187. package/dist/private/graphQL/schema/mutations/_buildLoginStatsUpdate.mjs.map +0 -1
  188. package/dist/private/graphQL/schema/mutations/_finalizeLoginCheck.mjs.map +0 -1
  189. package/dist/private/graphQL/schema/mutations/checkUserAdminLoginAuthorization.mjs.map +0 -1
  190. package/dist/private/graphQL/schema/mutations/checkUserLoginAuthorization.mjs.map +0 -1
  191. package/dist/private/graphQL/schema/mutations/infoUserAdminForLogin.mjs.map +0 -1
  192. package/dist/private/graphQL/schema/mutations/infoUserForLogin.mjs.map +0 -1
  193. package/dist/private/graphQL/schema/mutations/infoUserForLoginSQL.mjs.map +0 -1
  194. package/dist/private/graphQL/schema/mutations/setLastLoginSQL.mjs.map +0 -1
  195. package/dist/private/graphQL/schema/mutations/setRedisLoginSession.mjs.map +0 -1
  196. package/dist/private/graphQL/schema/mutations/updateAdminLoginStats.mjs.map +0 -1
  197. package/dist/private/graphQL/schema/mutations/updateLoginStats4ever.mjs.map +0 -1
  198. package/dist/private/graphQL/schema/mutations/updateLoginStatsRememberme.mjs.map +0 -1
  199. package/dist/private/lib/access/Constants.mjs.map +0 -1
  200. package/dist/private/lib/access/assertVerifyEmailAllowed.mjs.map +0 -1
  201. package/dist/private/lib/access/db/confirmNewEmail.mjs.map +0 -1
  202. package/dist/private/lib/access/db/deleteUserByEmail.mjs.map +0 -1
  203. package/dist/private/lib/access/db/enableEmailAccess.mjs.map +0 -1
  204. package/dist/private/lib/access/db/getResetPwd.mjs.map +0 -1
  205. package/dist/private/lib/access/db/incReqTimes.mjs.map +0 -1
  206. package/dist/private/lib/access/db/removeResetReq.mjs.map +0 -1
  207. package/dist/private/lib/access/db/saveResetReq.mjs.map +0 -1
  208. package/dist/private/lib/access/db/setEmailHash.mjs.map +0 -1
  209. package/dist/private/lib/access/db/updatePasswordDb.mjs.map +0 -1
  210. package/dist/private/lib/access/db/userData4VerifyEmail.mjs.map +0 -1
  211. package/dist/private/lib/access/handleBadDB.mjs.map +0 -1
  212. package/dist/private/lib/access/handleIfAccountDeleted.mjs.map +0 -1
  213. package/dist/private/lib/access/handleIfAccountDisabled.mjs.map +0 -1
  214. package/dist/private/lib/access/handleIfEmailAlreadyValid.mjs.map +0 -1
  215. package/dist/private/lib/access/handleIfHashBad.mjs.map +0 -1
  216. package/dist/private/lib/access/handleIfMoreThan3DaysPassed.mjs.map +0 -1
  217. package/dist/private/lib/access/handleIfTooMuchRequestsTimes.mjs.map +0 -1
  218. package/dist/private/lib/access/pathTools.mjs.map +0 -1
  219. package/dist/private/lib/makeBodyJson.mjs.map +0 -1
  220. package/dist/private/lib/verifyIntrospectionCode.mjs.map +0 -1
package/README.md CHANGED
@@ -16,14 +16,33 @@ yarn add @axiumine/koa-utils
16
16
  npm install @axiumine/koa-utils
17
17
  ```
18
18
 
19
- All runtime dependencies are declared as **peer dependencies**. Install the ones you use:
19
+ All runtime dependencies are declared as **peer dependencies** — the package ships zero `dependencies`, so the consuming project owns every installed version.
20
+
21
+ Seven are required. The auth core — sign-up, the login variants, refresh, logout, the middleware, the models and the error helpers — reaches all of them:
20
22
 
21
23
  ```bash
22
- yarn add @node-rs/bcrypt @sentry/node @socketlabs/email clamscan dotenv \
23
- file-type fs-extra graphql keygrip mongoose pg redis \
24
- reflect-metadata sequelize sequelize-typescript sharp uuid
24
+ yarn add @node-rs/bcrypt @sentry/node dotenv graphql mongoose redis uuid
25
25
  ```
26
26
 
27
+ The remaining twelve are declared **optional** in `peerDependenciesMeta`. There is no barrel export: each of these is reachable only through subpaths you opt into by importing them, so a project that never imports the subpath never loads the package, and npm/yarn will not warn about the missing peer. Install the row when you import the subpath:
28
+
29
+ | Optional peer | Required by |
30
+ |---|---|
31
+ | `@socketlabs/email` | `email/SocketLabsLib`, `lib/access/createResetPwdFlow`, `lib/access/createVerifyEmailFlow`, `lib/access/verifyEmailMailer`, `koa/router/verifyEmail`, and the `signUp` / `login*` / `resetPwd` / `updatePassword` / `emailChangeHashVerify` mutations |
32
+ | `clamscan` | `files/scanVirus`, `files/uploadTempImage`, `files/uploadTempPdf` |
33
+ | `file-type` | `files/validateMimeType`, `files/validateMimeTypeImages`, `files/validateJpgPngMimeType`, `files/uploadTempImage`, `files/uploadTempPdf` — loaded lazily, at first call |
34
+ | `fs-extra` | the `files/move*` and `files/validate*` helpers, `files/uploadTempImage`, `files/uploadTempPdf` |
35
+ | `keygrip` | `koa/middleware/authenticatedAuthorizationHandler`, `.../verifySignedRefreshToken`, `koa/middleware/authenticatedLogoutHandler` — types only; the `Keygrip` instance is yours to construct and pass in |
36
+ | `koa` | the `koa/middleware/*` handlers, `koa/tdwKoaErrorHandler`, `koa/logRequestToDb` — types only (`Next`) |
37
+ | `mariadb` | `dataSources/MariaDB` — Sequelize connects with `dialect: 'mariadb'` and loads the driver itself |
38
+ | `pg` | `dataSources/PostgreSQL` |
39
+ | `reflect-metadata` | `dataSources/MariaDB` — required by `sequelize-typescript`, never imported by this package |
40
+ | `sequelize` | `dataSources/MariaDB` — peer of `sequelize-typescript` |
41
+ | `sequelize-typescript` | `dataSources/MariaDB` |
42
+ | `sharp` | `files/reEncodeToJpeg`, `files/reEncodeToPng`, `files/reEncodeToWebp`, `files/uploadTempImage` |
43
+
44
+ Optionality is a promise about the load path, not a way to silence the warning: it holds only while the dependency stays behind a subpath the consumer opts into. Adding a root `"."` barrel, or importing one of these from a module that every subpath reaches, breaks it for every consumer at once.
45
+
27
46
  ## Usage
28
47
 
29
48
  No barrel — import each helper from its explicit subpath.
@@ -98,12 +117,21 @@ const { resetPwd, updatePassword } = createResetPwdFlow({
98
117
  }
99
118
  })
100
119
 
101
- const verify = createVerifyEmailFlow({ model: Account, paths: { email: 'mail', valid: 'verified' } })
120
+ const verify = createVerifyEmailFlow({
121
+ model: Account,
122
+ paths: { email: 'mail', valid: 'verified' },
123
+ onAbandon: 'soft-delete', // 'delete' (default) | 'soft-delete' | 'keep'
124
+ deletedValue: () => new Date() // what 'soft-delete' writes; default true
125
+ })
102
126
  router.get('/check/verify-email/:email/:hash', verify.routerVerifyEmail())
103
127
  ```
104
128
 
105
129
  Every `paths` key is optional and falls back to the `UserBase` layout, so the package-level exports are exactly these factories with no overrides. See [docs/code/lib-access.md](./docs/code/lib-access.md).
106
130
 
131
+ `onAbandon` decides what the two disposal guards — the fifth wrong hash and a link older than 3 days — do to a pending registration. The default `'delete'` removes the row; use `'soft-delete'` or `'keep'` when other collections depend on it, since mongo has no cascade, or pass `deleteUserByEmail` to replace the writer outright. The link is rejected either way.
132
+
133
+ Guard notifications are debounced per address per template (15 minutes) so an unauthenticated `GET /check/verify-email/…` cannot be looped into a mail bomb aimed at a registered address. Pass `mailThrottle` for a different window or a Redis-backed one, `mailThrottle: ALWAYS_MAIL` to opt out, or `mailer` to replace the sender entirely (any object with the six `IVerifyEmailMailer` methods).
134
+
107
135
  ### GraphQL error helpers
108
136
 
109
137
  ```ts
@@ -1,4 +1,5 @@
1
1
  import { IVerifyEmailPaths, TAccessModel } from "../../../lib/access/accessPaths.mjs";
2
+ import { IVerifyEmailMailer } from "../../../lib/access/verifyEmailMailer.mjs";
2
3
  import { TConfirmNewEmail } from "../../../private/lib/access/db/confirmNewEmail.mjs";
3
4
  import { TIncReqTimes } from "../../../private/lib/access/db/incReqTimes.mjs";
4
5
  import { GraphQLNonNull } from 'graphql';
@@ -13,6 +14,12 @@ export interface IEmailChangeHashVerifyDeps {
13
14
  paths: IVerifyEmailPaths;
14
15
  confirmNewEmail: TConfirmNewEmail;
15
16
  incReqTimes: TIncReqTimes;
17
+ /**
18
+ * Who sends the three notifications this resolver can trigger. Optional, defaulting to the debounced
19
+ * SocketLabs binding — the client used to be constructed in `resolve`, so no caller could exercise a
20
+ * branch without a real send.
21
+ */
22
+ mailer?: IVerifyEmailMailer;
16
23
  }
17
24
  /**
18
25
  * Change email - Verify match between email and hash
@@ -1,5 +1,5 @@
1
- import { SocketLabsLib } from "../../../email/SocketLabsLib.mjs";
2
1
  import { DEFAULT_VERIFY_EMAIL_PATHS } from "../../../lib/access/accessPaths.mjs";
2
+ import { defaultVerifyEmailMailer } from "../../../lib/access/verifyEmailMailer.mjs";
3
3
  import { StringLib } from "../../../lib/StringLib.mjs";
4
4
  import { UserBase } from "../../models/MongoDB/UserBase.mjs";
5
5
  import confirmNewEmail from "../../../private/lib/access/db/confirmNewEmail.mjs";
@@ -18,7 +18,7 @@ async function handleHashMismatch(ctx, uId, requestTimes) {
18
18
  }
19
19
  await ctx.deps.incReqTimes(uId);
20
20
  // noinspection ES6MissingAwait
21
- ctx.socketLabs.wrongHash(ctx.uEmail, requestTimes);
21
+ ctx.mailer.wrongHash(ctx.uEmail, requestTimes);
22
22
  return false;
23
23
  }
24
24
  /**
@@ -26,7 +26,7 @@ async function handleHashMismatch(ctx, uId, requestTimes) {
26
26
  * free, accept it. Extracted from resolve() only to keep it inside the max-lines-per-function budget.
27
27
  */
28
28
  async function handleValidHash(ctx, uId, dateLastReq) {
29
- const { deps, user, uEmail, socketLabs } = ctx;
29
+ const { deps, user, uEmail, mailer } = ctx;
30
30
  const { paths } = deps;
31
31
  if (typeof dateLastReq === 'undefined') {
32
32
  // @fixme sentry 'dateLastReq is undefined'
@@ -39,7 +39,7 @@ async function handleValidHash(ctx, uId, dateLastReq) {
39
39
  if (StrLibObj.isoToTimestamp(day3ago) > StrLibObj.isoToTimestamp(dateLastReq)) {
40
40
  // dateLastReq too old then 3 days
41
41
  // noinspection ES6MissingAwait
42
- socketLabs.hashReqTooOld(uEmail);
42
+ mailer.hashReqTooOld(uEmail);
43
43
  return false;
44
44
  }
45
45
  // account is deleted -> maybe by admin for any reason
@@ -52,7 +52,7 @@ async function handleValidHash(ctx, uId, dateLastReq) {
52
52
  // if account is disabled, for any reason
53
53
  if (readPath(user, paths.disabled)) {
54
54
  // noinspection ES6MissingAwait
55
- socketLabs.accountDisabled(uEmail);
55
+ mailer.accountDisabled(uEmail);
56
56
  return false;
57
57
  }
58
58
  // valid request. meanwhile, has some user registered with this email address ??
@@ -71,37 +71,40 @@ async function handleValidHash(ctx, uId, dateLastReq) {
71
71
  * The projection is built from the same map the reads use, which is what keeps a read field from going
72
72
  * missing — the exact bug that made every wrong hash answer 500 through 5.1.0.
73
73
  */
74
- export const createEmailChangeHashVerifyMutation = (deps) => ({
75
- description: 'Change email - Verify match between email and hash',
76
- type: new GraphQLNonNull(GraphQLBoolean),
77
- args: {
78
- email: { type: new GraphQLNonNull(GraphQLString) },
79
- hash: { type: new GraphQLNonNull(GraphQLString) }
80
- },
81
- async resolve(_, args) {
82
- const { paths } = deps;
83
- const uEmail = args.email.toLowerCase();
84
- // search if the email exists
85
- // Every field this resolver reads must be listed. account.email.requestTimes was missing, and
86
- // because this is a .lean() read the absent key made handleHashMismatch throw 500 on *every*
87
- // wrong hash: the strike counter never advanced and the owner never got the wrongHash warning.
88
- const user = await deps.model
89
- .findOne({ [paths.newEmailTmp]: uEmail })
90
- .select(buildProjection([paths.hash, paths.dateLastReq, paths.requestTimes, paths.deleted, paths.disabled]))
91
- .lean();
92
- // if email not found, return (do not tell the user the real problem !)
93
- if (user === null) {
94
- return false; // @fixme throw
74
+ export const createEmailChangeHashVerifyMutation = (deps) => {
75
+ const mailer = deps.mailer ?? defaultVerifyEmailMailer;
76
+ return {
77
+ description: 'Change email - Verify match between email and hash',
78
+ type: new GraphQLNonNull(GraphQLBoolean),
79
+ args: {
80
+ email: { type: new GraphQLNonNull(GraphQLString) },
81
+ hash: { type: new GraphQLNonNull(GraphQLString) }
82
+ },
83
+ async resolve(_, args) {
84
+ const { paths } = deps;
85
+ const uEmail = args.email.toLowerCase();
86
+ // search if the email exists
87
+ // Every field this resolver reads must be listed. account.email.requestTimes was missing, and
88
+ // because this is a .lean() read the absent key made handleHashMismatch throw 500 on *every*
89
+ // wrong hash: the strike counter never advanced and the owner never got the wrongHash warning.
90
+ const user = await deps.model
91
+ .findOne({ [paths.newEmailTmp]: uEmail })
92
+ .select(buildProjection([paths.hash, paths.dateLastReq, paths.requestTimes, paths.deleted, paths.disabled]))
93
+ .lean();
94
+ // if email not found, return (do not tell the user the real problem !)
95
+ if (user === null) {
96
+ return false; // @fixme throw
97
+ }
98
+ const ctx = { deps, user, uEmail, mailer };
99
+ const uId = readPath(user, '_id');
100
+ const dateLastReq = readPath(user, paths.dateLastReq);
101
+ if (args.hash === readPath(user, paths.hash)) {
102
+ return handleValidHash(ctx, uId, dateLastReq);
103
+ }
104
+ return handleHashMismatch(ctx, uId, readPath(user, paths.requestTimes));
95
105
  }
96
- const ctx = { deps, user, uEmail, socketLabs: new SocketLabsLib() };
97
- const uId = readPath(user, '_id');
98
- const dateLastReq = readPath(user, paths.dateLastReq);
99
- if (args.hash === readPath(user, paths.hash)) {
100
- return handleValidHash(ctx, uId, dateLastReq);
101
- }
102
- return handleHashMismatch(ctx, uId, readPath(user, paths.requestTimes));
103
- }
104
- });
106
+ };
107
+ };
105
108
  /** `UserBase`-bound default — the mutation every existing consumer already imports. */
106
109
  export const emailChangeHashVerify = createEmailChangeHashVerifyMutation({
107
110
  model: UserBase,
@@ -94,3 +94,21 @@ export declare const DEFAULT_VERIFY_EMAIL_PATHS: IVerifyEmailPaths;
94
94
  * `undefined`, so pass only the keys being changed.
95
95
  */
96
96
  export declare function resolveVerifyEmailPaths(paths?: Partial<IVerifyEmailPaths>): IVerifyEmailPaths;
97
+ /**
98
+ * What the verify-email guards do with an abandoned pending registration — a link older than 3 days, or a
99
+ * fifth wrong hash.
100
+ *
101
+ * `'delete'` removes the row. It is the behaviour through 5.6.1, the only one the chain had, and it is safe
102
+ * for `UserBase`, whose rows own nothing. It is not safe for a model at the head of a hierarchy the package
103
+ * cannot see: once the factory accepts an arbitrary model, the package no longer knows what deleting a row
104
+ * costs, and with no foreign keys and no cascade in Mongo it takes the children with it in effect while
105
+ * leaving them behind in fact.
106
+ *
107
+ * `'soft-delete'` writes `paths.deleted` instead — the one tombstone convention {@link IVerifyEmailPaths}
108
+ * already declares and the chain otherwise only ever read. The guards test it for truthiness, so the value
109
+ * written is the caller's (`deletedValue`), boolean or timestamp alike.
110
+ *
111
+ * `'keep'` leaves the document alone. The guard still throws, so the link is still refused; only the row
112
+ * survives, and disposing of it becomes the caller's job.
113
+ */
114
+ export type TOnAbandon = 'delete' | 'soft-delete' | 'keep';
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Answers "may this notification be sent?" for a key. `true` sends, `false` drops silently.
3
+ *
4
+ * Every `handleIf*` guard in the verify-email chain is reachable from an unauthenticated
5
+ * `GET /check/verify-email/:email/:hash`, and three of them have no counter to lean on:
6
+ * `handleIfEmailAlreadyValid`, `handleIfAccountDeleted` and `handleIfAccountDisabled` mailed the address
7
+ * on *every* request through 5.6.1. Anyone who knew a registered address could make the platform's own
8
+ * SocketLabs account mail its owner once per request — a mail bomb aimed at a third party, plus a
9
+ * sending-reputation problem, out of a GET nobody had to authenticate.
10
+ *
11
+ * The contract is one function so a deployment can replace it. A Redis `SET key NX PX <window>` returning
12
+ * whether the key was created is the obvious cross-instance implementation, and is a one-liner here.
13
+ */
14
+ export type TMailThrottle = (key: string) => boolean | Promise<boolean>;
15
+ /** Options of {@link createMailThrottle}. */
16
+ export interface ICreateMailThrottleArgs {
17
+ /** How long a key stays blocked after a send. Default 15 minutes. */
18
+ windowMs?: number;
19
+ /** Cap on tracked keys, so an attacker cycling addresses cannot grow the map without bound. Default 5000. */
20
+ maxKeys?: number;
21
+ }
22
+ /**
23
+ * In-process debounce: one send per key per `windowMs`.
24
+ *
25
+ * In-process on purpose — no runtime dependency, nothing to configure, and the amplification it has to
26
+ * stop arrives through one process. Behind several instances it degrades to one mail per instance per
27
+ * window, which is a cap rather than the unbounded fan-out it replaces; pass your own `TMailThrottle`
28
+ * when one mail per address across the fleet matters.
29
+ *
30
+ * State is per instance. `createVerifyEmailFlow` builds one per flow, so two flows never share a window.
31
+ */
32
+ export declare const createMailThrottle: ({ windowMs, maxKeys }?: ICreateMailThrottleArgs) => TMailThrottle;
33
+ /** Never debounce — one mail per request, as 5.6.1 and earlier did. Pass as `mailThrottle` to opt out. */
34
+ export declare const ALWAYS_MAIL: TMailThrottle;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * In-process debounce: one send per key per `windowMs`.
3
+ *
4
+ * In-process on purpose — no runtime dependency, nothing to configure, and the amplification it has to
5
+ * stop arrives through one process. Behind several instances it degrades to one mail per instance per
6
+ * window, which is a cap rather than the unbounded fan-out it replaces; pass your own `TMailThrottle`
7
+ * when one mail per address across the fleet matters.
8
+ *
9
+ * State is per instance. `createVerifyEmailFlow` builds one per flow, so two flows never share a window.
10
+ */
11
+ export const createMailThrottle = ({ windowMs = 15 * 60 * 1000, maxKeys = 5000 } = {}) => {
12
+ /** key → epoch ms of the send that blocked it. Insertion-ordered, which is what makes the eviction cheap. */
13
+ const sentAt = new Map();
14
+ return function maySend(key) {
15
+ const now = Date.now();
16
+ const previous = sentAt.get(key);
17
+ if (previous !== undefined && now - previous < windowMs) {
18
+ return false;
19
+ }
20
+ // Delete before the set below so the map stays ordered by send time, oldest first.
21
+ sentAt.delete(key);
22
+ if (sentAt.size >= maxKeys) {
23
+ for (const [tracked, at] of sentAt) {
24
+ if (now - at >= windowMs) {
25
+ sentAt.delete(tracked);
26
+ }
27
+ }
28
+ }
29
+ if (sentAt.size >= maxKeys) {
30
+ // Still full, so every tracked key is inside its window: drop the oldest — the first key the
31
+ // insertion-ordered map yields. Refusing to send instead would let a flood of fresh addresses
32
+ // mute the notifications of real ones. `done` is only true for a `maxKeys` of 0, which caps
33
+ // nothing and so has nothing to evict.
34
+ const oldest = sentAt.keys().next();
35
+ if (!oldest.done) {
36
+ sentAt.delete(oldest.value);
37
+ }
38
+ }
39
+ sentAt.set(key, now);
40
+ return true;
41
+ };
42
+ };
43
+ /** Never debounce — one mail per request, as 5.6.1 and earlier did. Pass as `mailThrottle` to opt out. */
44
+ export const ALWAYS_MAIL = () => true;
45
+ //# sourceMappingURL=createMailThrottle.mjs.map
@@ -7,11 +7,32 @@ import { TSetEmailHash } from "../../private/lib/access/db/setEmailHash.mjs";
7
7
  import { TUserData4VerifyEmail } from "../../private/lib/access/db/userData4VerifyEmail.mjs";
8
8
  import { TEmailChangeHashVerifyMutation } from '../../graphQL/schema/mutations/emailChangeHashVerify.mjs';
9
9
  import { TVerifyEmailRouter } from '../../koa/router/verifyEmail.mjs';
10
- import { IVerifyEmailPaths, TAccessModel } from './accessPaths.mjs';
11
- /** What the factory needs: the account model, plus any path that differs from the default layout. */
10
+ import { IVerifyEmailPaths, TAccessModel, TOnAbandon } from './accessPaths.mjs';
11
+ import { TMailThrottle } from './createMailThrottle.mjs';
12
+ import { IVerifyEmailMailer } from './verifyEmailMailer.mjs';
13
+ /** What the factory needs: the account model, plus any path or policy that differs from the default. */
12
14
  export interface ICreateVerifyEmailFlowArgs {
13
15
  model: TAccessModel;
14
16
  paths?: Partial<IVerifyEmailPaths>;
17
+ /** How an abandoned/expired registration is disposed of. Default `'delete'` — current behaviour. */
18
+ onAbandon?: TOnAbandon;
19
+ /**
20
+ * Value `'soft-delete'` writes to `paths.deleted`. A function is called once per write, so a layout
21
+ * storing a timestamp passes `() => new Date()`. Default `true`, matching `UserBase`. Ignored by the
22
+ * other two modes.
23
+ */
24
+ deletedValue?: unknown;
25
+ /** Full override of the disposal writer; wins over `onAbandon` and `deletedValue`. */
26
+ deleteUserByEmail?: TDeleteUserByEmail;
27
+ /** Who sends the verify-email notifications. Default: SocketLabs, debounced by `mailThrottle`. */
28
+ mailer?: IVerifyEmailMailer;
29
+ /**
30
+ * Debounce applied to every notification an unauthenticated request can trigger. Default: a 15 minute
31
+ * per-address, per-template window. Pass `ALWAYS_MAIL` for the send-every-time behaviour of 5.6.1 and earlier, or a
32
+ * Redis-backed one to share the window across instances. Ignored when `mailer` is supplied — wrap it
33
+ * yourself with `throttleMailer` if you want both.
34
+ */
35
+ mailThrottle?: TMailThrottle;
15
36
  }
16
37
  /** Everything the verify-email chain exposes, bound to the model and paths passed in. */
17
38
  export interface IVerifyEmailFlow {
@@ -37,12 +58,24 @@ export interface IVerifyEmailFlow {
37
58
  * flow reads: a schema storing the verification state as one required-members subdocument is left
38
59
  * invalid by unsetting a single member. Pass the container path in that case. See `IVerifyEmailPaths`.
39
60
  *
61
+ * Two guards dispose of an abandoned registration — the fifth wrong hash and a link older than 3 days.
62
+ * Through 5.6.1 that always meant `deleteOne`, which is wrong for any row other rows depend on: the
63
+ * package has no idea what a delete costs in a schema it was handed, and a mongo collection has no
64
+ * cascade to lean on. `onAbandon` picks the policy; `deleteUserByEmail` replaces the writer outright.
65
+ * Whatever it does, both guards still throw — disposal never decides whether the link is honoured.
66
+ *
67
+ * Replacing `flow.deleteUserByEmail` on the returned object does nothing, by design: the guards close
68
+ * over the writer at construction time. The value returned is the same one they hold, so it reports the
69
+ * policy rather than setting it.
70
+ *
40
71
  * ```ts
41
72
  * const flow = createVerifyEmailFlow({
42
73
  * model: Account,
43
- * paths: { email: 'mail', valid: 'verified', verifyClear: ['verification'] }
74
+ * paths: { email: 'mail', valid: 'verified', verifyClear: ['verification'] },
75
+ * onAbandon: 'soft-delete',
76
+ * deletedValue: () => new Date()
44
77
  * })
45
78
  * router.get('/check/verify-email/:email/:hash', flow.routerVerifyEmail())
46
79
  * ```
47
80
  */
48
- export declare const createVerifyEmailFlow: ({ model, paths }: ICreateVerifyEmailFlowArgs) => IVerifyEmailFlow;
81
+ export declare const createVerifyEmailFlow: ({ model, paths, onAbandon, deletedValue, deleteUserByEmail, mailer, mailThrottle }: ICreateVerifyEmailFlowArgs) => IVerifyEmailFlow;
@@ -1,16 +1,21 @@
1
1
  import { createAssertVerifyEmailAllowed } from "../../private/lib/access/assertVerifyEmailAllowed.mjs";
2
+ import { createAbandonUser } from "../../private/lib/access/db/abandonUser.mjs";
2
3
  import { createConfirmNewEmail } from "../../private/lib/access/db/confirmNewEmail.mjs";
3
- import { createDeleteUserByEmail } from "../../private/lib/access/db/deleteUserByEmail.mjs";
4
4
  import { createEnableEmailAccess } from "../../private/lib/access/db/enableEmailAccess.mjs";
5
5
  import { createIncReqTimes } from "../../private/lib/access/db/incReqTimes.mjs";
6
6
  import { createSetEmailHash } from "../../private/lib/access/db/setEmailHash.mjs";
7
7
  import { createUserData4VerifyEmail } from "../../private/lib/access/db/userData4VerifyEmail.mjs";
8
+ import { createHandleIfAccountDeleted } from "../../private/lib/access/handleIfAccountDeleted.mjs";
9
+ import { createHandleIfAccountDisabled } from "../../private/lib/access/handleIfAccountDisabled.mjs";
10
+ import { createHandleIfEmailAlreadyValid } from "../../private/lib/access/handleIfEmailAlreadyValid.mjs";
8
11
  import { createHandleIfHashBad } from "../../private/lib/access/handleIfHashBad.mjs";
9
12
  import { createHandleIfMoreThan3DaysPassed } from "../../private/lib/access/handleIfMoreThan3DaysPassed.mjs";
10
13
  import { createHandleIfTooMuchRequestsTimes } from "../../private/lib/access/handleIfTooMuchRequestsTimes.mjs";
11
14
  import { createEmailChangeHashVerifyMutation } from '../../graphQL/schema/mutations/emailChangeHashVerify.mjs';
12
15
  import { createVerifyEmailRouter } from '../../koa/router/verifyEmail.mjs';
13
16
  import { resolveVerifyEmailPaths } from './accessPaths.mjs';
17
+ import { createMailThrottle } from './createMailThrottle.mjs';
18
+ import { socketLabsVerifyEmailMailer, throttleMailer } from './verifyEmailMailer.mjs';
14
19
  /**
15
20
  * Build the whole email-verification chain against any mongoose model.
16
21
  *
@@ -23,40 +28,58 @@ import { resolveVerifyEmailPaths } from './accessPaths.mjs';
23
28
  * flow reads: a schema storing the verification state as one required-members subdocument is left
24
29
  * invalid by unsetting a single member. Pass the container path in that case. See `IVerifyEmailPaths`.
25
30
  *
31
+ * Two guards dispose of an abandoned registration — the fifth wrong hash and a link older than 3 days.
32
+ * Through 5.6.1 that always meant `deleteOne`, which is wrong for any row other rows depend on: the
33
+ * package has no idea what a delete costs in a schema it was handed, and a mongo collection has no
34
+ * cascade to lean on. `onAbandon` picks the policy; `deleteUserByEmail` replaces the writer outright.
35
+ * Whatever it does, both guards still throw — disposal never decides whether the link is honoured.
36
+ *
37
+ * Replacing `flow.deleteUserByEmail` on the returned object does nothing, by design: the guards close
38
+ * over the writer at construction time. The value returned is the same one they hold, so it reports the
39
+ * policy rather than setting it.
40
+ *
26
41
  * ```ts
27
42
  * const flow = createVerifyEmailFlow({
28
43
  * model: Account,
29
- * paths: { email: 'mail', valid: 'verified', verifyClear: ['verification'] }
44
+ * paths: { email: 'mail', valid: 'verified', verifyClear: ['verification'] },
45
+ * onAbandon: 'soft-delete',
46
+ * deletedValue: () => new Date()
30
47
  * })
31
48
  * router.get('/check/verify-email/:email/:hash', flow.routerVerifyEmail())
32
49
  * ```
33
50
  */
34
- export const createVerifyEmailFlow = ({ model, paths }) => {
51
+ export const createVerifyEmailFlow = ({ model, paths, onAbandon = 'delete', deletedValue, deleteUserByEmail, mailer, mailThrottle }) => {
35
52
  const resolved = resolveVerifyEmailPaths(paths);
53
+ const resolvedMailer = mailer ?? throttleMailer(socketLabsVerifyEmailMailer, mailThrottle ?? createMailThrottle());
36
54
  const userData4VerifyEmail = createUserData4VerifyEmail(model, resolved);
37
- const enableEmailAccess = createEnableEmailAccess(model, resolved);
55
+ const enableEmailAccess = createEnableEmailAccess(model, resolved, resolvedMailer);
38
56
  const confirmNewEmail = createConfirmNewEmail(model, resolved);
39
- const deleteUserByEmail = createDeleteUserByEmail(model, resolved);
57
+ // One writer, used by the guards and handed back — the returned member cannot disagree with what runs.
58
+ const abandonUser = deleteUserByEmail ?? createAbandonUser({ model, paths: resolved, mode: onAbandon, deletedValue });
40
59
  const incReqTimes = createIncReqTimes(model, resolved);
41
60
  const assertVerifyEmailAllowed = createAssertVerifyEmailAllowed({
42
61
  paths: resolved,
43
- handleIfHashBad: createHandleIfHashBad(incReqTimes),
44
- handleIfMoreThan3DaysPassed: createHandleIfMoreThan3DaysPassed(deleteUserByEmail),
45
- handleIfTooMuchRequestsTimes: createHandleIfTooMuchRequestsTimes(deleteUserByEmail)
62
+ handleIfEmailAlreadyValid: createHandleIfEmailAlreadyValid(resolvedMailer),
63
+ handleIfHashBad: createHandleIfHashBad(incReqTimes, resolvedMailer),
64
+ handleIfMoreThan3DaysPassed: createHandleIfMoreThan3DaysPassed(abandonUser, resolvedMailer),
65
+ handleIfTooMuchRequestsTimes: createHandleIfTooMuchRequestsTimes(abandonUser, resolvedMailer),
66
+ handleIfAccountDeleted: createHandleIfAccountDeleted(resolvedMailer),
67
+ handleIfAccountDisabled: createHandleIfAccountDisabled(resolvedMailer)
46
68
  });
47
69
  return {
48
70
  userData4VerifyEmail,
49
71
  setEmailHash: createSetEmailHash(model, resolved),
50
72
  enableEmailAccess,
51
73
  confirmNewEmail,
52
- deleteUserByEmail,
74
+ deleteUserByEmail: abandonUser,
53
75
  incReqTimes,
54
76
  assertVerifyEmailAllowed,
55
77
  emailChangeHashVerify: createEmailChangeHashVerifyMutation({
56
78
  model,
57
79
  paths: resolved,
58
80
  confirmNewEmail,
59
- incReqTimes
81
+ incReqTimes,
82
+ mailer: resolvedMailer
60
83
  }),
61
84
  routerVerifyEmail: createVerifyEmailRouter({
62
85
  userData4VerifyEmail,
@@ -0,0 +1,54 @@
1
+ import { TMailThrottle } from './createMailThrottle.mjs';
2
+ /**
3
+ * Every notification the email-verification chain sends.
4
+ *
5
+ * Each guard used to construct its own `SocketLabsLib` inline, which made no branch of the chain drivable
6
+ * from an integration suite: with real credentials in `.env` the only two paths reachable without mailing
7
+ * a real person were "address not found" and the bad-DB guard. Everything else was unit-tests-with-mocks
8
+ * only — including the success path, since `enableEmailAccess` sent the welcome mail itself.
9
+ *
10
+ * Structural, not nominal: any object carrying these six methods satisfies it, `SocketLabsLib` included.
11
+ * `sendWelcome` is the only one not reachable unauthenticated, and the only one the debounce leaves alone.
12
+ */
13
+ export interface IVerifyEmailMailer {
14
+ /** The address is already verified. No counter guards this branch — see {@link createMailThrottle}. */
15
+ emailAlreadyValid(email: string): Promise<unknown>;
16
+ /** The hash in the link does not match the stored one. `times` is the strike this attempt makes. */
17
+ wrongHash(email: string, times: number): Promise<unknown>;
18
+ /** The strike counter reached 5. */
19
+ tooMuchVerifyRequests(email: string): Promise<unknown>;
20
+ /** The link is older than the 3-day window. */
21
+ hashReqTooOld(email: string): Promise<unknown>;
22
+ /** The account is disabled — or deleted: there is no `accountDeleted` template, so both guards send this one. */
23
+ accountDisabled(email: string): Promise<unknown>;
24
+ /** The account has just been activated. Success path only, so never debounced. */
25
+ sendWelcome(email: string): Promise<unknown>;
26
+ }
27
+ /**
28
+ * SocketLabs, constructed per call exactly as the guards did inline.
29
+ *
30
+ * Per call rather than once at module load because the constructor reads `process.env` (server id, API key,
31
+ * platform name, domain, sender) and builds a client from it — hoisting that to import time would pin
32
+ * whatever the environment held when the module was first resolved.
33
+ */
34
+ export declare const socketLabsVerifyEmailMailer: IVerifyEmailMailer;
35
+ /**
36
+ * Wrap a mailer so each guard notification is asked of `throttle` first, keyed `<method>:<address>`.
37
+ *
38
+ * A dropped send resolves `undefined` and is invisible to the caller: the guard still throws, so the
39
+ * request still gets the same redirect it always did. Only the mail is suppressed.
40
+ *
41
+ * `sendWelcome` passes straight through. It fires once, on the success path, at the moment the account is
42
+ * activated — debouncing it could silently swallow the welcome mail of an address that re-registered
43
+ * inside the window, and no unauthenticated caller can trigger it twice anyway (the second request meets
44
+ * `handleIfEmailAlreadyValid`).
45
+ */
46
+ export declare const throttleMailer: (mailer: IVerifyEmailMailer, throttle: TMailThrottle) => IVerifyEmailMailer;
47
+ /**
48
+ * What the `UserBase`-bound guard exports mail through: SocketLabs, debounced on the default window.
49
+ *
50
+ * One shared throttle for the whole process, because these bindings are one shared chain — the
51
+ * `routerVerifyEmail` export every existing consumer imports. `createVerifyEmailFlow` does not use this
52
+ * value; it builds its own mailer and its own throttle per flow.
53
+ */
54
+ export declare const defaultVerifyEmailMailer: IVerifyEmailMailer;
@@ -0,0 +1,48 @@
1
+ import { SocketLabsLib } from "../../email/SocketLabsLib.mjs";
2
+ import { createMailThrottle } from './createMailThrottle.mjs';
3
+ /**
4
+ * SocketLabs, constructed per call exactly as the guards did inline.
5
+ *
6
+ * Per call rather than once at module load because the constructor reads `process.env` (server id, API key,
7
+ * platform name, domain, sender) and builds a client from it — hoisting that to import time would pin
8
+ * whatever the environment held when the module was first resolved.
9
+ */
10
+ export const socketLabsVerifyEmailMailer = {
11
+ emailAlreadyValid: (email) => new SocketLabsLib().emailAlreadyValid(email),
12
+ wrongHash: (email, times) => new SocketLabsLib().wrongHash(email, times),
13
+ tooMuchVerifyRequests: (email) => new SocketLabsLib().tooMuchVerifyRequests(email),
14
+ hashReqTooOld: (email) => new SocketLabsLib().hashReqTooOld(email),
15
+ accountDisabled: (email) => new SocketLabsLib().accountDisabled(email),
16
+ sendWelcome: (email) => new SocketLabsLib().sendWelcome(email)
17
+ };
18
+ /**
19
+ * Wrap a mailer so each guard notification is asked of `throttle` first, keyed `<method>:<address>`.
20
+ *
21
+ * A dropped send resolves `undefined` and is invisible to the caller: the guard still throws, so the
22
+ * request still gets the same redirect it always did. Only the mail is suppressed.
23
+ *
24
+ * `sendWelcome` passes straight through. It fires once, on the success path, at the moment the account is
25
+ * activated — debouncing it could silently swallow the welcome mail of an address that re-registered
26
+ * inside the window, and no unauthenticated caller can trigger it twice anyway (the second request meets
27
+ * `handleIfEmailAlreadyValid`).
28
+ */
29
+ export const throttleMailer = (mailer, throttle) => {
30
+ const gated = async (kind, email, deliver) => (await throttle(`${kind}:${email}`)) ? deliver() : undefined;
31
+ return {
32
+ emailAlreadyValid: (email) => gated('emailAlreadyValid', email, () => mailer.emailAlreadyValid(email)),
33
+ wrongHash: (email, times) => gated('wrongHash', email, () => mailer.wrongHash(email, times)),
34
+ tooMuchVerifyRequests: (email) => gated('tooMuchVerifyRequests', email, () => mailer.tooMuchVerifyRequests(email)),
35
+ hashReqTooOld: (email) => gated('hashReqTooOld', email, () => mailer.hashReqTooOld(email)),
36
+ accountDisabled: (email) => gated('accountDisabled', email, () => mailer.accountDisabled(email)),
37
+ sendWelcome: (email) => mailer.sendWelcome(email)
38
+ };
39
+ };
40
+ /**
41
+ * What the `UserBase`-bound guard exports mail through: SocketLabs, debounced on the default window.
42
+ *
43
+ * One shared throttle for the whole process, because these bindings are one shared chain — the
44
+ * `routerVerifyEmail` export every existing consumer imports. `createVerifyEmailFlow` does not use this
45
+ * value; it builds its own mailer and its own throttle per flow.
46
+ */
47
+ export const defaultVerifyEmailMailer = throttleMailer(socketLabsVerifyEmailMailer, createMailThrottle());
48
+ //# sourceMappingURL=verifyEmailMailer.mjs.map
@@ -1,5 +1,8 @@
1
1
  import { IVerifyEmailPaths } from "../../../lib/access/accessPaths.mjs";
2
2
  import { Types } from 'mongoose';
3
+ import { THandleIfAccountDeleted } from './handleIfAccountDeleted.mjs';
4
+ import { THandleIfAccountDisabled } from './handleIfAccountDisabled.mjs';
5
+ import { THandleIfEmailAlreadyValid } from './handleIfEmailAlreadyValid.mjs';
3
6
  import { THandleIfHashBad } from './handleIfHashBad.mjs';
4
7
  import { THandleIfMoreThan3DaysPassed } from './handleIfMoreThan3DaysPassed.mjs';
5
8
  import { THandleIfTooMuchRequestsTimes } from './handleIfTooMuchRequestsTimes.mjs';
@@ -17,12 +20,21 @@ export interface IVerifyEmailUser {
17
20
  disabled?: boolean;
18
21
  };
19
22
  }
20
- /** Collaborators the chain needs, all bound to the same model + paths by the caller. */
23
+ /**
24
+ * Collaborators the chain needs, all bound to the same model + paths by the caller.
25
+ *
26
+ * The three mail-only guards are here for the same reason the writer-backed ones are: hard-importing them
27
+ * meant the mailer they use was fixed at module load, so no caller could reach these branches without a real
28
+ * SocketLabs send. `handleBadDB` stays a direct import — it writes nothing and mails nobody.
29
+ */
21
30
  export interface IAssertVerifyEmailAllowedDeps {
22
31
  paths: IVerifyEmailPaths;
32
+ handleIfEmailAlreadyValid: THandleIfEmailAlreadyValid;
23
33
  handleIfHashBad: THandleIfHashBad;
24
34
  handleIfMoreThan3DaysPassed: THandleIfMoreThan3DaysPassed;
25
35
  handleIfTooMuchRequestsTimes: THandleIfTooMuchRequestsTimes;
36
+ handleIfAccountDeleted: THandleIfAccountDeleted;
37
+ handleIfAccountDisabled: THandleIfAccountDisabled;
26
38
  }
27
39
  /**
28
40
  * Run every guard that must pass before an email-verification link is honoured, in order.
@@ -37,7 +37,7 @@ export const createAssertVerifyEmailAllowed = (deps) => async function assertVer
37
37
  const dateLastReq = readPath(user, paths.dateLastReq);
38
38
  const deleted = readPath(user, paths.deleted);
39
39
  const disabled = readPath(user, paths.disabled);
40
- await handleIfEmailAlreadyValid(email, readPath(user, paths.valid));
40
+ await deps.handleIfEmailAlreadyValid(email, readPath(user, paths.valid));
41
41
  handleBadDB(requestTimes, dateLastReq);
42
42
  await deps.handleIfTooMuchRequestsTimes(email, requestTimes);
43
43
  // dbHash is the value STORED for this account — never the one supplied in the URL
@@ -53,15 +53,18 @@ export const createAssertVerifyEmailAllowed = (deps) => async function assertVer
53
53
  // and these are exactly what the driver found — which is only ever a boolean once
54
54
  // scripts/migrate-account-disabled-to-boolean.mjs has run. On un-migrated data a stored 'false'
55
55
  // is a truthy string and blocks the account; the fix is the migration, not a coercion here.
56
- await handleIfAccountDeleted(email, deleted);
57
- await handleIfAccountDisabled(email, disabled);
56
+ await deps.handleIfAccountDeleted(email, deleted);
57
+ await deps.handleIfAccountDisabled(email, disabled);
58
58
  return uId;
59
59
  };
60
60
  /** `UserBase`-bound default — the behaviour every existing consumer already imports. */
61
61
  export const assertVerifyEmailAllowed = createAssertVerifyEmailAllowed({
62
62
  paths: DEFAULT_VERIFY_EMAIL_PATHS,
63
+ handleIfEmailAlreadyValid,
63
64
  handleIfHashBad,
64
65
  handleIfMoreThan3DaysPassed,
65
- handleIfTooMuchRequestsTimes
66
+ handleIfTooMuchRequestsTimes,
67
+ handleIfAccountDeleted,
68
+ handleIfAccountDisabled
66
69
  });
67
70
  //# sourceMappingURL=assertVerifyEmailAllowed.mjs.map