@axiumine/koa-utils 7.1.0 → 7.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.
Files changed (87) hide show
  1. package/LICENSE +0 -5
  2. package/README.md +55 -3
  3. package/dist/dataSources/MariaDB.mjs +8 -6
  4. package/dist/dataSources/MongoDB.mjs +1 -1
  5. package/dist/dataSources/PostgreSQL.mjs +12 -12
  6. package/dist/dataSources/Redis.mjs +8 -7
  7. package/dist/email/SocketLabsLib.d.mts +6 -15
  8. package/dist/email/SocketLabsLib.mjs +54 -210
  9. package/dist/files/moveFileStaticDomain.mjs +1 -1
  10. package/dist/files/storeUploadAsTemp.mjs +5 -1
  11. package/dist/files/uploadTempImage.mjs +2 -1
  12. package/dist/files/uploadTempPdf.mjs +2 -1
  13. package/dist/graphQL/models/MongoDB/UserBase.d.mts +3 -1
  14. package/dist/graphQL/models/MongoDB/log/DevStatsGraphQLCalls.d.mts +3 -1
  15. package/dist/graphQL/models/MongoDB/log/LogGlobalError.d.mts +3 -1
  16. package/dist/graphQL/models/MongoDB/log/LogStatsGraphql.d.mts +3 -1
  17. package/dist/graphQL/models/MongoDB/log/LogThrow.d.mts +3 -1
  18. package/dist/graphQL/schema/mutations/emailChangeHashVerify.mjs +8 -76
  19. package/dist/graphQL/schema/mutations/login4Ever.mjs +1 -0
  20. package/dist/graphQL/schema/mutations/loginAdmin.mjs +1 -0
  21. package/dist/graphQL/schema/mutations/loginRememberme.mjs +1 -0
  22. package/dist/graphQL/schema/mutations/logout.mjs +2 -2
  23. package/dist/graphQL/schema/mutations/refresh.mjs +7 -5
  24. package/dist/graphQL/schema/mutations/resetPwd.d.mts +1 -1
  25. package/dist/graphQL/schema/mutations/signUp.mjs +1 -0
  26. package/dist/graphQL/schema/mutations/updatePassword.mjs +1 -48
  27. package/dist/koa/middleware/authenticatedAuthorizationHandler/index.mjs +2 -2
  28. package/dist/koa/middleware/authenticatedAuthorizationHandler/verifySignedRefreshToken.mjs +2 -0
  29. package/dist/koa/middleware/authenticatedLogoutHandler/index.mjs +2 -2
  30. package/dist/koa/middleware/authenticatedResourceHandler/index.mjs +2 -2
  31. package/dist/koa/tdwKoaErrorHandler.mjs +1 -1
  32. package/dist/lib/ArrayLib.mjs +4 -3
  33. package/dist/lib/DateLib.mjs +1 -0
  34. package/dist/lib/StringLib.mjs +56 -4
  35. package/dist/lib/access/resetPwdMailer.d.mts +3 -0
  36. package/dist/lib/access/resetPwdMailer.mjs +3 -0
  37. package/dist/lib/db/log/hitStat.mjs +1 -0
  38. package/dist/lib/isIntrospectionBypassAllowed.mjs +1 -1
  39. package/dist/lib/isSessionBlocked.mjs +1 -1
  40. package/dist/lib/tokens.mjs +2 -1
  41. package/dist/lib/tryCatchRethrow.mjs +1 -1
  42. package/dist/private/dataSources/isRedisTlsRequired.mjs +1 -1
  43. package/dist/private/email/IEmailContent.d.mts +9 -0
  44. package/dist/private/email/IEmailContent.mjs +2 -0
  45. package/dist/private/email/accountMessages.d.mts +11 -0
  46. package/dist/private/email/accountMessages.mjs +57 -0
  47. package/dist/private/email/escapeHtml.d.mts +9 -0
  48. package/dist/private/email/escapeHtml.mjs +17 -0
  49. package/dist/private/email/htmlFrame.d.mts +10 -0
  50. package/dist/private/email/htmlFrame.mjs +25 -0
  51. package/dist/private/email/messageParts.d.mts +21 -0
  52. package/dist/private/email/messageParts.mjs +65 -0
  53. package/dist/private/email/noticeMessages.d.mts +14 -0
  54. package/dist/private/email/noticeMessages.mjs +51 -0
  55. package/dist/private/email/orFalse.d.mts +2 -0
  56. package/dist/private/email/orFalse.mjs +12 -0
  57. package/dist/private/email/resetMessages.d.mts +17 -0
  58. package/dist/private/email/resetMessages.mjs +46 -0
  59. package/dist/private/graphQL/models/MongoDB/private/UserAdminKoaUtils.d.mts +4 -2
  60. package/dist/private/graphQL/schema/mutations/_buildLoginStatsUpdate.mjs +4 -4
  61. package/dist/private/graphQL/schema/mutations/infoUserForLoginSQL.mjs +5 -4
  62. package/dist/private/graphQL/schema/mutations/setRedisLoginSession.mjs +2 -2
  63. package/dist/private/graphQL/schema/mutations/updateLoginStats4ever.mjs +2 -2
  64. package/dist/private/lib/access/applyPasswordReset.d.mts +22 -0
  65. package/dist/private/lib/access/applyPasswordReset.mjs +22 -0
  66. package/dist/private/lib/access/assertResetAllowed.d.mts +14 -0
  67. package/dist/private/lib/access/assertResetAllowed.mjs +51 -0
  68. package/dist/private/lib/access/assertVerifyEmailAllowed.d.mts +6 -1
  69. package/dist/private/lib/access/db/abandonUser.mjs +3 -0
  70. package/dist/private/lib/access/db/confirmNewEmail.mjs +2 -0
  71. package/dist/private/lib/access/db/deleteUserByEmail.mjs +2 -0
  72. package/dist/private/lib/access/db/enableEmailAccess.mjs +9 -1
  73. package/dist/private/lib/access/db/getResetPwd.mjs +2 -0
  74. package/dist/private/lib/access/db/removeResetReq.mjs +2 -0
  75. package/dist/private/lib/access/db/saveResetReq.mjs +2 -0
  76. package/dist/private/lib/access/db/setEmailHash.mjs +2 -0
  77. package/dist/private/lib/access/db/updatePasswordDb.mjs +2 -0
  78. package/dist/private/lib/access/db/userData4VerifyEmail.mjs +2 -0
  79. package/dist/private/lib/access/emailChangeHandlers.d.mts +35 -0
  80. package/dist/private/lib/access/emailChangeHandlers.mjs +87 -0
  81. package/dist/private/lib/access/handleIfHashBad.d.mts +4 -2
  82. package/dist/private/lib/access/handleIfHashBad.mjs +4 -1
  83. package/dist/private/lib/access/safeEqualSecret.d.mts +13 -0
  84. package/dist/private/lib/access/safeEqualSecret.mjs +26 -0
  85. package/dist/private/lib/verifyIntrospectionCode.d.mts +4 -0
  86. package/dist/private/lib/verifyIntrospectionCode.mjs +8 -14
  87. package/package.json +62 -25
@@ -0,0 +1,65 @@
1
+ import { StringLib } from "../../lib/StringLib.mjs";
2
+ import { throwInternalError } from "../../graphQL/throw/throwInternalError.mjs";
3
+ import { escapeHtml } from './escapeHtml.mjs';
4
+ const strings = new StringLib();
5
+ /** Greeting suffix: a leading space plus the name, or nothing when there is no name. */
6
+ export function fixName(name) {
7
+ return name !== '' ? ` ${name}` : '';
8
+ }
9
+ /**
10
+ * Anchor for the HTML part. The URL goes into a single-quoted `href` and the text into element content, so both
11
+ * pass through {@link escapeHtml}; the plain-text part keeps the unescaped URL.
12
+ */
13
+ export function htmlLink(link, linkText = '') {
14
+ return strings.makeLink(escapeHtml(link), escapeHtml(linkText));
15
+ }
16
+ /** Drop every trailing `/`. A loop on `endsWith` instead of `/\/+$/`, which backtracks quadratically on long runs. */
17
+ function stripTrailingSlashes(value) {
18
+ let end = value.length;
19
+ while (value.endsWith('/', end))
20
+ end -= 1;
21
+ return value.slice(0, end);
22
+ }
23
+ /**
24
+ * Control characters, whitespace and backslash. The URL parser drops or rewrites them (it strips leading and
25
+ * trailing control characters and spaces, removes tab and newline anywhere, turns `\` into `/`), so a string
26
+ * that holds one parses as something other than what is written. The base is emitted as written, so it must be
27
+ * a string the parser reads as it stands.
28
+ */
29
+ const NOT_PARSED_AS_WRITTEN = /[\p{Cc}\s\\]/u;
30
+ /**
31
+ * Judge a link base on the parsed URL, never on its prefix: `JaVaScRiPt:`, ` javascript:` and `java\tscript:`
32
+ * all parse to the `javascript:` scheme, `//evil.example` has no scheme and does not parse at all, and
33
+ * `https://good@evil` is an `https:` URL whose host is `evil`. Only an absolute `http:` or `https:` URL passes,
34
+ * and one with no user name and no password, since a base never needs them and `user@host` is how a link is
35
+ * made to read as a host it does not go to.
36
+ */
37
+ function isHttpLinkBase(value) {
38
+ if (NOT_PARSED_AS_WRITTEN.test(value))
39
+ return false;
40
+ const url = URL.parse(value);
41
+ return url !== null && (url.protocol === 'http:' || url.protocol === 'https:') && url.username === '' && url.password === '';
42
+ }
43
+ /**
44
+ * The scheme + host every link in a mail is built on, checked before it is placed in a link or an `href`.
45
+ * Returns `linkBase` exactly as given when it is an absolute `http:` / `https:` URL; otherwise throws
46
+ * `throwInternalError()` (500 `Internal Server Error`, `Error reported to Dev Team.`), as `wrongHashMessage`
47
+ * does: a base that is not one is a configuration or caller mistake, never something the recipient can fix,
48
+ * and the mail is not sent. Escaping alone does not cover this: a `javascript:` base survives `escapeHtml`
49
+ * and becomes a link target.
50
+ */
51
+ export function httpLinkBase(linkBase) {
52
+ if (!isHttpLinkBase(linkBase))
53
+ throwInternalError();
54
+ return linkBase;
55
+ }
56
+ /**
57
+ * Confirmation or reset link: `<base><path>/<encodeURI(email)>/<hash>`. A trailing slash on `linkBase` and a
58
+ * missing leading slash on `linkPath` are normalised away. `linkBase` goes through {@link httpLinkBase} first.
59
+ */
60
+ export function confirmationLink(linkBase, linkPath, emailTo, hash) {
61
+ const base = stripTrailingSlashes(httpLinkBase(linkBase));
62
+ const path = `/${linkPath.replace(/^\/+/, '')}`;
63
+ return `${base}${path}/${encodeURI(emailTo)}/${hash}`;
64
+ }
65
+ //# sourceMappingURL=messageParts.mjs.map
@@ -0,0 +1,14 @@
1
+ import type { IEmailContent } from './IEmailContent.mjs';
2
+ export declare const ACCOUNT_DISABLED: IEmailContent;
3
+ export declare const ACCOUNT_BANNED: IEmailContent;
4
+ export declare const EMAIL_ALREADY_VALID: IEmailContent;
5
+ /** Activation link expired. */
6
+ export declare const HASH_REQ_TOO_OLD: IEmailContent;
7
+ /** Too many verification attempts. The HTML part words the limit differently from the text part. */
8
+ export declare const TOO_MUCH_VERIFY_REQUESTS: IEmailContent;
9
+ /** Wrong activation link. Past 5 attempts it throws instead; `times` is a number, so the remaining count needs no escaping. */
10
+ export declare function wrongHashMessage(times: number): IEmailContent;
11
+ /** Dev-team alert. `err` goes into the HTML part escaped and into the text part as is. */
12
+ export declare function alertDevMessage(platformName: string, err: string): IEmailContent;
13
+ /** Report notice for the dev team. Name, surname and id come from user data, so the HTML part escapes them. */
14
+ export declare function postReportedMessage(idPost: number | string, name: string, surname: string, userId: string): IEmailContent;
@@ -0,0 +1,51 @@
1
+ import { throwInternalError } from "../../graphQL/throw/throwInternalError.mjs";
2
+ import { escapeHtml } from './escapeHtml.mjs';
3
+ import { FALLBACK_FOOTER, standaloneHeader } from './htmlFrame.mjs';
4
+ function paragraph(subject, text) {
5
+ return { subject, textBody: text, htmlBody: `<p>${text}</p>` };
6
+ }
7
+ export const ACCOUNT_DISABLED = paragraph('Your account has been disabled', 'Hi, we are sorry but your account has been disabled. Contact us for more information.');
8
+ export const ACCOUNT_BANNED = paragraph('Your account has been banned', 'Hi, we are sorry but your account has been banned. Contact us for more information.');
9
+ export const EMAIL_ALREADY_VALID = paragraph('Account already valid', 'Hi, your account is already valid, you can log in.');
10
+ /** Activation link expired. */
11
+ export const HASH_REQ_TOO_OLD = paragraph('Activation link expired', 'Hi, the activation link you are trying to use is older than 3 days and has expired. You need to repeat the registration request.');
12
+ /** Too many verification attempts. The HTML part words the limit differently from the text part. */
13
+ export const TOO_MUCH_VERIFY_REQUESTS = {
14
+ subject: 'Too many attempts to verify your email',
15
+ textBody: 'Hi, you have made more than 5 attempts to verify your email. You need to repeat the registration request.',
16
+ htmlBody: '<p>Hi, you have made 5 or more attempts to verify your email. You need to repeat the registration request.</p>'
17
+ };
18
+ /** Wrong activation link. Past 5 attempts it throws instead; `times` is a number, so the remaining count needs no escaping. */
19
+ export function wrongHashMessage(times) {
20
+ if (times > 5)
21
+ throwInternalError();
22
+ return paragraph('Wrong activation link', `Hi, you or someone else is trying to verify your email with a wrong link. You have ${5 - times} attempts remaining.`);
23
+ }
24
+ /** Dev-team alert. `err` goes into the HTML part escaped and into the text part as is. */
25
+ export function alertDevMessage(platformName, err) {
26
+ return {
27
+ subject: `${platformName} error 500`,
28
+ textBody: 'error 500 ' + err,
29
+ htmlBody: '<p>error 500 <br><br>' + escapeHtml(err) + '</p>'
30
+ };
31
+ }
32
+ /** Report notice for the dev team. Name, surname and id come from user data, so the HTML part escapes them. */
33
+ export function postReportedMessage(idPost, name, surname, userId) {
34
+ const subject = 'Post ' + idPost + ' reported';
35
+ return {
36
+ subject,
37
+ textBody: 'Hi, post ' + idPost + ' has been reported by ' + name + ' ' + surname + ' (id: ' + userId + ').',
38
+ htmlBody: standaloneHeader(subject) +
39
+ 'Hi, post ' +
40
+ escapeHtml(idPost) +
41
+ ' has been reported by ' +
42
+ escapeHtml(name) +
43
+ ' ' +
44
+ escapeHtml(surname) +
45
+ ' (id: ' +
46
+ escapeHtml(userId) +
47
+ ').' +
48
+ FALLBACK_FOOTER
49
+ };
50
+ }
51
+ //# sourceMappingURL=noticeMessages.mjs.map
@@ -0,0 +1,2 @@
1
+ /** Run a send; a rejection or a throw becomes a Sentry report and `false`, so the caller never sees it. */
2
+ export declare function orFalse(send: () => Promise<boolean>): Promise<boolean>;
@@ -0,0 +1,12 @@
1
+ import * as Sentry from '@sentry/node';
2
+ /** Run a send; a rejection or a throw becomes a Sentry report and `false`, so the caller never sees it. */
3
+ export async function orFalse(send) {
4
+ try {
5
+ return await send();
6
+ }
7
+ catch (e) {
8
+ Sentry.captureException(e);
9
+ return false;
10
+ }
11
+ }
12
+ //# sourceMappingURL=orFalse.mjs.map
@@ -0,0 +1,17 @@
1
+ import type { IEmailContent } from './IEmailContent.mjs';
2
+ /** Password-reset request. `link` is the finished reset URL. */
3
+ export declare function resetMessage(platformName: string, link: string, name: string): IEmailContent;
4
+ /** Confirmation that the new password is set, linking to the platform home. */
5
+ export declare function resetConfirmationMessage(platformName: string, linkBase: string, name: string): IEmailContent;
6
+ /** Recipient of the legacy confirmation mail: the address, the greeting name and the reset hash. */
7
+ interface ILegacyRecipient {
8
+ email: string;
9
+ name: string;
10
+ hash: string;
11
+ }
12
+ /**
13
+ * Legacy confirmation mail whose HTML part is a full standalone document. The reset URL carries the hash and
14
+ * the `encodeURI`d address in its query string; it only appears in the HTML part, so it is escaped there.
15
+ */
16
+ export declare function resetConfirmationHashMessage(platformName: string, linkBase: string, to: ILegacyRecipient): IEmailContent;
17
+ export {};
@@ -0,0 +1,46 @@
1
+ import { escapeHtml } from './escapeHtml.mjs';
2
+ import { FALLBACK_FOOTER, standaloneHeader } from './htmlFrame.mjs';
3
+ import { fixName, htmlLink, httpLinkBase } from './messageParts.mjs';
4
+ /** Password-reset request. `link` is the finished reset URL. */
5
+ export function resetMessage(platformName, link, name) {
6
+ const nameFixed = fixName(name);
7
+ return {
8
+ subject: `Password reset for ${platformName}`,
9
+ textBody: `Hi${nameFixed}, you or someone else has requested a password reset. You can change your login password
10
+ by copying this link ${link} into your browser. The Team.`,
11
+ htmlBody: `Hi${escapeHtml(nameFixed)},<br>you or someone else has requested a password reset.<br><br>
12
+ You can change your password by clicking the link:<br>${htmlLink(link)}
13
+ <br><br>The Team.`
14
+ };
15
+ }
16
+ /** Confirmation that the new password is set, linking to the platform home. */
17
+ export function resetConfirmationMessage(platformName, linkBase, name) {
18
+ const base = httpLinkBase(linkBase);
19
+ const nameFixed = fixName(name);
20
+ return {
21
+ subject: `Password reset for ${platformName}`,
22
+ textBody: `Hi${nameFixed}, you have confirmed your new password. You can now log in at: ${base}. The Team.`,
23
+ htmlBody: `Hi${escapeHtml(nameFixed)},<br>you have confirmed your new password.<br><br>You can now log in at:<br>${htmlLink(base, platformName)}<br><br>The Team.`
24
+ };
25
+ }
26
+ /**
27
+ * Legacy confirmation mail whose HTML part is a full standalone document. The reset URL carries the hash and
28
+ * the `encodeURI`d address in its query string; it only appears in the HTML part, so it is escaped there.
29
+ */
30
+ export function resetConfirmationHashMessage(platformName, linkBase, to) {
31
+ const base = httpLinkBase(linkBase);
32
+ const subject = `Password change confirmation for ${platformName}`;
33
+ const linkReset = base + '/index.php?q=reset&hash=' + to.hash + '&email=' + encodeURI(to.email);
34
+ return {
35
+ subject,
36
+ textBody: 'Hi ' + to.name + ', you have confirmed your new password. You can now log in at: ' + base + ' . ',
37
+ htmlBody: standaloneHeader(subject) +
38
+ 'Hi ' +
39
+ escapeHtml(to.name) +
40
+ ',<br>you have confirmed your new password.<br><br>You can now log in at:<br> ' +
41
+ htmlLink(linkReset) +
42
+ '<br><br>The Team' +
43
+ FALLBACK_FOOTER
44
+ };
45
+ }
46
+ //# sourceMappingURL=resetMessages.mjs.map
@@ -14,7 +14,7 @@ export interface IInfoUserAdminForLogin {
14
14
  deleted?: boolean;
15
15
  };
16
16
  }
17
- export interface IUserAdminKoaUtilsSchema {
17
+ interface IUserAdminKoaUtilsSchema {
18
18
  _id: Types.ObjectId;
19
19
  login: {
20
20
  _id?: boolean;
@@ -54,5 +54,7 @@ declare const _default: import("mongoose").Model<IUserAdminKoaUtilsSchema, {}, {
54
54
  __v: number;
55
55
  } & {
56
56
  id: string;
57
- }, any, IUserAdminKoaUtilsSchema>;
57
+ }, any, IUserAdminKoaUtilsSchema & Required<{
58
+ _id: Types.ObjectId;
59
+ }>>;
58
60
  export default _default;
@@ -3,22 +3,22 @@ export function _buildLoginStatsUpdate(lastLogin, rememberMe) {
3
3
  // update last login
4
4
  const dbSet = {};
5
5
  const dbUnset = {};
6
- // @ts-expect-error avoid any
6
+ // @ts-expect-error avoid any: dynamic dotted Mongo path key
7
7
  dbSet['login.lastLogin'] = now;
8
8
  // set firstLogin if this is the first login.
9
9
  if (lastLogin === null) {
10
- // @ts-expect-error avoid any
10
+ // @ts-expect-error avoid any: dynamic dotted Mongo path key
11
11
  dbSet['login.firstLogin'] = now;
12
12
  }
13
13
  else {
14
14
  // not the first login
15
15
  }
16
16
  if (rememberMe) {
17
- // @ts-expect-error avoid any
17
+ // @ts-expect-error avoid any: dynamic dotted Mongo path key
18
18
  dbSet['account.rememberMe'] = true;
19
19
  }
20
20
  else {
21
- // @ts-expect-error avoid any
21
+ // @ts-expect-error avoid any: dynamic dotted Mongo path key
22
22
  dbUnset['account.rememberMe'] = 1;
23
23
  }
24
24
  return { dbSet, dbUnset };
@@ -3,14 +3,15 @@ import { throwErrorWrongUserInput } from "../../../../graphQL/throw/throwErrorWr
3
3
  import { QueryTypes } from 'sequelize';
4
4
  export async function infoUserForLoginSQL(email) {
5
5
  const sql = 'SELECT id, password, valid, deleted, disabled FROM user WHERE email=:email';
6
- let ret = (await sequelize.query(sql, {
6
+ const ret = await sequelize.query(sql, {
7
7
  type: QueryTypes.SELECT,
8
8
  replacements: {
9
9
  email: email
10
10
  }
11
- }));
12
- if (ret.length === 0)
11
+ });
12
+ const [first] = ret;
13
+ if (first === undefined)
13
14
  throw throwErrorWrongUserInput('User does not exist');
14
- return ret[0];
15
+ return first;
15
16
  }
16
17
  //# sourceMappingURL=infoUserForLoginSQL.mjs.map
@@ -7,8 +7,8 @@ dotenv.config();
7
7
  export async function setRedisLoginSession(id, accessToken, accTokenExp, refreshToken) {
8
8
  const keyDataAccess = { id: id.toString() };
9
9
  const keyDataRefresh = { ...keyDataAccess, access: accessToken };
10
- const keyAccess = `${process.env.REDIS_KEY}access:${accessToken}`;
11
- const keyRefresh = `${process.env.REDIS_KEY}refresh:${refreshToken}`;
10
+ const keyAccess = `${process.env['REDIS_KEY']}access:${accessToken}`;
11
+ const keyRefresh = `${process.env['REDIS_KEY']}refresh:${refreshToken}`;
12
12
  try {
13
13
  // Store session in Redis
14
14
  await Promise.all([
@@ -3,11 +3,11 @@ export async function updateLoginStats4ever(id, lastLogin, session) {
3
3
  const now = new Date();
4
4
  // update last login
5
5
  const dbSet = {};
6
- // @ts-expect-error avoid any
6
+ // @ts-expect-error avoid any: dynamic dotted Mongo path key
7
7
  dbSet['login.lastLogin'] = now;
8
8
  // set firstLogin if this is the first login.
9
9
  if (lastLogin === null) {
10
- // @ts-expect-error avoid any
10
+ // @ts-expect-error avoid any: dynamic dotted Mongo path key
11
11
  dbSet['login.firstLogin'] = now;
12
12
  }
13
13
  else {
@@ -0,0 +1,22 @@
1
+ import type { TGetResetPwd } from "./db/getResetPwd.mjs";
2
+ import type { TRemoveResetReq } from "./db/removeResetReq.mjs";
3
+ import type { TUpdatePasswordDb } from "./db/updatePasswordDb.mjs";
4
+ import type { ClientSession } from 'mongoose';
5
+ /** The reader and writers the reset transaction needs, all bound to the same model and paths by the caller. */
6
+ export interface IApplyPasswordResetDeps {
7
+ getResetPwd: TGetResetPwd;
8
+ updatePasswordDb: TUpdatePasswordDb;
9
+ removeResetReq: TRemoveResetReq;
10
+ }
11
+ /** Normalised inputs the transaction body works on, bundled to keep it within the max-params budget. */
12
+ export interface IApplyPasswordResetInput {
13
+ uEmail: string;
14
+ hash: string;
15
+ password: string;
16
+ }
17
+ /**
18
+ * The transactional core of `updatePassword`: validate the reset hash, apply the new password and clear the
19
+ * request. Extracted from the resolver only to keep it inside its complexity budget — behaviour unchanged.
20
+ * Returns the account holder's name so the caller can mail the post-commit confirmation.
21
+ */
22
+ export declare function applyPasswordReset(deps: IApplyPasswordResetDeps, session: ClientSession, input: IApplyPasswordResetInput): Promise<string>;
@@ -0,0 +1,22 @@
1
+ import { throwInternalError } from "../../../graphQL/throw/throwInternalError.mjs";
2
+ import { assertResetAllowed } from './assertResetAllowed.mjs';
3
+ /**
4
+ * The transactional core of `updatePassword`: validate the reset hash, apply the new password and clear the
5
+ * request. Extracted from the resolver only to keep it inside its complexity budget — behaviour unchanged.
6
+ * Returns the account holder's name so the caller can mail the post-commit confirmation.
7
+ */
8
+ export async function applyPasswordReset(deps, session, input) {
9
+ const { uEmail, hash, password } = input;
10
+ const resetPwd = await deps.getResetPwd(session, uEmail);
11
+ assertResetAllowed(resetPwd, uEmail, hash);
12
+ // typed unknown on purpose: the writer is injected, and a falsy result (not a thrown error) has always meant failure
13
+ const update = await deps.updatePasswordDb(session, resetPwd._id, password);
14
+ if (!update) {
15
+ throw throwInternalError(); // "System error while updating the password."
16
+ }
17
+ // delete password reset request data from db
18
+ await deps.removeResetReq(session, uEmail);
19
+ // the confirmation email is sent after the commit, not here
20
+ return resetPwd.name;
21
+ }
22
+ //# sourceMappingURL=applyPasswordReset.mjs.map
@@ -0,0 +1,14 @@
1
+ import type { IResetPwdRecord } from "./db/getResetPwd.mjs";
2
+ /**
3
+ * Decide whether a password reset may proceed for the record `getResetPwd` returned.
4
+ *
5
+ * Every rejection throws the same `throwForbiddenError()` (403), so a caller cannot tell an unknown
6
+ * address, an account with no reset pending, a wrong hash and an expired link apart. The hash is compared
7
+ * in constant time through `safeEqualSecret`. Extracted from `updatePassword` with the order of the checks
8
+ * unchanged, only to keep that resolver inside its complexity budget.
9
+ *
10
+ * @param resetPwd - the stored reset state, or `null` when no account matches the address
11
+ * @param uEmail - the normalised address, used only in the Sentry reports
12
+ * @param hash - the reset hash the caller sent
13
+ */
14
+ export declare function assertResetAllowed(resetPwd: IResetPwdRecord | null, uEmail: string, hash: string): asserts resetPwd is IResetPwdRecord;
@@ -0,0 +1,51 @@
1
+ import { DateLib } from "../../../lib/DateLib.mjs";
2
+ import * as Sentry from '@sentry/node';
3
+ import { throwForbiddenError } from "../../../graphQL/throw/throwForbiddenError.mjs";
4
+ import { safeEqualSecret } from './safeEqualSecret.mjs';
5
+ /** Minutes a reset link stays valid after the request was made. */
6
+ const RESET_LINK_LIFETIME_MIN = 60;
7
+ /**
8
+ * Decide whether a password reset may proceed for the record `getResetPwd` returned.
9
+ *
10
+ * Every rejection throws the same `throwForbiddenError()` (403), so a caller cannot tell an unknown
11
+ * address, an account with no reset pending, a wrong hash and an expired link apart. The hash is compared
12
+ * in constant time through `safeEqualSecret`. Extracted from `updatePassword` with the order of the checks
13
+ * unchanged, only to keep that resolver inside its complexity budget.
14
+ *
15
+ * @param resetPwd - the stored reset state, or `null` when no account matches the address
16
+ * @param uEmail - the normalised address, used only in the Sentry reports
17
+ * @param hash - the reset hash the caller sent
18
+ */
19
+ export function assertResetAllowed(resetPwd, uEmail, hash) {
20
+ // check if email is present in db
21
+ if (resetPwd === null) {
22
+ throw throwForbiddenError(); // don't reveal whether the email is present, for privacy
23
+ }
24
+ // No usable reset state. This is NOT an internal error as far as the caller is concerned:
25
+ // answering 500 here while an unknown address answers 403 turns this mutation into an
26
+ // account-enumeration oracle, because every registered account that has never requested a
27
+ // reset lands on this branch (getResetPwd yields resetHash === null whenever
28
+ // account.resetDateReq is undefined). Same 403 as the unknown-address path; the orphan
29
+ // state is reported to Sentry instead of to the caller.
30
+ if (resetPwd.resetHash === null) {
31
+ Sentry.captureMessage(`[updatePassword] no usable resetHash for ${uEmail}`);
32
+ throw throwForbiddenError();
33
+ }
34
+ // A stored `null` date is not typed as possible, but a lean read returns exactly that for an explicit
35
+ // null in the document, so the guard is reachable. Read as unknown to keep the check honest.
36
+ const resetDateReq = resetPwd.resetDateReq;
37
+ if (resetDateReq === null) {
38
+ Sentry.captureMessage(`[updatePassword] resetHash set but resetDateReq missing for ${uEmail}`);
39
+ throw throwForbiddenError();
40
+ }
41
+ // check if hash is missing or invalid
42
+ if (!safeEqualSecret(resetPwd.resetHash, hash)) {
43
+ throw throwForbiddenError(); // don't reveal whether the email is present, for privacy
44
+ }
45
+ // check if the request was made within 1 hour
46
+ const dt1 = new Date(String(resetPwd.resetDateReq));
47
+ if (DateLib.minElapsed(dt1) > RESET_LINK_LIFETIME_MIN) {
48
+ throw throwForbiddenError(); // The link is no longer valid
49
+ }
50
+ }
51
+ //# sourceMappingURL=assertResetAllowed.mjs.map
@@ -6,7 +6,12 @@ import { THandleIfEmailAlreadyValid } from './handleIfEmailAlreadyValid.mjs';
6
6
  import { THandleIfHashBad } from './handleIfHashBad.mjs';
7
7
  import { THandleIfMoreThan3DaysPassed } from './handleIfMoreThan3DaysPassed.mjs';
8
8
  import { THandleIfTooMuchRequestsTimes } from './handleIfTooMuchRequestsTimes.mjs';
9
- /** The projection userData4VerifyEmail selects under the default paths, as the guard chain needs it. */
9
+ /**
10
+ * The projection userData4VerifyEmail selects under the default paths, as the guard chain needs it.
11
+ *
12
+ * @public Documentation of a shape, referenced by nothing (the chain takes `unknown`). The tag keeps Knip from
13
+ * reporting it as an unused export; removing it would also lower the strict type-coverage ratchet.
14
+ */
10
15
  export interface IVerifyEmailUser {
11
16
  _id: Types.ObjectId;
12
17
  account: {
@@ -8,6 +8,7 @@ import { createDeleteUserByEmail } from './deleteUserByEmail.mjs';
8
8
  */
9
9
  export const createAbandonUser = ({ model, paths, mode, deletedValue = true }) => {
10
10
  if (mode === 'keep') {
11
+ // Stryker disable next-line BlockStatement: the body is only `return undefined`, and an empty async function body also resolves undefined.
11
12
  return async function keepUser() {
12
13
  // Nothing to do: the caller disposes of abandoned registrations themselves.
13
14
  return undefined;
@@ -18,6 +19,8 @@ export const createAbandonUser = ({ model, paths, mode, deletedValue = true }) =
18
19
  const value = typeof deletedValue === 'function' ? deletedValue() : deletedValue;
19
20
  // Only the tombstone is written. The verification fields are left as they are — the flag is what
20
21
  // every guard reads, and unsetting members of a strict subdocument is what `verifyClear` exists for.
22
+ // Field names come from the `paths` map fixed when the flow is built, never from request data; only the values do.
23
+ // nosemgrep: koa-utils.nosql-injection.dynamic-filter-key, koa-utils.nosql-injection.mass-assignment-update-doc
21
24
  await model.updateOne({ [paths.email]: email }, { $set: { [paths.deleted]: value } }, { runValidators: true });
22
25
  };
23
26
  }
@@ -2,6 +2,8 @@ import { DEFAULT_VERIFY_EMAIL_PATHS } from "../../../../lib/access/accessPaths.m
2
2
  import { UserBase } from "../../../../graphQL/models/MongoDB/UserBase.mjs";
3
3
  import { buildUnset } from "../pathTools.mjs";
4
4
  export const createConfirmNewEmail = (model, paths) => async function confirmNewEmail(_id, email) {
5
+ // Field names come from the `paths` map fixed when the flow is built, never from request data; only the values do.
6
+ // nosemgrep: koa-utils.nosql-injection.mass-assignment-update-doc
5
7
  return await model
6
8
  .updateOne({ _id }, {
7
9
  $set: { [paths.email]: email },
@@ -9,6 +9,8 @@ import * as Sentry from '@sentry/node';
9
9
  * See `TOnAbandon`.
10
10
  */
11
11
  export const createDeleteUserByEmail = (model, paths) => async function deleteUserByEmail(email) {
12
+ // Field name comes from the factory `paths` argument the consuming developer supplies at startup, never from request data.
13
+ // nosemgrep: koa-utils.nosql-injection.dynamic-filter-key
12
14
  const ret = await model.deleteOne({ [paths.email]: email });
13
15
  if (ret.deletedCount === 0) {
14
16
  // The caller read this account moments ago and its guards decided the registration was abandoned, so
@@ -2,6 +2,7 @@ import { DEFAULT_VERIFY_EMAIL_PATHS } from "../../../../lib/access/accessPaths.m
2
2
  import { defaultVerifyEmailMailer } from "../../../../lib/access/verifyEmailMailer.mjs";
3
3
  import { UserBase } from "../../../../graphQL/models/MongoDB/UserBase.mjs";
4
4
  import { buildUnset } from "../pathTools.mjs";
5
+ import * as Sentry from '@sentry/node';
5
6
  /**
6
7
  * Mark the address verified, clear the pending-verification fields, welcome the user.
7
8
  *
@@ -10,13 +11,20 @@ import { buildUnset } from "../pathTools.mjs";
10
11
  * a valid hash. See `throttleMailer`.
11
12
  */
12
13
  export const createEnableEmailAccess = (model, paths, mailer) => async function enableEmailAccess(_id, email) {
14
+ // Field names come from the `paths` map fixed when the flow is built, never from request data; only the values do.
15
+ // nosemgrep: koa-utils.nosql-injection.mass-assignment-update-doc
13
16
  await model.updateOne({ _id }, {
14
17
  $set: { [paths.valid]: true },
15
18
  $unset: buildUnset(paths.verifyClear)
16
19
  }, {
17
20
  runValidators: true
18
21
  });
19
- await mailer.sendWelcome(email);
22
+ try {
23
+ await mailer.sendWelcome(email);
24
+ }
25
+ catch (e) {
26
+ Sentry.captureException(e);
27
+ }
20
28
  };
21
29
  /** `UserBase`-bound default — the behaviour every existing consumer already imports. */
22
30
  export const enableEmailAccess = createEnableEmailAccess(UserBase, DEFAULT_VERIFY_EMAIL_PATHS, defaultVerifyEmailMailer);
@@ -3,6 +3,8 @@ import { UserBase } from "../../../../graphQL/models/MongoDB/UserBase.mjs";
3
3
  import { buildProjection, readPath } from "../pathTools.mjs";
4
4
  export const createGetResetPwd = (model, paths) => async function getResetPwd(session, email) {
5
5
  let ret = null;
6
+ // Field name comes from the factory `paths` argument the consuming developer supplies at startup, never from request data.
7
+ // nosemgrep: koa-utils.nosql-injection.dynamic-filter-key
6
8
  const queryRet = await model
7
9
  .findOne({ [paths.email]: email })
8
10
  .select(buildProjection([paths.name, paths.resetDateReq, paths.resetHash, paths.deleted, paths.disabled]))
@@ -11,6 +11,8 @@ export const createRemoveResetReq = (model, paths) => async function removeReset
11
11
  // The unset list comes from paths.resetClear, NOT from the fields saveResetReq writes. A layout
12
12
  // holding the request in one required subdocument can only be cleared by unsetting the container;
13
13
  // unsetting its members leaves a document that fails validation and the write is rejected.
14
+ // Field name comes from the factory `paths` argument the consuming developer supplies at startup, never from request data.
15
+ // nosemgrep: koa-utils.nosql-injection.dynamic-filter-key
14
16
  return model
15
17
  .updateOne({ [paths.email]: email }, { $unset: buildUnset(paths.resetClear) })
16
18
  .session(session)
@@ -3,6 +3,8 @@ import { throwMongoDBErrors } from "../../../../lib/MongoDB/throwMongoErrors.mjs
3
3
  import { UserBase } from "../../../../graphQL/models/MongoDB/UserBase.mjs";
4
4
  export const createSaveResetReq = (model, paths) => async function saveResetReq(session, _id, now, hash) {
5
5
  try {
6
+ // Field names come from the `paths` map fixed when the flow is built, never from request data; only the values do.
7
+ // nosemgrep: koa-utils.nosql-injection.mass-assignment-update-doc
6
8
  await model.updateOne({ _id }, {
7
9
  $set: {
8
10
  [paths.resetDateReq]: now,
@@ -5,6 +5,8 @@ export const createSetEmailHash = (model, paths) => async function setEmailHash(
5
5
  const hash = emailHash();
6
6
  //calculate password hash
7
7
  const dtNow = new Date();
8
+ // Field names come from the `paths` map fixed when the flow is built, never from request data; only the values do.
9
+ // nosemgrep: koa-utils.nosql-injection.mass-assignment-update-doc
8
10
  await model.updateOne({ _id: userId }, {
9
11
  $set: {
10
12
  [paths.hash]: hash,
@@ -4,6 +4,8 @@ import { hash } from '@node-rs/bcrypt';
4
4
  import { SALT_ROUNDS } from "../Constants.mjs";
5
5
  export const createUpdatePasswordDb = (model, paths) => async function updatePassword(session, _id, password) {
6
6
  const hashVal = await hash(password, SALT_ROUNDS);
7
+ // Field names come from the `paths` map fixed when the flow is built, never from request data; only the values do.
8
+ // nosemgrep: koa-utils.nosql-injection.mass-assignment-update-doc
7
9
  return model.updateOne({ _id }, { $set: { [paths.password]: hashVal } }, { session, runValidators: true });
8
10
  };
9
11
  /** `UserBase`-bound default — the behaviour every existing consumer already imports. */
@@ -7,6 +7,8 @@ export const createUserData4VerifyEmail = (model, paths) => async function userD
7
7
  // Every field the guard chain reads must be listed. This is a .lean() read, so a field left out
8
8
  // of the projection is simply absent on the returned object, with no error — which is how a
9
9
  // missing requestTimes turned every wrong-hash attempt into a 500 under a green coverage gate.
10
+ // Field name comes from the factory `paths` argument the consuming developer supplies at startup, never from request data.
11
+ // nosemgrep: koa-utils.nosql-injection.dynamic-filter-key
10
12
  const user = await model
11
13
  .findOne({ [paths.email]: uEmail })
12
14
  .select(buildProjection([paths.hash, paths.valid, paths.dateLastReq, paths.requestTimes, paths.deleted, paths.disabled]))
@@ -0,0 +1,35 @@
1
+ import { IVerifyEmailMailer } from "../../../lib/access/verifyEmailMailer.mjs";
2
+ import { Types } from 'mongoose';
3
+ import type { IEmailChangeHashVerifyDeps } from '../../../graphQL/schema/mutations/emailChangeHashVerify.mjs';
4
+ /**
5
+ * Everything the `emailChangeHashVerify` branch handlers need, bundled so each stays within the max-params
6
+ * budget: the bound deps, the lean document just read with its `_id`, the lowercased email and the resolved
7
+ * mailer. The `deps` type is imported as a type only, so there is no runtime cycle with the mutation.
8
+ */
9
+ export interface IVerifyContext {
10
+ deps: IEmailChangeHashVerifyDeps;
11
+ user: unknown;
12
+ uId: Types.ObjectId;
13
+ uEmail: string;
14
+ mailer: IVerifyEmailMailer;
15
+ }
16
+ /**
17
+ * Read the pending email-change row addressed by `uEmail` and bundle it into the context the handlers take,
18
+ * or resolve `null` when no account holds that address.
19
+ *
20
+ * Every field the handlers read must be listed in the projection. account.email.requestTimes was missing, and
21
+ * because this is a .lean() read the absent key made handleHashMismatch throw 500 on *every* wrong hash: the
22
+ * strike counter never advanced and the owner never got the wrongHash warning.
23
+ */
24
+ export declare function loadVerifyContext(deps: IEmailChangeHashVerifyDeps, mailer: IVerifyEmailMailer, uEmail: string): Promise<IVerifyContext | null>;
25
+ /**
26
+ * The submitted hash does not match the stored one: count the attempt and warn the account owner.
27
+ * Moved out of `emailChangeHashVerify.mts` to keep that file inside the FTA score target — behaviour unchanged.
28
+ */
29
+ export declare function handleHashMismatch(ctx: IVerifyContext): Promise<boolean>;
30
+ /**
31
+ * The submitted hash matches: enforce the freshness/account guards and, if the target email is still
32
+ * free, accept it. Moved out of `emailChangeHashVerify.mts` to keep that file inside the FTA score target
33
+ * — behaviour unchanged.
34
+ */
35
+ export declare function handleValidHash(ctx: IVerifyContext): Promise<boolean>;