@axiumine/koa-utils 7.1.0 → 7.1.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.
Files changed (84) hide show
  1. package/LICENSE +0 -5
  2. package/README.md +54 -2
  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 +0 -13
  8. package/dist/email/SocketLabsLib.mjs +48 -208
  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/db/log/hitStat.mjs +1 -0
  36. package/dist/lib/isIntrospectionBypassAllowed.mjs +1 -1
  37. package/dist/lib/isSessionBlocked.mjs +1 -1
  38. package/dist/lib/tokens.mjs +2 -1
  39. package/dist/lib/tryCatchRethrow.mjs +1 -1
  40. package/dist/private/dataSources/isRedisTlsRequired.mjs +1 -1
  41. package/dist/private/email/IEmailContent.d.mts +9 -0
  42. package/dist/private/email/IEmailContent.mjs +2 -0
  43. package/dist/private/email/accountMessages.d.mts +11 -0
  44. package/dist/private/email/accountMessages.mjs +55 -0
  45. package/dist/private/email/escapeHtml.d.mts +9 -0
  46. package/dist/private/email/escapeHtml.mjs +17 -0
  47. package/dist/private/email/htmlFrame.d.mts +10 -0
  48. package/dist/private/email/htmlFrame.mjs +25 -0
  49. package/dist/private/email/messageParts.d.mts +12 -0
  50. package/dist/private/email/messageParts.mjs +31 -0
  51. package/dist/private/email/noticeMessages.d.mts +14 -0
  52. package/dist/private/email/noticeMessages.mjs +51 -0
  53. package/dist/private/email/orFalse.d.mts +2 -0
  54. package/dist/private/email/orFalse.mjs +12 -0
  55. package/dist/private/email/resetMessages.d.mts +17 -0
  56. package/dist/private/email/resetMessages.mjs +44 -0
  57. package/dist/private/graphQL/models/MongoDB/private/UserAdminKoaUtils.d.mts +4 -2
  58. package/dist/private/graphQL/schema/mutations/_buildLoginStatsUpdate.mjs +4 -4
  59. package/dist/private/graphQL/schema/mutations/infoUserForLoginSQL.mjs +5 -4
  60. package/dist/private/graphQL/schema/mutations/setRedisLoginSession.mjs +2 -2
  61. package/dist/private/graphQL/schema/mutations/updateLoginStats4ever.mjs +2 -2
  62. package/dist/private/lib/access/applyPasswordReset.d.mts +22 -0
  63. package/dist/private/lib/access/applyPasswordReset.mjs +22 -0
  64. package/dist/private/lib/access/assertResetAllowed.d.mts +14 -0
  65. package/dist/private/lib/access/assertResetAllowed.mjs +51 -0
  66. package/dist/private/lib/access/assertVerifyEmailAllowed.d.mts +6 -1
  67. package/dist/private/lib/access/db/abandonUser.mjs +3 -0
  68. package/dist/private/lib/access/db/confirmNewEmail.mjs +2 -0
  69. package/dist/private/lib/access/db/deleteUserByEmail.mjs +2 -0
  70. package/dist/private/lib/access/db/enableEmailAccess.mjs +2 -0
  71. package/dist/private/lib/access/db/getResetPwd.mjs +2 -0
  72. package/dist/private/lib/access/db/removeResetReq.mjs +2 -0
  73. package/dist/private/lib/access/db/saveResetReq.mjs +2 -0
  74. package/dist/private/lib/access/db/setEmailHash.mjs +2 -0
  75. package/dist/private/lib/access/db/updatePasswordDb.mjs +2 -0
  76. package/dist/private/lib/access/db/userData4VerifyEmail.mjs +2 -0
  77. package/dist/private/lib/access/emailChangeHandlers.d.mts +35 -0
  78. package/dist/private/lib/access/emailChangeHandlers.mjs +87 -0
  79. package/dist/private/lib/access/handleIfHashBad.d.mts +4 -2
  80. package/dist/private/lib/access/handleIfHashBad.mjs +4 -1
  81. package/dist/private/lib/access/safeEqualSecret.d.mts +13 -0
  82. package/dist/private/lib/access/safeEqualSecret.mjs +26 -0
  83. package/dist/private/lib/verifyIntrospectionCode.mjs +1 -1
  84. package/package.json +59 -25
@@ -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);
@@ -15,10 +15,10 @@ export const logout = {
15
15
  // buildPrefixedRedisKey is idempotent: the tokens are already prefixed when ctx.state.user
16
16
  // comes from authenticatedLogoutHandler, so re-adding the prefix here would delete
17
17
  // 'refresh:refresh:<uuid>' — a key that was never written — and leave the session alive
18
- await redisClient.del(`${process.env.REDIS_KEY}${buildPrefixedRedisKey('refresh:', ctx.state.user.refreshToken)}`);
18
+ await redisClient.del(`${process.env['REDIS_KEY']}${buildPrefixedRedisKey('refresh:', ctx.state.user.refreshToken)}`);
19
19
  const accessToken = ctx.state.user?.accessToken || '';
20
20
  if (accessToken !== '') {
21
- await redisClient.del(`${process.env.REDIS_KEY}${buildPrefixedRedisKey('access:', accessToken)}`);
21
+ await redisClient.del(`${process.env['REDIS_KEY']}${buildPrefixedRedisKey('access:', accessToken)}`);
22
22
  }
23
23
  // delete cookies
24
24
  ctx.cookies.set('refresh_token', '', refreshTokenOptions);
@@ -11,16 +11,17 @@ export const refresh = {
11
11
  description: 'refresh token',
12
12
  type: new GraphQLNonNull(RefreshType),
13
13
  async resolve(_, {}, ctx) {
14
+ // Stryker disable next-line BooleanLiteral: every path that returns assigns status = true first; the catch path always throws via tryCatchRethrow, so the initial value is never read
14
15
  let status = false; // default
15
16
  // has the refresh token, access token already expired
16
17
  // gets the user id already copied into ctx
17
18
  const userId = ctx.state.user.id.toString();
18
19
  // generates the 2 new tokens
19
20
  let accessToken = generateAccessToken();
20
- let refreshToken = generateRefreshToken();
21
- const keyAccess = `${process.env.REDIS_KEY}access:${accessToken}`;
22
- const keyRefresh = `${process.env.REDIS_KEY}refresh:${refreshToken}`;
23
- let accessTokenData = ctx.state.user;
21
+ const refreshToken = generateRefreshToken();
22
+ const keyAccess = `${process.env['REDIS_KEY']}access:${accessToken}`;
23
+ const keyRefresh = `${process.env['REDIS_KEY']}refresh:${refreshToken}`;
24
+ const accessTokenData = ctx.state.user;
24
25
  const oldRefresh = ctx.state.user.refreshToken;
25
26
  // @ts-expect-error delete refresh
26
27
  delete accessTokenData.refreshToken;
@@ -36,13 +37,14 @@ export const refresh = {
36
37
  await Promise.all([redisClient.expire(keyAccess, accTokenExp), redisClient.expire(keyRefresh, REFRESH_TOKEN_EXPIRY)]);
37
38
  setLoginCookies(ctx, refreshToken);
38
39
  // deletes the refresh token used to make this call
39
- await redisClient.del(`${process.env.REDIS_KEY}${oldRefresh}`);
40
+ await redisClient.del(`${process.env['REDIS_KEY']}${oldRefresh}`);
40
41
  status = true;
41
42
  }
42
43
  catch (e) {
43
44
  Sentry.captureException(e);
44
45
  // delete keys
45
46
  await Promise.all([redisClient.del(keyAccess), redisClient.del(keyRefresh)]);
47
+ // Stryker disable next-line StringLiteral: tryCatchRethrow right below always throws (throwIfMongoErr throws or returns, then both branches throw), so this reset is never read by the return
46
48
  accessToken = '';
47
49
  tryCatchRethrow(e);
48
50
  }
@@ -18,7 +18,7 @@ export interface IResetPwdDeps {
18
18
  * flow that differs per audience, and it is not derivable from the account — two collections behind
19
19
  * one service look identical by the time the resolver has an email and a hash.
20
20
  */
21
- mailer?: IResetPwdMailer;
21
+ mailer?: IResetPwdMailer | undefined;
22
22
  }
23
23
  /**
24
24
  * Take the user email and send an email with a link for change the password.
@@ -20,6 +20,7 @@ export const signUp = {
20
20
  checkEmailLen(uEmail);
21
21
  checkPwdLen(password);
22
22
  const session = await mongoose.startSession();
23
+ // Stryker disable next-line BooleanLiteral: uExist is assigned from userExist() at the top of the transaction callback before its only read, so the initial value is never observed
23
24
  let uExist = false;
24
25
  try {
25
26
  await session.withTransaction(async () => {
@@ -1,61 +1,14 @@
1
1
  import { SocketLabsLib } from "../../../email/SocketLabsLib.mjs";
2
2
  import { checkEmailLen } from "../../../lib/checkEmailLen.mjs";
3
3
  import { checkPwdLen } from "../../../lib/checkPwdLen.mjs";
4
- import { DateLib } from "../../../lib/DateLib.mjs";
5
4
  import { tryCatchRethrow } from "../../../lib/tryCatchRethrow.mjs";
5
+ import { applyPasswordReset } from "../../../private/lib/access/applyPasswordReset.mjs";
6
6
  import { getResetPwd } from "../../../private/lib/access/db/getResetPwd.mjs";
7
7
  import removeResetReq from "../../../private/lib/access/db/removeResetReq.mjs";
8
8
  import updatePasswordDb from "../../../private/lib/access/db/updatePasswordDb.mjs";
9
9
  import * as Sentry from '@sentry/node';
10
- import { throwForbiddenError } from "../../throw/throwForbiddenError.mjs";
11
- import { throwInternalError } from "../../throw/throwInternalError.mjs";
12
10
  import { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql';
13
11
  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
- // No usable reset state. This is NOT an internal error as far as the caller is concerned:
27
- // answering 500 here while an unknown address answers 403 turns this mutation into an
28
- // account-enumeration oracle, because every registered account that has never requested a
29
- // reset lands on this branch (getResetPwd yields resetHash === null whenever
30
- // account.resetDateReq is undefined). Same 403 as the unknown-address path; the orphan
31
- // state is reported to Sentry instead of to the caller.
32
- if (resetPwd.resetHash === null) {
33
- Sentry.captureMessage(`[updatePassword] no usable resetHash for ${uEmail}`);
34
- throw throwForbiddenError();
35
- }
36
- /* c8 ignore next 4 -- defensive guard, resetDateReq cannot be null when resetHash is set */
37
- if (resetPwd.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 (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('' + resetPwd.resetDateReq);
47
- if (DateLib.minElapsed(dt1) > 60) {
48
- throw throwForbiddenError(); // The link is no longer valid
49
- }
50
- const update = await deps.updatePasswordDb(session, resetPwd._id, password);
51
- if (!update) {
52
- throw throwInternalError(); // "System error while updating the password."
53
- }
54
- // delete password reset request data from db
55
- await deps.removeResetReq(session, uEmail);
56
- // the confirmation email is sent after the commit, not here
57
- return resetPwd.name;
58
- }
59
12
  /**
60
13
  * Change the password of an account holding a valid, unexpired reset hash.
61
14
  *
@@ -14,7 +14,7 @@ export const authenticatedAuthorizationHandler = (keys) => async (ctx, next) =>
14
14
  */
15
15
  // does the key exist in redis? ok, read redis
16
16
  const refreshTokenRedis = verifySignedRefreshToken(ctx, keys);
17
- const redSession = await redisClient.hGetAll(`${process.env.REDIS_KEY}${refreshTokenRedis}`);
17
+ const redSession = await redisClient.hGetAll(`${process.env['REDIS_KEY']}${refreshTokenRedis}`);
18
18
  if (Object.keys(redSession).length !== 0) {
19
19
  const redData = { ...redSession }; // For safety, Redis return an object without the default Object.prototype in its prototype chain.
20
20
  // is the user reported as blocked within the session? (see isSessionBlocked)
@@ -23,7 +23,7 @@ export const authenticatedAuthorizationHandler = (keys) => async (ctx, next) =>
23
23
  }
24
24
  ctx.state.user = {
25
25
  ...redData,
26
- id: new Types.ObjectId(redData.id),
26
+ id: new Types.ObjectId(redData['id']),
27
27
  refreshToken: refreshTokenRedis
28
28
  };
29
29
  }
@@ -17,10 +17,12 @@ export function verifySignedRefreshToken(ctx, keys) {
17
17
  /**
18
18
  * 'refresh_token=27119032-9043-4a9f-bd4c-9d06fd576290; refresh_token.sig=P1gZO6-49xVEMkiMqkOjJ2Cxaf3mQb18GaflDsjibuv4fFWYIOzcW26didnVJ1aridyY40CFzDtufzI6zI8jkQ'
19
19
  */
20
+ // Stryker disable next-line OptionalChaining: cookies is a local object literal assigned above and never null, so ?. never short-circuits
20
21
  const refreshToken = cookies?.refresh_token;
21
22
  if (!refreshToken) {
22
23
  throw throwRefreshTokenRequired();
23
24
  }
25
+ // Stryker disable next-line OptionalChaining: cookies is a local object literal assigned above and never null, so ?. never short-circuits
24
26
  const signature = cookies?.['refresh_token.sig'];
25
27
  if (!signature) {
26
28
  throw throwRefreshTokenSignatureRequired();
@@ -34,7 +34,7 @@ export const authenticatedLogoutHandler = (keys) => async (ctx, next) => {
34
34
  }
35
35
  if (!introspection) {
36
36
  const refreshToken = verifySignedRefreshToken(ctx, keys);
37
- const redRefreshSession = await redisClient.hGet(`${process.env.REDIS_KEY}${refreshToken}`, 'id');
37
+ const redRefreshSession = await redisClient.hGet(`${process.env['REDIS_KEY']}${refreshToken}`, 'id');
38
38
  if (redRefreshSession != null) {
39
39
  ctx.state = {
40
40
  user: {
@@ -53,7 +53,7 @@ export const authenticatedLogoutHandler = (keys) => async (ctx, next) => {
53
53
  // rejected: the access token remains optional here.
54
54
  const accessToken = extractBearerAccessToken(authorization);
55
55
  if (accessToken !== '') {
56
- const redAccessSession = await redisClient.hGet(`${process.env.REDIS_KEY}${accessToken}`, 'id'); // 'access:' already present
56
+ const redAccessSession = await redisClient.hGet(`${process.env['REDIS_KEY']}${accessToken}`, 'id'); // 'access:' already present
57
57
  if (redAccessSession != null) {
58
58
  ctx.state.user.accessToken = accessToken;
59
59
  } // else no problem, session could be expired
@@ -33,7 +33,7 @@ export const authenticatedResourceHandler = () => async (ctx, next) => {
33
33
  throw throwMissingMalformedInvalidToken();
34
34
  }
35
35
  // does the key access:xxx exist in Redis ? read Redis...
36
- const redSession = await redisClient.hGetAll(`${process.env.REDIS_KEY}${key}` // 'access:' present inside key
36
+ const redSession = await redisClient.hGetAll(`${process.env['REDIS_KEY']}${key}` // 'access:' present inside key
37
37
  );
38
38
  if (Object.keys(redSession).length !== 0) {
39
39
  const redData = { ...redSession }; // For safety, Redis return an object without the default Object.prototype in its prototype chain.
@@ -43,7 +43,7 @@ export const authenticatedResourceHandler = () => async (ctx, next) => {
43
43
  }
44
44
  ctx.state.user = {
45
45
  ...redData,
46
- id: new Types.ObjectId(redData.id) // fix id as ObjectId
46
+ id: new Types.ObjectId(redData['id']) // fix id as ObjectId
47
47
  };
48
48
  }
49
49
  else if (!verifyIntrospectionCode(ctx.request.header?.['x-introspectioncode'])) {
@@ -27,7 +27,7 @@ function buildErrorBody(errKoa, isIstanceOfGQL, status) {
27
27
  }
28
28
  // more debug data ?
29
29
  function maybeCaptureSentryError(errKoa, isIstanceOfGQL) {
30
- if (process.env.NODE_ENV === 'development') {
30
+ if (process.env['NODE_ENV'] === 'development') {
31
31
  if (!isIstanceOfGQL) {
32
32
  Sentry.captureException(errKoa);
33
33
  }
@@ -1,9 +1,10 @@
1
1
  export class ArrayLib {
2
2
  constructor() { }
3
3
  arrDiff(arr1, arr2) {
4
- const arrays = [arr1, arr2].sort((a, b) => a.length - b.length);
5
- const smallSet = new Set(arrays[0]);
6
- return arrays[1].filter((x) => !smallSet.has(x));
4
+ const pair = [arr1, arr2];
5
+ const [smaller, larger] = pair.sort((a, b) => a.length - b.length);
6
+ const smallSet = new Set(smaller);
7
+ return larger.filter((x) => !smallSet.has(x));
7
8
  }
8
9
  } /* c8 ignore next */
9
10
  //# sourceMappingURL=ArrayLib.mjs.map
@@ -23,6 +23,7 @@ export const DateLib = class DateLib {
23
23
  return DateLib.timeDiffMin(lastReq, now);
24
24
  }
25
25
  static timeDiffMin(lastReq, now) {
26
+ // Stryker disable next-line EqualityOperator: only the >= replacement is equivalent (lastReq === now makes both ternary arms 0). The <= replacement is NOT equivalent and stays covered: Stryker cannot disable one replacement only, so it was applied by hand and 5 DateLib specs (returns minutes for delta >= 60s, returns absolute diff, ...) plus the resetPwd and updatePassword throttle specs fail on it.
26
27
  const difference = lastReq > now ? lastReq - now : now - lastReq;
27
28
  return Math.floor(difference / (1000 * 60));
28
29
  }
@@ -1,14 +1,66 @@
1
1
  import { randomBytes, randomInt } from 'node:crypto';
2
2
  // 32 chars, a subset of base36. 256 % 32 === 0 so a byte maps uniformly with % 32.
3
3
  const RANDOM_ALPHABET = '0123456789abcdefghijklmnopqrstuv';
4
+ /**
5
+ * Removes every `<...>` tag from `str` in linear time.
6
+ *
7
+ * Output is identical, for every string, to the regex this replaces: `str.replace(/(<([^>]+)>)/gi, '')`.
8
+ * That regex is quadratic (ReDoS, CWE-1333): on input with many `<` and no `>`, each `<` makes the engine
9
+ * scan to the end of the string before it fails, so n characters cost n^2 steps (80k characters took ~1.9 s).
10
+ *
11
+ * Reference semantics, kept exactly:
12
+ * - A tag starts at a `<` and needs at least one character that is not `>` (a newline counts), then a `>`.
13
+ * Hence `<>` is not a tag, while `<\n>` is.
14
+ * - Tags are non-overlapping and found left to right. A `<` inside a tag is consumed with it (`<<a>` -> ``).
15
+ * - A `<` with no later `>` starts nothing, and neither does any `<` after it, so the rest is kept verbatim.
16
+ * - Anything that is not a string (or a `String` object) throws a `TypeError`. The regex form did too, since an
17
+ * array or a Buffer has no `replace`. Without the check they would pass `indexOf` and `slice` and come back
18
+ * unstripped, which turns a sanitizer into a pass-through for untyped input.
19
+ *
20
+ * Algorithm: for a `<` at `open`, the first `>` after it is at `close`. The characters between them are all
21
+ * non-`>` by construction, so `close > open + 1` is exactly the regex condition.
22
+ * - `close === -1`: no `>` exists at or after `open`, so no tag can start here or later. Stop.
23
+ * - `close === open + 1`: the text is `<>`, not a tag. Resume the search for `<` at `close`.
24
+ * - otherwise: drop `open..close`, resume the search for `<` after `close`.
25
+ *
26
+ * Termination and cost: `open` and `keepFrom` only move forward and every iteration advances `open` past its
27
+ * previous value (to a `<` strictly after `open`, or to -1). Each `indexOf('<')` call starts where the previous
28
+ * one stopped, and each `indexOf('>')` call either returns at once (the `<>` case, one character) or its scan
29
+ * ends at `close`, from where the next `<` search resumes. No character is scanned twice by the same search, so
30
+ * the total work is O(n). The single failing `indexOf('>')` (`close === -1`) ends the loop.
31
+ */
32
+ function stripTags(input) {
33
+ if (typeof input !== 'string' && !(input instanceof String)) {
34
+ throw new TypeError('cleanHtml expects a string');
35
+ }
36
+ const str = String(input);
37
+ let out = '';
38
+ let keepFrom = 0;
39
+ let open = str.indexOf('<');
40
+ while (open !== -1) {
41
+ const close = str.indexOf('>', open + 1);
42
+ if (close === -1) {
43
+ break;
44
+ }
45
+ if (close === open + 1) {
46
+ open = str.indexOf('<', close);
47
+ }
48
+ else {
49
+ out += str.slice(keepFrom, open);
50
+ keepFrom = close + 1;
51
+ open = str.indexOf('<', keepFrom);
52
+ }
53
+ }
54
+ return out + str.slice(keepFrom);
55
+ }
4
56
  export class StringLib {
5
57
  // implements IStringLib
6
58
  constructor() { }
7
59
  cleanHtml(str) {
8
- return str.replace(/(<([^>]+)>)/gi, '');
60
+ return stripTags(str);
9
61
  }
10
62
  cleanHtmlUndefined(str) {
11
- return typeof str === 'undefined' ? str : str.replace(/(<([^>]+)>)/gi, '');
63
+ return typeof str === 'undefined' ? str : stripTags(str);
12
64
  }
13
65
  /**
14
66
  * Cryptographically random string of `length` characters.
@@ -70,13 +122,13 @@ export class StringLib {
70
122
  }
71
123
  isoFormatDMY(data) {
72
124
  const d = new Date(data);
73
- return d.getUTCDate() + '/' + (d.getUTCMonth() + +1) + '/' + d.getUTCFullYear();
125
+ return d.getUTCDate() + '/' + (d.getUTCMonth() + 1) + '/' + d.getUTCFullYear();
74
126
  }
75
127
  isoFormatDateTime(data) {
76
128
  const d = new Date(data);
77
129
  return (d.getUTCDate() +
78
130
  '/' +
79
- (d.getUTCMonth() + +1) +
131
+ (d.getUTCMonth() + 1) +
80
132
  '/' +
81
133
  d.getUTCFullYear() +
82
134
  ' ' +
@@ -2,6 +2,7 @@ import { DevStatsGraphQLCalls } from "../../../graphQL/models/MongoDB/log/DevSta
2
2
  export const hitStat = async function (call) {
3
3
  // get last document of stats
4
4
  const ret = await DevStatsGraphQLCalls.find({}).select('_id').sort({ dataora: -1 }).limit(1).lean();
5
+ // empty collection: doc stays undefined and `doc._id` below throws a TypeError, as before noUncheckedIndexedAccess
5
6
  const doc = ret[0];
6
7
  // set true for this call
7
8
  return DevStatsGraphQLCalls.updateOne({ _id: doc._id, 'list.name': call }, { 'list.$.hit': true }, { runValidators: true });
@@ -17,7 +17,7 @@
17
17
  * coherent while the library and the app agree on which environments are permitted to use it.
18
18
  */
19
19
  export function isIntrospectionBypassAllowed() {
20
- const nodeEnv = process.env.NODE_ENV;
20
+ const nodeEnv = process.env['NODE_ENV'];
21
21
  return nodeEnv === 'development' || nodeEnv === 'test';
22
22
  }
23
23
  //# sourceMappingURL=isIntrospectionBypassAllowed.mjs.map
@@ -5,6 +5,6 @@
5
5
  * Use this instead of deleting the token to block user access; set the flag from the control panel.
6
6
  */
7
7
  export function isSessionBlocked(redData) {
8
- return !!(redData?.disabled || redData?.deleted);
8
+ return !!(redData?.['disabled'] || redData?.['deleted']);
9
9
  }
10
10
  //# sourceMappingURL=isSessionBlocked.mjs.map
@@ -11,7 +11,8 @@ export function generateRefreshToken() {
11
11
  }
12
12
  export function accessTokenExpiry() {
13
13
  // Generate a random number between 0 (inclusive) and 1 (exclusive)
14
- const random = Math.random();
14
+ // eslint-disable-next-line sonarjs/pseudo-random -- intentional 30-90 min expiry jitter, not a secret
15
+ const random = Math.random(); // nosemgrep: ajinabraham.njsscan.crypto.crypto_node.node_insecure_random_generator -- 30-90 min expiry jitter, never a secret or token value
15
16
  // Scale it to the desired range (30 to 90)
16
17
  const scaledRandom = random * 61; // 90 - 30 + 1
17
18
  // Shift it to start from 30 and switch to minutes
@@ -9,7 +9,7 @@ export function tryCatchRethrow(e) {
9
9
  if (e instanceof GraphQLError) {
10
10
  // @ts-expect-error status do not exist
11
11
  const status = e.extensions?.http?.status || 500;
12
- const desc = e.extensions?.description || '';
12
+ const desc = e.extensions?.['description'] || '';
13
13
  throw throwGraphQLError(status, e.message, desc);
14
14
  }
15
15
  else {
@@ -16,5 +16,5 @@
16
16
  * Read at call time, never captured in a module-level constant: the ESM module cache would freeze a
17
17
  * constant at first import, and both callers here run at module load of `dataSources/Redis.mts`.
18
18
  */
19
- export const isRedisTlsRequired = () => process.env.REDIS_TLS === 'true';
19
+ export const isRedisTlsRequired = () => process.env['REDIS_TLS'] === 'true';
20
20
  //# sourceMappingURL=isRedisTlsRequired.mjs.map