@axiumine/koa-utils 5.1.1 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +26 -0
  2. package/dist/graphQL/schema/mutations/emailChangeHashVerify.d.mts +19 -1
  3. package/dist/graphQL/schema/mutations/emailChangeHashVerify.mjs +31 -15
  4. package/dist/graphQL/schema/mutations/emailChangeHashVerify.mjs.map +1 -1
  5. package/dist/graphQL/schema/mutations/resetPwd.d.mts +19 -2
  6. package/dist/graphQL/schema/mutations/resetPwd.mjs +60 -35
  7. package/dist/graphQL/schema/mutations/resetPwd.mjs.map +1 -1
  8. package/dist/graphQL/schema/mutations/updatePassword.d.mts +21 -1
  9. package/dist/graphQL/schema/mutations/updatePassword.mjs +63 -11
  10. package/dist/graphQL/schema/mutations/updatePassword.mjs.map +1 -1
  11. package/dist/koa/router/verifyEmail.d.mts +22 -1
  12. package/dist/koa/router/verifyEmail.mjs +18 -9
  13. package/dist/koa/router/verifyEmail.mjs.map +1 -1
  14. package/dist/lib/access/accessPaths.d.mts +92 -0
  15. package/dist/lib/access/accessPaths.mjs +46 -0
  16. package/dist/lib/access/accessPaths.mjs.map +1 -0
  17. package/dist/lib/access/createResetPwdFlow.d.mts +33 -0
  18. package/dist/lib/access/createResetPwdFlow.mjs +42 -0
  19. package/dist/lib/access/createResetPwdFlow.mjs.map +1 -0
  20. package/dist/lib/access/createVerifyEmailFlow.d.mts +48 -0
  21. package/dist/lib/access/createVerifyEmailFlow.mjs +68 -0
  22. package/dist/lib/access/createVerifyEmailFlow.mjs.map +1 -0
  23. package/dist/private/lib/access/assertVerifyEmailAllowed.d.mts +20 -2
  24. package/dist/private/lib/access/assertVerifyEmailAllowed.mjs +30 -12
  25. package/dist/private/lib/access/assertVerifyEmailAllowed.mjs.map +1 -1
  26. package/dist/private/lib/access/db/confirmNewEmail.d.mts +7 -1
  27. package/dist/private/lib/access/db/confirmNewEmail.mjs +12 -11
  28. package/dist/private/lib/access/db/confirmNewEmail.mjs.map +1 -1
  29. package/dist/private/lib/access/db/deleteUserByEmail.d.mts +7 -1
  30. package/dist/private/lib/access/db/deleteUserByEmail.mjs +6 -3
  31. package/dist/private/lib/access/db/deleteUserByEmail.mjs.map +1 -1
  32. package/dist/private/lib/access/db/enableEmailAccess.d.mts +6 -1
  33. package/dist/private/lib/access/db/enableEmailAccess.mjs +9 -9
  34. package/dist/private/lib/access/db/enableEmailAccess.mjs.map +1 -1
  35. package/dist/private/lib/access/db/getResetPwd.d.mts +11 -4
  36. package/dist/private/lib/access/db/getResetPwd.mjs +17 -12
  37. package/dist/private/lib/access/db/getResetPwd.mjs.map +1 -1
  38. package/dist/private/lib/access/db/incReqTimes.d.mts +6 -1
  39. package/dist/private/lib/access/db/incReqTimes.mjs +6 -3
  40. package/dist/private/lib/access/db/incReqTimes.mjs.map +1 -1
  41. package/dist/private/lib/access/db/removeResetReq.d.mts +7 -1
  42. package/dist/private/lib/access/db/removeResetReq.mjs +16 -7
  43. package/dist/private/lib/access/db/removeResetReq.mjs.map +1 -1
  44. package/dist/private/lib/access/db/saveResetReq.d.mts +6 -1
  45. package/dist/private/lib/access/db/saveResetReq.mjs +10 -7
  46. package/dist/private/lib/access/db/saveResetReq.mjs.map +1 -1
  47. package/dist/private/lib/access/db/setEmailHash.d.mts +6 -1
  48. package/dist/private/lib/access/db/setEmailHash.mjs +9 -6
  49. package/dist/private/lib/access/db/setEmailHash.mjs.map +1 -1
  50. package/dist/private/lib/access/db/updatePasswordDb.d.mts +7 -1
  51. package/dist/private/lib/access/db/updatePasswordDb.mjs +6 -3
  52. package/dist/private/lib/access/db/updatePasswordDb.mjs.map +1 -1
  53. package/dist/private/lib/access/db/userData4VerifyEmail.d.mts +6 -3
  54. package/dist/private/lib/access/db/userData4VerifyEmail.mjs +12 -5
  55. package/dist/private/lib/access/db/userData4VerifyEmail.mjs.map +1 -1
  56. package/dist/private/lib/access/handleIfHashBad.d.mts +10 -3
  57. package/dist/private/lib/access/handleIfHashBad.mjs +9 -5
  58. package/dist/private/lib/access/handleIfHashBad.mjs.map +1 -1
  59. package/dist/private/lib/access/handleIfMoreThan3DaysPassed.d.mts +12 -1
  60. package/dist/private/lib/access/handleIfMoreThan3DaysPassed.mjs +11 -3
  61. package/dist/private/lib/access/handleIfMoreThan3DaysPassed.mjs.map +1 -1
  62. package/dist/private/lib/access/handleIfTooMuchRequestsTimes.d.mts +12 -1
  63. package/dist/private/lib/access/handleIfTooMuchRequestsTimes.mjs +11 -3
  64. package/dist/private/lib/access/handleIfTooMuchRequestsTimes.mjs.map +1 -1
  65. package/dist/private/lib/access/pathTools.d.mts +25 -0
  66. package/dist/private/lib/access/pathTools.mjs +43 -0
  67. package/dist/private/lib/access/pathTools.mjs.map +1 -0
  68. package/package.json +13 -1
package/README.md CHANGED
@@ -76,6 +76,32 @@ const Mutation = new GraphQLObjectType({
76
76
  })
77
77
  ```
78
78
 
79
+ ### Access flows on your own model
80
+
81
+ The mutations above are bound to this package's `UserBase` model (collection `user`, fields under `login.*` / `account.*`). If your accounts live elsewhere, build the same flows against your own model and field layout instead:
82
+
83
+ ```ts
84
+ import { createResetPwdFlow } from '@axiumine/koa-utils/lib/access/createResetPwdFlow'
85
+ import { createVerifyEmailFlow } from '@axiumine/koa-utils/lib/access/createVerifyEmailFlow'
86
+
87
+ const { resetPwd, updatePassword } = createResetPwdFlow({
88
+ model: Account,
89
+ paths: {
90
+ email: 'mail',
91
+ password: 'pwd',
92
+ name: 'profile.fullName',
93
+ resetDateReq: 'resetPwd.resetDateReq',
94
+ resetHash: 'resetPwd.resetHash',
95
+ resetClear: ['resetPwd'] // paths to $unset — a container, not its members, on a strict subdocument
96
+ }
97
+ })
98
+
99
+ const verify = createVerifyEmailFlow({ model: Account, paths: { email: 'mail', valid: 'verified' } })
100
+ router.get('/check/verify-email/:email/:hash', verify.routerVerifyEmail())
101
+ ```
102
+
103
+ 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).
104
+
79
105
  ### GraphQL error helpers
80
106
 
81
107
  ```ts
@@ -1,12 +1,26 @@
1
+ import { IVerifyEmailPaths, TAccessModel } from "../../../lib/access/accessPaths.mjs";
2
+ import { TConfirmNewEmail } from "../../../private/lib/access/db/confirmNewEmail.mjs";
3
+ import { TIncReqTimes } from "../../../private/lib/access/db/incReqTimes.mjs";
1
4
  import { GraphQLNonNull } from 'graphql';
2
5
  interface IArgs {
3
6
  email: string;
4
7
  hash: string;
5
8
  }
9
+ /** Model, field map and writers the resolver needs, all bound together by the caller. */
10
+ export interface IEmailChangeHashVerifyDeps {
11
+ model: TAccessModel;
12
+ paths: IVerifyEmailPaths;
13
+ confirmNewEmail: TConfirmNewEmail;
14
+ incReqTimes: TIncReqTimes;
15
+ }
6
16
  /**
7
17
  * Change email - Verify match between email and hash
18
+ *
19
+ * The collection and every field path come from `deps`, so the same resolver serves any account model.
20
+ * The projection is built from the same map the reads use, which is what keeps a read field from going
21
+ * missing — the exact bug that made every wrong hash answer 500 through 5.1.0.
8
22
  */
9
- export declare const emailChangeHashVerify: {
23
+ export declare const createEmailChangeHashVerifyMutation: (deps: IEmailChangeHashVerifyDeps) => {
10
24
  description: string;
11
25
  type: GraphQLNonNull<import("graphql").GraphQLScalarType<boolean, boolean>>;
12
26
  args: {
@@ -19,4 +33,8 @@ export declare const emailChangeHashVerify: {
19
33
  };
20
34
  resolve(_: unknown, args: IArgs): Promise<boolean>;
21
35
  };
36
+ /** Shape of the bound mutation, for the modules that take it as a dependency. */
37
+ export type TEmailChangeHashVerifyMutation = ReturnType<typeof createEmailChangeHashVerifyMutation>;
38
+ /** `UserBase`-bound default — the mutation every existing consumer already imports. */
39
+ export declare const emailChangeHashVerify: TEmailChangeHashVerifyMutation;
22
40
  export {};
@@ -1,29 +1,35 @@
1
1
  import { SocketLabsLib } from "../../../email/SocketLabsLib.mjs";
2
+ import { DEFAULT_VERIFY_EMAIL_PATHS } from "../../../lib/access/accessPaths.mjs";
2
3
  import { StringLib } from "../../../lib/StringLib.mjs";
3
4
  import { UserBase } from "../../models/MongoDB/UserBase.mjs";
4
5
  import confirmNewEmail from "../../../private/lib/access/db/confirmNewEmail.mjs";
5
6
  import { incReqTimes } from "../../../private/lib/access/db/incReqTimes.mjs";
7
+ import { buildProjection, readPath } from "../../../private/lib/access/pathTools.mjs";
6
8
  import { throwInternalError } from "../../throw/throwInternalError.mjs";
7
9
  import { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql';
8
10
  /**
9
11
  * The submitted hash does not match the stored one: count the attempt and warn the account owner.
10
12
  * Extracted from resolve() only to keep it inside the max-lines-per-function budget — behaviour unchanged.
11
13
  */
12
- async function handleHashMismatch(uId, uEmail, requestTimes, SocketLabsObj) {
14
+ async function handleHashMismatch(incReqTimesFn, uId, uEmail, requestTimes, SocketLabsObj) {
13
15
  // hash failed
14
16
  console.debug('HASH FAILED');
15
17
  if (typeof requestTimes === 'undefined') {
16
18
  throw throwInternalError();
17
19
  }
18
- await incReqTimes(uId);
20
+ await incReqTimesFn(uId);
19
21
  // noinspection ES6MissingAwait
20
22
  SocketLabsObj.wrongHash(uEmail, requestTimes);
21
23
  return false;
22
24
  }
23
25
  /**
24
26
  * Change email - Verify match between email and hash
27
+ *
28
+ * The collection and every field path come from `deps`, so the same resolver serves any account model.
29
+ * The projection is built from the same map the reads use, which is what keeps a read field from going
30
+ * missing — the exact bug that made every wrong hash answer 500 through 5.1.0.
25
31
  */
26
- export const emailChangeHashVerify = {
32
+ export const createEmailChangeHashVerifyMutation = (deps) => ({
27
33
  description: 'Change email - Verify match between email and hash',
28
34
  type: new GraphQLNonNull(GraphQLBoolean),
29
35
  args: {
@@ -31,14 +37,16 @@ export const emailChangeHashVerify = {
31
37
  hash: { type: new GraphQLNonNull(GraphQLString) }
32
38
  },
33
39
  async resolve(_, args) {
40
+ const { paths } = deps;
34
41
  const { email, hash } = args;
35
42
  const uEmail = email.toLowerCase();
36
43
  // search if the email exists
37
44
  // Every field this resolver reads must be listed. account.email.requestTimes was missing, and
38
45
  // because this is a .lean() read the absent key made handleHashMismatch throw 500 on *every*
39
46
  // wrong hash: the strike counter never advanced and the owner never got the wrongHash warning.
40
- const user = await UserBase.findOne({ 'account.email.newEmailTmp': uEmail })
41
- .select('_id account.email.hash account.email.dateLastReq account.email.requestTimes account.deleted account.disabled')
47
+ const user = await deps.model
48
+ .findOne({ [paths.newEmailTmp]: uEmail })
49
+ .select(buildProjection([paths.hash, paths.dateLastReq, paths.requestTimes, paths.deleted, paths.disabled]))
42
50
  .lean();
43
51
  // if email not found, return
44
52
  if (user === null) {
@@ -50,9 +58,10 @@ export const emailChangeHashVerify = {
50
58
  const SocketLabsObj = new SocketLabsLib();
51
59
  const StrLibObj = new StringLib();
52
60
  console.debug('comparing hash ');
53
- const accountEmail = user.account.email;
54
- if (hash === accountEmail.hash) {
55
- if (typeof accountEmail.dateLastReq === 'undefined') {
61
+ const uId = readPath(user, '_id');
62
+ const dateLastReq = readPath(user, paths.dateLastReq);
63
+ if (hash === readPath(user, paths.hash)) {
64
+ if (typeof dateLastReq === 'undefined') {
56
65
  // @fixme sentry 'dateLastReq is undefined'
57
66
  throw throwInternalError();
58
67
  }
@@ -62,7 +71,7 @@ export const emailChangeHashVerify = {
62
71
  */
63
72
  const now = new Date();
64
73
  const day3ago = new Date(now.setDate(now.getDate() - 3));
65
- const tsReq = StrLibObj.isoToTimestamp(accountEmail.dateLastReq);
74
+ const tsReq = StrLibObj.isoToTimestamp(dateLastReq);
66
75
  const ts3DayAgo = StrLibObj.isoToTimestamp(day3ago);
67
76
  if (ts3DayAgo > tsReq) {
68
77
  // dateLastReq too old then 3 days
@@ -75,11 +84,11 @@ export const emailChangeHashVerify = {
75
84
  // Read raw: this is a .lean() query, so Mongoose casting never runs and these are real
76
85
  // booleans only on data that scripts/migrate-account-disabled-to-boolean.mjs has been
77
86
  // through. A legacy string 'false' is truthy and blocks here — migrate, don't coerce.
78
- else if (user.account.deleted) {
87
+ else if (readPath(user, paths.deleted)) {
79
88
  return false;
80
89
  }
81
90
  // if account is disabled, for any reason
82
- else if (user.account.disabled) {
91
+ else if (readPath(user, paths.disabled)) {
83
92
  // noinspection ES6MissingAwait
84
93
  SocketLabsObj.accountDisabled(uEmail);
85
94
  return false;
@@ -87,10 +96,10 @@ export const emailChangeHashVerify = {
87
96
  else {
88
97
  // valid request. is this email free ?
89
98
  // meanwhile, has some user registered with this email address ??
90
- const qty = await UserBase.countDocuments({ 'login.email': uEmail });
99
+ const qty = await deps.model.countDocuments({ [paths.email]: uEmail });
91
100
  if (qty === 0) {
92
101
  // accept new email
93
- await confirmNewEmail(user._id, uEmail);
102
+ await deps.confirmNewEmail(uId, uEmail);
94
103
  return true;
95
104
  }
96
105
  else {
@@ -99,8 +108,15 @@ export const emailChangeHashVerify = {
99
108
  }
100
109
  }
101
110
  else {
102
- return handleHashMismatch(user._id, uEmail, accountEmail.requestTimes, SocketLabsObj);
111
+ return handleHashMismatch(deps.incReqTimes, uId, uEmail, readPath(user, paths.requestTimes), SocketLabsObj);
103
112
  }
104
113
  }
105
- };
114
+ });
115
+ /** `UserBase`-bound default — the mutation every existing consumer already imports. */
116
+ export const emailChangeHashVerify = createEmailChangeHashVerifyMutation({
117
+ model: UserBase,
118
+ paths: DEFAULT_VERIFY_EMAIL_PATHS,
119
+ confirmNewEmail,
120
+ incReqTimes
121
+ });
106
122
  //# sourceMappingURL=emailChangeHashVerify.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"emailChangeHashVerify.mjs","sourceRoot":"","sources":["../../../../src/graphQL/schema/mutations/emailChangeHashVerify.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,yCAAgC;AACxD,OAAO,EAAE,SAAS,EAAE,mCAA0B;AAC9C,OAAO,EAAE,QAAQ,EAAE,0CAAoC;AACvD,OAAO,eAAe,2DAAkD;AACxE,OAAO,EAAE,WAAW,EAAE,uDAA8C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I,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;gBAC/B,OAAO,KAAK,CAAA;YACb,CAAC;YACD,yCAAyC;iBACpC,IAAI,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;gBAChC,+BAA+B;gBAC/B,aAAa,CAAC,eAAe,CAAC,MAAM,CAAC,CAAA;gBACrC,OAAO,KAAK,CAAA;YACb,CAAC;iBAAM,CAAC;gBACP,sCAAsC;gBAEtC,iEAAiE;gBACjE,MAAM,GAAG,GAAG,MAAM,QAAQ,CAAC,cAAc,CAAC,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC,CAAA;gBAEpE,IAAI,GAAG,KAAK,CAAC,EAAE,CAAC;oBACf,mBAAmB;oBACnB,MAAM,eAAe,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;oBACvC,OAAO,IAAI,CAAA;gBACZ,CAAC;qBAAM,CAAC;oBACP,OAAO,KAAK,CAAA;gBACb,CAAC;YACF,CAAC;QACF,CAAC;aAAM,CAAC;YACP,OAAO,kBAAkB,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,YAAY,CAAC,YAAY,EAAE,aAAa,CAAC,CAAA;QACtF,CAAC;IACF,CAAC;CACD,CAAA","sourcesContent":["import { SocketLabsLib } from '@email/SocketLabsLib.mjs'\nimport { StringLib } from '@lib/StringLib.mjs'\nimport { UserBase } from '@models/MongoDB/UserBase.mjs'\nimport confirmNewEmail from '@private/lib/access/db/confirmNewEmail.mjs'\nimport { incReqTimes } from '@private/lib/access/db/incReqTimes.mjs'\nimport { throwInternalError } from '@throw/throwInternalError.mjs'\nimport { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql'\nimport { Types } from 'mongoose'\n\ninterface IArgs {\n\temail: string\n\thash: string\n}\n\n/**\n * The submitted hash does not match the stored one: count the attempt and warn the account owner.\n * Extracted from resolve() only to keep it inside the max-lines-per-function budget — behaviour unchanged.\n */\nasync function handleHashMismatch(\n\tuId: Types.ObjectId,\n\tuEmail: string,\n\trequestTimes: number | undefined,\n\tSocketLabsObj: SocketLabsLib\n) {\n\t// hash failed\n\tconsole.debug('HASH FAILED')\n\n\tif (typeof requestTimes === 'undefined') {\n\t\tthrow throwInternalError()\n\t}\n\n\tawait incReqTimes(uId)\n\t// noinspection ES6MissingAwait\n\tSocketLabsObj.wrongHash(uEmail, requestTimes)\n\treturn false\n}\n\n/**\n * Change email - Verify match between email and hash\n */\nexport const emailChangeHashVerify = {\n\tdescription: 'Change email - Verify match between email and hash',\n\ttype: new GraphQLNonNull(GraphQLBoolean),\n\targs: {\n\t\temail: { type: new GraphQLNonNull(GraphQLString) },\n\t\thash: { type: new GraphQLNonNull(GraphQLString) }\n\t},\n\tasync resolve(_: unknown, args: IArgs) {\n\t\tconst { email, hash } = args\n\t\tconst uEmail = email.toLowerCase()\n\n\t\t// search if the email exists\n\t\t// Every field this resolver reads must be listed. account.email.requestTimes was missing, and\n\t\t// because this is a .lean() read the absent key made handleHashMismatch throw 500 on *every*\n\t\t// wrong hash: the strike counter never advanced and the owner never got the wrongHash warning.\n\t\tconst user = await UserBase.findOne({ 'account.email.newEmailTmp': uEmail })\n\t\t\t.select('_id account.email.hash account.email.dateLastReq account.email.requestTimes account.deleted account.disabled')\n\t\t\t.lean()\n\n\t\t// if email not found, return\n\t\tif (user === null) {\n\t\t\t// <- not found or wrong, do not say to the user the real problem !\n\t\t\tconsole.debug('email NOT found ', uEmail)\n\n\t\t\treturn false // @fixme throw\n\t\t}\n\t\tconsole.debug('email found')\n\n\t\tconst SocketLabsObj = new SocketLabsLib()\n\t\tconst StrLibObj = new StringLib()\n\n\t\tconsole.debug('comparing hash ')\n\t\tconst accountEmail = user.account.email\n\t\tif (hash === accountEmail.hash) {\n\t\t\tif (typeof accountEmail.dateLastReq === 'undefined') {\n\t\t\t\t// @fixme sentry 'dateLastReq is undefined'\n\t\t\t\tthrow throwInternalError()\n\t\t\t}\n\n\t\t\tconsole.debug('activation link hash is valid')\n\t\t\t/****************************************************\n\t\t\t * if dateLastReq too old then 3 days send email\n\t\t\t */\n\n\t\t\tconst now = new Date()\n\t\t\tconst day3ago = new Date(now.setDate(now.getDate() - 3))\n\t\t\tconst tsReq = StrLibObj.isoToTimestamp(accountEmail.dateLastReq)\n\t\t\tconst ts3DayAgo = StrLibObj.isoToTimestamp(day3ago)\n\n\t\t\tif (ts3DayAgo > tsReq) {\n\t\t\t\t// dateLastReq too old then 3 days\n\t\t\t\tconsole.debug('but link is too old')\n\n\t\t\t\t// noinspection ES6MissingAwait\n\t\t\t\tSocketLabsObj.hashReqTooOld(uEmail)\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// account is deleted -> maybe by admin for any reason\n\t\t\t// Read raw: this is a .lean() query, so Mongoose casting never runs and these are real\n\t\t\t// booleans only on data that scripts/migrate-account-disabled-to-boolean.mjs has been\n\t\t\t// through. A legacy string 'false' is truthy and blocks here — migrate, don't coerce.\n\t\t\telse if (user.account.deleted) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t// if account is disabled, for any reason\n\t\t\telse if (user.account.disabled) {\n\t\t\t\t// noinspection ES6MissingAwait\n\t\t\t\tSocketLabsObj.accountDisabled(uEmail)\n\t\t\t\treturn false\n\t\t\t} else {\n\t\t\t\t// valid request. is this email free ?\n\n\t\t\t\t// meanwhile, has some user registered with this email address ??\n\t\t\t\tconst qty = await UserBase.countDocuments({ 'login.email': uEmail })\n\n\t\t\t\tif (qty === 0) {\n\t\t\t\t\t// accept new email\n\t\t\t\t\tawait confirmNewEmail(user._id, uEmail)\n\t\t\t\t\treturn true\n\t\t\t\t} else {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn handleHashMismatch(user._id, uEmail, accountEmail.requestTimes, SocketLabsObj)\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"emailChangeHashVerify.mjs","sourceRoot":"","sources":["../../../../src/graphQL/schema/mutations/emailChangeHashVerify.mts"],"names":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E,MAAM,CAAC,CAAA;oBACvC,OAAO,IAAI,CAAA;gBACZ,CAAC;qBAAM,CAAC;oBACP,OAAO,KAAK,CAAA;gBACb,CAAC;YACF,CAAC;QACF,CAAC;aAAM,CAAC;YACP,OAAO,kBAAkB,CACxB,IAAI,CAAC,WAAW,EAChB,GAAG,EACH,MAAM,EACN,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC,YAAY,CAAuB,EACxD,aAAa,CACb,CAAA;QACF,CAAC;IACF,CAAC;CACD,CAAC,CAAA;AAKF,uFAAuF;AACvF,MAAM,CAAC,MAAM,qBAAqB,GAAmC,mCAAmC,CAAC;IACxG,KAAK,EAAE,QAAQ;IACf,KAAK,EAAE,0BAA0B;IACjC,eAAe;IACf,WAAW;CACX,CAAC,CAAA","sourcesContent":["import { SocketLabsLib } from '@email/SocketLabsLib.mjs'\nimport { DEFAULT_VERIFY_EMAIL_PATHS, IVerifyEmailPaths, TAccessModel } from '@lib/access/accessPaths.mjs'\nimport { StringLib } from '@lib/StringLib.mjs'\nimport { UserBase } from '@models/MongoDB/UserBase.mjs'\nimport confirmNewEmail, { TConfirmNewEmail } from '@private/lib/access/db/confirmNewEmail.mjs'\nimport { incReqTimes, TIncReqTimes } from '@private/lib/access/db/incReqTimes.mjs'\nimport { buildProjection, readPath } from '@private/lib/access/pathTools.mjs'\nimport { throwInternalError } from '@throw/throwInternalError.mjs'\nimport { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql'\nimport { Types } from 'mongoose'\n\ninterface IArgs {\n\temail: string\n\thash: string\n}\n\n/** Model, field map and writers the resolver needs, all bound together by the caller. */\nexport interface IEmailChangeHashVerifyDeps {\n\tmodel: TAccessModel\n\tpaths: IVerifyEmailPaths\n\tconfirmNewEmail: TConfirmNewEmail\n\tincReqTimes: TIncReqTimes\n}\n\n/**\n * The submitted hash does not match the stored one: count the attempt and warn the account owner.\n * Extracted from resolve() only to keep it inside the max-lines-per-function budget — behaviour unchanged.\n */\nasync function handleHashMismatch(\n\tincReqTimesFn: TIncReqTimes,\n\tuId: Types.ObjectId,\n\tuEmail: string,\n\trequestTimes: number | undefined,\n\tSocketLabsObj: SocketLabsLib\n) {\n\t// hash failed\n\tconsole.debug('HASH FAILED')\n\n\tif (typeof requestTimes === 'undefined') {\n\t\tthrow throwInternalError()\n\t}\n\n\tawait incReqTimesFn(uId)\n\t// noinspection ES6MissingAwait\n\tSocketLabsObj.wrongHash(uEmail, requestTimes)\n\treturn false\n}\n\n/**\n * Change email - Verify match between email and hash\n *\n * The collection and every field path come from `deps`, so the same resolver serves any account model.\n * The projection is built from the same map the reads use, which is what keeps a read field from going\n * missing — the exact bug that made every wrong hash answer 500 through 5.1.0.\n */\nexport const createEmailChangeHashVerifyMutation = (deps: IEmailChangeHashVerifyDeps) => ({\n\tdescription: 'Change email - Verify match between email and hash',\n\ttype: new GraphQLNonNull(GraphQLBoolean),\n\targs: {\n\t\temail: { type: new GraphQLNonNull(GraphQLString) },\n\t\thash: { type: new GraphQLNonNull(GraphQLString) }\n\t},\n\tasync resolve(_: unknown, args: IArgs) {\n\t\tconst { paths } = deps\n\t\tconst { email, hash } = args\n\t\tconst uEmail = email.toLowerCase()\n\n\t\t// search if the email exists\n\t\t// Every field this resolver reads must be listed. account.email.requestTimes was missing, and\n\t\t// because this is a .lean() read the absent key made handleHashMismatch throw 500 on *every*\n\t\t// wrong hash: the strike counter never advanced and the owner never got the wrongHash warning.\n\t\tconst user = await deps.model\n\t\t\t.findOne({ [paths.newEmailTmp]: uEmail })\n\t\t\t.select(buildProjection([paths.hash, paths.dateLastReq, paths.requestTimes, paths.deleted, paths.disabled]))\n\t\t\t.lean()\n\n\t\t// if email not found, return\n\t\tif (user === null) {\n\t\t\t// <- not found or wrong, do not say to the user the real problem !\n\t\t\tconsole.debug('email NOT found ', uEmail)\n\n\t\t\treturn false // @fixme throw\n\t\t}\n\t\tconsole.debug('email found')\n\n\t\tconst SocketLabsObj = new SocketLabsLib()\n\t\tconst StrLibObj = new StringLib()\n\n\t\tconsole.debug('comparing hash ')\n\t\tconst uId = readPath(user, '_id') as Types.ObjectId\n\t\tconst dateLastReq = readPath(user, paths.dateLastReq) as Date | undefined\n\t\tif (hash === readPath(user, paths.hash)) {\n\t\t\tif (typeof dateLastReq === 'undefined') {\n\t\t\t\t// @fixme sentry 'dateLastReq is undefined'\n\t\t\t\tthrow throwInternalError()\n\t\t\t}\n\n\t\t\tconsole.debug('activation link hash is valid')\n\t\t\t/****************************************************\n\t\t\t * if dateLastReq too old then 3 days send email\n\t\t\t */\n\n\t\t\tconst now = new Date()\n\t\t\tconst day3ago = new Date(now.setDate(now.getDate() - 3))\n\t\t\tconst tsReq = StrLibObj.isoToTimestamp(dateLastReq)\n\t\t\tconst ts3DayAgo = StrLibObj.isoToTimestamp(day3ago)\n\n\t\t\tif (ts3DayAgo > tsReq) {\n\t\t\t\t// dateLastReq too old then 3 days\n\t\t\t\tconsole.debug('but link is too old')\n\n\t\t\t\t// noinspection ES6MissingAwait\n\t\t\t\tSocketLabsObj.hashReqTooOld(uEmail)\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// account is deleted -> maybe by admin for any reason\n\t\t\t// Read raw: this is a .lean() query, so Mongoose casting never runs and these are real\n\t\t\t// booleans only on data that scripts/migrate-account-disabled-to-boolean.mjs has been\n\t\t\t// through. A legacy string 'false' is truthy and blocks here — migrate, don't coerce.\n\t\t\telse if (readPath(user, paths.deleted)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t// if account is disabled, for any reason\n\t\t\telse if (readPath(user, paths.disabled)) {\n\t\t\t\t// noinspection ES6MissingAwait\n\t\t\t\tSocketLabsObj.accountDisabled(uEmail)\n\t\t\t\treturn false\n\t\t\t} else {\n\t\t\t\t// valid request. is this email free ?\n\n\t\t\t\t// meanwhile, has some user registered with this email address ??\n\t\t\t\tconst qty = await deps.model.countDocuments({ [paths.email]: uEmail })\n\n\t\t\t\tif (qty === 0) {\n\t\t\t\t\t// accept new email\n\t\t\t\t\tawait deps.confirmNewEmail(uId, uEmail)\n\t\t\t\t\treturn true\n\t\t\t\t} else {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn handleHashMismatch(\n\t\t\t\tdeps.incReqTimes,\n\t\t\t\tuId,\n\t\t\t\tuEmail,\n\t\t\t\treadPath(user, paths.requestTimes) as number | undefined,\n\t\t\t\tSocketLabsObj\n\t\t\t)\n\t\t}\n\t}\n})\n\n/** Shape of the bound mutation, for the modules that take it as a dependency. */\nexport type TEmailChangeHashVerifyMutation = ReturnType<typeof createEmailChangeHashVerifyMutation>\n\n/** `UserBase`-bound default — the mutation every existing consumer already imports. */\nexport const emailChangeHashVerify: TEmailChangeHashVerifyMutation = createEmailChangeHashVerifyMutation({\n\tmodel: UserBase,\n\tpaths: DEFAULT_VERIFY_EMAIL_PATHS,\n\tconfirmNewEmail,\n\tincReqTimes\n})\n"]}
@@ -1,12 +1,25 @@
1
+ import { TGetResetPwd } from "../../../private/lib/access/db/getResetPwd.mjs";
2
+ import { TSaveResetReq } from "../../../private/lib/access/db/saveResetReq.mjs";
1
3
  import { GraphQLNonNull } from 'graphql';
2
4
  interface IArgs {
3
5
  email: string;
4
6
  }
7
+ /** Readers and writers the resolver needs, all bound to the same model + paths by the caller. */
8
+ export interface IResetPwdDeps {
9
+ getResetPwd: TGetResetPwd;
10
+ saveResetReq: TSaveResetReq;
11
+ }
5
12
  /**
6
13
  * Take the user email and send an email with a link for change the password.
7
- * for privacy, true is returned if given email do not exist
14
+ * for privacy, true is returned whatever happens: unknown address, first request, or a request
15
+ * throttled because the previous one is less than 10 minutes old. The caller can never tell them apart,
16
+ * and the mail is queued after the commit without being awaited so the response time does not tell
17
+ * them apart either.
18
+ *
19
+ * The collection and field layout live entirely in the injected reader/writer, so the same resolver
20
+ * serves any account model. Nothing about the flow itself changes.
8
21
  */
9
- export declare const resetPwd: {
22
+ export declare const createResetPwdMutation: (deps: IResetPwdDeps) => {
10
23
  description: string;
11
24
  type: GraphQLNonNull<import("graphql").GraphQLScalarType<boolean, boolean>>;
12
25
  args: {
@@ -16,4 +29,8 @@ export declare const resetPwd: {
16
29
  };
17
30
  resolve(_: unknown, args: IArgs): Promise<boolean>;
18
31
  };
32
+ /** Shape of the bound mutation, for the modules that take it as a dependency. */
33
+ export type TResetPwdMutation = ReturnType<typeof createResetPwdMutation>;
34
+ /** `UserBase`-bound default — the mutation every existing consumer already imports. */
35
+ export declare const resetPwd: TResetPwdMutation;
19
36
  export {};
@@ -6,14 +6,20 @@ import { StringLib } from "../../../lib/StringLib.mjs";
6
6
  import { tryCatchRethrow } from "../../../lib/tryCatchRethrow.mjs";
7
7
  import { getResetPwd } from "../../../private/lib/access/db/getResetPwd.mjs";
8
8
  import { saveResetReq } from "../../../private/lib/access/db/saveResetReq.mjs";
9
- import { throwTooManyRequestsError } from "../../throw/throwTooManyRequestsError.mjs";
9
+ import * as Sentry from '@sentry/node';
10
10
  import { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql';
11
11
  import mongoose from 'mongoose';
12
12
  /**
13
13
  * Take the user email and send an email with a link for change the password.
14
- * for privacy, true is returned if given email do not exist
14
+ * for privacy, true is returned whatever happens: unknown address, first request, or a request
15
+ * throttled because the previous one is less than 10 minutes old. The caller can never tell them apart,
16
+ * and the mail is queued after the commit without being awaited so the response time does not tell
17
+ * them apart either.
18
+ *
19
+ * The collection and field layout live entirely in the injected reader/writer, so the same resolver
20
+ * serves any account model. Nothing about the flow itself changes.
15
21
  */
16
- export const resetPwd = {
22
+ export const createResetPwdMutation = (deps) => ({
17
23
  description: 'send reset password link',
18
24
  type: new GraphQLNonNull(GraphQLBoolean),
19
25
  args: {
@@ -23,12 +29,15 @@ export const resetPwd = {
23
29
  const { email } = args;
24
30
  const uEmail = email.toLowerCase().trim();
25
31
  checkEmailLen(uEmail);
32
+ // Set only when the transaction actually persisted a fresh reset request. The mail itself goes
33
+ // out after the commit, and is not awaited — see the block below the transaction.
34
+ let pendingMail = null;
26
35
  const session = await mongoose.startSession();
27
36
  try {
28
37
  await session.withTransaction(async () => {
29
38
  // console.debug('email exists ?')
30
39
  // email exists? -> retrieve whether there have already been reset requests -> return 4xx ??
31
- const resetPwdVal = await getResetPwd(session, uEmail);
40
+ const resetPwdVal = await deps.getResetPwd(session, uEmail);
32
41
  // don't reveal that the email doesn't exist, for privacy
33
42
  if (resetPwdVal === null)
34
43
  return;
@@ -38,44 +47,27 @@ export const resetPwd = {
38
47
  // if a password request already exists, read the date in seconds.
39
48
  const lastReq = typeof resetPwdVal.resetDateReq !== 'undefined' ? new Date('' + resetPwdVal.resetDateReq) : null;
40
49
  // request already made previously?
41
- // send a new email with the recovery link if it was sent less than 10 minutes ago
42
- let elapsedMin = 0;
50
+ // send a new email with the recovery link only if the last one is at least 10 minutes old
43
51
  const nowDt = new Date();
44
- let calculateHash = false;
52
+ // The throttle is enforced silently. Throwing 429 here answered "this address is
53
+ // registered and has a reset pending" to an unauthenticated caller, while an unknown
54
+ // address returned true — an enumeration oracle for any address that had been through
55
+ // this flow. Both cases now return true and send nothing.
56
+ let calculateHash = true;
45
57
  if (lastReq !== null) {
46
58
  // console.debug('reset request already made')
47
- elapsedMin = DateLib.minElapsed(lastReq);
48
- // console.debug('previous pwd reset request: ' + lastReq + ' it is now ' + now + ' and ' + elapsedMin + ' minutes have passed')
49
- // if a password reset request has already been made, at least 10 minutes must have passed
50
- if (elapsedMin < 10) {
51
- // console.debug('last req < 10 min')
52
- // Don't reveal that the email was found and
53
- elapsedMin = 10 - elapsedMin;
54
- /* c8 ignore next -- defensive: 10-elapsedMin is always >= 0 inside this branch */
55
- if (elapsedMin < 0)
56
- elapsedMin = 1; // to round up the seconds of the last minute, set minute = 1
57
- // console.debug('wait ' + message + ' min ' + uEmail)
58
- throw throwTooManyRequestsError(elapsedMin.toString());
59
- }
60
- else {
61
- // ok, more than 10 minutes, so generate hash for new email
62
- calculateHash = true;
63
- }
64
- }
65
- else {
66
- //console.debug('first reset request')
67
- calculateHash = true;
68
- }
59
+ // console.debug('previous pwd reset request: ' + lastReq + ' it is now ' + nowDt)
60
+ calculateHash = DateLib.minElapsed(lastReq) >= 10;
61
+ } //else console.debug('first reset request')
69
62
  if (calculateHash) {
70
63
  // generate hash for password reset
71
64
  const StrObj = new StringLib();
72
65
  const hash = StrObj.randomString(EMAIL_HASH_LEN);
73
66
  // set hash and current reset date
74
- await saveResetReq(session, resetPwdVal._id, nowDt, hash);
75
- // send email with new hash, last request > 10 minutes ago
76
- const SocketLabsObj = new SocketLabsLib();
77
- await SocketLabsObj.sendEmailReset(uEmail, hash, resetPwdVal.name);
78
- } // calculateHash & sendEmail
67
+ await deps.saveResetReq(session, resetPwdVal._id, nowDt, hash);
68
+ // the mail is queued after the commit, not here
69
+ pendingMail = { hash, name: resetPwdVal.name };
70
+ } // calculateHash
79
71
  });
80
72
  }
81
73
  catch (e) {
@@ -84,7 +76,40 @@ export const resetPwd = {
84
76
  finally {
85
77
  await session.endSession();
86
78
  }
79
+ // Reached only on a committed transaction: tryCatchRethrow above always throws.
80
+ //
81
+ // Three reasons this send sits here and is deliberately not awaited:
82
+ // 1. Timing. Awaiting a network round-trip to SocketLabs made the response measurably slower
83
+ // exactly when the address was registered and not throttled — the same fact the removed 429
84
+ // used to state outright. What is left is one extra updateOne, ~a millisecond against
85
+ // internet jitter, and the 10-minute throttle caps an attacker at one sample per address,
86
+ // so there is nothing to average out.
87
+ // 2. Retries. session.withTransaction re-runs its callback on a transient error. With the send
88
+ // inside, a retried commit mailed the user a second link and invalidated the first.
89
+ // 3. Failure disclosure. A SocketLabs outage used to surface as a 500, which only an address
90
+ // that actually exists could ever receive.
91
+ // The cost is that a delivery failure is now visible in Sentry only, mail in flight is lost if
92
+ // the process is killed before the request settles, and — the one a user feels — the hash is
93
+ // already committed when the send fails, so the 10-minute throttle is armed for a link that
94
+ // never arrived. Clearing resetHash/resetDateReq from the catch below to undo that was
95
+ // considered and rejected: a rejected promise does not prove non-delivery, and a timeout after
96
+ // SocketLabs accepted the message would kill a link already sitting in the user's inbox.
97
+ const mail = pendingMail;
98
+ if (mail !== null) {
99
+ try {
100
+ const SocketLabsObj = new SocketLabsLib();
101
+ void SocketLabsObj.sendEmailReset(uEmail, mail.hash, mail.name).catch((e) => {
102
+ Sentry.captureException(e);
103
+ });
104
+ }
105
+ catch (e) {
106
+ // the constructor, or a synchronous throw before the promise exists
107
+ Sentry.captureException(e);
108
+ }
109
+ }
87
110
  return true;
88
111
  }
89
- };
112
+ });
113
+ /** `UserBase`-bound default — the mutation every existing consumer already imports. */
114
+ export const resetPwd = createResetPwdMutation({ getResetPwd, saveResetReq });
90
115
  //# sourceMappingURL=resetPwd.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"resetPwd.mjs","sourceRoot":"","sources":["../../../../src/graphQL/schema/mutations/resetPwd.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,yCAAgC;AACxD,OAAO,EAAE,aAAa,EAAE,uCAA8B;AACtD,OAAO,EAAE,cAAc,EAAE,mCAA0B;AACnD,OAAO,EAAE,OAAO,EAAE,iCAAwB;AAC1C,OAAO,EAAE,SAAS,EAAE,mCAA0B;AAC9C,OAAO,EAAE,eAAe,EAAE,yCAAgC;AAC1D,OAAO,EAAE,WAAW,EAAE,uDAA8C;AACpE,OAAO,EAAE,YAAY,EAAE,wDAA+C;AACtE,OAAO,EAAE,yBAAyB,EAAE,kDAA4C;AAChF,OAAO,EAAE,cAAc,EAAgB,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AACrF,OAAO,QAAQ,MAAM,UAAU,CAAA;AAM/B;;;GAGG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG;IACvB,WAAW,EAAE,0BAA0B;IACvC,IAAI,EAAE,IAAI,cAAc,CAAC,cAAc,CAAC;IACxC,IAAI,EAAE;QACL,KAAK,EAAE,EAAE,IAAI,EAAE,IAAI,cAAc,CAAC,aAAa,CAAC,EAAE;KAClD;IACD,KAAK,CA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CAAC,6DAA6D;wBAChG,sDAAsD;wBACtD,MAAM,yBAAyB,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC,CAAA;oBACvD,CAAC;yBAAM,CAAC;wBACP,2DAA2D;wBAC3D,aAAa,GAAG,IAAI,CAAA;oBACrB,CAAC;gBACF,CAAC;qBAAM,CAAC;oBACP,sCAAsC;oBACtC,aAAa,GAAG,IAAI,CAAA;gBACrB,CAAC;gBAED,IAAI,aAAa,EAAE,CAAC;oBACnB,mCAAmC;oBACnC,MAAM,MAAM,GAAG,IAAI,SAAS,EAAE,CAAA;oBAC9B,MAAM,IAAI,GAAG,MAAM,CAAC,YAAY,CAAC,cAAc,CAAC,CAAA;oBAEhD,kCAAkC;oBAClC,MAAM,YAAY,CAAC,OAAO,EAAE,WAAW,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,CAAA;oBAEzD,0DAA0D;oBAC1D,MAAM,aAAa,GAAG,IAAI,aAAa,EAAE,CAAA;oBACzC,MAAM,aAAa,CAAC,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC,CAAA;gBACnE,CAAC,CAAC,4BAA4B;YAC/B,CAAC,CAAC,CAAA;QACH,CAAC;QAAC,OAAO,CAAU,EAAE,CAAC;YACrB,eAAe,CAAC,CAAyB,CAAC,CAAA;QAC3C,CAAC;gBAAS,CAAC;YACV,MAAM,OAAO,CAAC,UAAU,EAAE,CAAA;QAC3B,CAAC;QAED,OAAO,IAAI,CAAA;IACZ,CAAC;CACD,CAAA","sourcesContent":["import { SocketLabsLib } from '@email/SocketLabsLib.mjs'\nimport { checkEmailLen } from '@lib/checkEmailLen.mjs'\nimport { EMAIL_HASH_LEN } from '@lib/Constants.mjs'\nimport { DateLib } from '@lib/DateLib.mjs'\nimport { StringLib } from '@lib/StringLib.mjs'\nimport { tryCatchRethrow } from '@lib/tryCatchRethrow.mjs'\nimport { getResetPwd } from '@private/lib/access/db/getResetPwd.mjs'\nimport { saveResetReq } from '@private/lib/access/db/saveResetReq.mjs'\nimport { throwTooManyRequestsError } from '@throw/throwTooManyRequestsError.mjs'\nimport { GraphQLBoolean, GraphQLError, GraphQLNonNull, GraphQLString } from 'graphql'\nimport mongoose from 'mongoose'\n\ninterface IArgs {\n\temail: string\n}\n\n/**\n * Take the user email and send an email with a link for change the password.\n * for privacy, true is returned if given email do not exist\n */\nexport const resetPwd = {\n\tdescription: 'send reset password link',\n\ttype: new GraphQLNonNull(GraphQLBoolean),\n\targs: {\n\t\temail: { type: new GraphQLNonNull(GraphQLString) }\n\t},\n\tasync resolve(_: unknown, args: IArgs) {\n\t\tconst { email } = args\n\n\t\tconst uEmail = email.toLowerCase().trim()\n\t\tcheckEmailLen(uEmail)\n\n\t\tconst session = await mongoose.startSession()\n\t\ttry {\n\t\t\tawait session.withTransaction(async () => {\n\t\t\t\t// console.debug('email exists ?')\n\t\t\t\t// email exists? -> retrieve whether there have already been reset requests -> return 4xx ??\n\t\t\t\tconst resetPwdVal = await getResetPwd(session, uEmail)\n\n\t\t\t\t// don't reveal that the email doesn't exist, for privacy\n\t\t\t\tif (resetPwdVal === null) return\n\t\t\t\t// console.debug(\"the email exists\")\n\n\t\t\t\t// ok, email exists\n\n\t\t\t\t// -> wait 10 minutes from the last password reset request\n\n\t\t\t\t// if a password request already exists, read the date in seconds.\n\t\t\t\tconst lastReq = typeof resetPwdVal.resetDateReq !== 'undefined' ? new Date('' + resetPwdVal.resetDateReq) : null\n\n\t\t\t\t// request already made previously?\n\t\t\t\t// send a new email with the recovery link if it was sent less than 10 minutes ago\n\t\t\t\tlet elapsedMin = 0\n\t\t\t\tconst nowDt = new Date()\n\n\t\t\t\tlet calculateHash = false\n\t\t\t\tif (lastReq !== null) {\n\t\t\t\t\t// console.debug('reset request already made')\n\t\t\t\t\telapsedMin = DateLib.minElapsed(lastReq)\n\n\t\t\t\t\t// console.debug('previous pwd reset request: ' + lastReq + ' it is now ' + now + ' and ' + elapsedMin + ' minutes have passed')\n\t\t\t\t\t// if a password reset request has already been made, at least 10 minutes must have passed\n\t\t\t\t\tif (elapsedMin < 10) {\n\t\t\t\t\t\t// console.debug('last req < 10 min')\n\t\t\t\t\t\t// Don't reveal that the email was found and\n\t\t\t\t\t\telapsedMin = 10 - elapsedMin\n\t\t\t\t\t\t/* c8 ignore next -- defensive: 10-elapsedMin is always >= 0 inside this branch */\n\t\t\t\t\t\tif (elapsedMin < 0) elapsedMin = 1 // to round up the seconds of the last minute, set minute = 1\n\t\t\t\t\t\t// console.debug('wait ' + message + ' min ' + uEmail)\n\t\t\t\t\t\tthrow throwTooManyRequestsError(elapsedMin.toString())\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// ok, more than 10 minutes, so generate hash for new email\n\t\t\t\t\t\tcalculateHash = true\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t//console.debug('first reset request')\n\t\t\t\t\tcalculateHash = true\n\t\t\t\t}\n\n\t\t\t\tif (calculateHash) {\n\t\t\t\t\t// generate hash for password reset\n\t\t\t\t\tconst StrObj = new StringLib()\n\t\t\t\t\tconst hash = StrObj.randomString(EMAIL_HASH_LEN)\n\n\t\t\t\t\t// set hash and current reset date\n\t\t\t\t\tawait saveResetReq(session, resetPwdVal._id, nowDt, hash)\n\n\t\t\t\t\t// send email with new hash, last request > 10 minutes ago\n\t\t\t\t\tconst SocketLabsObj = new SocketLabsLib()\n\t\t\t\t\tawait SocketLabsObj.sendEmailReset(uEmail, hash, resetPwdVal.name)\n\t\t\t\t} // calculateHash & sendEmail\n\t\t\t})\n\t\t} catch (e: unknown) {\n\t\t\ttryCatchRethrow(e as GraphQLError | Error)\n\t\t} finally {\n\t\t\tawait session.endSession()\n\t\t}\n\n\t\treturn true\n\t}\n}\n"]}
1
+ {"version":3,"file":"resetPwd.mjs","sourceRoot":"","sources":["../../../../src/graphQL/schema/mutations/resetPwd.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,yCAAgC;AACxD,OAAO,EAAE,aA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ChF,EAAE;QACF,qEAAqE;QACrE,+FAA+F;QAC/F,iGAAiG;QACjG,2FAA2F;QAC3F,+FAA+F;QAC/F,2CAA2C;QAC3C,iGAAiG;QACjG,yFAAyF;QACzF,+FAA+F;QAC/F,gDAAgD;QAChD,+FAA+F;QAC/F,6FAA6F;QAC7F,4FAA4F;QAC5F,uFAAuF;QACvF,+FAA+F;QAC/F,yFAAyF;QACzF,MAAM,IAAI,GAAG,WAAkC,CAAA;QAC/C,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YACnB,IAAI,CAAC;gBACJ,MAAM,aAAa,GAAG,IAAI,aAAa,EAAE,CAAA;gBACzC,KAAK,aAAa,CAAC,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAU,EAAE,EAAE;oBACpF,MAAM,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAA;gBAC3B,CAAC,CAAC,CAAA;YACH,CAAC;YAAC,OAAO,CAAU,EAAE,CAAC;gBACrB,oEAAoE;gBACpE,MAAM,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAA;YAC3B,CAAC;QACF,CAAC;QAED,OAAO,IAAI,CAAA;IACZ,CAAC;CACD,CAAC,CAAA;AAKF,uFAAuF;AACvF,MAAM,CAAC,MAAM,QAAQ,GAAsB,sBAAsB,CAAC,EAAE,WAAW,EAAE,YAAY,EAAE,CAAC,CAAA","sourcesContent":["import { SocketLabsLib } from '@email/SocketLabsLib.mjs'\nimport { checkEmailLen } from '@lib/checkEmailLen.mjs'\nimport { EMAIL_HASH_LEN } from '@lib/Constants.mjs'\nimport { DateLib } from '@lib/DateLib.mjs'\nimport { StringLib } from '@lib/StringLib.mjs'\nimport { tryCatchRethrow } from '@lib/tryCatchRethrow.mjs'\nimport { getResetPwd, TGetResetPwd } from '@private/lib/access/db/getResetPwd.mjs'\nimport { saveResetReq, TSaveResetReq } from '@private/lib/access/db/saveResetReq.mjs'\nimport * as Sentry from '@sentry/node'\nimport { GraphQLBoolean, GraphQLError, GraphQLNonNull, GraphQLString } from 'graphql'\nimport mongoose from 'mongoose'\n\ninterface IArgs {\n\temail: string\n}\n\n/** What the committed transaction leaves behind for the post-commit send. */\ninterface IPendingMail {\n\thash: string\n\tname: string\n}\n\n/** Readers and writers the resolver needs, all bound to the same model + paths by the caller. */\nexport interface IResetPwdDeps {\n\tgetResetPwd: TGetResetPwd\n\tsaveResetReq: TSaveResetReq\n}\n\n/**\n * Take the user email and send an email with a link for change the password.\n * for privacy, true is returned whatever happens: unknown address, first request, or a request\n * throttled because the previous one is less than 10 minutes old. The caller can never tell them apart,\n * and the mail is queued after the commit without being awaited so the response time does not tell\n * them apart either.\n *\n * The collection and field layout live entirely in the injected reader/writer, so the same resolver\n * serves any account model. Nothing about the flow itself changes.\n */\nexport const createResetPwdMutation = (deps: IResetPwdDeps) => ({\n\tdescription: 'send reset password link',\n\ttype: new GraphQLNonNull(GraphQLBoolean),\n\targs: {\n\t\temail: { type: new GraphQLNonNull(GraphQLString) }\n\t},\n\tasync resolve(_: unknown, args: IArgs) {\n\t\tconst { email } = args\n\n\t\tconst uEmail = email.toLowerCase().trim()\n\t\tcheckEmailLen(uEmail)\n\n\t\t// Set only when the transaction actually persisted a fresh reset request. The mail itself goes\n\t\t// out after the commit, and is not awaited — see the block below the transaction.\n\t\tlet pendingMail: IPendingMail | null = null\n\n\t\tconst session = await mongoose.startSession()\n\t\ttry {\n\t\t\tawait session.withTransaction(async () => {\n\t\t\t\t// console.debug('email exists ?')\n\t\t\t\t// email exists? -> retrieve whether there have already been reset requests -> return 4xx ??\n\t\t\t\tconst resetPwdVal = await deps.getResetPwd(session, uEmail)\n\n\t\t\t\t// don't reveal that the email doesn't exist, for privacy\n\t\t\t\tif (resetPwdVal === null) return\n\t\t\t\t// console.debug(\"the email exists\")\n\n\t\t\t\t// ok, email exists\n\n\t\t\t\t// -> wait 10 minutes from the last password reset request\n\n\t\t\t\t// if a password request already exists, read the date in seconds.\n\t\t\t\tconst lastReq = typeof resetPwdVal.resetDateReq !== 'undefined' ? new Date('' + resetPwdVal.resetDateReq) : null\n\n\t\t\t\t// request already made previously?\n\t\t\t\t// send a new email with the recovery link only if the last one is at least 10 minutes old\n\t\t\t\tconst nowDt = new Date()\n\n\t\t\t\t// The throttle is enforced silently. Throwing 429 here answered \"this address is\n\t\t\t\t// registered and has a reset pending\" to an unauthenticated caller, while an unknown\n\t\t\t\t// address returned true — an enumeration oracle for any address that had been through\n\t\t\t\t// this flow. Both cases now return true and send nothing.\n\t\t\t\tlet calculateHash = true\n\t\t\t\tif (lastReq !== null) {\n\t\t\t\t\t// console.debug('reset request already made')\n\t\t\t\t\t// console.debug('previous pwd reset request: ' + lastReq + ' it is now ' + nowDt)\n\t\t\t\t\tcalculateHash = DateLib.minElapsed(lastReq) >= 10\n\t\t\t\t} //else console.debug('first reset request')\n\n\t\t\t\tif (calculateHash) {\n\t\t\t\t\t// generate hash for password reset\n\t\t\t\t\tconst StrObj = new StringLib()\n\t\t\t\t\tconst hash = StrObj.randomString(EMAIL_HASH_LEN)\n\n\t\t\t\t\t// set hash and current reset date\n\t\t\t\t\tawait deps.saveResetReq(session, resetPwdVal._id, nowDt, hash)\n\n\t\t\t\t\t// the mail is queued after the commit, not here\n\t\t\t\t\tpendingMail = { hash, name: resetPwdVal.name }\n\t\t\t\t} // calculateHash\n\t\t\t})\n\t\t} catch (e: unknown) {\n\t\t\ttryCatchRethrow(e as GraphQLError | Error)\n\t\t} finally {\n\t\t\tawait session.endSession()\n\t\t}\n\n\t\t// Reached only on a committed transaction: tryCatchRethrow above always throws.\n\t\t//\n\t\t// Three reasons this send sits here and is deliberately not awaited:\n\t\t// 1. Timing. Awaiting a network round-trip to SocketLabs made the response measurably slower\n\t\t// exactly when the address was registered and not throttled — the same fact the removed 429\n\t\t// used to state outright. What is left is one extra updateOne, ~a millisecond against\n\t\t// internet jitter, and the 10-minute throttle caps an attacker at one sample per address,\n\t\t// so there is nothing to average out.\n\t\t// 2. Retries. session.withTransaction re-runs its callback on a transient error. With the send\n\t\t// inside, a retried commit mailed the user a second link and invalidated the first.\n\t\t// 3. Failure disclosure. A SocketLabs outage used to surface as a 500, which only an address\n\t\t// that actually exists could ever receive.\n\t\t// The cost is that a delivery failure is now visible in Sentry only, mail in flight is lost if\n\t\t// the process is killed before the request settles, and — the one a user feels — the hash is\n\t\t// already committed when the send fails, so the 10-minute throttle is armed for a link that\n\t\t// never arrived. Clearing resetHash/resetDateReq from the catch below to undo that was\n\t\t// considered and rejected: a rejected promise does not prove non-delivery, and a timeout after\n\t\t// SocketLabs accepted the message would kill a link already sitting in the user's inbox.\n\t\tconst mail = pendingMail as IPendingMail | null\n\t\tif (mail !== null) {\n\t\t\ttry {\n\t\t\t\tconst SocketLabsObj = new SocketLabsLib()\n\t\t\t\tvoid SocketLabsObj.sendEmailReset(uEmail, mail.hash, mail.name).catch((e: unknown) => {\n\t\t\t\t\tSentry.captureException(e)\n\t\t\t\t})\n\t\t\t} catch (e: unknown) {\n\t\t\t\t// the constructor, or a synchronous throw before the promise exists\n\t\t\t\tSentry.captureException(e)\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n})\n\n/** Shape of the bound mutation, for the modules that take it as a dependency. */\nexport type TResetPwdMutation = ReturnType<typeof createResetPwdMutation>\n\n/** `UserBase`-bound default — the mutation every existing consumer already imports. */\nexport const resetPwd: TResetPwdMutation = createResetPwdMutation({ getResetPwd, saveResetReq })\n"]}
@@ -1,10 +1,26 @@
1
+ import { TGetResetPwd } from "../../../private/lib/access/db/getResetPwd.mjs";
2
+ import { TRemoveResetReq } from "../../../private/lib/access/db/removeResetReq.mjs";
3
+ import { TUpdatePasswordDb } from "../../../private/lib/access/db/updatePasswordDb.mjs";
1
4
  import { GraphQLNonNull } from 'graphql';
2
5
  interface IArgs {
3
6
  email: string;
4
7
  hash: string;
5
8
  password: string;
6
9
  }
7
- export declare const updatePassword: {
10
+ /** Readers and writers the resolver needs, all bound to the same model + paths by the caller. */
11
+ export interface IUpdatePasswordDeps {
12
+ getResetPwd: TGetResetPwd;
13
+ updatePasswordDb: TUpdatePasswordDb;
14
+ removeResetReq: TRemoveResetReq;
15
+ }
16
+ /**
17
+ * Change the password of an account holding a valid, unexpired reset hash.
18
+ *
19
+ * The collection and field layout live entirely in the injected reader/writers, so the same resolver
20
+ * serves any account model. In particular the cleanup unsets whatever `resetClear` names, which is not
21
+ * necessarily the two leaf paths this resolver reads — see `removeResetReq`.
22
+ */
23
+ export declare const createUpdatePasswordMutation: (deps: IUpdatePasswordDeps) => {
8
24
  description: string;
9
25
  type: GraphQLNonNull<import("graphql").GraphQLScalarType<boolean, boolean>>;
10
26
  args: {
@@ -20,4 +36,8 @@ export declare const updatePassword: {
20
36
  };
21
37
  resolve(_: unknown, args: IArgs): Promise<boolean>;
22
38
  };
39
+ /** Shape of the bound mutation, for the modules that take it as a dependency. */
40
+ export type TUpdatePasswordMutation = ReturnType<typeof createUpdatePasswordMutation>;
41
+ /** `UserBase`-bound default — the mutation every existing consumer already imports. */
42
+ export declare const updatePassword: TUpdatePasswordMutation;
23
43
  export {};