@axiumine/koa-utils 5.4.0 → 5.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/graphQL/schema/mutations/emailChangeHashVerify.mjs +54 -58
- package/dist/graphQL/schema/mutations/emailChangeHashVerify.mjs.map +1 -1
- package/dist/graphQL/schema/mutations/updatePassword.mjs +47 -38
- package/dist/graphQL/schema/mutations/updatePassword.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -11,17 +11,62 @@ import { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql';
|
|
|
11
11
|
* The submitted hash does not match the stored one: count the attempt and warn the account owner.
|
|
12
12
|
* Extracted from resolve() only to keep it inside the max-lines-per-function budget — behaviour unchanged.
|
|
13
13
|
*/
|
|
14
|
-
async function handleHashMismatch(
|
|
14
|
+
async function handleHashMismatch(ctx, uId, requestTimes) {
|
|
15
15
|
// hash failed
|
|
16
16
|
console.debug('HASH FAILED');
|
|
17
17
|
if (typeof requestTimes === 'undefined') {
|
|
18
18
|
throw throwInternalError();
|
|
19
19
|
}
|
|
20
|
-
await
|
|
20
|
+
await ctx.deps.incReqTimes(uId);
|
|
21
21
|
// noinspection ES6MissingAwait
|
|
22
|
-
|
|
22
|
+
ctx.socketLabs.wrongHash(ctx.uEmail, requestTimes);
|
|
23
23
|
return false;
|
|
24
24
|
}
|
|
25
|
+
/**
|
|
26
|
+
* The submitted hash matches: enforce the freshness/account guards and, if the target email is still
|
|
27
|
+
* free, accept it. Extracted from resolve() only to keep it inside the max-lines-per-function budget.
|
|
28
|
+
*/
|
|
29
|
+
async function handleValidHash(ctx, uId, dateLastReq) {
|
|
30
|
+
const { deps, user, uEmail, socketLabs } = ctx;
|
|
31
|
+
const { paths } = deps;
|
|
32
|
+
if (typeof dateLastReq === 'undefined') {
|
|
33
|
+
// @fixme sentry 'dateLastReq is undefined'
|
|
34
|
+
throw throwInternalError();
|
|
35
|
+
}
|
|
36
|
+
console.debug('activation link hash is valid');
|
|
37
|
+
// if dateLastReq is older than 3 days, warn and stop
|
|
38
|
+
const StrLibObj = new StringLib();
|
|
39
|
+
const now = new Date();
|
|
40
|
+
const day3ago = new Date(now.setDate(now.getDate() - 3));
|
|
41
|
+
if (StrLibObj.isoToTimestamp(day3ago) > StrLibObj.isoToTimestamp(dateLastReq)) {
|
|
42
|
+
// dateLastReq too old then 3 days
|
|
43
|
+
console.debug('but link is too old');
|
|
44
|
+
// noinspection ES6MissingAwait
|
|
45
|
+
socketLabs.hashReqTooOld(uEmail);
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
// account is deleted -> maybe by admin for any reason
|
|
49
|
+
// Read raw: this is a .lean() query, so Mongoose casting never runs and these are real booleans
|
|
50
|
+
// only on data that scripts/migrate-account-disabled-to-boolean.mjs has been through. A legacy
|
|
51
|
+
// string 'false' is truthy and blocks here — migrate, don't coerce.
|
|
52
|
+
if (readPath(user, paths.deleted)) {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
// if account is disabled, for any reason
|
|
56
|
+
if (readPath(user, paths.disabled)) {
|
|
57
|
+
// noinspection ES6MissingAwait
|
|
58
|
+
socketLabs.accountDisabled(uEmail);
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
// valid request. meanwhile, has some user registered with this email address ??
|
|
62
|
+
const qty = await deps.model.countDocuments({ [paths.email]: uEmail });
|
|
63
|
+
if (qty > 0) {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
// accept new email
|
|
67
|
+
await deps.confirmNewEmail(uId, uEmail);
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
25
70
|
/**
|
|
26
71
|
* Change email - Verify match between email and hash
|
|
27
72
|
*
|
|
@@ -38,8 +83,7 @@ export const createEmailChangeHashVerifyMutation = (deps) => ({
|
|
|
38
83
|
},
|
|
39
84
|
async resolve(_, args) {
|
|
40
85
|
const { paths } = deps;
|
|
41
|
-
const
|
|
42
|
-
const uEmail = email.toLowerCase();
|
|
86
|
+
const uEmail = args.email.toLowerCase();
|
|
43
87
|
// search if the email exists
|
|
44
88
|
// Every field this resolver reads must be listed. account.email.requestTimes was missing, and
|
|
45
89
|
// because this is a .lean() read the absent key made handleHashMismatch throw 500 on *every*
|
|
@@ -48,68 +92,20 @@ export const createEmailChangeHashVerifyMutation = (deps) => ({
|
|
|
48
92
|
.findOne({ [paths.newEmailTmp]: uEmail })
|
|
49
93
|
.select(buildProjection([paths.hash, paths.dateLastReq, paths.requestTimes, paths.deleted, paths.disabled]))
|
|
50
94
|
.lean();
|
|
51
|
-
// if email not found, return
|
|
95
|
+
// if email not found, return (do not tell the user the real problem !)
|
|
52
96
|
if (user === null) {
|
|
53
|
-
// <- not found or wrong, do not say to the user the real problem !
|
|
54
97
|
console.debug('email NOT found ', uEmail);
|
|
55
98
|
return false; // @fixme throw
|
|
56
99
|
}
|
|
57
100
|
console.debug('email found');
|
|
58
|
-
const
|
|
59
|
-
const StrLibObj = new StringLib();
|
|
101
|
+
const ctx = { deps, user, uEmail, socketLabs: new SocketLabsLib() };
|
|
60
102
|
console.debug('comparing hash ');
|
|
61
103
|
const uId = readPath(user, '_id');
|
|
62
104
|
const dateLastReq = readPath(user, paths.dateLastReq);
|
|
63
|
-
if (hash === readPath(user, paths.hash)) {
|
|
64
|
-
|
|
65
|
-
// @fixme sentry 'dateLastReq is undefined'
|
|
66
|
-
throw throwInternalError();
|
|
67
|
-
}
|
|
68
|
-
console.debug('activation link hash is valid');
|
|
69
|
-
/****************************************************
|
|
70
|
-
* if dateLastReq too old then 3 days send email
|
|
71
|
-
*/
|
|
72
|
-
const now = new Date();
|
|
73
|
-
const day3ago = new Date(now.setDate(now.getDate() - 3));
|
|
74
|
-
const tsReq = StrLibObj.isoToTimestamp(dateLastReq);
|
|
75
|
-
const ts3DayAgo = StrLibObj.isoToTimestamp(day3ago);
|
|
76
|
-
if (ts3DayAgo > tsReq) {
|
|
77
|
-
// dateLastReq too old then 3 days
|
|
78
|
-
console.debug('but link is too old');
|
|
79
|
-
// noinspection ES6MissingAwait
|
|
80
|
-
SocketLabsObj.hashReqTooOld(uEmail);
|
|
81
|
-
return false;
|
|
82
|
-
}
|
|
83
|
-
// account is deleted -> maybe by admin for any reason
|
|
84
|
-
// Read raw: this is a .lean() query, so Mongoose casting never runs and these are real
|
|
85
|
-
// booleans only on data that scripts/migrate-account-disabled-to-boolean.mjs has been
|
|
86
|
-
// through. A legacy string 'false' is truthy and blocks here — migrate, don't coerce.
|
|
87
|
-
else if (readPath(user, paths.deleted)) {
|
|
88
|
-
return false;
|
|
89
|
-
}
|
|
90
|
-
// if account is disabled, for any reason
|
|
91
|
-
else if (readPath(user, paths.disabled)) {
|
|
92
|
-
// noinspection ES6MissingAwait
|
|
93
|
-
SocketLabsObj.accountDisabled(uEmail);
|
|
94
|
-
return false;
|
|
95
|
-
}
|
|
96
|
-
else {
|
|
97
|
-
// valid request. is this email free ?
|
|
98
|
-
// meanwhile, has some user registered with this email address ??
|
|
99
|
-
const qty = await deps.model.countDocuments({ [paths.email]: uEmail });
|
|
100
|
-
if (qty === 0) {
|
|
101
|
-
// accept new email
|
|
102
|
-
await deps.confirmNewEmail(uId, uEmail);
|
|
103
|
-
return true;
|
|
104
|
-
}
|
|
105
|
-
else {
|
|
106
|
-
return false;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
else {
|
|
111
|
-
return handleHashMismatch(deps.incReqTimes, uId, uEmail, readPath(user, paths.requestTimes), SocketLabsObj);
|
|
105
|
+
if (args.hash === readPath(user, paths.hash)) {
|
|
106
|
+
return handleValidHash(ctx, uId, dateLastReq);
|
|
112
107
|
}
|
|
108
|
+
return handleHashMismatch(ctx, uId, readPath(user, paths.requestTimes));
|
|
113
109
|
}
|
|
114
110
|
});
|
|
115
111
|
/** `UserBase`-bound default — the mutation every existing consumer already imports. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"emailChangeHashVerify.mjs","s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ACf,mBAAmB;oBACnB,MAAM,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;oBACvC,OAAO,IAAI,CAAA;gBACZ,CAAC;qBAAM,CAAC;oBACP,OAAO,KAAK,CAAA;gBACb,CAAC;YACF,CAAC;QACF,CAAC;aAAM,CAAC;YACP,OAAO,kBAAkB,CACxB,IAAI,CAAC,WAAW,EAChB,GAAG,EACH,MAAM,EACN,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC,YAAY,CAAuB,EACxD,aAAa,CACb,CAAA;QACF,CAAC;IACF,CAAC;CACD,CAAC,CAAA;AAKF,uFAAuF;AACvF,MAAM,CAAC,MAAM,qBAAqB,GAAmC,mCAAmC,CAAC;IACxG,KAAK,EAAE,QAAQ;IACf,KAAK,EAAE,0BAA0B;IACjC,eAAe;IACf,WAAW;CACX,CAAC,CAAA","sourcesContent":["import { SocketLabsLib } from '@email/SocketLabsLib.mjs'\nimport { DEFAULT_VERIFY_EMAIL_PATHS, IVerifyEmailPaths, TAccessModel } from '@lib/access/accessPaths.mjs'\nimport { StringLib } from '@lib/StringLib.mjs'\nimport { UserBase } from '@models/MongoDB/UserBase.mjs'\nimport confirmNewEmail, { TConfirmNewEmail } from '@private/lib/access/db/confirmNewEmail.mjs'\nimport { incReqTimes, TIncReqTimes } from '@private/lib/access/db/incReqTimes.mjs'\nimport { buildProjection, readPath } from '@private/lib/access/pathTools.mjs'\nimport { throwInternalError } from '@throw/throwInternalError.mjs'\nimport { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql'\nimport { Types } from 'mongoose'\n\n/** Arguments accepted by the `emailChangeHashVerify` mutation. Exported so a consumer re-exporting the bound mutation can name its type. */\nexport interface IEmailChangeHashVerifyArgs {\n\temail: string\n\thash: string\n}\n\n/** Model, field map and writers the resolver needs, all bound together by the caller. */\nexport interface IEmailChangeHashVerifyDeps {\n\tmodel: TAccessModel\n\tpaths: IVerifyEmailPaths\n\tconfirmNewEmail: TConfirmNewEmail\n\tincReqTimes: TIncReqTimes\n}\n\n/**\n * The submitted hash does not match the stored one: count the attempt and warn the account owner.\n * Extracted from resolve() only to keep it inside the max-lines-per-function budget — behaviour unchanged.\n */\nasync function handleHashMismatch(\n\tincReqTimesFn: TIncReqTimes,\n\tuId: Types.ObjectId,\n\tuEmail: string,\n\trequestTimes: number | undefined,\n\tSocketLabsObj: SocketLabsLib\n) {\n\t// hash failed\n\tconsole.debug('HASH FAILED')\n\n\tif (typeof requestTimes === 'undefined') {\n\t\tthrow throwInternalError()\n\t}\n\n\tawait incReqTimesFn(uId)\n\t// noinspection ES6MissingAwait\n\tSocketLabsObj.wrongHash(uEmail, requestTimes)\n\treturn false\n}\n\n/**\n * Change email - Verify match between email and hash\n *\n * The collection and every field path come from `deps`, so the same resolver serves any account model.\n * The projection is built from the same map the reads use, which is what keeps a read field from going\n * missing — the exact bug that made every wrong hash answer 500 through 5.1.0.\n */\nexport const createEmailChangeHashVerifyMutation = (deps: IEmailChangeHashVerifyDeps) => ({\n\tdescription: 'Change email - Verify match between email and hash',\n\ttype: new GraphQLNonNull(GraphQLBoolean),\n\targs: {\n\t\temail: { type: new GraphQLNonNull(GraphQLString) },\n\t\thash: { type: new GraphQLNonNull(GraphQLString) }\n\t},\n\tasync resolve(_: unknown, args: IEmailChangeHashVerifyArgs) {\n\t\tconst { paths } = deps\n\t\tconst { email, hash } = args\n\t\tconst uEmail = email.toLowerCase()\n\n\t\t// search if the email exists\n\t\t// Every field this resolver reads must be listed. account.email.requestTimes was missing, and\n\t\t// because this is a .lean() read the absent key made handleHashMismatch throw 500 on *every*\n\t\t// wrong hash: the strike counter never advanced and the owner never got the wrongHash warning.\n\t\tconst user = await deps.model\n\t\t\t.findOne({ [paths.newEmailTmp]: uEmail })\n\t\t\t.select(buildProjection([paths.hash, paths.dateLastReq, paths.requestTimes, paths.deleted, paths.disabled]))\n\t\t\t.lean()\n\n\t\t// if email not found, return\n\t\tif (user === null) {\n\t\t\t// <- not found or wrong, do not say to the user the real problem !\n\t\t\tconsole.debug('email NOT found ', uEmail)\n\n\t\t\treturn false // @fixme throw\n\t\t}\n\t\tconsole.debug('email found')\n\n\t\tconst SocketLabsObj = new SocketLabsLib()\n\t\tconst StrLibObj = new StringLib()\n\n\t\tconsole.debug('comparing hash ')\n\t\tconst uId = readPath(user, '_id') as Types.ObjectId\n\t\tconst dateLastReq = readPath(user, paths.dateLastReq) as Date | undefined\n\t\tif (hash === readPath(user, paths.hash)) {\n\t\t\tif (typeof dateLastReq === 'undefined') {\n\t\t\t\t// @fixme sentry 'dateLastReq is undefined'\n\t\t\t\tthrow throwInternalError()\n\t\t\t}\n\n\t\t\tconsole.debug('activation link hash is valid')\n\t\t\t/****************************************************\n\t\t\t * if dateLastReq too old then 3 days send email\n\t\t\t */\n\n\t\t\tconst now = new Date()\n\t\t\tconst day3ago = new Date(now.setDate(now.getDate() - 3))\n\t\t\tconst tsReq = StrLibObj.isoToTimestamp(dateLastReq)\n\t\t\tconst ts3DayAgo = StrLibObj.isoToTimestamp(day3ago)\n\n\t\t\tif (ts3DayAgo > tsReq) {\n\t\t\t\t// dateLastReq too old then 3 days\n\t\t\t\tconsole.debug('but link is too old')\n\n\t\t\t\t// noinspection ES6MissingAwait\n\t\t\t\tSocketLabsObj.hashReqTooOld(uEmail)\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// account is deleted -> maybe by admin for any reason\n\t\t\t// Read raw: this is a .lean() query, so Mongoose casting never runs and these are real\n\t\t\t// booleans only on data that scripts/migrate-account-disabled-to-boolean.mjs has been\n\t\t\t// through. A legacy string 'false' is truthy and blocks here — migrate, don't coerce.\n\t\t\telse if (readPath(user, paths.deleted)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t// if account is disabled, for any reason\n\t\t\telse if (readPath(user, paths.disabled)) {\n\t\t\t\t// noinspection ES6MissingAwait\n\t\t\t\tSocketLabsObj.accountDisabled(uEmail)\n\t\t\t\treturn false\n\t\t\t} else {\n\t\t\t\t// valid request. is this email free ?\n\n\t\t\t\t// meanwhile, has some user registered with this email address ??\n\t\t\t\tconst qty = await deps.model.countDocuments({ [paths.email]: uEmail })\n\n\t\t\t\tif (qty === 0) {\n\t\t\t\t\t// accept new email\n\t\t\t\t\tawait deps.confirmNewEmail(uId, uEmail)\n\t\t\t\t\treturn true\n\t\t\t\t} else {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn handleHashMismatch(\n\t\t\t\tdeps.incReqTimes,\n\t\t\t\tuId,\n\t\t\t\tuEmail,\n\t\t\t\treadPath(user, paths.requestTimes) as number | undefined,\n\t\t\t\tSocketLabsObj\n\t\t\t)\n\t\t}\n\t}\n})\n\n/** Shape of the bound mutation, for the modules that take it as a dependency. */\nexport type TEmailChangeHashVerifyMutation = ReturnType<typeof createEmailChangeHashVerifyMutation>\n\n/** `UserBase`-bound default — the mutation every existing consumer already imports. */\nexport const emailChangeHashVerify: TEmailChangeHashVerifyMutation = createEmailChangeHashVerifyMutation({\n\tmodel: UserBase,\n\tpaths: DEFAULT_VERIFY_EMAIL_PATHS,\n\tconfirmNewEmail,\n\tincReqTimes\n})\n"]}
|
|
1
|
+
{"version":3,"file":"emailChangeHashVerify.mjs","sourceRoot":"","sources":["../../../../src/graphQL/schema/mutations/emailChangeHashVerify.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,yCAAgC;AACxD,OAAO,EAAE,0BAA0B,EAAmC,4CAAmC;AACzG,OAAO,EAAE,SAAS,EAAE,mCAA0B;AAC9C,OAAO,EAAE,QAAQ,EAAE,0CAAoC;AACvD,OAAO,eAAqC,2DAAkD;AAC9F,OAAO,EAAE,WAAW,EAAgB,uDAA8C;AAClF,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,kDAAyC;AAC7E,OAAO,EAAE,kBAAkB,EAAE,2CAAqC;AAClE,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;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;IAC9F,CAAC;CACD,CAAC,CAAA;AAKF,uFAAuF;AACvF,MAAM,CAAC,MAAM,qBAAqB,GAAmC,mCAAmC,CAAC;IACxG,KAAK,EAAE,QAAQ;IACf,KAAK,EAAE,0BAA0B;IACjC,eAAe;IACf,WAAW;CACX,CAAC,CAAA","sourcesContent":["import { SocketLabsLib } from '@email/SocketLabsLib.mjs'\nimport { DEFAULT_VERIFY_EMAIL_PATHS, IVerifyEmailPaths, TAccessModel } from '@lib/access/accessPaths.mjs'\nimport { StringLib } from '@lib/StringLib.mjs'\nimport { UserBase } from '@models/MongoDB/UserBase.mjs'\nimport confirmNewEmail, { TConfirmNewEmail } from '@private/lib/access/db/confirmNewEmail.mjs'\nimport { incReqTimes, TIncReqTimes } from '@private/lib/access/db/incReqTimes.mjs'\nimport { buildProjection, readPath } from '@private/lib/access/pathTools.mjs'\nimport { throwInternalError } from '@throw/throwInternalError.mjs'\nimport { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql'\nimport { Types } from 'mongoose'\n\n/** Arguments accepted by the `emailChangeHashVerify` mutation. Exported so a consumer re-exporting the bound mutation can name its type. */\nexport interface IEmailChangeHashVerifyArgs {\n\temail: string\n\thash: string\n}\n\n/** Model, field map and writers the resolver needs, all bound together by the caller. */\nexport interface IEmailChangeHashVerifyDeps {\n\tmodel: TAccessModel\n\tpaths: IVerifyEmailPaths\n\tconfirmNewEmail: TConfirmNewEmail\n\tincReqTimes: TIncReqTimes\n}\n\n/**\n * Everything the extracted branch handlers need, bundled so each stays within the max-params budget:\n * the bound deps, the lean document just read, the lowercased email and one shared SocketLabs client.\n */\ninterface IVerifyContext {\n\tdeps: IEmailChangeHashVerifyDeps\n\tuser: unknown\n\tuEmail: string\n\tsocketLabs: SocketLabsLib\n}\n\n/**\n * The submitted hash does not match the stored one: count the attempt and warn the account owner.\n * Extracted from resolve() only to keep it inside the max-lines-per-function budget — behaviour unchanged.\n */\nasync function handleHashMismatch(ctx: IVerifyContext, uId: Types.ObjectId, requestTimes: number | undefined) {\n\t// hash failed\n\tconsole.debug('HASH FAILED')\n\n\tif (typeof requestTimes === 'undefined') {\n\t\tthrow throwInternalError()\n\t}\n\n\tawait ctx.deps.incReqTimes(uId)\n\t// noinspection ES6MissingAwait\n\tctx.socketLabs.wrongHash(ctx.uEmail, requestTimes)\n\treturn false\n}\n\n/**\n * The submitted hash matches: enforce the freshness/account guards and, if the target email is still\n * free, accept it. Extracted from resolve() only to keep it inside the max-lines-per-function budget.\n */\nasync function handleValidHash(ctx: IVerifyContext, uId: Types.ObjectId, dateLastReq: Date | undefined) {\n\tconst { deps, user, uEmail, socketLabs } = ctx\n\tconst { paths } = deps\n\n\tif (typeof dateLastReq === 'undefined') {\n\t\t// @fixme sentry 'dateLastReq is undefined'\n\t\tthrow throwInternalError()\n\t}\n\n\tconsole.debug('activation link hash is valid')\n\n\t// if dateLastReq is older than 3 days, warn and stop\n\tconst StrLibObj = new StringLib()\n\tconst now = new Date()\n\tconst day3ago = new Date(now.setDate(now.getDate() - 3))\n\n\tif (StrLibObj.isoToTimestamp(day3ago) > StrLibObj.isoToTimestamp(dateLastReq)) {\n\t\t// dateLastReq too old then 3 days\n\t\tconsole.debug('but link is too old')\n\n\t\t// noinspection ES6MissingAwait\n\t\tsocketLabs.hashReqTooOld(uEmail)\n\t\treturn false\n\t}\n\n\t// account is deleted -> maybe by admin for any reason\n\t// Read raw: this is a .lean() query, so Mongoose casting never runs and these are real booleans\n\t// only on data that scripts/migrate-account-disabled-to-boolean.mjs has been through. A legacy\n\t// string 'false' is truthy and blocks here — migrate, don't coerce.\n\tif (readPath(user, paths.deleted)) {\n\t\treturn false\n\t}\n\t// if account is disabled, for any reason\n\tif (readPath(user, paths.disabled)) {\n\t\t// noinspection ES6MissingAwait\n\t\tsocketLabs.accountDisabled(uEmail)\n\t\treturn false\n\t}\n\n\t// valid request. meanwhile, has some user registered with this email address ??\n\tconst qty = await deps.model.countDocuments({ [paths.email]: uEmail })\n\tif (qty > 0) {\n\t\treturn false\n\t}\n\n\t// accept new email\n\tawait deps.confirmNewEmail(uId, uEmail)\n\treturn true\n}\n\n/**\n * Change email - Verify match between email and hash\n *\n * The collection and every field path come from `deps`, so the same resolver serves any account model.\n * The projection is built from the same map the reads use, which is what keeps a read field from going\n * missing — the exact bug that made every wrong hash answer 500 through 5.1.0.\n */\nexport const createEmailChangeHashVerifyMutation = (deps: IEmailChangeHashVerifyDeps) => ({\n\tdescription: 'Change email - Verify match between email and hash',\n\ttype: new GraphQLNonNull(GraphQLBoolean),\n\targs: {\n\t\temail: { type: new GraphQLNonNull(GraphQLString) },\n\t\thash: { type: new GraphQLNonNull(GraphQLString) }\n\t},\n\tasync resolve(_: unknown, args: IEmailChangeHashVerifyArgs) {\n\t\tconst { paths } = deps\n\t\tconst uEmail = args.email.toLowerCase()\n\n\t\t// search if the email exists\n\t\t// Every field this resolver reads must be listed. account.email.requestTimes was missing, and\n\t\t// because this is a .lean() read the absent key made handleHashMismatch throw 500 on *every*\n\t\t// wrong hash: the strike counter never advanced and the owner never got the wrongHash warning.\n\t\tconst user = await deps.model\n\t\t\t.findOne({ [paths.newEmailTmp]: uEmail })\n\t\t\t.select(buildProjection([paths.hash, paths.dateLastReq, paths.requestTimes, paths.deleted, paths.disabled]))\n\t\t\t.lean()\n\n\t\t// if email not found, return (do not tell the user the real problem !)\n\t\tif (user === null) {\n\t\t\tconsole.debug('email NOT found ', uEmail)\n\n\t\t\treturn false // @fixme throw\n\t\t}\n\t\tconsole.debug('email found')\n\n\t\tconst ctx: IVerifyContext = { deps, user, uEmail, socketLabs: new SocketLabsLib() }\n\n\t\tconsole.debug('comparing hash ')\n\t\tconst uId = readPath(user, '_id') as Types.ObjectId\n\t\tconst dateLastReq = readPath(user, paths.dateLastReq) as Date | undefined\n\n\t\tif (args.hash === readPath(user, paths.hash)) {\n\t\t\treturn handleValidHash(ctx, uId, dateLastReq)\n\t\t}\n\t\treturn handleHashMismatch(ctx, uId, readPath(user, paths.requestTimes) as number | undefined)\n\t}\n})\n\n/** Shape of the bound mutation, for the modules that take it as a dependency. */\nexport type TEmailChangeHashVerifyMutation = ReturnType<typeof createEmailChangeHashVerifyMutation>\n\n/** `UserBase`-bound default — the mutation every existing consumer already imports. */\nexport const emailChangeHashVerify: TEmailChangeHashVerifyMutation = createEmailChangeHashVerifyMutation({\n\tmodel: UserBase,\n\tpaths: DEFAULT_VERIFY_EMAIL_PATHS,\n\tconfirmNewEmail,\n\tincReqTimes\n})\n"]}
|
|
@@ -11,6 +11,52 @@ import { throwForbiddenError } from "../../throw/throwForbiddenError.mjs";
|
|
|
11
11
|
import { throwInternalError } from "../../throw/throwInternalError.mjs";
|
|
12
12
|
import { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql';
|
|
13
13
|
import mongoose from 'mongoose';
|
|
14
|
+
/**
|
|
15
|
+
* The transactional core: validate the reset hash, apply the new password and clear the request.
|
|
16
|
+
* Extracted from resolve() only to keep it inside the max-lines-per-function budget — behaviour
|
|
17
|
+
* unchanged. Returns the account holder's name so the caller can mail the post-commit confirmation.
|
|
18
|
+
*/
|
|
19
|
+
async function applyPasswordReset(deps, session, input) {
|
|
20
|
+
const { uEmail, hash, password } = input;
|
|
21
|
+
const resetPwd = await deps.getResetPwd(session, uEmail);
|
|
22
|
+
// check if email is present in db
|
|
23
|
+
if (resetPwd === null) {
|
|
24
|
+
throw throwForbiddenError(); // don't reveal whether the email is present, for privacy
|
|
25
|
+
}
|
|
26
|
+
// console.debug('--email present')
|
|
27
|
+
// No usable reset state. This is NOT an internal error as far as the caller is concerned:
|
|
28
|
+
// answering 500 here while an unknown address answers 403 turns this mutation into an
|
|
29
|
+
// account-enumeration oracle, because every registered account that has never requested a
|
|
30
|
+
// reset lands on this branch (getResetPwd yields resetHash === null whenever
|
|
31
|
+
// account.resetDateReq is undefined). Same 403 as the unknown-address path; the orphan
|
|
32
|
+
// state is reported to Sentry instead of to the caller.
|
|
33
|
+
if (resetPwd.resetHash === null) {
|
|
34
|
+
Sentry.captureMessage(`[updatePassword] no usable resetHash for ${uEmail}`);
|
|
35
|
+
throw throwForbiddenError();
|
|
36
|
+
}
|
|
37
|
+
/* c8 ignore next 4 -- defensive guard, resetDateReq cannot be null when resetHash is set */
|
|
38
|
+
if (resetPwd.resetDateReq === null) {
|
|
39
|
+
Sentry.captureMessage(`[updatePassword] resetHash set but resetDateReq missing for ${uEmail}`);
|
|
40
|
+
throw throwForbiddenError();
|
|
41
|
+
}
|
|
42
|
+
// check if hash is missing or invalid
|
|
43
|
+
if (resetPwd.resetHash !== hash) {
|
|
44
|
+
throw throwForbiddenError(); // don't reveal whether the email is present, for privacy
|
|
45
|
+
} // else console.debug('--hash valid')
|
|
46
|
+
// check if the request was made within 1 hour
|
|
47
|
+
const dt1 = new Date('' + resetPwd.resetDateReq);
|
|
48
|
+
if (DateLib.minElapsed(dt1) > 60) {
|
|
49
|
+
throw throwForbiddenError(); // The link is no longer valid
|
|
50
|
+
} // else console.debug('--link valid')
|
|
51
|
+
const update = await deps.updatePasswordDb(session, resetPwd._id, password);
|
|
52
|
+
if (!update) {
|
|
53
|
+
throw throwInternalError(); // "System error while updating the password."
|
|
54
|
+
} // else console.debug('--pwd updated')
|
|
55
|
+
// delete password reset request data from db
|
|
56
|
+
await deps.removeResetReq(session, uEmail);
|
|
57
|
+
// the confirmation email is sent after the commit, not here
|
|
58
|
+
return resetPwd.name;
|
|
59
|
+
}
|
|
14
60
|
/**
|
|
15
61
|
* Change the password of an account holding a valid, unexpired reset hash.
|
|
16
62
|
*
|
|
@@ -37,44 +83,7 @@ export const createUpdatePasswordMutation = (deps) => ({
|
|
|
37
83
|
const session = await mongoose.startSession();
|
|
38
84
|
try {
|
|
39
85
|
await session.withTransaction(async () => {
|
|
40
|
-
|
|
41
|
-
// check if email is present in db
|
|
42
|
-
if (resetPwd === null) {
|
|
43
|
-
throw throwForbiddenError(); // don't reveal whether the email is present, for privacy
|
|
44
|
-
}
|
|
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.
|
|
52
|
-
if (resetPwd.resetHash === null) {
|
|
53
|
-
Sentry.captureMessage(`[updatePassword] no usable resetHash for ${uEmail}`);
|
|
54
|
-
throw throwForbiddenError();
|
|
55
|
-
}
|
|
56
|
-
/* c8 ignore next 4 -- defensive guard, resetDateReq cannot be null when resetHash is set */
|
|
57
|
-
if (resetPwd.resetDateReq === null) {
|
|
58
|
-
Sentry.captureMessage(`[updatePassword] resetHash set but resetDateReq missing for ${uEmail}`);
|
|
59
|
-
throw throwForbiddenError();
|
|
60
|
-
}
|
|
61
|
-
// check if hash is missing or invalid
|
|
62
|
-
if (resetPwd.resetHash !== hash) {
|
|
63
|
-
throw throwForbiddenError(); // don't reveal whether the email is present, for privacy
|
|
64
|
-
} // else console.debug('--hash valid')
|
|
65
|
-
// check if the request was made within 1 hour
|
|
66
|
-
const dt1 = new Date('' + resetPwd.resetDateReq);
|
|
67
|
-
if (DateLib.minElapsed(dt1) > 60) {
|
|
68
|
-
throw throwForbiddenError(); // The link is no longer valid
|
|
69
|
-
} // else console.debug('--link valid')
|
|
70
|
-
const update = await deps.updatePasswordDb(session, resetPwd._id, password);
|
|
71
|
-
if (!update) {
|
|
72
|
-
throw throwInternalError(); // "System error while updating the password."
|
|
73
|
-
} // else console.debug('--pwd updated')
|
|
74
|
-
// delete password reset request data from db
|
|
75
|
-
await deps.removeResetReq(session, uEmail);
|
|
76
|
-
// the confirmation email is sent after the commit, not here
|
|
77
|
-
confirmTo = resetPwd.name;
|
|
86
|
+
confirmTo = await applyPasswordReset(deps, session, { uEmail, hash, password });
|
|
78
87
|
});
|
|
79
88
|
}
|
|
80
89
|
catch (e) {
|
|
@@ -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,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;AAgB/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,IAAyB;QAClD,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAA;QAEtC,MAAM,MA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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\n/** Arguments accepted by the `updatePassword` mutation. Exported so a consumer re-exporting the bound mutation can name its type. */\nexport interface IUpdatePasswordArgs {\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: IUpdatePasswordArgs) {\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
|
+
{"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,QAA2B,MAAM,UAAU,CAAA;AAuBlD;;;;GAIG;AACH,KA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AAC,IAAI,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAA;YAChF,CAAC,CAAC,CAAA;QACH,CAAC;QAAC,OAAO,CAAU,EAAE,CAAC;YACrB,eAAe,CAAC,CAAyB,CAAC,CAAA;QAC3C,CAAC;gBAAS,CAAC;YACV,MAAM,OAAO,CAAC,UAAU,EAAE,CAAA;QAC3B,CAAC;QAED,gFAAgF;QAChF,EAAE;QACF,6FAA6F;QAC7F,6FAA6F;QAC7F,+FAA+F;QAC/F,sFAAsF;QACtF,EAAE;QACF,8FAA8F;QAC9F,8FAA8F;QAC9F,+FAA+F;QAC/F,6FAA6F;QAC7F,iEAAiE;QACjE,EAAE;QACF,6FAA6F;QAC7F,4FAA4F;QAC5F,yFAAyF;QACzF,0FAA0F;QAC1F,uCAAuC;QACvC,MAAM,IAAI,GAAG,SAA0B,CAAA;QACvC,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YACnB,IAAI,CAAC;gBACJ,MAAM,aAAa,GAAG,IAAI,aAAa,EAAE,CAAA;gBACzC,MAAM,aAAa,CAAC,wBAAwB,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;YAC3D,CAAC;YAAC,OAAO,CAAU,EAAE,CAAC;gBACrB,MAAM,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAA;YAC3B,CAAC;QACF,CAAC;QAED,OAAO,IAAI,CAAA;IACZ,CAAC;CACD,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, { ClientSession } from 'mongoose'\n\n/** Arguments accepted by the `updatePassword` mutation. Exported so a consumer re-exporting the bound mutation can name its type. */\nexport interface IUpdatePasswordArgs {\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/** Normalised inputs the transaction body works on, bundled to keep it within the max-params budget. */\ninterface IUpdatePasswordInput {\n\tuEmail: string\n\thash: string\n\tpassword: string\n}\n\n/**\n * The transactional core: validate the reset hash, apply the new password and clear the request.\n * Extracted from resolve() only to keep it inside the max-lines-per-function budget — behaviour\n * unchanged. Returns the account holder's name so the caller can mail the post-commit confirmation.\n */\nasync function applyPasswordReset(\n\tdeps: IUpdatePasswordDeps,\n\tsession: ClientSession,\n\tinput: IUpdatePasswordInput\n): Promise<string> {\n\tconst { uEmail, hash, password } = input\n\tconst resetPwd = await deps.getResetPwd(session, uEmail)\n\n\t// check if email is present in db\n\tif (resetPwd === null) {\n\t\tthrow throwForbiddenError() // don't reveal whether the email is present, for privacy\n\t}\n\t// console.debug('--email present')\n\n\t// No usable reset state. This is NOT an internal error as far as the caller is concerned:\n\t// answering 500 here while an unknown address answers 403 turns this mutation into an\n\t// account-enumeration oracle, because every registered account that has never requested a\n\t// reset lands on this branch (getResetPwd yields resetHash === null whenever\n\t// account.resetDateReq is undefined). Same 403 as the unknown-address path; the orphan\n\t// state is reported to Sentry instead of to the caller.\n\tif (resetPwd.resetHash === null) {\n\t\tSentry.captureMessage(`[updatePassword] no usable resetHash for ${uEmail}`)\n\t\tthrow throwForbiddenError()\n\t}\n\t/* c8 ignore next 4 -- defensive guard, resetDateReq cannot be null when resetHash is set */\n\tif (resetPwd.resetDateReq === null) {\n\t\tSentry.captureMessage(`[updatePassword] resetHash set but resetDateReq missing for ${uEmail}`)\n\t\tthrow throwForbiddenError()\n\t}\n\n\t// check if hash is missing or invalid\n\tif (resetPwd.resetHash !== hash) {\n\t\tthrow throwForbiddenError() // don't reveal whether the email is present, for privacy\n\t} // else console.debug('--hash valid')\n\n\t// check if the request was made within 1 hour\n\tconst dt1 = new Date('' + resetPwd.resetDateReq)\n\tif (DateLib.minElapsed(dt1) > 60) {\n\t\tthrow throwForbiddenError() // The link is no longer valid\n\t} // else console.debug('--link valid')\n\n\tconst update = await deps.updatePasswordDb(session, resetPwd._id, password)\n\tif (!update) {\n\t\tthrow throwInternalError() // \"System error while updating the password.\"\n\t} // else console.debug('--pwd updated')\n\n\t// delete password reset request data from db\n\tawait deps.removeResetReq(session, uEmail)\n\n\t// the confirmation email is sent after the commit, not here\n\treturn resetPwd.name\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: IUpdatePasswordArgs) {\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\tconfirmTo = await applyPasswordReset(deps, session, { uEmail, hash, password })\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"]}
|