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