@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
@@ -6,11 +6,19 @@ import { tryCatchRethrow } from "../../../lib/tryCatchRethrow.mjs";
6
6
  import { getResetPwd } from "../../../private/lib/access/db/getResetPwd.mjs";
7
7
  import removeResetReq from "../../../private/lib/access/db/removeResetReq.mjs";
8
8
  import updatePasswordDb from "../../../private/lib/access/db/updatePasswordDb.mjs";
9
+ import * as Sentry from '@sentry/node';
9
10
  import { throwForbiddenError } from "../../throw/throwForbiddenError.mjs";
10
11
  import { throwInternalError } from "../../throw/throwInternalError.mjs";
11
12
  import { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql';
12
13
  import mongoose from 'mongoose';
13
- 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) => ({
14
22
  description: "changes the user's password",
15
23
  type: new GraphQLNonNull(GraphQLBoolean),
16
24
  args: {
@@ -23,21 +31,32 @@ export const updatePassword = {
23
31
  const uEmail = email.trim().toLowerCase();
24
32
  checkEmailLen(uEmail);
25
33
  checkPwdLen(password);
34
+ // Set only once the transaction has actually persisted the new password. Carries the user's
35
+ // name to the post-commit confirmation email.
36
+ let confirmTo = null;
26
37
  const session = await mongoose.startSession();
27
38
  try {
28
39
  await session.withTransaction(async () => {
29
- const resetPwd = await getResetPwd(session, uEmail);
40
+ const resetPwd = await deps.getResetPwd(session, uEmail);
30
41
  // check if email is present in db
31
42
  if (resetPwd === null) {
32
43
  throw throwForbiddenError(); // don't reveal whether the email is present, for privacy
33
44
  }
34
45
  // console.debug('--email present')
46
+ // No usable reset state. This is NOT an internal error as far as the caller is concerned:
47
+ // answering 500 here while an unknown address answers 403 turns this mutation into an
48
+ // account-enumeration oracle, because every registered account that has never requested a
49
+ // reset lands on this branch (getResetPwd yields resetHash === null whenever
50
+ // account.resetDateReq is undefined). Same 403 as the unknown-address path; the orphan
51
+ // state is reported to Sentry instead of to the caller.
35
52
  if (resetPwd.resetHash === null) {
36
- throw throwInternalError();
53
+ Sentry.captureMessage(`[updatePassword] no usable resetHash for ${uEmail}`);
54
+ throw throwForbiddenError();
37
55
  }
38
- /* c8 ignore next 3 -- defensive guard, resetDateReq cannot be null when resetHash is set */
56
+ /* c8 ignore next 4 -- defensive guard, resetDateReq cannot be null when resetHash is set */
39
57
  if (resetPwd.resetDateReq === null) {
40
- throw throwInternalError(); // throwSoftwareError('resetDateReq missing !')
58
+ Sentry.captureMessage(`[updatePassword] resetHash set but resetDateReq missing for ${uEmail}`);
59
+ throw throwForbiddenError();
41
60
  }
42
61
  // check if hash is missing or invalid
43
62
  if (resetPwd.resetHash !== hash) {
@@ -48,15 +67,14 @@ export const updatePassword = {
48
67
  if (DateLib.minElapsed(dt1) > 60) {
49
68
  throw throwForbiddenError(); // The link is no longer valid
50
69
  } // else console.debug('--link valid')
51
- const update = await updatePasswordDb(session, resetPwd._id, password);
70
+ const update = await deps.updatePasswordDb(session, resetPwd._id, password);
52
71
  if (!update) {
53
72
  throw throwInternalError(); // "System error while updating the password."
54
73
  } // else console.debug('--pwd updated')
55
74
  // delete password reset request data from db
56
- await removeResetReq(session, uEmail);
57
- // send new password confirmation email
58
- const SocketLabsObj = new SocketLabsLib();
59
- await SocketLabsObj.sendResetPwdConfirmation(uEmail, resetPwd.name);
75
+ await deps.removeResetReq(session, uEmail);
76
+ // the confirmation email is sent after the commit, not here
77
+ confirmTo = resetPwd.name;
60
78
  });
61
79
  }
62
80
  catch (e) {
@@ -65,7 +83,41 @@ export const updatePassword = {
65
83
  finally {
66
84
  await session.endSession();
67
85
  }
86
+ // Reached only on a committed transaction: tryCatchRethrow above always throws.
87
+ //
88
+ // The send sits here rather than inside the callback because session.withTransaction re-runs
89
+ // its callback on a transient error, and a retried commit therefore mailed the user a second
90
+ // "your password was changed" notice. It is still awaited — unlike resetPwd there is no timing
91
+ // oracle to close here, since reaching this point at all requires a valid reset hash.
92
+ //
93
+ // A delivery failure no longer fails the request. It used to abort the transaction and answer
94
+ // 500, rolling back the password change with it — consistent, but it made the mail provider a
95
+ // hard dependency: with SocketLabs down, nobody could complete a reset at all. The password is
96
+ // committed by the time we get here, so the failure goes to Sentry and the caller still gets
97
+ // true. The confirmation is a notice, not part of the operation.
98
+ //
99
+ // Don't "restore" the abort: there is no transaction left to abort at this point. Rethrowing
100
+ // would report 500 for a password that is already live, and compensating would mean writing
101
+ // back the old bcrypt hash, which this flow never reads. Moving the send back inside the
102
+ // callback brings back the duplicate notice AND lets a mail go out for a commit that then
103
+ // fails — an email cannot be recalled.
104
+ const name = confirmTo;
105
+ if (name !== null) {
106
+ try {
107
+ const SocketLabsObj = new SocketLabsLib();
108
+ await SocketLabsObj.sendResetPwdConfirmation(uEmail, name);
109
+ }
110
+ catch (e) {
111
+ Sentry.captureException(e);
112
+ }
113
+ }
68
114
  return true;
69
115
  }
70
- };
116
+ });
117
+ /** `UserBase`-bound default — the mutation every existing consumer already imports. */
118
+ export const updatePassword = createUpdatePasswordMutation({
119
+ getResetPwd,
120
+ updatePasswordDb,
121
+ removeResetReq
122
+ });
71
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,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,CAAC,EAAE;QACjD,QAAQ,EAAE,EAAE,IAAI,EAAE,IAAI,cAAc,CAAC,aAAa,CAAC,EAAE;KACrD;IACD,KAAK,CAAC,OAAO,CAAC,CAAU,EAAE,IAAW;QACpC,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAA;QAEtC,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAA;QACzC,aAAa,CAAC,M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BAC1E,CAAC,CAAC,sCAAsC;gBAExC,6CAA6C;gBAC7C,MAAM,cAAc,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;gBAErC,uCAAuC;gBACvC,MAAM,aAAa,GAAG,IAAI,aAAa,EAAE,CAAA;gBACzC,MAAM,aAAa,CAAC,wBAAwB,CAAC,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAA;YACpE,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 { 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 { 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\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\tif (resetPwd.resetHash === null) {\n\t\t\t\t\tthrow throwInternalError()\n\t\t\t\t}\n\t\t\t\t/* c8 ignore next 3 -- defensive guard, resetDateReq cannot be null when resetHash is set */\n\t\t\t\tif (resetPwd.resetDateReq === null) {\n\t\t\t\t\tthrow throwInternalError() // throwSoftwareError('resetDateReq missing !')\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// send new password confirmation email\n\t\t\t\tconst SocketLabsObj = new SocketLabsLib()\n\t\t\t\tawait SocketLabsObj.sendResetPwdConfirmation(uEmail, 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\treturn true\n\t}\n}\n"]}
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,EAAgB,uDAA8C;AAClF,OAAO,cAAmC,0DAAiD;AAC3F,OAAO,gBAAuC,4DAAmD;AACjG,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;AAe/B;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,CAAC,IAAyB,EAAE,EAAE,CAAC,CAAC;IAC3E,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,CAAC,EAAE;QACjD,QAAQ,EAAE,EAAE,IAAI,EAAE,IAAI,cAAc,CAAC,aAAa,CAAC,EAAE;KACrD;IACD,KAAK,CAAC,OAAO,CAAC,CAAU,EAAE,IAAW;QACpC,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,I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,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,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}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CAAA;QACzB,CAAC;IACF,CAAC;AACF,CAAC,CAAA;AAKD,qFAAqF;AACrF,MAAM,CAAC,MAAM,iBAAiB,GAAuB,uBAAuB,CAAC;IAC5E,oBAAoB;IACpB,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"]}
@@ -0,0 +1,92 @@
1
+ import { Model } from 'mongoose';
2
+ /**
3
+ * Any mongoose model an access flow can be pointed at.
4
+ *
5
+ * Deliberately `Model<any>`: the flows only ever call `findOne`, `updateOne`, `countDocuments` and
6
+ * `deleteOne` with computed field paths, so nothing here can be typed against a concrete document
7
+ * shape without forcing every consumer to describe theirs. The `paths` map below is what pins the
8
+ * contract instead — a wrong path is a runtime no-op, which is why the defaults are exported and the
9
+ * flows are tested against them.
10
+ */
11
+ export type TAccessModel = Model<any>;
12
+ /**
13
+ * Field paths the password-reset flow reads and writes.
14
+ *
15
+ * Every value is a dotted mongo path into the account document. They are supplied as data rather
16
+ * than hard-coded because `UserBase` is only one possible layout: a consumer whose accounts live in
17
+ * another collection, or under another field tree, could not use `resetPwd` / `updatePassword` at
18
+ * all while the paths were baked in.
19
+ */
20
+ export interface IResetPwdPaths {
21
+ /** Login address. Used as the lookup filter by `getResetPwd` and `removeResetReq`. */
22
+ email: string;
23
+ /** Bcrypt hash slot `updatePassword` overwrites. */
24
+ password: string;
25
+ /** Display name passed to the reset / confirmation emails. Missing value ⇒ empty string. */
26
+ name: string;
27
+ /** When the pending reset was requested. Drives the 10-minute throttle and the 60-minute expiry. */
28
+ resetDateReq: string;
29
+ /** Password-reset token. Must stay disjoint from the email-verification hash slot. */
30
+ resetHash: string;
31
+ /**
32
+ * Paths `removeResetReq` `$unset`s once a reset has been consumed.
33
+ *
34
+ * Kept separate from `resetDateReq` / `resetHash` on purpose — it is NOT always the same list.
35
+ * A layout that stores the request as one all-or-nothing subdocument, e.g.
36
+ * `resetPwd: { resetDateReq, resetHash }` under `validationLevel: 'strict'` +
37
+ * `validationAction: 'error'`, rejects a write that unsets a single member: the leftover document
38
+ * fails validation. The only legal cleanup there is `$unset: { resetPwd: '' }` — one container
39
+ * path, not two leaf paths. Deriving this list from the leaves would make that layout impossible
40
+ * to express, and the flat default hides the problem completely.
41
+ */
42
+ resetClear: readonly string[];
43
+ }
44
+ /** The layout of `UserBase` — i.e. the behaviour of the flow before it took a `paths` map. */
45
+ export declare const DEFAULT_RESET_PWD_PATHS: IResetPwdPaths;
46
+ /**
47
+ * Merge a partial override over {@link DEFAULT_RESET_PWD_PATHS}.
48
+ *
49
+ * Plain spread: a key present with an explicit `undefined` value overrides the default with
50
+ * `undefined`, so pass only the keys being changed.
51
+ */
52
+ export declare function resolveResetPwdPaths(paths?: Partial<IResetPwdPaths>): IResetPwdPaths;
53
+ /**
54
+ * Field paths the email-verification and email-change flows read and write.
55
+ *
56
+ * Same rationale as {@link IResetPwdPaths}. Note that `hash` here is the inbox-proof token
57
+ * (activation and email change, 3-day life, `requestTimes` throttle) and must never be pointed at
58
+ * the same field as `IResetPwdPaths.resetHash`: while the two shared one slot, a hash issued by
59
+ * either flow authenticated the other, and an unauthenticated reset request killed pending
60
+ * activation links.
61
+ */
62
+ export interface IVerifyEmailPaths {
63
+ /** Live login address — lookup filter, and the field `confirmNewEmail` writes on an email change. */
64
+ email: string;
65
+ /** Boolean flag `enableEmailAccess` flips once a verification link is honoured. */
66
+ valid: string;
67
+ /** Verification / email-change token. Never the password-reset slot. */
68
+ hash: string;
69
+ /** When the current token was issued. Drives the 3-day link window. */
70
+ dateLastReq: string;
71
+ /** Strike counter. Five wrong hashes delete the account. */
72
+ requestTimes: string;
73
+ /** Address awaiting confirmation during an email change. */
74
+ newEmailTmp: string;
75
+ /** Account tombstone flag. */
76
+ deleted: string;
77
+ /** Account lockout flag. */
78
+ disabled: string;
79
+ /** Paths `enableEmailAccess` `$unset`s once a verification link is honoured. */
80
+ verifyClear: readonly string[];
81
+ /** Paths `confirmNewEmail` `$unset`s once a new address is accepted. */
82
+ emailChangeClear: readonly string[];
83
+ }
84
+ /** The layout of `UserBase` — i.e. the behaviour of the flow before it took a `paths` map. */
85
+ export declare const DEFAULT_VERIFY_EMAIL_PATHS: IVerifyEmailPaths;
86
+ /**
87
+ * Merge a partial override over {@link DEFAULT_VERIFY_EMAIL_PATHS}.
88
+ *
89
+ * Plain spread: a key present with an explicit `undefined` value overrides the default with
90
+ * `undefined`, so pass only the keys being changed.
91
+ */
92
+ export declare function resolveVerifyEmailPaths(paths?: Partial<IVerifyEmailPaths>): IVerifyEmailPaths;
@@ -0,0 +1,46 @@
1
+ /** The layout of `UserBase` — i.e. the behaviour of the flow before it took a `paths` map. */
2
+ export const DEFAULT_RESET_PWD_PATHS = Object.freeze({
3
+ email: 'login.email',
4
+ password: 'login.password',
5
+ name: 'personalData.name',
6
+ resetDateReq: 'account.resetDateReq',
7
+ resetHash: 'account.resetHash',
8
+ resetClear: Object.freeze(['account.resetDateReq', 'account.resetHash'])
9
+ });
10
+ /**
11
+ * Merge a partial override over {@link DEFAULT_RESET_PWD_PATHS}.
12
+ *
13
+ * Plain spread: a key present with an explicit `undefined` value overrides the default with
14
+ * `undefined`, so pass only the keys being changed.
15
+ */
16
+ export function resolveResetPwdPaths(paths) {
17
+ return { ...DEFAULT_RESET_PWD_PATHS, ...paths };
18
+ }
19
+ /** The layout of `UserBase` — i.e. the behaviour of the flow before it took a `paths` map. */
20
+ export const DEFAULT_VERIFY_EMAIL_PATHS = Object.freeze({
21
+ email: 'login.email',
22
+ valid: 'account.email.valid',
23
+ hash: 'account.email.hash',
24
+ dateLastReq: 'account.email.dateLastReq',
25
+ requestTimes: 'account.email.requestTimes',
26
+ newEmailTmp: 'account.email.newEmailTmp',
27
+ deleted: 'account.deleted',
28
+ disabled: 'account.disabled',
29
+ verifyClear: Object.freeze(['account.email.hash', 'account.email.dateLastReq', 'account.email.requestTimes']),
30
+ emailChangeClear: Object.freeze([
31
+ 'account.email.hash',
32
+ 'account.email.dateLastReq',
33
+ 'account.email.requestTimes',
34
+ 'account.email.newEmailTmp'
35
+ ])
36
+ });
37
+ /**
38
+ * Merge a partial override over {@link DEFAULT_VERIFY_EMAIL_PATHS}.
39
+ *
40
+ * Plain spread: a key present with an explicit `undefined` value overrides the default with
41
+ * `undefined`, so pass only the keys being changed.
42
+ */
43
+ export function resolveVerifyEmailPaths(paths) {
44
+ return { ...DEFAULT_VERIFY_EMAIL_PATHS, ...paths };
45
+ }
46
+ //# sourceMappingURL=accessPaths.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accessPaths.mjs","sourceRoot":"","sources":["../../../src/lib/access/accessPaths.mts"],"names":[],"mappings":"AA+CA,8FAA8F;AAC9F,MAAM,CAAC,MAAM,uBAAuB,GAAmB,MAAM,CAAC,MAAM,CAAC;IACpE,KAAK,EAAE,aAAa;IACpB,QAAQ,EAAE,gBAAgB;IAC1B,IAAI,EAAE,mBAAmB;IACzB,YAAY,EAAE,sBAAsB;IACpC,SAAS,EAAE,mBAAmB;IAC9B,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,sBAAsB,EAAE,mBAAmB,CAAC,CAAC;CACxE,CAAC,CAAA;AAEF;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,KAA+B;IACnE,OAAO,EAAE,GAAG,uBAAuB,EAAE,GAAG,KAAK,EAAE,CAAA;AAChD,CAAC;AAkCD,8FAA8F;AAC9F,MAAM,CAAC,MAAM,0BAA0B,GAAsB,MAAM,CAAC,MAAM,CAAC;IAC1E,KAAK,EAAE,aAAa;IACpB,KAAK,EAAE,qBAAqB;IAC5B,IAAI,EAAE,oBAAoB;IAC1B,WAAW,EAAE,2BAA2B;IACxC,YAAY,EAAE,4BAA4B;IAC1C,WAAW,EAAE,2BAA2B;IACxC,OAAO,EAAE,iBAAiB;IAC1B,QAAQ,EAAE,kBAAkB;IAC5B,WAAW,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,oBAAoB,EAAE,2BAA2B,EAAE,4BAA4B,CAAC,CAAC;IAC7G,gBAAgB,EAAE,MAAM,CAAC,MAAM,CAAC;QAC/B,oBAAoB;QACpB,2BAA2B;QAC3B,4BAA4B;QAC5B,2BAA2B;KAC3B,CAAC;CACF,CAAC,CAAA;AAEF;;;;;GAKG;AACH,MAAM,UAAU,uBAAuB,CAAC,KAAkC;IACzE,OAAO,EAAE,GAAG,0BAA0B,EAAE,GAAG,KAAK,EAAE,CAAA;AACnD,CAAC","sourcesContent":["import { Model } from 'mongoose'\n\n/**\n * Any mongoose model an access flow can be pointed at.\n *\n * Deliberately `Model<any>`: the flows only ever call `findOne`, `updateOne`, `countDocuments` and\n * `deleteOne` with computed field paths, so nothing here can be typed against a concrete document\n * shape without forcing every consumer to describe theirs. The `paths` map below is what pins the\n * contract instead — a wrong path is a runtime no-op, which is why the defaults are exported and the\n * flows are tested against them.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type TAccessModel = Model<any>\n\n/**\n * Field paths the password-reset flow reads and writes.\n *\n * Every value is a dotted mongo path into the account document. They are supplied as data rather\n * than hard-coded because `UserBase` is only one possible layout: a consumer whose accounts live in\n * another collection, or under another field tree, could not use `resetPwd` / `updatePassword` at\n * all while the paths were baked in.\n */\nexport interface IResetPwdPaths {\n\t/** Login address. Used as the lookup filter by `getResetPwd` and `removeResetReq`. */\n\temail: string\n\t/** Bcrypt hash slot `updatePassword` overwrites. */\n\tpassword: string\n\t/** Display name passed to the reset / confirmation emails. Missing value ⇒ empty string. */\n\tname: string\n\t/** When the pending reset was requested. Drives the 10-minute throttle and the 60-minute expiry. */\n\tresetDateReq: string\n\t/** Password-reset token. Must stay disjoint from the email-verification hash slot. */\n\tresetHash: string\n\t/**\n\t * Paths `removeResetReq` `$unset`s once a reset has been consumed.\n\t *\n\t * Kept separate from `resetDateReq` / `resetHash` on purpose — it is NOT always the same list.\n\t * A layout that stores the request as one all-or-nothing subdocument, e.g.\n\t * `resetPwd: { resetDateReq, resetHash }` under `validationLevel: 'strict'` +\n\t * `validationAction: 'error'`, rejects a write that unsets a single member: the leftover document\n\t * fails validation. The only legal cleanup there is `$unset: { resetPwd: '' }` — one container\n\t * path, not two leaf paths. Deriving this list from the leaves would make that layout impossible\n\t * to express, and the flat default hides the problem completely.\n\t */\n\tresetClear: readonly string[]\n}\n\n/** The layout of `UserBase` — i.e. the behaviour of the flow before it took a `paths` map. */\nexport const DEFAULT_RESET_PWD_PATHS: IResetPwdPaths = Object.freeze({\n\temail: 'login.email',\n\tpassword: 'login.password',\n\tname: 'personalData.name',\n\tresetDateReq: 'account.resetDateReq',\n\tresetHash: 'account.resetHash',\n\tresetClear: Object.freeze(['account.resetDateReq', 'account.resetHash'])\n})\n\n/**\n * Merge a partial override over {@link DEFAULT_RESET_PWD_PATHS}.\n *\n * Plain spread: a key present with an explicit `undefined` value overrides the default with\n * `undefined`, so pass only the keys being changed.\n */\nexport function resolveResetPwdPaths(paths?: Partial<IResetPwdPaths>): IResetPwdPaths {\n\treturn { ...DEFAULT_RESET_PWD_PATHS, ...paths }\n}\n\n/**\n * Field paths the email-verification and email-change flows read and write.\n *\n * Same rationale as {@link IResetPwdPaths}. Note that `hash` here is the inbox-proof token\n * (activation and email change, 3-day life, `requestTimes` throttle) and must never be pointed at\n * the same field as `IResetPwdPaths.resetHash`: while the two shared one slot, a hash issued by\n * either flow authenticated the other, and an unauthenticated reset request killed pending\n * activation links.\n */\nexport interface IVerifyEmailPaths {\n\t/** Live login address — lookup filter, and the field `confirmNewEmail` writes on an email change. */\n\temail: string\n\t/** Boolean flag `enableEmailAccess` flips once a verification link is honoured. */\n\tvalid: string\n\t/** Verification / email-change token. Never the password-reset slot. */\n\thash: string\n\t/** When the current token was issued. Drives the 3-day link window. */\n\tdateLastReq: string\n\t/** Strike counter. Five wrong hashes delete the account. */\n\trequestTimes: string\n\t/** Address awaiting confirmation during an email change. */\n\tnewEmailTmp: string\n\t/** Account tombstone flag. */\n\tdeleted: string\n\t/** Account lockout flag. */\n\tdisabled: string\n\t/** Paths `enableEmailAccess` `$unset`s once a verification link is honoured. */\n\tverifyClear: readonly string[]\n\t/** Paths `confirmNewEmail` `$unset`s once a new address is accepted. */\n\temailChangeClear: readonly string[]\n}\n\n/** The layout of `UserBase` — i.e. the behaviour of the flow before it took a `paths` map. */\nexport const DEFAULT_VERIFY_EMAIL_PATHS: IVerifyEmailPaths = Object.freeze({\n\temail: 'login.email',\n\tvalid: 'account.email.valid',\n\thash: 'account.email.hash',\n\tdateLastReq: 'account.email.dateLastReq',\n\trequestTimes: 'account.email.requestTimes',\n\tnewEmailTmp: 'account.email.newEmailTmp',\n\tdeleted: 'account.deleted',\n\tdisabled: 'account.disabled',\n\tverifyClear: Object.freeze(['account.email.hash', 'account.email.dateLastReq', 'account.email.requestTimes']),\n\temailChangeClear: Object.freeze([\n\t\t'account.email.hash',\n\t\t'account.email.dateLastReq',\n\t\t'account.email.requestTimes',\n\t\t'account.email.newEmailTmp'\n\t])\n})\n\n/**\n * Merge a partial override over {@link DEFAULT_VERIFY_EMAIL_PATHS}.\n *\n * Plain spread: a key present with an explicit `undefined` value overrides the default with\n * `undefined`, so pass only the keys being changed.\n */\nexport function resolveVerifyEmailPaths(paths?: Partial<IVerifyEmailPaths>): IVerifyEmailPaths {\n\treturn { ...DEFAULT_VERIFY_EMAIL_PATHS, ...paths }\n}\n"]}
@@ -0,0 +1,33 @@
1
+ import { TResetPwdMutation } from '../../graphQL/schema/mutations/resetPwd.mjs';
2
+ import { TUpdatePasswordMutation } from '../../graphQL/schema/mutations/updatePassword.mjs';
3
+ import { IResetPwdPaths, TAccessModel } from './accessPaths.mjs';
4
+ /** What the factory needs: the account model, plus any path that differs from the default layout. */
5
+ export interface ICreateResetPwdFlowArgs {
6
+ model: TAccessModel;
7
+ paths?: Partial<IResetPwdPaths>;
8
+ }
9
+ /** The two mutations the flow exposes, bound to the model and paths passed in. */
10
+ export interface IResetPwdFlow {
11
+ resetPwd: TResetPwdMutation;
12
+ updatePassword: TUpdatePasswordMutation;
13
+ }
14
+ /**
15
+ * Build the password-reset mutations against any mongoose model.
16
+ *
17
+ * The package's own `resetPwd` / `updatePassword` exports are this factory applied to `UserBase` with
18
+ * `DEFAULT_RESET_PWD_PATHS`, so switching to it changes nothing until a path is overridden.
19
+ *
20
+ * Every key of `paths` is optional and falls back to the default layout. `resetClear` is the one to
21
+ * look at twice: it is the list of paths the cleanup `$unset`s, and it is NOT derived from
22
+ * `resetDateReq` + `resetHash`. A schema storing the request as one required-members subdocument under
23
+ * `validationLevel: 'strict'` is left invalid by unsetting a single member, and the write is rejected —
24
+ * such a schema must pass the container path instead. See `IResetPwdPaths.resetClear`.
25
+ *
26
+ * ```ts
27
+ * const { resetPwd, updatePassword } = createResetPwdFlow({
28
+ * model: Account,
29
+ * paths: { email: 'mail', password: 'pwd', name: 'profile.fullName', resetClear: ['resetPwd'] }
30
+ * })
31
+ * ```
32
+ */
33
+ export declare const createResetPwdFlow: ({ model, paths }: ICreateResetPwdFlowArgs) => IResetPwdFlow;
@@ -0,0 +1,42 @@
1
+ import { createGetResetPwd } from "../../private/lib/access/db/getResetPwd.mjs";
2
+ import { createRemoveResetReq } from "../../private/lib/access/db/removeResetReq.mjs";
3
+ import { createSaveResetReq } from "../../private/lib/access/db/saveResetReq.mjs";
4
+ import { createUpdatePasswordDb } from "../../private/lib/access/db/updatePasswordDb.mjs";
5
+ import { createResetPwdMutation } from '../../graphQL/schema/mutations/resetPwd.mjs';
6
+ import { createUpdatePasswordMutation } from '../../graphQL/schema/mutations/updatePassword.mjs';
7
+ import { resolveResetPwdPaths } from './accessPaths.mjs';
8
+ /**
9
+ * Build the password-reset mutations against any mongoose model.
10
+ *
11
+ * The package's own `resetPwd` / `updatePassword` exports are this factory applied to `UserBase` with
12
+ * `DEFAULT_RESET_PWD_PATHS`, so switching to it changes nothing until a path is overridden.
13
+ *
14
+ * Every key of `paths` is optional and falls back to the default layout. `resetClear` is the one to
15
+ * look at twice: it is the list of paths the cleanup `$unset`s, and it is NOT derived from
16
+ * `resetDateReq` + `resetHash`. A schema storing the request as one required-members subdocument under
17
+ * `validationLevel: 'strict'` is left invalid by unsetting a single member, and the write is rejected —
18
+ * such a schema must pass the container path instead. See `IResetPwdPaths.resetClear`.
19
+ *
20
+ * ```ts
21
+ * const { resetPwd, updatePassword } = createResetPwdFlow({
22
+ * model: Account,
23
+ * paths: { email: 'mail', password: 'pwd', name: 'profile.fullName', resetClear: ['resetPwd'] }
24
+ * })
25
+ * ```
26
+ */
27
+ export const createResetPwdFlow = ({ model, paths }) => {
28
+ const resolved = resolveResetPwdPaths(paths);
29
+ const getResetPwd = createGetResetPwd(model, resolved);
30
+ return {
31
+ resetPwd: createResetPwdMutation({
32
+ getResetPwd,
33
+ saveResetReq: createSaveResetReq(model, resolved)
34
+ }),
35
+ updatePassword: createUpdatePasswordMutation({
36
+ getResetPwd,
37
+ updatePasswordDb: createUpdatePasswordDb(model, resolved),
38
+ removeResetReq: createRemoveResetReq(model, resolved)
39
+ })
40
+ };
41
+ };
42
+ //# sourceMappingURL=createResetPwdFlow.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createResetPwdFlow.mjs","sourceRoot":"","sources":["../../../src/lib/access/createResetPwdFlow.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,oDAA8C;AAC1E,OAAO,EAAE,oBAAoB,EAAE,uDAAiD;AAChF,OAAO,EAAE,kBAAkB,EAAE,qDAA+C;AAC5E,OAAO,EAAE,sBAAsB,EAAE,yDAAmD;AAEpF,OAAO,EAAE,sBAAsB,EAAqB,MAAM,6CAA6C,CAAA;AACvG,OAAO,EAAE,4BAA4B,EAA2B,MAAM,mDAAmD,CAAA;AACzH,OAAO,EAAkB,oBAAoB,EAAgB,MAAM,mBAAmB,CAAA;AActF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,EAAE,KAAK,EAAE,KAAK,EAA2B,EAAiB,EAAE;IAC9F,MAAM,QAAQ,GAAG,oBAAoB,CAAC,KAAK,CAAC,CAAA;IAE5C,MAAM,WAAW,GAAG,iBAAiB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;IAEtD,OAAO;QACN,QAAQ,EAAE,sBAAsB,CAAC;YAChC,WAAW;YACX,YAAY,EAAE,kBAAkB,CAAC,KAAK,EAAE,QAAQ,CAAC;SACjD,CAAC;QACF,cAAc,EAAE,4BAA4B,CAAC;YAC5C,WAAW;YACX,gBAAgB,EAAE,sBAAsB,CAAC,KAAK,EAAE,QAAQ,CAAC;YACzD,cAAc,EAAE,oBAAoB,CAAC,KAAK,EAAE,QAAQ,CAAC;SACrD,CAAC;KACF,CAAA;AACF,CAAC,CAAA","sourcesContent":["import { createGetResetPwd } from '@private/lib/access/db/getResetPwd.mjs'\nimport { createRemoveResetReq } from '@private/lib/access/db/removeResetReq.mjs'\nimport { createSaveResetReq } from '@private/lib/access/db/saveResetReq.mjs'\nimport { createUpdatePasswordDb } from '@private/lib/access/db/updatePasswordDb.mjs'\n\nimport { createResetPwdMutation, TResetPwdMutation } from '../../graphQL/schema/mutations/resetPwd.mjs'\nimport { createUpdatePasswordMutation, TUpdatePasswordMutation } from '../../graphQL/schema/mutations/updatePassword.mjs'\nimport { IResetPwdPaths, resolveResetPwdPaths, TAccessModel } from './accessPaths.mjs'\n\n/** What the factory needs: the account model, plus any path that differs from the default layout. */\nexport interface ICreateResetPwdFlowArgs {\n\tmodel: TAccessModel\n\tpaths?: Partial<IResetPwdPaths>\n}\n\n/** The two mutations the flow exposes, bound to the model and paths passed in. */\nexport interface IResetPwdFlow {\n\tresetPwd: TResetPwdMutation\n\tupdatePassword: TUpdatePasswordMutation\n}\n\n/**\n * Build the password-reset mutations against any mongoose model.\n *\n * The package's own `resetPwd` / `updatePassword` exports are this factory applied to `UserBase` with\n * `DEFAULT_RESET_PWD_PATHS`, so switching to it changes nothing until a path is overridden.\n *\n * Every key of `paths` is optional and falls back to the default layout. `resetClear` is the one to\n * look at twice: it is the list of paths the cleanup `$unset`s, and it is NOT derived from\n * `resetDateReq` + `resetHash`. A schema storing the request as one required-members subdocument under\n * `validationLevel: 'strict'` is left invalid by unsetting a single member, and the write is rejected —\n * such a schema must pass the container path instead. See `IResetPwdPaths.resetClear`.\n *\n * ```ts\n * const { resetPwd, updatePassword } = createResetPwdFlow({\n * model: Account,\n * paths: { email: 'mail', password: 'pwd', name: 'profile.fullName', resetClear: ['resetPwd'] }\n * })\n * ```\n */\nexport const createResetPwdFlow = ({ model, paths }: ICreateResetPwdFlowArgs): IResetPwdFlow => {\n\tconst resolved = resolveResetPwdPaths(paths)\n\n\tconst getResetPwd = createGetResetPwd(model, resolved)\n\n\treturn {\n\t\tresetPwd: createResetPwdMutation({\n\t\t\tgetResetPwd,\n\t\t\tsaveResetReq: createSaveResetReq(model, resolved)\n\t\t}),\n\t\tupdatePassword: createUpdatePasswordMutation({\n\t\t\tgetResetPwd,\n\t\t\tupdatePasswordDb: createUpdatePasswordDb(model, resolved),\n\t\t\tremoveResetReq: createRemoveResetReq(model, resolved)\n\t\t})\n\t}\n}\n"]}
@@ -0,0 +1,48 @@
1
+ import { TAssertVerifyEmailAllowed } from "../../private/lib/access/assertVerifyEmailAllowed.mjs";
2
+ import { TConfirmNewEmail } from "../../private/lib/access/db/confirmNewEmail.mjs";
3
+ import { TDeleteUserByEmail } from "../../private/lib/access/db/deleteUserByEmail.mjs";
4
+ import { TEnableEmailAccess } from "../../private/lib/access/db/enableEmailAccess.mjs";
5
+ import { TIncReqTimes } from "../../private/lib/access/db/incReqTimes.mjs";
6
+ import { TSetEmailHash } from "../../private/lib/access/db/setEmailHash.mjs";
7
+ import { TUserData4VerifyEmail } from "../../private/lib/access/db/userData4VerifyEmail.mjs";
8
+ import { TEmailChangeHashVerifyMutation } from '../../graphQL/schema/mutations/emailChangeHashVerify.mjs';
9
+ import { TVerifyEmailRouter } from '../../koa/router/verifyEmail.mjs';
10
+ import { IVerifyEmailPaths, TAccessModel } from './accessPaths.mjs';
11
+ /** What the factory needs: the account model, plus any path that differs from the default layout. */
12
+ export interface ICreateVerifyEmailFlowArgs {
13
+ model: TAccessModel;
14
+ paths?: Partial<IVerifyEmailPaths>;
15
+ }
16
+ /** Everything the verify-email chain exposes, bound to the model and paths passed in. */
17
+ export interface IVerifyEmailFlow {
18
+ userData4VerifyEmail: TUserData4VerifyEmail;
19
+ setEmailHash: TSetEmailHash;
20
+ enableEmailAccess: TEnableEmailAccess;
21
+ confirmNewEmail: TConfirmNewEmail;
22
+ deleteUserByEmail: TDeleteUserByEmail;
23
+ incReqTimes: TIncReqTimes;
24
+ assertVerifyEmailAllowed: TAssertVerifyEmailAllowed;
25
+ emailChangeHashVerify: TEmailChangeHashVerifyMutation;
26
+ routerVerifyEmail: TVerifyEmailRouter;
27
+ }
28
+ /**
29
+ * Build the whole email-verification chain against any mongoose model.
30
+ *
31
+ * The package's own exports (`userData4VerifyEmail`, `setEmailHash`, `enableEmailAccess`,
32
+ * `confirmNewEmail`, `emailChangeHashVerify`, `routerVerifyEmail`) are this factory applied to
33
+ * `UserBase` with `DEFAULT_VERIFY_EMAIL_PATHS`, so switching to it changes nothing until a path is
34
+ * overridden.
35
+ *
36
+ * The two `*Clear` keys are lists of paths to `$unset`, and neither is derived from the leaf paths the
37
+ * flow reads: a schema storing the verification state as one required-members subdocument is left
38
+ * invalid by unsetting a single member. Pass the container path in that case. See `IVerifyEmailPaths`.
39
+ *
40
+ * ```ts
41
+ * const flow = createVerifyEmailFlow({
42
+ * model: Account,
43
+ * paths: { email: 'mail', valid: 'verified', verifyClear: ['verification'] }
44
+ * })
45
+ * router.get('/check/verify-email/:email/:hash', flow.routerVerifyEmail())
46
+ * ```
47
+ */
48
+ export declare const createVerifyEmailFlow: ({ model, paths }: ICreateVerifyEmailFlowArgs) => IVerifyEmailFlow;
@@ -0,0 +1,68 @@
1
+ import { createAssertVerifyEmailAllowed } from "../../private/lib/access/assertVerifyEmailAllowed.mjs";
2
+ import { createConfirmNewEmail } from "../../private/lib/access/db/confirmNewEmail.mjs";
3
+ import { createDeleteUserByEmail } from "../../private/lib/access/db/deleteUserByEmail.mjs";
4
+ import { createEnableEmailAccess } from "../../private/lib/access/db/enableEmailAccess.mjs";
5
+ import { createIncReqTimes } from "../../private/lib/access/db/incReqTimes.mjs";
6
+ import { createSetEmailHash } from "../../private/lib/access/db/setEmailHash.mjs";
7
+ import { createUserData4VerifyEmail } from "../../private/lib/access/db/userData4VerifyEmail.mjs";
8
+ import { createHandleIfHashBad } from "../../private/lib/access/handleIfHashBad.mjs";
9
+ import { createHandleIfMoreThan3DaysPassed } from "../../private/lib/access/handleIfMoreThan3DaysPassed.mjs";
10
+ import { createHandleIfTooMuchRequestsTimes } from "../../private/lib/access/handleIfTooMuchRequestsTimes.mjs";
11
+ import { createEmailChangeHashVerifyMutation } from '../../graphQL/schema/mutations/emailChangeHashVerify.mjs';
12
+ import { createVerifyEmailRouter } from '../../koa/router/verifyEmail.mjs';
13
+ import { resolveVerifyEmailPaths } from './accessPaths.mjs';
14
+ /**
15
+ * Build the whole email-verification chain against any mongoose model.
16
+ *
17
+ * The package's own exports (`userData4VerifyEmail`, `setEmailHash`, `enableEmailAccess`,
18
+ * `confirmNewEmail`, `emailChangeHashVerify`, `routerVerifyEmail`) are this factory applied to
19
+ * `UserBase` with `DEFAULT_VERIFY_EMAIL_PATHS`, so switching to it changes nothing until a path is
20
+ * overridden.
21
+ *
22
+ * The two `*Clear` keys are lists of paths to `$unset`, and neither is derived from the leaf paths the
23
+ * flow reads: a schema storing the verification state as one required-members subdocument is left
24
+ * invalid by unsetting a single member. Pass the container path in that case. See `IVerifyEmailPaths`.
25
+ *
26
+ * ```ts
27
+ * const flow = createVerifyEmailFlow({
28
+ * model: Account,
29
+ * paths: { email: 'mail', valid: 'verified', verifyClear: ['verification'] }
30
+ * })
31
+ * router.get('/check/verify-email/:email/:hash', flow.routerVerifyEmail())
32
+ * ```
33
+ */
34
+ export const createVerifyEmailFlow = ({ model, paths }) => {
35
+ const resolved = resolveVerifyEmailPaths(paths);
36
+ const userData4VerifyEmail = createUserData4VerifyEmail(model, resolved);
37
+ const enableEmailAccess = createEnableEmailAccess(model, resolved);
38
+ const confirmNewEmail = createConfirmNewEmail(model, resolved);
39
+ const deleteUserByEmail = createDeleteUserByEmail(model, resolved);
40
+ const incReqTimes = createIncReqTimes(model, resolved);
41
+ const assertVerifyEmailAllowed = createAssertVerifyEmailAllowed({
42
+ paths: resolved,
43
+ handleIfHashBad: createHandleIfHashBad(incReqTimes),
44
+ handleIfMoreThan3DaysPassed: createHandleIfMoreThan3DaysPassed(deleteUserByEmail),
45
+ handleIfTooMuchRequestsTimes: createHandleIfTooMuchRequestsTimes(deleteUserByEmail)
46
+ });
47
+ return {
48
+ userData4VerifyEmail,
49
+ setEmailHash: createSetEmailHash(model, resolved),
50
+ enableEmailAccess,
51
+ confirmNewEmail,
52
+ deleteUserByEmail,
53
+ incReqTimes,
54
+ assertVerifyEmailAllowed,
55
+ emailChangeHashVerify: createEmailChangeHashVerifyMutation({
56
+ model,
57
+ paths: resolved,
58
+ confirmNewEmail,
59
+ incReqTimes
60
+ }),
61
+ routerVerifyEmail: createVerifyEmailRouter({
62
+ userData4VerifyEmail,
63
+ assertVerifyEmailAllowed,
64
+ enableEmailAccess
65
+ })
66
+ };
67
+ };
68
+ //# sourceMappingURL=createVerifyEmailFlow.mjs.map