@axiumine/koa-utils 7.0.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 (89) hide show
  1. package/LICENSE +0 -5
  2. package/README.md +78 -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 +16 -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.d.mts +19 -0
  41. package/dist/private/dataSources/isRedisTlsRequired.mjs +20 -0
  42. package/dist/private/dataSources/redisNodeUrl.d.mts +14 -0
  43. package/dist/private/dataSources/redisNodeUrl.mjs +16 -0
  44. package/dist/private/dataSources/resolveRedisUrl.d.mts +17 -0
  45. package/dist/private/dataSources/resolveRedisUrl.mjs +37 -0
  46. package/dist/private/email/IEmailContent.d.mts +9 -0
  47. package/dist/private/email/IEmailContent.mjs +2 -0
  48. package/dist/private/email/accountMessages.d.mts +11 -0
  49. package/dist/private/email/accountMessages.mjs +55 -0
  50. package/dist/private/email/escapeHtml.d.mts +9 -0
  51. package/dist/private/email/escapeHtml.mjs +17 -0
  52. package/dist/private/email/htmlFrame.d.mts +10 -0
  53. package/dist/private/email/htmlFrame.mjs +25 -0
  54. package/dist/private/email/messageParts.d.mts +12 -0
  55. package/dist/private/email/messageParts.mjs +31 -0
  56. package/dist/private/email/noticeMessages.d.mts +14 -0
  57. package/dist/private/email/noticeMessages.mjs +51 -0
  58. package/dist/private/email/orFalse.d.mts +2 -0
  59. package/dist/private/email/orFalse.mjs +12 -0
  60. package/dist/private/email/resetMessages.d.mts +17 -0
  61. package/dist/private/email/resetMessages.mjs +44 -0
  62. package/dist/private/graphQL/models/MongoDB/private/UserAdminKoaUtils.d.mts +4 -2
  63. package/dist/private/graphQL/schema/mutations/_buildLoginStatsUpdate.mjs +4 -4
  64. package/dist/private/graphQL/schema/mutations/infoUserForLoginSQL.mjs +5 -4
  65. package/dist/private/graphQL/schema/mutations/setRedisLoginSession.mjs +2 -2
  66. package/dist/private/graphQL/schema/mutations/updateLoginStats4ever.mjs +2 -2
  67. package/dist/private/lib/access/applyPasswordReset.d.mts +22 -0
  68. package/dist/private/lib/access/applyPasswordReset.mjs +22 -0
  69. package/dist/private/lib/access/assertResetAllowed.d.mts +14 -0
  70. package/dist/private/lib/access/assertResetAllowed.mjs +51 -0
  71. package/dist/private/lib/access/assertVerifyEmailAllowed.d.mts +6 -1
  72. package/dist/private/lib/access/db/abandonUser.mjs +3 -0
  73. package/dist/private/lib/access/db/confirmNewEmail.mjs +2 -0
  74. package/dist/private/lib/access/db/deleteUserByEmail.mjs +2 -0
  75. package/dist/private/lib/access/db/enableEmailAccess.mjs +2 -0
  76. package/dist/private/lib/access/db/getResetPwd.mjs +2 -0
  77. package/dist/private/lib/access/db/removeResetReq.mjs +2 -0
  78. package/dist/private/lib/access/db/saveResetReq.mjs +2 -0
  79. package/dist/private/lib/access/db/setEmailHash.mjs +2 -0
  80. package/dist/private/lib/access/db/updatePasswordDb.mjs +2 -0
  81. package/dist/private/lib/access/db/userData4VerifyEmail.mjs +2 -0
  82. package/dist/private/lib/access/emailChangeHandlers.d.mts +35 -0
  83. package/dist/private/lib/access/emailChangeHandlers.mjs +87 -0
  84. package/dist/private/lib/access/handleIfHashBad.d.mts +4 -2
  85. package/dist/private/lib/access/handleIfHashBad.mjs +4 -1
  86. package/dist/private/lib/access/safeEqualSecret.d.mts +13 -0
  87. package/dist/private/lib/access/safeEqualSecret.mjs +26 -0
  88. package/dist/private/lib/verifyIntrospectionCode.mjs +1 -1
  89. package/package.json +59 -25
@@ -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 {
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Does this process require a TLS Redis connection?
3
+ *
4
+ * True only when `process.env.REDIS_TLS` is exactly the string `'true'`. Every other value — unset,
5
+ * empty, `'1'`, `'TRUE'`, `'yes'` — returns `false` and leaves the plaintext `redis://` scheme in
6
+ * place, byte-for-byte the behaviour every deployment had before this flag existed.
7
+ *
8
+ * ⚠️ The match is exact, and the trade-off it makes is deliberate rather than an oversight. A
9
+ * misspelled value (`REDIS_TLS=TRUE`, `REDIS_TLS=1`) silently leaves the connection on plaintext
10
+ * instead of failing, which is the price of keeping the flag strictly opt-in: the accepted spelling
11
+ * is documented in `README.md`, and the gate is loud in the other direction — once the flag is on,
12
+ * a non-`rediss://` `REDIS_URL` refuses to boot at all. Do not widen this to a truthiness test: `Boolean(process.env.REDIS_TLS)` reads the literal string
13
+ * `'false'` as true, and `process.env.REDIS_TLS !== 'false'` enables TLS for an unset variable —
14
+ * both change the scheme of connections whose operator never asked for it.
15
+ *
16
+ * Read at call time, never captured in a module-level constant: the ESM module cache would freeze a
17
+ * constant at first import, and both callers here run at module load of `dataSources/Redis.mts`.
18
+ */
19
+ export declare const isRedisTlsRequired: () => boolean;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Does this process require a TLS Redis connection?
3
+ *
4
+ * True only when `process.env.REDIS_TLS` is exactly the string `'true'`. Every other value — unset,
5
+ * empty, `'1'`, `'TRUE'`, `'yes'` — returns `false` and leaves the plaintext `redis://` scheme in
6
+ * place, byte-for-byte the behaviour every deployment had before this flag existed.
7
+ *
8
+ * ⚠️ The match is exact, and the trade-off it makes is deliberate rather than an oversight. A
9
+ * misspelled value (`REDIS_TLS=TRUE`, `REDIS_TLS=1`) silently leaves the connection on plaintext
10
+ * instead of failing, which is the price of keeping the flag strictly opt-in: the accepted spelling
11
+ * is documented in `README.md`, and the gate is loud in the other direction — once the flag is on,
12
+ * a non-`rediss://` `REDIS_URL` refuses to boot at all. Do not widen this to a truthiness test: `Boolean(process.env.REDIS_TLS)` reads the literal string
13
+ * `'false'` as true, and `process.env.REDIS_TLS !== 'false'` enables TLS for an unset variable —
14
+ * both change the scheme of connections whose operator never asked for it.
15
+ *
16
+ * Read at call time, never captured in a module-level constant: the ESM module cache would freeze a
17
+ * constant at first import, and both callers here run at module load of `dataSources/Redis.mts`.
18
+ */
19
+ export const isRedisTlsRequired = () => process.env['REDIS_TLS'] === 'true';
20
+ //# sourceMappingURL=isRedisTlsRequired.mjs.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Builds one cluster root-node URL — `redis://host:port`, or `rediss://host:port` when
3
+ * `isRedisTlsRequired()`.
4
+ *
5
+ * This lives in its own module so the scheme choice stays unit-tested. Its only call site is the
6
+ * `createCluster` arm of `dataSources/Redis.mts`, which is `c8 ignore`d wholesale because it needs
7
+ * `REDIS_IS_CLUSTER=1` plus three live nodes; interpolating the scheme inline there would park the
8
+ * one security-relevant decision of that arm outside coverage.
9
+ *
10
+ * `host` and `port` are interpolated exactly as the previous inline template did, `undefined`
11
+ * included — an unset `REDIS_DB1_HOST` still yields the literal `'undefined'` in the URL. Validating
12
+ * them is out of scope here and intentionally unchanged.
13
+ */
14
+ export declare const redisNodeUrl: (host: string | undefined, port: string | undefined) => string;
@@ -0,0 +1,16 @@
1
+ import { isRedisTlsRequired } from './isRedisTlsRequired.mjs';
2
+ /**
3
+ * Builds one cluster root-node URL — `redis://host:port`, or `rediss://host:port` when
4
+ * `isRedisTlsRequired()`.
5
+ *
6
+ * This lives in its own module so the scheme choice stays unit-tested. Its only call site is the
7
+ * `createCluster` arm of `dataSources/Redis.mts`, which is `c8 ignore`d wholesale because it needs
8
+ * `REDIS_IS_CLUSTER=1` plus three live nodes; interpolating the scheme inline there would park the
9
+ * one security-relevant decision of that arm outside coverage.
10
+ *
11
+ * `host` and `port` are interpolated exactly as the previous inline template did, `undefined`
12
+ * included — an unset `REDIS_DB1_HOST` still yields the literal `'undefined'` in the URL. Validating
13
+ * them is out of scope here and intentionally unchanged.
14
+ */
15
+ export const redisNodeUrl = (host, port) => `${isRedisTlsRequired() ? 'rediss' : 'redis'}://${host}:${port}`;
16
+ //# sourceMappingURL=redisNodeUrl.mjs.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Returns the standalone-client connection URL, refusing a plaintext one when TLS is required.
3
+ *
4
+ * With `REDIS_TLS` off this is a pass-through: `REDIS_URL` reaches `createClient` untouched,
5
+ * `undefined` included, exactly as before the flag existed.
6
+ *
7
+ * With `REDIS_TLS=true` the URL must carry the `rediss:` scheme; anything else throws here, at
8
+ * module load of `dataSources/Redis.mts`, before a socket is ever opened. Fail-closed rather than a
9
+ * silent upgrade to `rediss://`: rewriting the scheme under an operator who wrote `redis://` hides
10
+ * the misconfiguration until the TLS handshake fails, against a host that may not be the intended
11
+ * one. Refusing at load turns it into a single unmissable startup error instead.
12
+ *
13
+ * The scheme is read through `new URL()` rather than `startsWith`, so it is compared the way
14
+ * node-redis compares it — `URL` lower-cases the protocol, which makes `REDISS://host:6379` a valid
15
+ * TLS URL both here and in `RedisClient.parseURL`.
16
+ */
17
+ export declare const resolveRedisUrl: (url: string | undefined) => string | undefined;
@@ -0,0 +1,37 @@
1
+ import { isRedisTlsRequired } from './isRedisTlsRequired.mjs';
2
+ /**
3
+ * Returns the standalone-client connection URL, refusing a plaintext one when TLS is required.
4
+ *
5
+ * With `REDIS_TLS` off this is a pass-through: `REDIS_URL` reaches `createClient` untouched,
6
+ * `undefined` included, exactly as before the flag existed.
7
+ *
8
+ * With `REDIS_TLS=true` the URL must carry the `rediss:` scheme; anything else throws here, at
9
+ * module load of `dataSources/Redis.mts`, before a socket is ever opened. Fail-closed rather than a
10
+ * silent upgrade to `rediss://`: rewriting the scheme under an operator who wrote `redis://` hides
11
+ * the misconfiguration until the TLS handshake fails, against a host that may not be the intended
12
+ * one. Refusing at load turns it into a single unmissable startup error instead.
13
+ *
14
+ * The scheme is read through `new URL()` rather than `startsWith`, so it is compared the way
15
+ * node-redis compares it — `URL` lower-cases the protocol, which makes `REDISS://host:6379` a valid
16
+ * TLS URL both here and in `RedisClient.parseURL`.
17
+ */
18
+ export const resolveRedisUrl = (url) => {
19
+ if (!isRedisTlsRequired()) {
20
+ return url;
21
+ }
22
+ if (typeof url !== 'string' || url.length === 0) {
23
+ throw new Error('[Redis] REDIS_TLS is enabled but REDIS_URL is not set — a rediss:// URL is required.');
24
+ }
25
+ let protocol;
26
+ try {
27
+ protocol = new URL(url).protocol;
28
+ }
29
+ catch {
30
+ throw new Error('[Redis] REDIS_TLS is enabled but REDIS_URL is not a valid URL — a rediss:// URL is required.');
31
+ }
32
+ if (protocol !== 'rediss:') {
33
+ throw new Error(`[Redis] REDIS_TLS is enabled but REDIS_URL uses scheme "${protocol}" — rediss:// required.`);
34
+ }
35
+ return url;
36
+ };
37
+ //# sourceMappingURL=resolveRedisUrl.mjs.map
@@ -0,0 +1,9 @@
1
+ /**
2
+ * One outgoing message as the three strings `SocketLabsLib` hands to SocketLabs. `subject` and `textBody` carry
3
+ * the raw values; every value interpolated into `htmlBody` has already been escaped for its HTML context.
4
+ */
5
+ export interface IEmailContent {
6
+ subject: string;
7
+ textBody: string;
8
+ htmlBody: string;
9
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=IEmailContent.mjs.map
@@ -0,0 +1,11 @@
1
+ import type { IEmailContent } from './IEmailContent.mjs';
2
+ /** Registration confirmation. `link` is the finished confirmation URL. */
3
+ export declare function verifyMessage(platformName: string, link: string, name: string): IEmailContent;
4
+ /** Email-change confirmation. `link` is the finished confirmation URL. */
5
+ export declare function changeVerifyMessage(platformName: string, link: string, name: string): IEmailContent;
6
+ /** Welcome mail linking to the platform home. */
7
+ export declare function welcomeMessage(platformName: string, linkBase: string): IEmailContent;
8
+ /** Subscription confirmation with the activation code. */
9
+ export declare function subscriptionMessage(platformName: string, linkBase: string, otp: string): IEmailContent;
10
+ /** One-time code mail. */
11
+ export declare function otpMessage(platformName: string, otp: string): IEmailContent;
@@ -0,0 +1,55 @@
1
+ import { escapeHtml } from './escapeHtml.mjs';
2
+ import { fixName, htmlLink } from './messageParts.mjs';
3
+ /** Registration confirmation. `link` is the finished confirmation URL. */
4
+ export function verifyMessage(platformName, link, name) {
5
+ const nameFixed = fixName(name);
6
+ const platform = escapeHtml(platformName);
7
+ return {
8
+ subject: `Confirm your email for ${platformName}`,
9
+ textBody: `Hi${nameFixed}, you or someone else is registering you on ${platformName}.
10
+ You can confirm the registration by copying this link ${link} into your browser. The Team`,
11
+ htmlBody: `Hi${escapeHtml(nameFixed)},<br>you or someone else is registering you on ${platform}.<br><br>
12
+ You can confirm the registration by visiting this link ${htmlLink(link)}<br><br>
13
+ <br><br>The Team`
14
+ };
15
+ }
16
+ /** Email-change confirmation. `link` is the finished confirmation URL. */
17
+ export function changeVerifyMessage(platformName, link, name) {
18
+ const nameFixed = fixName(name);
19
+ return {
20
+ subject: `Confirm your email for ${platformName}`,
21
+ textBody: `Hi${nameFixed}, you or someone else has changed the email you sign in with.
22
+ You can confirm by copying this link ${link} into your browser. The Team.`,
23
+ htmlBody: `Hi${escapeHtml(nameFixed)},<br>you or someone else has changed the email you sign in with.<br><br>
24
+ You can confirm the registration by visiting this link ${htmlLink(link)}
25
+ <br><br>The Team.`
26
+ };
27
+ }
28
+ /** Welcome mail linking to the platform home. */
29
+ export function welcomeMessage(platformName, linkBase) {
30
+ return {
31
+ subject: `Welcome to ${platformName}`,
32
+ textBody: `Welcome to ${platformName}`,
33
+ htmlBody: `Welcome to ${htmlLink(linkBase, platformName)}`
34
+ };
35
+ }
36
+ /** Subscription confirmation with the activation code. */
37
+ export function subscriptionMessage(platformName, linkBase, otp) {
38
+ const url = `${linkBase}/x/emailVerify`;
39
+ return {
40
+ subject: `Activate your ${platformName} account`,
41
+ textBody: `To confirm your subscription on ${platformName}, open the following link in your browser
42
+ ${url} and enter the following activation code: ${otp}`,
43
+ htmlBody: `<p>To confirm your subscription on ${htmlLink(linkBase, platformName)}, open the following link in your browser
44
+ ${htmlLink(url)} and enter the following activation code: ${escapeHtml(otp)}</p>`
45
+ };
46
+ }
47
+ /** One-time code mail. */
48
+ export function otpMessage(platformName, otp) {
49
+ return {
50
+ subject: `OTP code for ${platformName}`,
51
+ textBody: `To confirm your subscription on ${platformName}, enter the following OTP code: ${otp}`,
52
+ htmlBody: `<p>To confirm your subscription on ${escapeHtml(platformName)}, enter the following OTP code: ${escapeHtml(otp)}</p>`
53
+ };
54
+ }
55
+ //# sourceMappingURL=accountMessages.mjs.map
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Escape a value for HTML text content and for a quoted attribute value (`"` or `'`).
3
+ *
4
+ * The one place the mail templates escape: `&` goes first so the entities added after it are not escaped
5
+ * again. Non-ASCII characters pass through untouched, since the mail is sent as UTF-8. A number is accepted
6
+ * because callers interpolate ids that may arrive as one, and anything else is stringified the way the old
7
+ * string concatenation did.
8
+ */
9
+ export declare function escapeHtml(value: string | number): string;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Escape a value for HTML text content and for a quoted attribute value (`"` or `'`).
3
+ *
4
+ * The one place the mail templates escape: `&` goes first so the entities added after it are not escaped
5
+ * again. Non-ASCII characters pass through untouched, since the mail is sent as UTF-8. A number is accepted
6
+ * because callers interpolate ids that may arrive as one, and anything else is stringified the way the old
7
+ * string concatenation did.
8
+ */
9
+ export function escapeHtml(value) {
10
+ return String(value)
11
+ .replaceAll('&', '&amp;')
12
+ .replaceAll('<', '&lt;')
13
+ .replaceAll('>', '&gt;')
14
+ .replaceAll('"', '&quot;')
15
+ .replaceAll("'", '&#39;');
16
+ }
17
+ //# sourceMappingURL=escapeHtml.mjs.map
@@ -0,0 +1,10 @@
1
+ /** Fallback header, first half: everything up to the opening `<title>` tag. */
2
+ export declare const FALLBACK_HEADER_1: string;
3
+ /** Fallback header, second half: from `</title>` to the opening of the content paragraph. */
4
+ export declare const FALLBACK_HEADER_2: string;
5
+ /** Fallback footer: closes the paragraph, cell, row, table and body the header opened. */
6
+ export declare const FALLBACK_FOOTER: string;
7
+ /** Standalone header for the legacy mails that build a full document; `title` is escaped. */
8
+ export declare function standaloneHeader(title: string): string;
9
+ /** A custom fragment from the constructor, or the fallback when none was given. */
10
+ export declare function orFallback(custom: string, fallback: string): string;