@axiumine/koa-utils 5.2.0 → 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 +15 -1
  6. package/dist/graphQL/schema/mutations/resetPwd.mjs +9 -4
  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 +18 -5
  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,15 +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
14
  * for privacy, true is returned whatever happens: unknown address, first request, or a request
8
15
  * throttled because the previous one is less than 10 minutes old. The caller can never tell them apart,
9
16
  * and the mail is queued after the commit without being awaited so the response time does not tell
10
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.
11
21
  */
12
- export declare const resetPwd: {
22
+ export declare const createResetPwdMutation: (deps: IResetPwdDeps) => {
13
23
  description: string;
14
24
  type: GraphQLNonNull<import("graphql").GraphQLScalarType<boolean, boolean>>;
15
25
  args: {
@@ -19,4 +29,8 @@ export declare const resetPwd: {
19
29
  };
20
30
  resolve(_: unknown, args: IArgs): Promise<boolean>;
21
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;
22
36
  export {};
@@ -15,8 +15,11 @@ import mongoose from 'mongoose';
15
15
  * throttled because the previous one is less than 10 minutes old. The caller can never tell them apart,
16
16
  * and the mail is queued after the commit without being awaited so the response time does not tell
17
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.
18
21
  */
19
- export const resetPwd = {
22
+ export const createResetPwdMutation = (deps) => ({
20
23
  description: 'send reset password link',
21
24
  type: new GraphQLNonNull(GraphQLBoolean),
22
25
  args: {
@@ -34,7 +37,7 @@ export const resetPwd = {
34
37
  await session.withTransaction(async () => {
35
38
  // console.debug('email exists ?')
36
39
  // email exists? -> retrieve whether there have already been reset requests -> return 4xx ??
37
- const resetPwdVal = await getResetPwd(session, uEmail);
40
+ const resetPwdVal = await deps.getResetPwd(session, uEmail);
38
41
  // don't reveal that the email doesn't exist, for privacy
39
42
  if (resetPwdVal === null)
40
43
  return;
@@ -61,7 +64,7 @@ export const resetPwd = {
61
64
  const StrObj = new StringLib();
62
65
  const hash = StrObj.randomString(EMAIL_HASH_LEN);
63
66
  // set hash and current reset date
64
- await saveResetReq(session, resetPwdVal._id, nowDt, hash);
67
+ await deps.saveResetReq(session, resetPwdVal._id, nowDt, hash);
65
68
  // the mail is queued after the commit, not here
66
69
  pendingMail = { hash, name: resetPwdVal.name };
67
70
  } // calculateHash
@@ -106,5 +109,7 @@ export const resetPwd = {
106
109
  }
107
110
  return true;
108
111
  }
109
- };
112
+ });
113
+ /** `UserBase`-bound default — the mutation every existing consumer already imports. */
114
+ export const resetPwd = createResetPwdMutation({ getResetPwd, saveResetReq });
110
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,KAAK,MAAM,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,cAAc,EAAgB,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AACrF,OAAO,QAAQ,MAAM,UAAU,CAAA;AAY/B;;;;;;GAMG;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,CAAC,OAAO,CAAC,CAAU,EAAE,IAAW;QACpC,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAA;QAEtB,MAAM,MAAM,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAA;QACzC,aAAa,CAAC,MAAM,CAAC,CAAA;QAErB,+FAA+F;QAC/F,kFAAkF;QAClF,IAAI,WAAW,GAAwB,IAAI,CAAA;QAE3C,MAAM,OAAO,GAAG,MAAM,QAAQ,CAAC,YAAY,EAAE,CAAA;Q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nB,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,gFAAgF;QAChF,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,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 * 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/**\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 */\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\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 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 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"]}
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,EAAgB,uDAA8C;AAClF,OAAO,EAAE,YAAY,EAAiB,wDAA+C;AACrF,OAAO,KAAK,MAAM,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,cAAc,EAAgB,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AACrF,OAAO,QAAQ,MAAM,UAAU,CAAA;AAkB/B;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,CA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,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 {};
@@ -11,7 +11,14 @@ import { throwForbiddenError } from "../../throw/throwForbiddenError.mjs";
11
11
  import { throwInternalError } from "../../throw/throwInternalError.mjs";
12
12
  import { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql';
13
13
  import mongoose from 'mongoose';
14
- export const updatePassword = {
14
+ /**
15
+ * Change the password of an account holding a valid, unexpired reset hash.
16
+ *
17
+ * The collection and field layout live entirely in the injected reader/writers, so the same resolver
18
+ * serves any account model. In particular the cleanup unsets whatever `resetClear` names, which is not
19
+ * necessarily the two leaf paths this resolver reads — see `removeResetReq`.
20
+ */
21
+ export const createUpdatePasswordMutation = (deps) => ({
15
22
  description: "changes the user's password",
16
23
  type: new GraphQLNonNull(GraphQLBoolean),
17
24
  args: {
@@ -30,7 +37,7 @@ export const updatePassword = {
30
37
  const session = await mongoose.startSession();
31
38
  try {
32
39
  await session.withTransaction(async () => {
33
- const resetPwd = await getResetPwd(session, uEmail);
40
+ const resetPwd = await deps.getResetPwd(session, uEmail);
34
41
  // check if email is present in db
35
42
  if (resetPwd === null) {
36
43
  throw throwForbiddenError(); // don't reveal whether the email is present, for privacy
@@ -60,12 +67,12 @@ export const updatePassword = {
60
67
  if (DateLib.minElapsed(dt1) > 60) {
61
68
  throw throwForbiddenError(); // The link is no longer valid
62
69
  } // else console.debug('--link valid')
63
- const update = await updatePasswordDb(session, resetPwd._id, password);
70
+ const update = await deps.updatePasswordDb(session, resetPwd._id, password);
64
71
  if (!update) {
65
72
  throw throwInternalError(); // "System error while updating the password."
66
73
  } // else console.debug('--pwd updated')
67
74
  // delete password reset request data from db
68
- await removeResetReq(session, uEmail);
75
+ await deps.removeResetReq(session, uEmail);
69
76
  // the confirmation email is sent after the commit, not here
70
77
  confirmTo = resetPwd.name;
71
78
  });
@@ -106,5 +113,11 @@ export const updatePassword = {
106
113
  }
107
114
  return true;
108
115
  }
109
- };
116
+ });
117
+ /** `UserBase`-bound default — the mutation every existing consumer already imports. */
118
+ export const updatePassword = createUpdatePasswordMutation({
119
+ getResetPwd,
120
+ updatePasswordDb,
121
+ removeResetReq
122
+ });
110
123
  //# sourceMappingURL=updatePassword.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"updatePassword.mjs","sourceRoot":"","sources":["../../../../src/graphQL/schema/mutations/updatePassword.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,yCAAgC;AACxD,OAAO,EAAE,aAAa,EAAE,uCAA8B;AACtD,OAAO,EAAE,WAAW,EAAE,qCAA4B;AAClD,OAAO,EAAE,OAAO,EAAE,iCAAwB;AAC1C,OAAO,EAAE,eAAe,EAAE,yCAAgC;AAC1D,OAAO,EAAE,WAAW,EAAE,uDAA8C;AACpE,OAAO,cAAc,0DAAiD;AACtE,OAAO,gBAAgB,4DAAmD;AAC1E,OAAO,KAAK,MAAM,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,mBAAmB,EAAE,4CAAsC;AACpE,OAAO,EAAE,kBAAkB,EAAE,2CAAqC;AAClE,OAAO,EAAE,cAAc,EAAgB,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AACrF,OAAO,QAAQ,MAAM,UAAU,CAAA;AAQ/B,MAAM,CAAC,MAAM,cAAc,GAAG;IAC7B,WAAW,EAAE,6BAA6B;IAC1C,IAAI,EAAE,IAAI,cAAc,CAAC,cAAc,CAAC;IACxC,IAAI,EAAE;QACL,KAAK,EAAE,EAAE,IAAI,EAAE,IAAI,cAAc,CAAC,aAAa,CAAC,EAAE;QAClD,IAAI,EAAE,EAAE,IAAI,EAAE,IAAI,cAAc,CAAC,aAAa,C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C,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YACnB,IAAI,CAAC;gBACJ,MAAM,aAAa,GAAG,IAAI,aAAa,EAAE,CAAA;gBACzC,MAAM,aAAa,CAAC,wBAAwB,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;YAC3D,CAAC;YAAC,OAAO,CAAU,EAAE,CAAC;gBACrB,MAAM,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAA;YAC3B,CAAC;QACF,CAAC;QAED,OAAO,IAAI,CAAA;IACZ,CAAC;CACD,CAAA","sourcesContent":["import { SocketLabsLib } from '@email/SocketLabsLib.mjs'\nimport { checkEmailLen } from '@lib/checkEmailLen.mjs'\nimport { checkPwdLen } from '@lib/checkPwdLen.mjs'\nimport { DateLib } from '@lib/DateLib.mjs'\nimport { tryCatchRethrow } from '@lib/tryCatchRethrow.mjs'\nimport { getResetPwd } from '@private/lib/access/db/getResetPwd.mjs'\nimport removeResetReq from '@private/lib/access/db/removeResetReq.mjs'\nimport updatePasswordDb from '@private/lib/access/db/updatePasswordDb.mjs'\nimport * as Sentry from '@sentry/node'\nimport { throwForbiddenError } from '@throw/throwForbiddenError.mjs'\nimport { throwInternalError } from '@throw/throwInternalError.mjs'\nimport { GraphQLBoolean, GraphQLError, GraphQLNonNull, GraphQLString } from 'graphql'\nimport mongoose from 'mongoose'\n\ninterface IArgs {\n\temail: string\n\thash: string\n\tpassword: string\n}\n\nexport const updatePassword = {\n\tdescription: \"changes the user's password\",\n\ttype: new GraphQLNonNull(GraphQLBoolean),\n\targs: {\n\t\temail: { type: new GraphQLNonNull(GraphQLString) },\n\t\thash: { type: new GraphQLNonNull(GraphQLString) },\n\t\tpassword: { type: new GraphQLNonNull(GraphQLString) }\n\t},\n\tasync resolve(_: unknown, args: IArgs) {\n\t\tconst { email, hash, password } = args\n\n\t\tconst uEmail = email.trim().toLowerCase()\n\t\tcheckEmailLen(uEmail)\n\t\tcheckPwdLen(password)\n\n\t\t// Set only once the transaction has actually persisted the new password. Carries the user's\n\t\t// name to the post-commit confirmation email.\n\t\tlet confirmTo: string | null = null\n\n\t\tconst session = await mongoose.startSession()\n\n\t\ttry {\n\t\t\tawait session.withTransaction(async () => {\n\t\t\t\tconst resetPwd = await getResetPwd(session, uEmail)\n\n\t\t\t\t// check if email is present in db\n\t\t\t\tif (resetPwd === null) {\n\t\t\t\t\tthrow throwForbiddenError() // don't reveal whether the email is present, for privacy\n\t\t\t\t}\n\t\t\t\t// console.debug('--email present')\n\n\t\t\t\t// No usable reset state. This is NOT an internal error as far as the caller is concerned:\n\t\t\t\t// answering 500 here while an unknown address answers 403 turns this mutation into an\n\t\t\t\t// account-enumeration oracle, because every registered account that has never requested a\n\t\t\t\t// reset lands on this branch (getResetPwd yields resetHash === null whenever\n\t\t\t\t// account.resetDateReq is undefined). Same 403 as the unknown-address path; the orphan\n\t\t\t\t// state is reported to Sentry instead of to the caller.\n\t\t\t\tif (resetPwd.resetHash === null) {\n\t\t\t\t\tSentry.captureMessage(`[updatePassword] no usable resetHash for ${uEmail}`)\n\t\t\t\t\tthrow throwForbiddenError()\n\t\t\t\t}\n\t\t\t\t/* c8 ignore next 4 -- defensive guard, resetDateReq cannot be null when resetHash is set */\n\t\t\t\tif (resetPwd.resetDateReq === null) {\n\t\t\t\t\tSentry.captureMessage(`[updatePassword] resetHash set but resetDateReq missing for ${uEmail}`)\n\t\t\t\t\tthrow throwForbiddenError()\n\t\t\t\t}\n\n\t\t\t\t// check if hash is missing or invalid\n\t\t\t\tif (resetPwd.resetHash !== hash) {\n\t\t\t\t\tthrow throwForbiddenError() // don't reveal whether the email is present, for privacy\n\t\t\t\t} // else console.debug('--hash valid')\n\n\t\t\t\t// check if the request was made within 1 hour\n\t\t\t\tconst dt1 = new Date('' + resetPwd.resetDateReq)\n\t\t\t\tif (DateLib.minElapsed(dt1) > 60) {\n\t\t\t\t\tthrow throwForbiddenError() // The link is no longer valid\n\t\t\t\t} // else console.debug('--link valid')\n\n\t\t\t\tconst update = await updatePasswordDb(session, resetPwd._id, password)\n\t\t\t\tif (!update) {\n\t\t\t\t\tthrow throwInternalError() // \"System error while updating the password.\"\n\t\t\t\t} // else console.debug('--pwd updated')\n\n\t\t\t\t// delete password reset request data from db\n\t\t\t\tawait removeResetReq(session, uEmail)\n\n\t\t\t\t// the confirmation email is sent after the commit, not here\n\t\t\t\tconfirmTo = resetPwd.name\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// The send sits here rather than inside the callback because session.withTransaction re-runs\n\t\t// its callback on a transient error, and a retried commit therefore mailed the user a second\n\t\t// \"your password was changed\" notice. It is still awaited — unlike resetPwd there is no timing\n\t\t// oracle to close here, since reaching this point at all requires a valid reset hash.\n\t\t//\n\t\t// A delivery failure no longer fails the request. It used to abort the transaction and answer\n\t\t// 500, rolling back the password change with it — consistent, but it made the mail provider a\n\t\t// hard dependency: with SocketLabs down, nobody could complete a reset at all. The password is\n\t\t// committed by the time we get here, so the failure goes to Sentry and the caller still gets\n\t\t// true. The confirmation is a notice, not part of the operation.\n\t\t//\n\t\t// Don't \"restore\" the abort: there is no transaction left to abort at this point. Rethrowing\n\t\t// would report 500 for a password that is already live, and compensating would mean writing\n\t\t// back the old bcrypt hash, which this flow never reads. Moving the send back inside the\n\t\t// callback brings back the duplicate notice AND lets a mail go out for a commit that then\n\t\t// fails — an email cannot be recalled.\n\t\tconst name = confirmTo as string | null\n\t\tif (name !== null) {\n\t\t\ttry {\n\t\t\t\tconst SocketLabsObj = new SocketLabsLib()\n\t\t\t\tawait SocketLabsObj.sendResetPwdConfirmation(uEmail, name)\n\t\t\t} catch (e: unknown) {\n\t\t\t\tSentry.captureException(e)\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n}\n"]}
1
+ {"version":3,"file":"updatePassword.mjs","sourceRoot":"","s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AED,OAAO,IAAI,CAAA;IACZ,CAAC;CACD,CAAC,CAAA;AAKF,uFAAuF;AACvF,MAAM,CAAC,MAAM,cAAc,GAA4B,4BAA4B,CAAC;IACnF,WAAW;IACX,gBAAgB;IAChB,cAAc;CACd,CAAC,CAAA","sourcesContent":["import { SocketLabsLib } from '@email/SocketLabsLib.mjs'\nimport { checkEmailLen } from '@lib/checkEmailLen.mjs'\nimport { checkPwdLen } from '@lib/checkPwdLen.mjs'\nimport { DateLib } from '@lib/DateLib.mjs'\nimport { tryCatchRethrow } from '@lib/tryCatchRethrow.mjs'\nimport { getResetPwd, TGetResetPwd } from '@private/lib/access/db/getResetPwd.mjs'\nimport removeResetReq, { TRemoveResetReq } from '@private/lib/access/db/removeResetReq.mjs'\nimport updatePasswordDb, { TUpdatePasswordDb } from '@private/lib/access/db/updatePasswordDb.mjs'\nimport * as Sentry from '@sentry/node'\nimport { throwForbiddenError } from '@throw/throwForbiddenError.mjs'\nimport { throwInternalError } from '@throw/throwInternalError.mjs'\nimport { GraphQLBoolean, GraphQLError, GraphQLNonNull, GraphQLString } from 'graphql'\nimport mongoose from 'mongoose'\n\ninterface IArgs {\n\temail: string\n\thash: string\n\tpassword: string\n}\n\n/** Readers and writers the resolver needs, all bound to the same model + paths by the caller. */\nexport interface IUpdatePasswordDeps {\n\tgetResetPwd: TGetResetPwd\n\tupdatePasswordDb: TUpdatePasswordDb\n\tremoveResetReq: TRemoveResetReq\n}\n\n/**\n * Change the password of an account holding a valid, unexpired reset hash.\n *\n * The collection and field layout live entirely in the injected reader/writers, so the same resolver\n * serves any account model. In particular the cleanup unsets whatever `resetClear` names, which is not\n * necessarily the two leaf paths this resolver reads — see `removeResetReq`.\n */\nexport const createUpdatePasswordMutation = (deps: IUpdatePasswordDeps) => ({\n\tdescription: \"changes the user's password\",\n\ttype: new GraphQLNonNull(GraphQLBoolean),\n\targs: {\n\t\temail: { type: new GraphQLNonNull(GraphQLString) },\n\t\thash: { type: new GraphQLNonNull(GraphQLString) },\n\t\tpassword: { type: new GraphQLNonNull(GraphQLString) }\n\t},\n\tasync resolve(_: unknown, args: IArgs) {\n\t\tconst { email, hash, password } = args\n\n\t\tconst uEmail = email.trim().toLowerCase()\n\t\tcheckEmailLen(uEmail)\n\t\tcheckPwdLen(password)\n\n\t\t// Set only once the transaction has actually persisted the new password. Carries the user's\n\t\t// name to the post-commit confirmation email.\n\t\tlet confirmTo: string | null = null\n\n\t\tconst session = await mongoose.startSession()\n\n\t\ttry {\n\t\t\tawait session.withTransaction(async () => {\n\t\t\t\tconst resetPwd = await deps.getResetPwd(session, uEmail)\n\n\t\t\t\t// check if email is present in db\n\t\t\t\tif (resetPwd === null) {\n\t\t\t\t\tthrow throwForbiddenError() // don't reveal whether the email is present, for privacy\n\t\t\t\t}\n\t\t\t\t// console.debug('--email present')\n\n\t\t\t\t// No usable reset state. This is NOT an internal error as far as the caller is concerned:\n\t\t\t\t// answering 500 here while an unknown address answers 403 turns this mutation into an\n\t\t\t\t// account-enumeration oracle, because every registered account that has never requested a\n\t\t\t\t// reset lands on this branch (getResetPwd yields resetHash === null whenever\n\t\t\t\t// account.resetDateReq is undefined). Same 403 as the unknown-address path; the orphan\n\t\t\t\t// state is reported to Sentry instead of to the caller.\n\t\t\t\tif (resetPwd.resetHash === null) {\n\t\t\t\t\tSentry.captureMessage(`[updatePassword] no usable resetHash for ${uEmail}`)\n\t\t\t\t\tthrow throwForbiddenError()\n\t\t\t\t}\n\t\t\t\t/* c8 ignore next 4 -- defensive guard, resetDateReq cannot be null when resetHash is set */\n\t\t\t\tif (resetPwd.resetDateReq === null) {\n\t\t\t\t\tSentry.captureMessage(`[updatePassword] resetHash set but resetDateReq missing for ${uEmail}`)\n\t\t\t\t\tthrow throwForbiddenError()\n\t\t\t\t}\n\n\t\t\t\t// check if hash is missing or invalid\n\t\t\t\tif (resetPwd.resetHash !== hash) {\n\t\t\t\t\tthrow throwForbiddenError() // don't reveal whether the email is present, for privacy\n\t\t\t\t} // else console.debug('--hash valid')\n\n\t\t\t\t// check if the request was made within 1 hour\n\t\t\t\tconst dt1 = new Date('' + resetPwd.resetDateReq)\n\t\t\t\tif (DateLib.minElapsed(dt1) > 60) {\n\t\t\t\t\tthrow throwForbiddenError() // The link is no longer valid\n\t\t\t\t} // else console.debug('--link valid')\n\n\t\t\t\tconst update = await deps.updatePasswordDb(session, resetPwd._id, password)\n\t\t\t\tif (!update) {\n\t\t\t\t\tthrow throwInternalError() // \"System error while updating the password.\"\n\t\t\t\t} // else console.debug('--pwd updated')\n\n\t\t\t\t// delete password reset request data from db\n\t\t\t\tawait deps.removeResetReq(session, uEmail)\n\n\t\t\t\t// the confirmation email is sent after the commit, not here\n\t\t\t\tconfirmTo = resetPwd.name\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// The send sits here rather than inside the callback because session.withTransaction re-runs\n\t\t// its callback on a transient error, and a retried commit therefore mailed the user a second\n\t\t// \"your password was changed\" notice. It is still awaited — unlike resetPwd there is no timing\n\t\t// oracle to close here, since reaching this point at all requires a valid reset hash.\n\t\t//\n\t\t// A delivery failure no longer fails the request. It used to abort the transaction and answer\n\t\t// 500, rolling back the password change with it — consistent, but it made the mail provider a\n\t\t// hard dependency: with SocketLabs down, nobody could complete a reset at all. The password is\n\t\t// committed by the time we get here, so the failure goes to Sentry and the caller still gets\n\t\t// true. The confirmation is a notice, not part of the operation.\n\t\t//\n\t\t// Don't \"restore\" the abort: there is no transaction left to abort at this point. Rethrowing\n\t\t// would report 500 for a password that is already live, and compensating would mean writing\n\t\t// back the old bcrypt hash, which this flow never reads. Moving the send back inside the\n\t\t// callback brings back the duplicate notice AND lets a mail go out for a commit that then\n\t\t// fails — an email cannot be recalled.\n\t\tconst name = confirmTo as string | null\n\t\tif (name !== null) {\n\t\t\ttry {\n\t\t\t\tconst SocketLabsObj = new SocketLabsLib()\n\t\t\t\tawait SocketLabsObj.sendResetPwdConfirmation(uEmail, name)\n\t\t\t} catch (e: unknown) {\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 TUpdatePasswordMutation = ReturnType<typeof createUpdatePasswordMutation>\n\n/** `UserBase`-bound default — the mutation every existing consumer already imports. */\nexport const updatePassword: TUpdatePasswordMutation = createUpdatePasswordMutation({\n\tgetResetPwd,\n\tupdatePasswordDb,\n\tremoveResetReq\n})\n"]}
@@ -1,2 +1,23 @@
1
1
  import { IContextVerifyEmail } from "../../private/graphQL/schema/context/IContextVerifyEmail.mjs";
2
- export declare const routerVerifyEmail: () => (ctx: IContextVerifyEmail) => Promise<void>;
2
+ import { TAssertVerifyEmailAllowed } from "../../private/lib/access/assertVerifyEmailAllowed.mjs";
3
+ import { TEnableEmailAccess } from "../../private/lib/access/db/enableEmailAccess.mjs";
4
+ import { TUserData4VerifyEmail } from "../../private/lib/access/db/userData4VerifyEmail.mjs";
5
+ /** Reader, guard chain and writer the handler needs, all bound to the same model + paths by the caller. */
6
+ export interface IVerifyEmailRouterDeps {
7
+ userData4VerifyEmail: TUserData4VerifyEmail;
8
+ assertVerifyEmailAllowed: TAssertVerifyEmailAllowed;
9
+ enableEmailAccess: TEnableEmailAccess;
10
+ }
11
+ /**
12
+ * Koa handler for the email-activation link.
13
+ *
14
+ * Taking the collaborators as arguments is what makes the handler testable at all: the DB read used to
15
+ * be an ESM live binding that the tsx loader refuses to let sinon replace, so the whole try-body was
16
+ * dead code in the suite and sat under a `c8 ignore`. It is now injected, the ignore is gone, and every
17
+ * path is exercised directly.
18
+ */
19
+ export declare const createVerifyEmailRouter: (deps: IVerifyEmailRouterDeps) => () => (ctx: IContextVerifyEmail) => Promise<void>;
20
+ /** Shape of the bound router, for the modules that take it as a dependency. */
21
+ export type TVerifyEmailRouter = ReturnType<typeof createVerifyEmailRouter>;
22
+ /** `UserBase`-bound default — the router every existing consumer already imports. */
23
+ export declare const routerVerifyEmail: TVerifyEmailRouter;
@@ -2,20 +2,24 @@ import { isSafeRedirectTarget } from "../../lib/isSafeRedirectTarget.mjs";
2
2
  import { assertVerifyEmailAllowed } from "../../private/lib/access/assertVerifyEmailAllowed.mjs";
3
3
  import { enableEmailAccess } from "../../private/lib/access/db/enableEmailAccess.mjs";
4
4
  import { userData4VerifyEmail } from "../../private/lib/access/db/userData4VerifyEmail.mjs";
5
- /* c8 ignore start -- ESM live-binding limit: inner async handler stubs (@private/lib/access/*) are non-configurable in tsx loader, integration coverage on consumer */
6
- export const routerVerifyEmail = () => async (ctx) => {
5
+ /**
6
+ * Koa handler for the email-activation link.
7
+ *
8
+ * Taking the collaborators as arguments is what makes the handler testable at all: the DB read used to
9
+ * be an ESM live binding that the tsx loader refuses to let sinon replace, so the whole try-body was
10
+ * dead code in the suite and sat under a `c8 ignore`. It is now injected, the ignore is gone, and every
11
+ * path is exercised directly.
12
+ */
13
+ export const createVerifyEmailRouter = (deps) => () => async (ctx) => {
7
14
  const { email, hash } = ctx.params;
8
15
  const uEmail = email.toLowerCase();
9
16
  try {
10
17
  // search if the email exists
11
- const user = await userData4VerifyEmail(uEmail);
18
+ const user = await deps.userData4VerifyEmail(uEmail);
12
19
  // Every access guard lives in assertVerifyEmailAllowed, which is unit-tested.
13
- // This handler is unreachable in the suite (the DB read above cannot be stubbed
14
- // under the tsx loader), so any logic left inline here is untestable by
15
- // construction — see the note on that function.
16
- const uId = await assertVerifyEmailAllowed(user, email, hash);
20
+ const uId = await deps.assertVerifyEmailAllowed(user, email, hash);
17
21
  // ok enable email — only ever reached once every guard above has passed
18
- await enableEmailAccess(uId, email);
22
+ await deps.enableEmailAccess(uId, email);
19
23
  ctx.redirect('/x/registration-done'); // url without prefix
20
24
  // ctx.redirect('https://google.it') // external url
21
25
  }
@@ -29,5 +33,10 @@ export const routerVerifyEmail = () => async (ctx) => {
29
33
  }
30
34
  }
31
35
  };
32
- /* c8 ignore stop */
36
+ /** `UserBase`-bound default — the router every existing consumer already imports. */
37
+ export const routerVerifyEmail = createVerifyEmailRouter({
38
+ userData4VerifyEmail,
39
+ assertVerifyEmailAllowed,
40
+ enableEmailAccess
41
+ });
33
42
  //# sourceMappingURL=verifyEmail.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"verifyEmail.mjs","sourceRoot":"","sources":["../../../src/koa/router/verifyEmail.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,2CAAqC;AAEpE,OAAO,EAAE,wBAAwB,EAAE,8DAAwD;AAC3F,OAAO,EAAE,iBAAiB,EAAE,0DAAoD;AAChF,OAAO,EAAE,oBAAoB,EAAE,6DAAuD;AAEtF,uKAAuK;AACvK,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,EAAE,CAAC,KAAK,EAAE,GAAwB,EAAE,EAAE;IACzE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC,MAAM,CAAA;IAElC,MAAM,MAAM,GAAG,KAAK,CAAC,WAAW,EAAE,CAAA;IAElC,IAAI,CAAC;QACJ,6BAA6B;QAC7B,MAAM,IAAI,GAAG,MAAM,oBAAoB,CAAC,MAAM,CAAC,CAAA;QAE/C,8EAA8E;QAC9E,gFAAgF;QAChF,wEAAwE;QACxE,gDAAgD;QAChD,MAAM,GAAG,GAAG,MAAM,wBAAwB,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,CAAA;QAE7D,wEAAwE;QACxE,MAAM,iBAAiB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;QACnC,GAAG,CAAC,QAAQ,CAAC,sBAAsB,CAAC,CAAA,CAAC,qBAAqB;QAC1D,oDAAoD;IACrD,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACvB,MAAM,IAAI,GAAI,GAAa,CAAC,OAAiB,CAAA;QAC7C,IAAI,oBAAoB,CAAC,IAAI,CAAC,EAAE,CAAC;YAChC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAA;QACnB,CAAC;aAAM,CAAC;YACP,GAAG,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAA;QACzB,CAAC;IACF,CAAC;AACF,CAAC,CAAA;AACD,oBAAoB","sourcesContent":["import { isSafeRedirectTarget } from '@lib/isSafeRedirectTarget.mjs'\nimport { IContextVerifyEmail } from '@private/graphQL/schema/context/IContextVerifyEmail.mjs'\nimport { assertVerifyEmailAllowed } from '@private/lib/access/assertVerifyEmailAllowed.mjs'\nimport { enableEmailAccess } from '@private/lib/access/db/enableEmailAccess.mjs'\nimport { userData4VerifyEmail } from '@private/lib/access/db/userData4VerifyEmail.mjs'\n\n/* c8 ignore start -- ESM live-binding limit: inner async handler stubs (@private/lib/access/*) are non-configurable in tsx loader, integration coverage on consumer */\nexport const routerVerifyEmail = () => async (ctx: IContextVerifyEmail) => {\n\tconst { email, hash } = ctx.params\n\n\tconst uEmail = email.toLowerCase()\n\n\ttry {\n\t\t// search if the email exists\n\t\tconst user = await userData4VerifyEmail(uEmail)\n\n\t\t// Every access guard lives in assertVerifyEmailAllowed, which is unit-tested.\n\t\t// This handler is unreachable in the suite (the DB read above cannot be stubbed\n\t\t// under the tsx loader), so any logic left inline here is untestable by\n\t\t// construction — see the note on that function.\n\t\tconst uId = await assertVerifyEmailAllowed(user, email, hash)\n\n\t\t// ok enable email — only ever reached once every guard above has passed\n\t\tawait enableEmailAccess(uId, email)\n\t\tctx.redirect('/x/registration-done') // url without prefix\n\t\t// ctx.redirect('https://google.it') // external url\n\t} catch (err: unknown) {\n\t\tconst link = (err as Error).message as string\n\t\tif (isSafeRedirectTarget(link)) {\n\t\t\tctx.redirect(link)\n\t\t} else {\n\t\t\tctx.redirect('/x/error')\n\t\t}\n\t}\n}\n/* c8 ignore stop */\n"]}
1
+ {"version":3,"file":"verifyEmail.mjs","sourceRoot":"","sources":["../../../src/koa/router/verifyEmail.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B,wBAAwB;IACxB,iBAAiB;CACjB,CAAC,CAAA","sourcesContent":["import { isSafeRedirectTarget } from '@lib/isSafeRedirectTarget.mjs'\nimport { IContextVerifyEmail } from '@private/graphQL/schema/context/IContextVerifyEmail.mjs'\nimport { assertVerifyEmailAllowed, TAssertVerifyEmailAllowed } from '@private/lib/access/assertVerifyEmailAllowed.mjs'\nimport { enableEmailAccess, TEnableEmailAccess } from '@private/lib/access/db/enableEmailAccess.mjs'\nimport { TUserData4VerifyEmail, userData4VerifyEmail } from '@private/lib/access/db/userData4VerifyEmail.mjs'\n\n/** Reader, guard chain and writer the handler needs, all bound to the same model + paths by the caller. */\nexport interface IVerifyEmailRouterDeps {\n\tuserData4VerifyEmail: TUserData4VerifyEmail\n\tassertVerifyEmailAllowed: TAssertVerifyEmailAllowed\n\tenableEmailAccess: TEnableEmailAccess\n}\n\n/**\n * Koa handler for the email-activation link.\n *\n * Taking the collaborators as arguments is what makes the handler testable at all: the DB read used to\n * be an ESM live binding that the tsx loader refuses to let sinon replace, so the whole try-body was\n * dead code in the suite and sat under a `c8 ignore`. It is now injected, the ignore is gone, and every\n * path is exercised directly.\n */\nexport const createVerifyEmailRouter = (deps: IVerifyEmailRouterDeps) => () => async (ctx: IContextVerifyEmail) => {\n\tconst { email, hash } = ctx.params\n\n\tconst uEmail = email.toLowerCase()\n\n\ttry {\n\t\t// search if the email exists\n\t\tconst user = await deps.userData4VerifyEmail(uEmail)\n\n\t\t// Every access guard lives in assertVerifyEmailAllowed, which is unit-tested.\n\t\tconst uId = await deps.assertVerifyEmailAllowed(user, email, hash)\n\n\t\t// ok enable email — only ever reached once every guard above has passed\n\t\tawait deps.enableEmailAccess(uId, email)\n\t\tctx.redirect('/x/registration-done') // url without prefix\n\t\t// ctx.redirect('https://google.it') // external url\n\t} catch (err: unknown) {\n\t\tconst link = (err as Error).message as string\n\t\tif (isSafeRedirectTarget(link)) {\n\t\t\tctx.redirect(link)\n\t\t} else {\n\t\t\tctx.redirect('/x/error')\n\t\t}\n\t}\n}\n\n/** Shape of the bound router, for the modules that take it as a dependency. */\nexport type TVerifyEmailRouter = ReturnType<typeof createVerifyEmailRouter>\n\n/** `UserBase`-bound default — the router every existing consumer already imports. */\nexport const routerVerifyEmail: TVerifyEmailRouter = createVerifyEmailRouter({\n\tuserData4VerifyEmail,\n\tassertVerifyEmailAllowed,\n\tenableEmailAccess\n})\n"]}