@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
@@ -1,15 +1,19 @@
1
- import { StringLib } from "../lib/StringLib.mjs";
1
+ import * as account from "../private/email/accountMessages.mjs";
2
+ import { escapeHtml } from "../private/email/escapeHtml.mjs";
3
+ import { FALLBACK_FOOTER, FALLBACK_HEADER_1, FALLBACK_HEADER_2, orFallback, standaloneHeader } from "../private/email/htmlFrame.mjs";
4
+ import { confirmationLink, httpLinkBase } from "../private/email/messageParts.mjs";
5
+ import * as notice from "../private/email/noticeMessages.mjs";
6
+ import { orFalse } from "../private/email/orFalse.mjs";
7
+ import * as reset from "../private/email/resetMessages.mjs";
2
8
  import * as Sentry from '@sentry/node';
3
9
  import { BasicMessage, SocketLabsClient } from '@socketlabs/email';
4
- import { throwInternalError } from "../graphQL/throw/throwInternalError.mjs";
5
10
  import * as dotenv from 'dotenv';
6
11
  dotenv.config();
7
12
  export class SocketLabsLib {
8
- StringObj;
9
13
  platformName;
10
14
  linkBase;
11
15
  emailFrom;
12
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
16
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- @socketlabs/email ships no types (untyped module in src/types/socketlabs-email.d.ts), so the client is untyped
13
17
  client;
14
18
  emailHtmlHeader1;
15
19
  emailHtmlHeader2;
@@ -17,14 +21,13 @@ export class SocketLabsLib {
17
21
  constructor(htmlHeader1 = '', htmlHeader2 = '', htmlFooter = '') {
18
22
  this.client = new SocketLabsClient(
19
23
  /* c8 ignore next -- env fallback '0' covered only when SOCKETLABS_SERVER_ID is unset */
20
- parseInt(process.env.SOCKETLABS_SERVER_ID || '0'), `${process.env.SOCKETLABS_SERVER_APIKEY}`, { requestTimeout: 120, numberOfRetries: 3 });
21
- this.StringObj = new StringLib();
22
- this.platformName = `${process.env.PLATFORM_NAME}`;
23
- this.linkBase = `${process.env.APP_DOMAIN}`;
24
- this.emailFrom = `${process.env.EMAIL_FROM}`;
25
- this.emailHtmlHeader1 = htmlHeader1 === '' ? this.htmlHeader1() : htmlHeader1;
26
- this.emailHtmlHeader2 = htmlHeader2 === '' ? this.htmlHeader2() : htmlHeader2;
27
- this.emailHtmlFooter = htmlFooter === '' ? this.htmlFooter() : htmlFooter;
24
+ parseInt(process.env['SOCKETLABS_SERVER_ID'] || '0'), `${process.env['SOCKETLABS_SERVER_APIKEY']}`, { requestTimeout: 120, numberOfRetries: 3 });
25
+ this.platformName = `${process.env['PLATFORM_NAME']}`;
26
+ this.linkBase = `${process.env['APP_DOMAIN']}`;
27
+ this.emailFrom = `${process.env['EMAIL_FROM']}`;
28
+ this.emailHtmlHeader1 = orFallback(htmlHeader1, FALLBACK_HEADER_1);
29
+ this.emailHtmlHeader2 = orFallback(htmlHeader2, FALLBACK_HEADER_2);
30
+ this.emailHtmlFooter = orFallback(htmlFooter, FALLBACK_FOOTER);
28
31
  }
29
32
  /**
30
33
  * Send the registration confirmation link.
@@ -41,26 +44,20 @@ export class SocketLabsLib {
41
44
  * normalised away — the caller supplies configuration, not a pre-joined URL, and `//check` or
42
45
  * `example.comcheck` are not errors worth surfacing to a user mid-registration.
43
46
  *
47
+ * The base, whether passed or taken from `APP_DOMAIN`, must parse as an absolute `http:` / `https:` URL
48
+ * with no user name, password, control character or whitespace; any other value (`javascript:`, `data:`,
49
+ * `//host`, a host with no scheme) makes the call reject with `throwInternalError()` and sends nothing.
50
+ *
44
51
  * @param emailTo recipient, also embedded in the link (URI-encoded)
45
52
  * @param hash the activation hash stored on the account
46
53
  * @param name optional greeting name
47
- * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`
54
+ * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`. An absolute `http:` / `https:` URL, else the call rejects with a 500
48
55
  * @param linkPath route prefix the receiving service listens on; defaults to `/check/verify-email`
49
56
  */
57
+ // eslint-disable-next-line max-params -- public signature, an options object would break consumers
50
58
  async sendEmailVerify(emailTo, hash, name = '', linkBase = this.linkBase, linkPath = '/check/verify-email') {
51
- const subject = `Confirm your email for ${this.platformName}`;
52
- const encodedEmail = encodeURI(emailTo);
53
- const nameFixed = this.fixName(name);
54
- const base = linkBase.replace(/\/+$/, '');
55
- const path = `/${linkPath.replace(/^\/+/, '')}`;
56
- const link = `${base}${path}/${encodedEmail}/${hash}`;
57
- const linkHtml = this.StringObj.makeLink(link);
58
- const messageTxt = `Hi${nameFixed}, you or someone else is registering you on ${this.platformName}.
59
- You can confirm the registration by copying this link ${link} into your browser. The Team`;
60
- const messageHtml = `Hi${nameFixed},<br>you or someone else is registering you on ${this.platformName}.<br><br>
61
- You can confirm the registration by visiting this link ${linkHtml}<br><br>
62
- <br><br>The Team`;
63
- return await this.sendTemplate(emailTo, subject, messageTxt, messageHtml);
59
+ const link = confirmationLink(linkBase, linkPath, emailTo, hash);
60
+ return await this.sendTemplate(emailTo, account.verifyMessage(this.platformName, link, name));
64
61
  }
65
62
  /*
66
63
  async sendEmailPostReported(userInfo, idPost) {
@@ -118,53 +115,32 @@ SendResponse {
118
115
  }
119
116
  */
120
117
  async sendEmailChangeVerify(emailTo, hash, name = '') {
121
- const encodedEmail = encodeURI(emailTo);
122
- const subject = `Confirm your email for ${this.platformName}`;
123
- const nameFixed = this.fixName(name);
124
- const link = `${this.linkBase}/check/verify-change-email/${encodedEmail}/${hash}`;
125
- const linkHtml = this.StringObj.makeLink(link);
126
- const messageTxt = `Hi${nameFixed}, you or someone else has changed the email you sign in with.
127
- You can confirm by copying this link ${link} into your browser. The Team.`;
128
- const messageHtml = `Hi${nameFixed},<br>you or someone else has changed the email you sign in with.<br><br>
129
- You can confirm the registration by visiting this link ${linkHtml}
130
- <br><br>The Team.`;
131
- return await this.sendTemplate(emailTo, subject, messageTxt, messageHtml);
118
+ const link = `${httpLinkBase(this.linkBase)}/check/verify-change-email/${encodeURI(emailTo)}/${hash}`;
119
+ return await this.sendTemplate(emailTo, account.changeVerifyMessage(this.platformName, link, name));
132
120
  }
133
121
  async sendWelcome(emailTo) {
134
- const subject = `Welcome to ${this.platformName}`;
135
- const linkHtml = this.StringObj.makeLink(this.linkBase, this.platformName);
136
- const messageTxt = `Welcome to ${this.platformName}`;
137
- const messageHtml = `Welcome to ${linkHtml}`;
138
- return await this.sendTemplate(emailTo, subject, messageTxt, messageHtml);
122
+ return await this.sendTemplate(emailTo, account.welcomeMessage(this.platformName, this.linkBase));
139
123
  }
140
124
  /**
141
125
  * Send account disabled notification
142
126
  * @param emailTo
143
127
  */
144
128
  async accountDisabled(emailTo) {
145
- const subject = 'Your account has been disabled';
146
- const textBody = 'Hi, we are sorry but your account has been disabled. Contact us for more information.';
147
- const htmlBody = `<p>${textBody}</p>`;
148
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
129
+ return await this.sendTemplate(emailTo, notice.ACCOUNT_DISABLED);
149
130
  }
150
131
  /**
151
132
  * Send account disabled notification
152
133
  * @param emailTo
153
134
  */
154
135
  async accountBanned(emailTo) {
155
- const subject = 'Your account has been banned';
156
- const textBody = 'Hi, we are sorry but your account has been banned. Contact us for more information.';
157
- const htmlBody = `<p>${textBody}</p>`;
158
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
136
+ return await this.sendTemplate(emailTo, notice.ACCOUNT_BANNED);
159
137
  }
160
138
  /**
161
139
  * alertDevTeam
162
140
  * @param err
163
141
  */
164
142
  async alertDevTeam(err) {
165
- const textBody = 'error 500 ' + err;
166
- const htmlBody = '<p>error 500 <br><br>' + err + '</p>';
167
- return await this.sendTemplate(`${process.env.DEV_TEAM_EMAIL}`, `${this.platformName} error 500`, textBody, htmlBody);
143
+ return await this.sendTemplate(`${process.env['DEV_TEAM_EMAIL']}`, notice.alertDevMessage(this.platformName, err));
168
144
  }
169
145
  /**
170
146
  *
@@ -172,13 +148,7 @@ SendResponse {
172
148
  * @param times
173
149
  */
174
150
  async wrongHash(emailTo, times) {
175
- if (times > 5)
176
- throwInternalError();
177
- const remainingTimes = 5 - times;
178
- const subject = 'Wrong activation link';
179
- const textBody = `Hi, you or someone else is trying to verify your email with a wrong link. You have ${remainingTimes} attempts remaining.`;
180
- const htmlBody = `<p>${textBody}</p>`;
181
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
151
+ return await this.sendTemplate(emailTo, notice.wrongHashMessage(times));
182
152
  }
183
153
  /*****************
184
154
  * Too much verify requests
@@ -186,30 +156,21 @@ SendResponse {
186
156
  * @returns {Promise<string|null>}
187
157
  */
188
158
  async tooMuchVerifyRequests(emailTo) {
189
- const subject = 'Too many attempts to verify your email';
190
- const textBody = 'Hi, you have made more than 5 attempts to verify your email. You need to repeat the registration request.';
191
- const htmlBody = '<p>Hi, you have made 5 or more attempts to verify your email. You need to repeat the registration request.</p>';
192
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
159
+ return await this.sendTemplate(emailTo, notice.TOO_MUCH_VERIFY_REQUESTS);
193
160
  }
194
161
  /*****************
195
162
  * @param emailTo
196
163
  * @returns {Promise<string|null>}
197
164
  */
198
165
  async hashReqTooOld(emailTo) {
199
- const subject = 'Activation link expired';
200
- const textBody = 'Hi, the activation link you are trying to use is older than 3 days and has expired. You need to repeat the registration request.';
201
- const htmlBody = '<p>Hi, the activation link you are trying to use is older than 3 days and has expired. You need to repeat the registration request.</p>';
202
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
166
+ return await this.sendTemplate(emailTo, notice.HASH_REQ_TOO_OLD);
203
167
  }
204
168
  /*****************
205
169
  * @param emailTo
206
170
  * @returns {Promise<string|null>}
207
171
  */
208
172
  async emailAlreadyValid(emailTo) {
209
- const subject = 'Account already valid';
210
- const textBody = 'Hi, your account is already valid, you can log in.';
211
- const htmlBody = `<p>${textBody}</p>`;
212
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
173
+ return await this.sendTemplate(emailTo, notice.EMAIL_ALREADY_VALID);
213
174
  }
214
175
  /**
215
176
  * Send subscription email
@@ -217,44 +178,14 @@ SendResponse {
217
178
  * @param otp
218
179
  */
219
180
  async sendSubscriptionEmail(emailTo, otp) {
220
- const subject = `Activate your ${this.platformName} account`;
221
- const url = `${this.linkBase}/x/emailVerify`;
222
- const urlHtml = this.StringObj.makeLink(url);
223
- const linkHomeHtml = this.StringObj.makeLink(this.linkBase, this.platformName);
224
- const textBody = `To confirm your subscription on ${this.platformName}, open the following link in your browser
225
- ${url} and enter the following activation code: ${otp}`;
226
- const htmlBody = `<p>To confirm your subscription on ${linkHomeHtml}, open the following link in your browser
227
- ${urlHtml} and enter the following activation code: ${otp}</p>`;
228
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
181
+ return await this.sendTemplate(emailTo, account.subscriptionMessage(this.platformName, this.linkBase, otp));
229
182
  }
230
183
  async sendResetPwdConfirmation(emailTo, name = '') {
231
- const subject = `Password reset for ${this.platformName}`;
232
- const link = this.linkBase;
233
- const linkHtml = this.StringObj.makeLink(link, this.platformName);
234
- const nameFixed = this.fixName(name);
235
- const textBody = `Hi${nameFixed}, you have confirmed your new password. You can now log in at: ${link}. The Team.`;
236
- const htmlBody = `Hi${nameFixed},<br>you have confirmed your new password.<br><br>You can now log in at:<br>${linkHtml}<br><br>The Team.`;
237
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
184
+ return await this.sendTemplate(emailTo, reset.resetConfirmationMessage(this.platformName, this.linkBase, name));
238
185
  }
239
186
  async sendResetPwdConfirmationHash(email, name, hash) {
240
- const encodedEmail = encodeURI(email);
241
- const subject = `Password change confirmation for ${this.platformName}`;
242
- const linkReset = this.linkBase + '/index.php?q=reset&hash=' + hash + '&email=' + encodedEmail;
243
- const textBody = 'Hi ' + name + ', you have confirmed your new password. You can now log in at: ' + this.linkBase + ' . ';
244
- const htmlBody = this.getHtmlHeader(subject) +
245
- 'Hi ' +
246
- name +
247
- ',<br>you have confirmed your new password.<br><br>You can now log in at:<br> ' +
248
- this.StringObj.makeLink(linkReset) +
249
- '<br><br>The Team' +
250
- this.getHtmlFooter();
251
- try {
252
- return await this.sendTemplate(email, subject, textBody, htmlBody);
253
- }
254
- catch (e) {
255
- Sentry.captureException(e);
256
- return false;
257
- }
187
+ const content = reset.resetConfirmationHashMessage(this.platformName, this.linkBase, { email, name, hash });
188
+ return await orFalse(() => this.sendTemplate(email, content));
258
189
  }
259
190
  /**
260
191
  * Send the password-reset link.
@@ -272,29 +203,19 @@ SendResponse {
272
203
  * @param emailTo recipient, also embedded in the link (URI-encoded)
273
204
  * @param hash the reset hash stored on the account
274
205
  * @param name optional greeting name
275
- * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`
206
+ * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`. An absolute `http:` / `https:` URL, else the call rejects with a 500
276
207
  * @param linkPath front-end route prefix that renders the new-password form; defaults to `/x/reset`
277
208
  */
209
+ // eslint-disable-next-line max-params -- public signature, an options object would break consumers
278
210
  async sendEmailReset(emailTo, hash, name = '', linkBase = this.linkBase, linkPath = '/x/reset') {
279
- const subject = `Password reset for ${this.platformName}`;
280
- const encodedEmail = encodeURI(emailTo);
281
- const base = linkBase.replace(/\/+$/, '');
282
- const path = `/${linkPath.replace(/^\/+/, '')}`;
283
- const link = `${base}${path}/${encodedEmail}/${hash}`;
284
- const linkHtml = this.StringObj.makeLink(link);
285
- const nameFixed = this.fixName(name);
286
- const textBody = `Hi${nameFixed}, you or someone else has requested a password reset. You can change your login password
287
- by copying this link ${link} into your browser. The Team.`;
288
- const htmlBody = `Hi${nameFixed},<br>you or someone else has requested a password reset.<br><br>
289
- You can change your password by clicking the link:<br>${linkHtml}
290
- <br><br>The Team.`;
291
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
211
+ const link = confirmationLink(linkBase, linkPath, emailTo, hash);
212
+ return await this.sendTemplate(emailTo, reset.resetMessage(this.platformName, link, name));
292
213
  }
293
214
  /**
294
215
  * fallback footer
295
216
  */
296
217
  htmlFooter() {
297
- return '</p></td>' + ' </tr>' + ' </table>' + '</body>';
218
+ return FALLBACK_FOOTER;
298
219
  }
299
220
  /**
300
221
  * send OTP
@@ -302,77 +223,28 @@ SendResponse {
302
223
  * @param otp
303
224
  */
304
225
  async sendOTP(emailTo, otp) {
305
- const subject = `OTP code for ${this.platformName}`;
306
- const textBody = `To confirm your subscription on ${this.platformName}, enter the following OTP code: ${otp}`;
307
- const htmlBody = `<p>To confirm your subscription on ${this.platformName}, enter the following OTP code: ${otp}</p>`;
308
- try {
309
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
310
- }
311
- catch (e) {
312
- Sentry.captureException(e);
313
- return false;
314
- }
226
+ const content = account.otpMessage(this.platformName, otp);
227
+ return await orFalse(() => this.sendTemplate(emailTo, content));
315
228
  }
316
229
  async sendEmailPostReported(userInfo, idPost) {
317
- const subject = 'Post ' + idPost + ' reported';
318
- const messageTxt = 'Hi, post ' +
319
- idPost +
320
- ' has been reported by ' +
321
- userInfo.personalData.name +
322
- ' ' +
323
- userInfo.personalData.surname +
324
- ' (id: ' +
325
- userInfo._id +
326
- ').';
327
- const messageHtml = this.getHtmlHeader(subject) +
328
- 'Hi, post ' +
329
- idPost +
330
- ' has been reported by ' +
331
- userInfo.personalData.name +
332
- ' ' +
333
- userInfo.personalData.surname +
334
- ' (id: ' +
335
- userInfo._id +
336
- ').' +
337
- this.getHtmlFooter();
338
- return await this.sendTemplate(`${process.env.DEV_TEAM_EMAIL}`, subject, messageTxt, messageHtml);
230
+ const { name, surname } = userInfo.personalData;
231
+ const content = notice.postReportedMessage(idPost, name, surname, userInfo._id);
232
+ return await this.sendTemplate(`${process.env['DEV_TEAM_EMAIL']}`, content);
339
233
  }
340
234
  getHtmlHeader(title) {
341
- return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
342
- '<html xmlns="http://www.w3.org/1999/xhtml">' +
343
- ' <head>' +
344
- ' <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
345
- ' <title>' +
346
- title +
347
- '</title>' +
348
- ' <meta name="viewport" content="width=device-width, initial-scale=1.0"/>' +
349
- '</head>' +
350
- '</html>' +
351
- '<body style="margin: 0; padding: 0;">' +
352
- ' <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">' +
353
- ' <tr>' +
354
- ' <td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;"><p style="color: #000000; font-family: Verdana, sans-serif; font-size: 12pt;">');
235
+ return standaloneHeader(title);
355
236
  }
356
237
  getHtmlFooter() {
357
- return '</p></td>' + ' </tr>' + ' </table>' + '</body>';
238
+ return FALLBACK_FOOTER;
358
239
  }
359
- async sendTemplate(emailTo, subject, textBody, htmlBody) {
360
- return await this.sendEmail({
361
- emailFrom: this.emailFrom,
362
- emailFromName: this.platformName,
363
- emailTo,
364
- subject,
365
- textBody,
366
- htmlBody
367
- });
368
- }
369
- async sendEmail(args) {
370
- const { emailFrom, emailFromName, emailTo, subject, textBody, htmlBody } = args;
240
+ async sendTemplate(emailTo, content) {
241
+ const { subject, textBody, htmlBody } = content;
371
242
  const basicMessage = new BasicMessage();
372
- basicMessage.setFromAddress(emailFrom, emailFromName);
243
+ basicMessage.setFromAddress(this.emailFrom, this.platformName);
373
244
  basicMessage.setSubject(subject);
374
245
  basicMessage.setTextBody(textBody);
375
- basicMessage.setHtmlBody(this.emailHtmlHeader1 + subject + this.emailHtmlHeader2 + htmlBody + this.emailHtmlFooter);
246
+ // The subject is plain text for the subject line and the text part, so only its copy placed in the HTML is escaped.
247
+ basicMessage.setHtmlBody(this.emailHtmlHeader1 + escapeHtml(subject) + this.emailHtmlHeader2 + htmlBody + this.emailHtmlFooter);
376
248
  basicMessage.setTo(emailTo);
377
249
  return this.client.send(basicMessage).then(() => {
378
250
  //Handle successful API call
@@ -384,33 +256,5 @@ SendResponse {
384
256
  return false;
385
257
  });
386
258
  }
387
- /**
388
- * fallback header
389
- * @private
390
- */
391
- htmlHeader1() {
392
- return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
393
- '<html lang="en" xmlns="http://www.w3.org/1999/xhtml">' +
394
- ' <head>' +
395
- ' <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
396
- ' <title>');
397
- }
398
- /**
399
- * fallback header
400
- * @private
401
- */
402
- htmlHeader2() {
403
- return ('</title>' +
404
- ' <meta name="viewport" content="width=device-width, initial-scale=1.0"/>' +
405
- '</head>' +
406
- '</html>' +
407
- '<body style="margin: 0; padding: 0;">' +
408
- ' <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">' +
409
- ' <tr>' +
410
- ' <td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;"><p style="color: #000000; font-family: Verdana, sans-serif; font-size: 12pt;">');
411
- }
412
- fixName(name) {
413
- return name !== '' ? ` ${name}` : '';
414
- }
415
259
  }
416
260
  //# sourceMappingURL=SocketLabsLib.mjs.map
@@ -11,7 +11,7 @@ export async function moveFileStaticDomain(sourceFilePath, folder, secondFolder,
11
11
  // folder/secondFolder are path segments: a `..` in them escapes STATIC_FOLDER
12
12
  assertNoTraversal(folder, 'folder');
13
13
  assertNoTraversal(secondFolder, 'secondFolder');
14
- const destinationDir = `${process.env.STATIC_FOLDER}/${folder}/${secondFolder}`;
14
+ const destinationDir = `${process.env['STATIC_FOLDER']}/${folder}/${secondFolder}`;
15
15
  await moveTempFile(sourceFilePath, destFilename, destinationDir);
16
16
  }
17
17
  //# sourceMappingURL=moveFileStaticDomain.mjs.map
@@ -33,7 +33,11 @@ export async function storeUploadAsTemp(upload, maxFileSize = MAX_FILE_SIZE) {
33
33
  });
34
34
  // Best-effort cleanup, then reject. Cleanup is fire-and-forget by design: the
35
35
  // upload has already failed, and an unlink error must not mask the real cause.
36
- const removeThenReject = (reason) => unlink(storedFileUrl, () => reject(reason));
36
+ const removeThenReject = (reason) => {
37
+ unlink(storedFileUrl, () => {
38
+ reject(reason);
39
+ });
40
+ };
37
41
  // 'close' is the single settle point. Every failure path below only RECORDS what
38
42
  // went wrong and stops the stream; nothing settles the Promise itself. Rejecting
39
43
  // from inside an unlink callback instead would lose the race — destroy() emits
@@ -9,6 +9,7 @@ import { validateJpgPngMimeType } from './validateMimeTypeImages.mjs';
9
9
  * @param img
10
10
  */
11
11
  export async function uploadTempImage(img) {
12
+ // Stryker disable next-line StringLiteral: initial value is overwritten by the reEncodeToWebp assignment in the try block before the only read (return); every other path throws.
12
13
  let storedTempFile = '';
13
14
  try {
14
15
  // Step 1 - Readme.md
@@ -16,7 +17,7 @@ export async function uploadTempImage(img) {
16
17
  await validateJpgPngExtension(fileName, filePath);
17
18
  await validateJpgPngMimeType(filePath);
18
19
  // step 2
19
- await scanVirus(`${filePath}`);
20
+ await scanVirus(filePath);
20
21
  // step 3
21
22
  storedTempFile = await reEncodeToWebp(filePath);
22
23
  // await checkForNSFW(filePath)
@@ -8,6 +8,7 @@ import { validatePdfExtension } from './validatePdfExtension.mjs';
8
8
  * @param pdf
9
9
  */
10
10
  export async function uploadTempPdf(pdf) {
11
+ // Stryker disable next-line StringLiteral: initial value is overwritten by the storedTempFile = filePath assignment in the try block before the only read (return); every other path throws.
11
12
  let storedTempFile = '';
12
13
  try {
13
14
  // Step 1 - Readme.md
@@ -15,7 +16,7 @@ export async function uploadTempPdf(pdf) {
15
16
  await validatePdfExtension(fileName, filePath);
16
17
  await validateMimeTypePdf(filePath);
17
18
  // step 2
18
- await scanVirus(`${filePath}`);
19
+ await scanVirus(filePath);
19
20
  // step 3
20
21
  // @todo reencode with dangerzone https://github.com/freedomofpress/dangerzone/tree/main
21
22
  storedTempFile = filePath;
@@ -65,5 +65,7 @@ declare const UserBase: import("mongoose").Model<IUserBaseSchema, {}, {}, {}, im
65
65
  __v: number;
66
66
  } & {
67
67
  id: string;
68
- }, any, IUserBaseSchema>;
68
+ }, any, IUserBaseSchema & Required<{
69
+ _id: Types.ObjectId;
70
+ }>>;
69
71
  export { UserBase };
@@ -21,5 +21,7 @@ declare const DevStatsGraphQLCalls: import("mongoose").Model<IDevStatsGraphQLCal
21
21
  __v: number;
22
22
  } & {
23
23
  id: string;
24
- }, any, IDevStatsGraphQLCallsSchema>;
24
+ }, any, IDevStatsGraphQLCallsSchema & Required<{
25
+ _id: Types.ObjectId;
26
+ }>>;
25
27
  export { DevStatsGraphQLCalls };
@@ -12,5 +12,7 @@ declare const LogGlobalError: import("mongoose").Model<IGlobalErrorGraphqlSchema
12
12
  __v: number;
13
13
  } & {
14
14
  id: string;
15
- }, any, IGlobalErrorGraphqlSchema>;
15
+ }, any, IGlobalErrorGraphqlSchema & Required<{
16
+ _id: Types.ObjectId;
17
+ }>>;
16
18
  export { LogGlobalError };
@@ -15,5 +15,7 @@ declare const LogStatsGraphql: import("mongoose").Model<IStatsGraphqlSchema, {},
15
15
  __v: number;
16
16
  } & {
17
17
  id: string;
18
- }, any, IStatsGraphqlSchema>;
18
+ }, any, IStatsGraphqlSchema & Required<{
19
+ _id: Types.ObjectId;
20
+ }>>;
19
21
  export { LogStatsGraphql };
@@ -13,5 +13,7 @@ declare const LogThrow: import("mongoose").Model<ILogThrowGraphqlSchema, {}, {},
13
13
  __v: number;
14
14
  } & {
15
15
  id: string;
16
- }, any, ILogThrowGraphqlSchema>;
16
+ }, any, ILogThrowGraphqlSchema & Required<{
17
+ _id: Types.ObjectId;
18
+ }>>;
17
19
  export { LogThrow };
@@ -1,69 +1,12 @@
1
1
  import { DEFAULT_VERIFY_EMAIL_PATHS } from "../../../lib/access/accessPaths.mjs";
2
2
  import { defaultVerifyEmailMailer } from "../../../lib/access/verifyEmailMailer.mjs";
3
- import { StringLib } from "../../../lib/StringLib.mjs";
4
3
  import { UserBase } from "../../models/MongoDB/UserBase.mjs";
5
4
  import confirmNewEmail from "../../../private/lib/access/db/confirmNewEmail.mjs";
6
5
  import { incReqTimes } from "../../../private/lib/access/db/incReqTimes.mjs";
7
- import { buildProjection, readPath } from "../../../private/lib/access/pathTools.mjs";
8
- import { throwInternalError } from "../../throw/throwInternalError.mjs";
6
+ import { handleHashMismatch, handleValidHash, loadVerifyContext } from "../../../private/lib/access/emailChangeHandlers.mjs";
7
+ import { readPath } from "../../../private/lib/access/pathTools.mjs";
8
+ import { safeEqualSecret } from "../../../private/lib/access/safeEqualSecret.mjs";
9
9
  import { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql';
10
- /**
11
- * The submitted hash does not match the stored one: count the attempt and warn the account owner.
12
- * Extracted from resolve() only to keep it inside the max-lines-per-function budget — behaviour unchanged.
13
- */
14
- async function handleHashMismatch(ctx, uId, requestTimes) {
15
- // hash failed
16
- if (typeof requestTimes === 'undefined') {
17
- throw throwInternalError();
18
- }
19
- await ctx.deps.incReqTimes(uId);
20
- // noinspection ES6MissingAwait
21
- ctx.mailer.wrongHash(ctx.uEmail, requestTimes);
22
- return false;
23
- }
24
- /**
25
- * The submitted hash matches: enforce the freshness/account guards and, if the target email is still
26
- * free, accept it. Extracted from resolve() only to keep it inside the max-lines-per-function budget.
27
- */
28
- async function handleValidHash(ctx, uId, dateLastReq) {
29
- const { deps, user, uEmail, mailer } = ctx;
30
- const { paths } = deps;
31
- if (typeof dateLastReq === 'undefined') {
32
- // @fixme sentry 'dateLastReq is undefined'
33
- throw throwInternalError();
34
- }
35
- // if dateLastReq is older than 3 days, warn and stop
36
- const StrLibObj = new StringLib();
37
- const now = new Date();
38
- const day3ago = new Date(now.setDate(now.getDate() - 3));
39
- if (StrLibObj.isoToTimestamp(day3ago) > StrLibObj.isoToTimestamp(dateLastReq)) {
40
- // dateLastReq too old then 3 days
41
- // noinspection ES6MissingAwait
42
- mailer.hashReqTooOld(uEmail);
43
- return false;
44
- }
45
- // account is deleted -> maybe by admin for any reason
46
- // Read raw: this is a .lean() query, so Mongoose casting never runs and these are real booleans
47
- // only on data that scripts/migrate-account-disabled-to-boolean.mjs has been through. A legacy
48
- // string 'false' is truthy and blocks here — migrate, don't coerce.
49
- if (readPath(user, paths.deleted)) {
50
- return false;
51
- }
52
- // if account is disabled, for any reason
53
- if (readPath(user, paths.disabled)) {
54
- // noinspection ES6MissingAwait
55
- mailer.accountDisabled(uEmail);
56
- return false;
57
- }
58
- // valid request. meanwhile, has some user registered with this email address ??
59
- const qty = await deps.model.countDocuments({ [paths.email]: uEmail });
60
- if (qty > 0) {
61
- return false;
62
- }
63
- // accept new email
64
- await deps.confirmNewEmail(uId, uEmail);
65
- return true;
66
- }
67
10
  /**
68
11
  * Change email - Verify match between email and hash
69
12
  *
@@ -81,27 +24,16 @@ export const createEmailChangeHashVerifyMutation = (deps) => {
81
24
  hash: { type: new GraphQLNonNull(GraphQLString) }
82
25
  },
83
26
  async resolve(_, args) {
84
- const { paths } = deps;
85
- const uEmail = args.email.toLowerCase();
86
27
  // search if the email exists
87
- // Every field this resolver reads must be listed. account.email.requestTimes was missing, and
88
- // because this is a .lean() read the absent key made handleHashMismatch throw 500 on *every*
89
- // wrong hash: the strike counter never advanced and the owner never got the wrongHash warning.
90
- const user = await deps.model
91
- .findOne({ [paths.newEmailTmp]: uEmail })
92
- .select(buildProjection([paths.hash, paths.dateLastReq, paths.requestTimes, paths.deleted, paths.disabled]))
93
- .lean();
28
+ const ctx = await loadVerifyContext(deps, mailer, args.email.toLowerCase());
94
29
  // if email not found, return (do not tell the user the real problem !)
95
- if (user === null) {
30
+ if (ctx === null) {
96
31
  return false; // @fixme throw
97
32
  }
98
- const ctx = { deps, user, uEmail, mailer };
99
- const uId = readPath(user, '_id');
100
- const dateLastReq = readPath(user, paths.dateLastReq);
101
- if (args.hash === readPath(user, paths.hash)) {
102
- return handleValidHash(ctx, uId, dateLastReq);
33
+ if (safeEqualSecret(args.hash, readPath(ctx.user, deps.paths.hash))) {
34
+ return handleValidHash(ctx);
103
35
  }
104
- return handleHashMismatch(ctx, uId, readPath(user, paths.requestTimes));
36
+ return handleHashMismatch(ctx);
105
37
  }
106
38
  };
107
39
  };
@@ -39,6 +39,7 @@ export const login4Ever = {
39
39
  });
40
40
  }
41
41
  catch (e) {
42
+ // Stryker disable next-line StringLiteral: tryCatchRethrow below always throws (throwIfMongoErr throws or returns, then both branches throw), so this reset is never read by the return
42
43
  accessToken = '';
43
44
  Sentry.captureException(e);
44
45
  tryCatchRethrow(e);
@@ -43,6 +43,7 @@ export const loginAdmin = {
43
43
  });
44
44
  }
45
45
  catch (e) {
46
+ // Stryker disable next-line StringLiteral: tryCatchRethrow below always throws (throwIfMongoErr throws or returns, then both branches throw), so this reset is never read by the return
46
47
  accessToken = '';
47
48
  Sentry.captureException(e);
48
49
  tryCatchRethrow(e);
@@ -40,6 +40,7 @@ export const loginRememberme = {
40
40
  });
41
41
  }
42
42
  catch (e) {
43
+ // Stryker disable next-line StringLiteral: tryCatchRethrow below always throws (throwIfMongoErr throws or returns, then both branches throw), so this reset is never read by the return
43
44
  accessToken = '';
44
45
  Sentry.captureException(e);
45
46
  tryCatchRethrow(e);