@axiumine/koa-utils 5.1.1 → 5.2.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.
@@ -4,7 +4,10 @@ interface IArgs {
4
4
  }
5
5
  /**
6
6
  * Take the user email and send an email with a link for change the password.
7
- * for privacy, true is returned if given email do not exist
7
+ * for privacy, true is returned whatever happens: unknown address, first request, or a request
8
+ * throttled because the previous one is less than 10 minutes old. The caller can never tell them apart,
9
+ * and the mail is queued after the commit without being awaited so the response time does not tell
10
+ * them apart either.
8
11
  */
9
12
  export declare const resetPwd: {
10
13
  description: string;
@@ -6,12 +6,15 @@ import { StringLib } from "../../../lib/StringLib.mjs";
6
6
  import { tryCatchRethrow } from "../../../lib/tryCatchRethrow.mjs";
7
7
  import { getResetPwd } from "../../../private/lib/access/db/getResetPwd.mjs";
8
8
  import { saveResetReq } from "../../../private/lib/access/db/saveResetReq.mjs";
9
- import { throwTooManyRequestsError } from "../../throw/throwTooManyRequestsError.mjs";
9
+ import * as Sentry from '@sentry/node';
10
10
  import { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql';
11
11
  import mongoose from 'mongoose';
12
12
  /**
13
13
  * Take the user email and send an email with a link for change the password.
14
- * for privacy, true is returned if given email do not exist
14
+ * for privacy, true is returned whatever happens: unknown address, first request, or a request
15
+ * throttled because the previous one is less than 10 minutes old. The caller can never tell them apart,
16
+ * and the mail is queued after the commit without being awaited so the response time does not tell
17
+ * them apart either.
15
18
  */
16
19
  export const resetPwd = {
17
20
  description: 'send reset password link',
@@ -23,6 +26,9 @@ export const resetPwd = {
23
26
  const { email } = args;
24
27
  const uEmail = email.toLowerCase().trim();
25
28
  checkEmailLen(uEmail);
29
+ // Set only when the transaction actually persisted a fresh reset request. The mail itself goes
30
+ // out after the commit, and is not awaited — see the block below the transaction.
31
+ let pendingMail = null;
26
32
  const session = await mongoose.startSession();
27
33
  try {
28
34
  await session.withTransaction(async () => {
@@ -38,44 +44,27 @@ export const resetPwd = {
38
44
  // if a password request already exists, read the date in seconds.
39
45
  const lastReq = typeof resetPwdVal.resetDateReq !== 'undefined' ? new Date('' + resetPwdVal.resetDateReq) : null;
40
46
  // request already made previously?
41
- // send a new email with the recovery link if it was sent less than 10 minutes ago
42
- let elapsedMin = 0;
47
+ // send a new email with the recovery link only if the last one is at least 10 minutes old
43
48
  const nowDt = new Date();
44
- let calculateHash = false;
49
+ // The throttle is enforced silently. Throwing 429 here answered "this address is
50
+ // registered and has a reset pending" to an unauthenticated caller, while an unknown
51
+ // address returned true — an enumeration oracle for any address that had been through
52
+ // this flow. Both cases now return true and send nothing.
53
+ let calculateHash = true;
45
54
  if (lastReq !== null) {
46
55
  // console.debug('reset request already made')
47
- elapsedMin = DateLib.minElapsed(lastReq);
48
- // console.debug('previous pwd reset request: ' + lastReq + ' it is now ' + now + ' and ' + elapsedMin + ' minutes have passed')
49
- // if a password reset request has already been made, at least 10 minutes must have passed
50
- if (elapsedMin < 10) {
51
- // console.debug('last req < 10 min')
52
- // Don't reveal that the email was found and
53
- elapsedMin = 10 - elapsedMin;
54
- /* c8 ignore next -- defensive: 10-elapsedMin is always >= 0 inside this branch */
55
- if (elapsedMin < 0)
56
- elapsedMin = 1; // to round up the seconds of the last minute, set minute = 1
57
- // console.debug('wait ' + message + ' min ' + uEmail)
58
- throw throwTooManyRequestsError(elapsedMin.toString());
59
- }
60
- else {
61
- // ok, more than 10 minutes, so generate hash for new email
62
- calculateHash = true;
63
- }
64
- }
65
- else {
66
- //console.debug('first reset request')
67
- calculateHash = true;
68
- }
56
+ // console.debug('previous pwd reset request: ' + lastReq + ' it is now ' + nowDt)
57
+ calculateHash = DateLib.minElapsed(lastReq) >= 10;
58
+ } //else console.debug('first reset request')
69
59
  if (calculateHash) {
70
60
  // generate hash for password reset
71
61
  const StrObj = new StringLib();
72
62
  const hash = StrObj.randomString(EMAIL_HASH_LEN);
73
63
  // set hash and current reset date
74
64
  await saveResetReq(session, resetPwdVal._id, nowDt, hash);
75
- // send email with new hash, last request > 10 minutes ago
76
- const SocketLabsObj = new SocketLabsLib();
77
- await SocketLabsObj.sendEmailReset(uEmail, hash, resetPwdVal.name);
78
- } // calculateHash & sendEmail
65
+ // the mail is queued after the commit, not here
66
+ pendingMail = { hash, name: resetPwdVal.name };
67
+ } // calculateHash
79
68
  });
80
69
  }
81
70
  catch (e) {
@@ -84,6 +73,37 @@ export const resetPwd = {
84
73
  finally {
85
74
  await session.endSession();
86
75
  }
76
+ // Reached only on a committed transaction: tryCatchRethrow above always throws.
77
+ //
78
+ // Three reasons this send sits here and is deliberately not awaited:
79
+ // 1. Timing. Awaiting a network round-trip to SocketLabs made the response measurably slower
80
+ // exactly when the address was registered and not throttled — the same fact the removed 429
81
+ // used to state outright. What is left is one extra updateOne, ~a millisecond against
82
+ // internet jitter, and the 10-minute throttle caps an attacker at one sample per address,
83
+ // so there is nothing to average out.
84
+ // 2. Retries. session.withTransaction re-runs its callback on a transient error. With the send
85
+ // inside, a retried commit mailed the user a second link and invalidated the first.
86
+ // 3. Failure disclosure. A SocketLabs outage used to surface as a 500, which only an address
87
+ // that actually exists could ever receive.
88
+ // The cost is that a delivery failure is now visible in Sentry only, mail in flight is lost if
89
+ // the process is killed before the request settles, and — the one a user feels — the hash is
90
+ // already committed when the send fails, so the 10-minute throttle is armed for a link that
91
+ // never arrived. Clearing resetHash/resetDateReq from the catch below to undo that was
92
+ // considered and rejected: a rejected promise does not prove non-delivery, and a timeout after
93
+ // SocketLabs accepted the message would kill a link already sitting in the user's inbox.
94
+ const mail = pendingMail;
95
+ if (mail !== null) {
96
+ try {
97
+ const SocketLabsObj = new SocketLabsLib();
98
+ void SocketLabsObj.sendEmailReset(uEmail, mail.hash, mail.name).catch((e) => {
99
+ Sentry.captureException(e);
100
+ });
101
+ }
102
+ catch (e) {
103
+ // the constructor, or a synchronous throw before the promise exists
104
+ Sentry.captureException(e);
105
+ }
106
+ }
87
107
  return true;
88
108
  }
89
109
  };
@@ -1 +1 @@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kC;oBAClC,MAAM,YAAY,CAAC,OAAO,EAAE,WAAW,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,CAAA;oBAEzD,0DAA0D;oBAC1D,MAAM,aAAa,GAAG,IAAI,aAAa,EAAE,CAAA;oBACzC,MAAM,aAAa,CAAC,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC,CAAA;gBACnE,CAAC,CAAC,4BAA4B;YAC/B,CAAC,CAAC,CAAA;QACH,CAAC;QAAC,OAAO,CAAU,EAAE,CAAC;YACrB,eAAe,CAAC,CAAyB,CAAC,CAAA;QAC3C,CAAC;gBAAS,CAAC;YACV,MAAM,OAAO,CAAC,UAAU,EAAE,CAAA;QAC3B,CAAC;QAED,OAAO,IAAI,CAAA;IACZ,CAAC;CACD,CAAA","sourcesContent":["import { SocketLabsLib } from '@email/SocketLabsLib.mjs'\nimport { checkEmailLen } from '@lib/checkEmailLen.mjs'\nimport { EMAIL_HASH_LEN } from '@lib/Constants.mjs'\nimport { DateLib } from '@lib/DateLib.mjs'\nimport { StringLib } from '@lib/StringLib.mjs'\nimport { tryCatchRethrow } from '@lib/tryCatchRethrow.mjs'\nimport { getResetPwd } from '@private/lib/access/db/getResetPwd.mjs'\nimport { saveResetReq } from '@private/lib/access/db/saveResetReq.mjs'\nimport { throwTooManyRequestsError } from '@throw/throwTooManyRequestsError.mjs'\nimport { GraphQLBoolean, GraphQLError, GraphQLNonNull, GraphQLString } from 'graphql'\nimport mongoose from 'mongoose'\n\ninterface IArgs {\n\temail: string\n}\n\n/**\n * Take the user email and send an email with a link for change the password.\n * for privacy, true is returned if given email do not exist\n */\nexport const resetPwd = {\n\tdescription: 'send reset password link',\n\ttype: new GraphQLNonNull(GraphQLBoolean),\n\targs: {\n\t\temail: { type: new GraphQLNonNull(GraphQLString) }\n\t},\n\tasync resolve(_: unknown, args: IArgs) {\n\t\tconst { email } = args\n\n\t\tconst uEmail = email.toLowerCase().trim()\n\t\tcheckEmailLen(uEmail)\n\n\t\tconst session = await mongoose.startSession()\n\t\ttry {\n\t\t\tawait session.withTransaction(async () => {\n\t\t\t\t// console.debug('email exists ?')\n\t\t\t\t// email exists? -> retrieve whether there have already been reset requests -> return 4xx ??\n\t\t\t\tconst resetPwdVal = await getResetPwd(session, uEmail)\n\n\t\t\t\t// don't reveal that the email doesn't exist, for privacy\n\t\t\t\tif (resetPwdVal === null) return\n\t\t\t\t// console.debug(\"the email exists\")\n\n\t\t\t\t// ok, email exists\n\n\t\t\t\t// -> wait 10 minutes from the last password reset request\n\n\t\t\t\t// if a password request already exists, read the date in seconds.\n\t\t\t\tconst lastReq = typeof resetPwdVal.resetDateReq !== 'undefined' ? new Date('' + resetPwdVal.resetDateReq) : null\n\n\t\t\t\t// request already made previously?\n\t\t\t\t// send a new email with the recovery link if it was sent less than 10 minutes ago\n\t\t\t\tlet elapsedMin = 0\n\t\t\t\tconst nowDt = new Date()\n\n\t\t\t\tlet calculateHash = false\n\t\t\t\tif (lastReq !== null) {\n\t\t\t\t\t// console.debug('reset request already made')\n\t\t\t\t\telapsedMin = DateLib.minElapsed(lastReq)\n\n\t\t\t\t\t// console.debug('previous pwd reset request: ' + lastReq + ' it is now ' + now + ' and ' + elapsedMin + ' minutes have passed')\n\t\t\t\t\t// if a password reset request has already been made, at least 10 minutes must have passed\n\t\t\t\t\tif (elapsedMin < 10) {\n\t\t\t\t\t\t// console.debug('last req < 10 min')\n\t\t\t\t\t\t// Don't reveal that the email was found and\n\t\t\t\t\t\telapsedMin = 10 - elapsedMin\n\t\t\t\t\t\t/* c8 ignore next -- defensive: 10-elapsedMin is always >= 0 inside this branch */\n\t\t\t\t\t\tif (elapsedMin < 0) elapsedMin = 1 // to round up the seconds of the last minute, set minute = 1\n\t\t\t\t\t\t// console.debug('wait ' + message + ' min ' + uEmail)\n\t\t\t\t\t\tthrow throwTooManyRequestsError(elapsedMin.toString())\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// ok, more than 10 minutes, so generate hash for new email\n\t\t\t\t\t\tcalculateHash = true\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t//console.debug('first reset request')\n\t\t\t\t\tcalculateHash = true\n\t\t\t\t}\n\n\t\t\t\tif (calculateHash) {\n\t\t\t\t\t// generate hash for password reset\n\t\t\t\t\tconst StrObj = new StringLib()\n\t\t\t\t\tconst hash = StrObj.randomString(EMAIL_HASH_LEN)\n\n\t\t\t\t\t// set hash and current reset date\n\t\t\t\t\tawait saveResetReq(session, resetPwdVal._id, nowDt, hash)\n\n\t\t\t\t\t// send email with new hash, last request > 10 minutes ago\n\t\t\t\t\tconst SocketLabsObj = new SocketLabsLib()\n\t\t\t\t\tawait SocketLabsObj.sendEmailReset(uEmail, hash, resetPwdVal.name)\n\t\t\t\t} // calculateHash & sendEmail\n\t\t\t})\n\t\t} catch (e: unknown) {\n\t\t\ttryCatchRethrow(e as GraphQLError | Error)\n\t\t} finally {\n\t\t\tawait session.endSession()\n\t\t}\n\n\t\treturn true\n\t}\n}\n"]}
1
+ {"version":3,"file":"resetPwd.mjs","sourceRoot":"","sources":["../../../../src/graphQL/schema/mutations/resetPwd.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,yCAAgC;AACxD,OAAO,EAAE,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,M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,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"]}
@@ -6,6 +6,7 @@ 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';
@@ -23,6 +24,9 @@ export const updatePassword = {
23
24
  const uEmail = email.trim().toLowerCase();
24
25
  checkEmailLen(uEmail);
25
26
  checkPwdLen(password);
27
+ // Set only once the transaction has actually persisted the new password. Carries the user's
28
+ // name to the post-commit confirmation email.
29
+ let confirmTo = null;
26
30
  const session = await mongoose.startSession();
27
31
  try {
28
32
  await session.withTransaction(async () => {
@@ -32,12 +36,20 @@ export const updatePassword = {
32
36
  throw throwForbiddenError(); // don't reveal whether the email is present, for privacy
33
37
  }
34
38
  // console.debug('--email present')
39
+ // No usable reset state. This is NOT an internal error as far as the caller is concerned:
40
+ // answering 500 here while an unknown address answers 403 turns this mutation into an
41
+ // account-enumeration oracle, because every registered account that has never requested a
42
+ // reset lands on this branch (getResetPwd yields resetHash === null whenever
43
+ // account.resetDateReq is undefined). Same 403 as the unknown-address path; the orphan
44
+ // state is reported to Sentry instead of to the caller.
35
45
  if (resetPwd.resetHash === null) {
36
- throw throwInternalError();
46
+ Sentry.captureMessage(`[updatePassword] no usable resetHash for ${uEmail}`);
47
+ throw throwForbiddenError();
37
48
  }
38
- /* c8 ignore next 3 -- defensive guard, resetDateReq cannot be null when resetHash is set */
49
+ /* c8 ignore next 4 -- defensive guard, resetDateReq cannot be null when resetHash is set */
39
50
  if (resetPwd.resetDateReq === null) {
40
- throw throwInternalError(); // throwSoftwareError('resetDateReq missing !')
51
+ Sentry.captureMessage(`[updatePassword] resetHash set but resetDateReq missing for ${uEmail}`);
52
+ throw throwForbiddenError();
41
53
  }
42
54
  // check if hash is missing or invalid
43
55
  if (resetPwd.resetHash !== hash) {
@@ -54,9 +66,8 @@ export const updatePassword = {
54
66
  } // else console.debug('--pwd updated')
55
67
  // delete password reset request data from db
56
68
  await removeResetReq(session, uEmail);
57
- // send new password confirmation email
58
- const SocketLabsObj = new SocketLabsLib();
59
- await SocketLabsObj.sendResetPwdConfirmation(uEmail, resetPwd.name);
69
+ // the confirmation email is sent after the commit, not here
70
+ confirmTo = resetPwd.name;
60
71
  });
61
72
  }
62
73
  catch (e) {
@@ -65,6 +76,34 @@ export const updatePassword = {
65
76
  finally {
66
77
  await session.endSession();
67
78
  }
79
+ // Reached only on a committed transaction: tryCatchRethrow above always throws.
80
+ //
81
+ // The send sits here rather than inside the callback because session.withTransaction re-runs
82
+ // its callback on a transient error, and a retried commit therefore mailed the user a second
83
+ // "your password was changed" notice. It is still awaited — unlike resetPwd there is no timing
84
+ // oracle to close here, since reaching this point at all requires a valid reset hash.
85
+ //
86
+ // A delivery failure no longer fails the request. It used to abort the transaction and answer
87
+ // 500, rolling back the password change with it — consistent, but it made the mail provider a
88
+ // hard dependency: with SocketLabs down, nobody could complete a reset at all. The password is
89
+ // committed by the time we get here, so the failure goes to Sentry and the caller still gets
90
+ // true. The confirmation is a notice, not part of the operation.
91
+ //
92
+ // Don't "restore" the abort: there is no transaction left to abort at this point. Rethrowing
93
+ // would report 500 for a password that is already live, and compensating would mean writing
94
+ // back the old bcrypt hash, which this flow never reads. Moving the send back inside the
95
+ // callback brings back the duplicate notice AND lets a mail go out for a commit that then
96
+ // fails — an email cannot be recalled.
97
+ const name = confirmTo;
98
+ if (name !== null) {
99
+ try {
100
+ const SocketLabsObj = new SocketLabsLib();
101
+ await SocketLabsObj.sendResetPwdConfirmation(uEmail, name);
102
+ }
103
+ catch (e) {
104
+ Sentry.captureException(e);
105
+ }
106
+ }
68
107
  return true;
69
108
  }
70
109
  };
@@ -1 +1 @@
1
- {"version":3,"file":"updatePassword.mjs","sourceRoot":"","sources":["../../../../src/graphQL/schema/mutations/updatePassword.mts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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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\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"]}
@@ -16,7 +16,7 @@ export const getResetPwd = async function (session, email) {
16
16
  // caller sending that same literal as the hash argument — a reset with no secret at all.
17
17
  // The two fields must also stay disjoint: reading the verification slot here is what let a
18
18
  // hash issued by one flow authenticate the other. Anything but a stored string => null,
19
- // which updatePassword rejects with a 500.
19
+ // which updatePassword rejects with the same 403 it gives an unknown address.
20
20
  if (typeof storedHash === 'string') {
21
21
  resetHash = storedHash;
22
22
  }
@@ -1 +1 @@
1
- {"version":3,"file":"getResetPwd.mjs","sourceRoot":"","sources":["../../../../../src/private/lib/access/db/getResetPwd.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,wDAAoC;AAGvD,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,WAAW,OAAsB,EAAE,KAAa;IAC/E,IAAI,GAAG,GAAG,IAAI,CAAA;IAEd,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,EAAE,aAAa,EAAE,KAAK,EAAE,CAAC;SAC/D,MAAM,CAAC,8DAA8D,CAAC;SACtE,OAAO,CAAC,OAAO,CAAC;SAChB,IAAI,EAAE,CAAA;IAER,8BAA8B;IAC9B,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;QACvB,MAAM,YAAY,GAAG,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAA;QAClD,IAAI,SAAS,GAAG,IAAI,CAAA;QAEpB,IAAI,OAAO,YAAY,KAAK,WAAW,EAAE,CAAC;YACzC,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,CAAC,SAAS,CAAA;YAE7C,wFAAwF;YACxF,0FAA0F;YAC1F,yFAAyF;YACzF,2FAA2F;YAC3F,wFAAwF;YACxF,2CAA2C;YAC3C,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE,CAAC;gBACpC,SAAS,GAAG,UAAU,CAAA;YACvB,CAAC;QACF,CAAC;QAED,GAAG,GAAG;YACL,GAAG,EAAE,QAAQ,CAAC,GAAG;YACjB,YAAY;YACZ,SAAS;YACT,IAAI,EAAE,QAAQ,CAAC,YAAY,EAAE,IAAI,IAAI,EAAE;SACvC,CAAA;IACF,CAAC;IACD,OAAO,GAAG,CAAA;AACX,CAAC,CAAA","sourcesContent":["import { UserBase } from '@models/MongoDB/UserBase.mjs'\nimport { ClientSession } from 'mongoose'\n\nexport const getResetPwd = async function (session: ClientSession, email: string) {\n\tlet ret = null\n\n\tconst queryRet = await UserBase.findOne({ 'login.email': email })\n\t\t.select('_id personalData.name account.resetDateReq account.resetHash')\n\t\t.session(session)\n\t\t.lean()\n\n\t// if a reset request is found\n\tif (queryRet !== null) {\n\t\tconst resetDateReq = queryRet.account.resetDateReq\n\t\tlet resetHash = null\n\n\t\tif (typeof resetDateReq !== 'undefined') {\n\t\t\tconst storedHash = queryRet.account.resetHash\n\n\t\t\t// Never stringify, and never fall back to account.email.hash. '' + undefined yields the\n\t\t\t// literal string \"undefined\", which passed updatePassword's null check and then matched a\n\t\t\t// caller sending that same literal as the hash argument — a reset with no secret at all.\n\t\t\t// The two fields must also stay disjoint: reading the verification slot here is what let a\n\t\t\t// hash issued by one flow authenticate the other. Anything but a stored string => null,\n\t\t\t// which updatePassword rejects with a 500.\n\t\t\tif (typeof storedHash === 'string') {\n\t\t\t\tresetHash = storedHash\n\t\t\t}\n\t\t}\n\n\t\tret = {\n\t\t\t_id: queryRet._id,\n\t\t\tresetDateReq,\n\t\t\tresetHash,\n\t\t\tname: queryRet.personalData?.name || ''\n\t\t}\n\t}\n\treturn ret\n}\n"]}
1
+ {"version":3,"file":"getResetPwd.mjs","sourceRoot":"","sources":["../../../../../src/private/lib/access/db/getResetPwd.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,wDAAoC;AAGvD,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,WAAW,OAAsB,EAAE,KAAa;IAC/E,IAAI,GAAG,GAAG,IAAI,CAAA;IAEd,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,EAAE,aAAa,EAAE,KAAK,EAAE,CAAC;SAC/D,MAAM,CAAC,8DAA8D,CAAC;SACtE,OAAO,CAAC,OAAO,CAAC;SAChB,IAAI,EAAE,CAAA;IAER,8BAA8B;IAC9B,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;QACvB,MAAM,YAAY,GAAG,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAA;QAClD,IAAI,SAAS,GAAG,IAAI,CAAA;QAEpB,IAAI,OAAO,YAAY,KAAK,WAAW,EAAE,CAAC;YACzC,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,CAAC,SAAS,CAAA;YAE7C,wFAAwF;YACxF,0FAA0F;YAC1F,yFAAyF;YACzF,2FAA2F;YAC3F,wFAAwF;YACxF,8EAA8E;YAC9E,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE,CAAC;gBACpC,SAAS,GAAG,UAAU,CAAA;YACvB,CAAC;QACF,CAAC;QAED,GAAG,GAAG;YACL,GAAG,EAAE,QAAQ,CAAC,GAAG;YACjB,YAAY;YACZ,SAAS;YACT,IAAI,EAAE,QAAQ,CAAC,YAAY,EAAE,IAAI,IAAI,EAAE;SACvC,CAAA;IACF,CAAC;IACD,OAAO,GAAG,CAAA;AACX,CAAC,CAAA","sourcesContent":["import { UserBase } from '@models/MongoDB/UserBase.mjs'\nimport { ClientSession } from 'mongoose'\n\nexport const getResetPwd = async function (session: ClientSession, email: string) {\n\tlet ret = null\n\n\tconst queryRet = await UserBase.findOne({ 'login.email': email })\n\t\t.select('_id personalData.name account.resetDateReq account.resetHash')\n\t\t.session(session)\n\t\t.lean()\n\n\t// if a reset request is found\n\tif (queryRet !== null) {\n\t\tconst resetDateReq = queryRet.account.resetDateReq\n\t\tlet resetHash = null\n\n\t\tif (typeof resetDateReq !== 'undefined') {\n\t\t\tconst storedHash = queryRet.account.resetHash\n\n\t\t\t// Never stringify, and never fall back to account.email.hash. '' + undefined yields the\n\t\t\t// literal string \"undefined\", which passed updatePassword's null check and then matched a\n\t\t\t// caller sending that same literal as the hash argument — a reset with no secret at all.\n\t\t\t// The two fields must also stay disjoint: reading the verification slot here is what let a\n\t\t\t// hash issued by one flow authenticate the other. Anything but a stored string => null,\n\t\t\t// which updatePassword rejects with the same 403 it gives an unknown address.\n\t\t\tif (typeof storedHash === 'string') {\n\t\t\t\tresetHash = storedHash\n\t\t\t}\n\t\t}\n\n\t\tret = {\n\t\t\t_id: queryRet._id,\n\t\t\tresetDateReq,\n\t\t\tresetHash,\n\t\t\tname: queryRet.personalData?.name || ''\n\t\t}\n\t}\n\treturn ret\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@axiumine/koa-utils",
3
- "version": "5.1.1",
3
+ "version": "5.2.0",
4
4
  "description": "Koa Utils",
5
5
  "type": "module",
6
6
  "repository": {