@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.
- package/LICENSE +0 -5
- package/README.md +55 -3
- package/dist/dataSources/MariaDB.mjs +8 -6
- package/dist/dataSources/MongoDB.mjs +1 -1
- package/dist/dataSources/PostgreSQL.mjs +12 -12
- package/dist/dataSources/Redis.mjs +8 -7
- package/dist/email/SocketLabsLib.d.mts +6 -15
- package/dist/email/SocketLabsLib.mjs +54 -210
- package/dist/files/moveFileStaticDomain.mjs +1 -1
- package/dist/files/storeUploadAsTemp.mjs +5 -1
- package/dist/files/uploadTempImage.mjs +2 -1
- package/dist/files/uploadTempPdf.mjs +2 -1
- package/dist/graphQL/models/MongoDB/UserBase.d.mts +3 -1
- package/dist/graphQL/models/MongoDB/log/DevStatsGraphQLCalls.d.mts +3 -1
- package/dist/graphQL/models/MongoDB/log/LogGlobalError.d.mts +3 -1
- package/dist/graphQL/models/MongoDB/log/LogStatsGraphql.d.mts +3 -1
- package/dist/graphQL/models/MongoDB/log/LogThrow.d.mts +3 -1
- package/dist/graphQL/schema/mutations/emailChangeHashVerify.mjs +8 -76
- package/dist/graphQL/schema/mutations/login4Ever.mjs +1 -0
- package/dist/graphQL/schema/mutations/loginAdmin.mjs +1 -0
- package/dist/graphQL/schema/mutations/loginRememberme.mjs +1 -0
- package/dist/graphQL/schema/mutations/logout.mjs +2 -2
- package/dist/graphQL/schema/mutations/refresh.mjs +7 -5
- package/dist/graphQL/schema/mutations/resetPwd.d.mts +1 -1
- package/dist/graphQL/schema/mutations/signUp.mjs +1 -0
- package/dist/graphQL/schema/mutations/updatePassword.mjs +1 -48
- package/dist/koa/middleware/authenticatedAuthorizationHandler/index.mjs +2 -2
- package/dist/koa/middleware/authenticatedAuthorizationHandler/verifySignedRefreshToken.mjs +2 -0
- package/dist/koa/middleware/authenticatedLogoutHandler/index.mjs +2 -2
- package/dist/koa/middleware/authenticatedResourceHandler/index.mjs +2 -2
- package/dist/koa/tdwKoaErrorHandler.mjs +1 -1
- package/dist/lib/ArrayLib.mjs +4 -3
- package/dist/lib/DateLib.mjs +1 -0
- package/dist/lib/StringLib.mjs +56 -4
- package/dist/lib/access/resetPwdMailer.d.mts +3 -0
- package/dist/lib/access/resetPwdMailer.mjs +3 -0
- package/dist/lib/db/log/hitStat.mjs +1 -0
- package/dist/lib/isIntrospectionBypassAllowed.mjs +1 -1
- package/dist/lib/isSessionBlocked.mjs +1 -1
- package/dist/lib/tokens.mjs +2 -1
- package/dist/lib/tryCatchRethrow.mjs +1 -1
- package/dist/private/dataSources/isRedisTlsRequired.mjs +1 -1
- package/dist/private/email/IEmailContent.d.mts +9 -0
- package/dist/private/email/IEmailContent.mjs +2 -0
- package/dist/private/email/accountMessages.d.mts +11 -0
- package/dist/private/email/accountMessages.mjs +57 -0
- package/dist/private/email/escapeHtml.d.mts +9 -0
- package/dist/private/email/escapeHtml.mjs +17 -0
- package/dist/private/email/htmlFrame.d.mts +10 -0
- package/dist/private/email/htmlFrame.mjs +25 -0
- package/dist/private/email/messageParts.d.mts +21 -0
- package/dist/private/email/messageParts.mjs +65 -0
- package/dist/private/email/noticeMessages.d.mts +14 -0
- package/dist/private/email/noticeMessages.mjs +51 -0
- package/dist/private/email/orFalse.d.mts +2 -0
- package/dist/private/email/orFalse.mjs +12 -0
- package/dist/private/email/resetMessages.d.mts +17 -0
- package/dist/private/email/resetMessages.mjs +46 -0
- package/dist/private/graphQL/models/MongoDB/private/UserAdminKoaUtils.d.mts +4 -2
- package/dist/private/graphQL/schema/mutations/_buildLoginStatsUpdate.mjs +4 -4
- package/dist/private/graphQL/schema/mutations/infoUserForLoginSQL.mjs +5 -4
- package/dist/private/graphQL/schema/mutations/setRedisLoginSession.mjs +2 -2
- package/dist/private/graphQL/schema/mutations/updateLoginStats4ever.mjs +2 -2
- package/dist/private/lib/access/applyPasswordReset.d.mts +22 -0
- package/dist/private/lib/access/applyPasswordReset.mjs +22 -0
- package/dist/private/lib/access/assertResetAllowed.d.mts +14 -0
- package/dist/private/lib/access/assertResetAllowed.mjs +51 -0
- package/dist/private/lib/access/assertVerifyEmailAllowed.d.mts +6 -1
- package/dist/private/lib/access/db/abandonUser.mjs +3 -0
- package/dist/private/lib/access/db/confirmNewEmail.mjs +2 -0
- package/dist/private/lib/access/db/deleteUserByEmail.mjs +2 -0
- package/dist/private/lib/access/db/enableEmailAccess.mjs +9 -1
- package/dist/private/lib/access/db/getResetPwd.mjs +2 -0
- package/dist/private/lib/access/db/removeResetReq.mjs +2 -0
- package/dist/private/lib/access/db/saveResetReq.mjs +2 -0
- package/dist/private/lib/access/db/setEmailHash.mjs +2 -0
- package/dist/private/lib/access/db/updatePasswordDb.mjs +2 -0
- package/dist/private/lib/access/db/userData4VerifyEmail.mjs +2 -0
- package/dist/private/lib/access/emailChangeHandlers.d.mts +35 -0
- package/dist/private/lib/access/emailChangeHandlers.mjs +87 -0
- package/dist/private/lib/access/handleIfHashBad.d.mts +4 -2
- package/dist/private/lib/access/handleIfHashBad.mjs +4 -1
- package/dist/private/lib/access/safeEqualSecret.d.mts +13 -0
- package/dist/private/lib/access/safeEqualSecret.mjs +26 -0
- package/dist/private/lib/verifyIntrospectionCode.d.mts +4 -0
- package/dist/private/lib/verifyIntrospectionCode.mjs +8 -14
- package/package.json +62 -25
|
@@ -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
|
|
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
|
|
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
|
-
|
|
21
|
-
const keyAccess = `${process.env
|
|
22
|
-
const keyRefresh = `${process.env
|
|
23
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
30
|
+
if (process.env['NODE_ENV'] === 'development') {
|
|
31
31
|
if (!isIstanceOfGQL) {
|
|
32
32
|
Sentry.captureException(errKoa);
|
|
33
33
|
}
|
package/dist/lib/ArrayLib.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
export class ArrayLib {
|
|
2
2
|
constructor() { }
|
|
3
3
|
arrDiff(arr1, arr2) {
|
|
4
|
-
const
|
|
5
|
-
const
|
|
6
|
-
|
|
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
|
package/dist/lib/DateLib.mjs
CHANGED
|
@@ -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
|
}
|
package/dist/lib/StringLib.mjs
CHANGED
|
@@ -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
|
|
60
|
+
return stripTags(str);
|
|
9
61
|
}
|
|
10
62
|
cleanHtmlUndefined(str) {
|
|
11
|
-
return typeof str === 'undefined' ? str : str
|
|
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() +
|
|
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() +
|
|
131
|
+
(d.getUTCMonth() + 1) +
|
|
80
132
|
'/' +
|
|
81
133
|
d.getUTCFullYear() +
|
|
82
134
|
' ' +
|
|
@@ -37,6 +37,9 @@ export declare const socketLabsResetPwdMailer: IResetPwdMailer;
|
|
|
37
37
|
* arrives as `undefined` and the default takes over — `APP_DOMAIN` for the base, `/x/reset` for the path.
|
|
38
38
|
* Normalising that to `''` at the call site instead would produce a link with no host at all.
|
|
39
39
|
*
|
|
40
|
+
* `linkBase` must be an absolute `http:` / `https:` URL. Anything else (`javascript:`, `//host`, a host with no
|
|
41
|
+
* scheme, `''`) makes `sendEmailReset` reject with a 500 and send nothing.
|
|
42
|
+
*
|
|
40
43
|
* ⚠️ `linkPath` names a **front-end route**, not a backend mount. It has to match the route that renders
|
|
41
44
|
* the new-password form in the app `linkBase` serves; there is nothing on the server side that would fail
|
|
42
45
|
* loudly if it does not, because the link is only ever followed by a person.
|
|
@@ -21,6 +21,9 @@ export const socketLabsResetPwdMailer = {
|
|
|
21
21
|
* arrives as `undefined` and the default takes over — `APP_DOMAIN` for the base, `/x/reset` for the path.
|
|
22
22
|
* Normalising that to `''` at the call site instead would produce a link with no host at all.
|
|
23
23
|
*
|
|
24
|
+
* `linkBase` must be an absolute `http:` / `https:` URL. Anything else (`javascript:`, `//host`, a host with no
|
|
25
|
+
* scheme, `''`) makes `sendEmailReset` reject with a 500 and send nothing.
|
|
26
|
+
*
|
|
24
27
|
* ⚠️ `linkPath` names a **front-end route**, not a backend mount. It has to match the route that renders
|
|
25
28
|
* the new-password form in the app `linkBase` serves; there is nothing on the server side that would fail
|
|
26
29
|
* loudly if it does not, because the link is only ever followed by a person.
|
|
@@ -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
|
|
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
|
package/dist/lib/tokens.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
|
19
|
+
export const isRedisTlsRequired = () => process.env['REDIS_TLS'] === 'true';
|
|
20
20
|
//# sourceMappingURL=isRedisTlsRequired.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,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,57 @@
|
|
|
1
|
+
import { escapeHtml } from './escapeHtml.mjs';
|
|
2
|
+
import { fixName, htmlLink, httpLinkBase } 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
|
+
const base = httpLinkBase(linkBase);
|
|
31
|
+
return {
|
|
32
|
+
subject: `Welcome to ${platformName}`,
|
|
33
|
+
textBody: `Welcome to ${platformName}`,
|
|
34
|
+
htmlBody: `Welcome to ${htmlLink(base, platformName)}`
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Subscription confirmation with the activation code. */
|
|
38
|
+
export function subscriptionMessage(platformName, linkBase, otp) {
|
|
39
|
+
const base = httpLinkBase(linkBase);
|
|
40
|
+
const url = `${base}/x/emailVerify`;
|
|
41
|
+
return {
|
|
42
|
+
subject: `Activate your ${platformName} account`,
|
|
43
|
+
textBody: `To confirm your subscription on ${platformName}, open the following link in your browser
|
|
44
|
+
${url} and enter the following activation code: ${otp}`,
|
|
45
|
+
htmlBody: `<p>To confirm your subscription on ${htmlLink(base, platformName)}, open the following link in your browser
|
|
46
|
+
${htmlLink(url)} and enter the following activation code: ${escapeHtml(otp)}</p>`
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** One-time code mail. */
|
|
50
|
+
export function otpMessage(platformName, otp) {
|
|
51
|
+
return {
|
|
52
|
+
subject: `OTP code for ${platformName}`,
|
|
53
|
+
textBody: `To confirm your subscription on ${platformName}, enter the following OTP code: ${otp}`,
|
|
54
|
+
htmlBody: `<p>To confirm your subscription on ${escapeHtml(platformName)}, enter the following OTP code: ${escapeHtml(otp)}</p>`
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
//# 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('&', '&')
|
|
12
|
+
.replaceAll('<', '<')
|
|
13
|
+
.replaceAll('>', '>')
|
|
14
|
+
.replaceAll('"', '"')
|
|
15
|
+
.replaceAll("'", ''');
|
|
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;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { escapeHtml } from './escapeHtml.mjs';
|
|
2
|
+
const DOCTYPE = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
|
|
3
|
+
const HEAD_OPEN = ' <head>' + ' <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' + ' <title>';
|
|
4
|
+
/** Fallback header, first half: everything up to the opening `<title>` tag. */
|
|
5
|
+
export const FALLBACK_HEADER_1 = DOCTYPE + '<html lang="en" xmlns="http://www.w3.org/1999/xhtml">' + HEAD_OPEN;
|
|
6
|
+
/** Fallback header, second half: from `</title>` to the opening of the content paragraph. */
|
|
7
|
+
export const FALLBACK_HEADER_2 = '</title>' +
|
|
8
|
+
' <meta name="viewport" content="width=device-width, initial-scale=1.0"/>' +
|
|
9
|
+
'</head>' +
|
|
10
|
+
'</html>' +
|
|
11
|
+
'<body style="margin: 0; padding: 0;">' +
|
|
12
|
+
' <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">' +
|
|
13
|
+
' <tr>' +
|
|
14
|
+
' <td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;"><p style="color: #000000; font-family: Verdana, sans-serif; font-size: 12pt;">';
|
|
15
|
+
/** Fallback footer: closes the paragraph, cell, row, table and body the header opened. */
|
|
16
|
+
export const FALLBACK_FOOTER = '</p></td>' + ' </tr>' + ' </table>' + '</body>';
|
|
17
|
+
/** Standalone header for the legacy mails that build a full document; `title` is escaped. */
|
|
18
|
+
export function standaloneHeader(title) {
|
|
19
|
+
return DOCTYPE + '<html xmlns="http://www.w3.org/1999/xhtml">' + HEAD_OPEN + escapeHtml(title) + FALLBACK_HEADER_2;
|
|
20
|
+
}
|
|
21
|
+
/** A custom fragment from the constructor, or the fallback when none was given. */
|
|
22
|
+
export function orFallback(custom, fallback) {
|
|
23
|
+
return custom === '' ? fallback : custom;
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=htmlFrame.mjs.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Greeting suffix: a leading space plus the name, or nothing when there is no name. */
|
|
2
|
+
export declare function fixName(name: string): string;
|
|
3
|
+
/**
|
|
4
|
+
* Anchor for the HTML part. The URL goes into a single-quoted `href` and the text into element content, so both
|
|
5
|
+
* pass through {@link escapeHtml}; the plain-text part keeps the unescaped URL.
|
|
6
|
+
*/
|
|
7
|
+
export declare function htmlLink(link: string, linkText?: string): string;
|
|
8
|
+
/**
|
|
9
|
+
* The scheme + host every link in a mail is built on, checked before it is placed in a link or an `href`.
|
|
10
|
+
* Returns `linkBase` exactly as given when it is an absolute `http:` / `https:` URL; otherwise throws
|
|
11
|
+
* `throwInternalError()` (500 `Internal Server Error`, `Error reported to Dev Team.`), as `wrongHashMessage`
|
|
12
|
+
* does: a base that is not one is a configuration or caller mistake, never something the recipient can fix,
|
|
13
|
+
* and the mail is not sent. Escaping alone does not cover this: a `javascript:` base survives `escapeHtml`
|
|
14
|
+
* and becomes a link target.
|
|
15
|
+
*/
|
|
16
|
+
export declare function httpLinkBase(linkBase: string): string;
|
|
17
|
+
/**
|
|
18
|
+
* Confirmation or reset link: `<base><path>/<encodeURI(email)>/<hash>`. A trailing slash on `linkBase` and a
|
|
19
|
+
* missing leading slash on `linkPath` are normalised away. `linkBase` goes through {@link httpLinkBase} first.
|
|
20
|
+
*/
|
|
21
|
+
export declare function confirmationLink(linkBase: string, linkPath: string, emailTo: string, hash: string): string;
|