@axiumine/koa-utils 5.6.1 → 5.7.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/README.md +10 -1
- package/dist/graphQL/schema/mutations/emailChangeHashVerify.d.mts +7 -0
- package/dist/graphQL/schema/mutations/emailChangeHashVerify.mjs +38 -35
- package/dist/graphQL/schema/mutations/emailChangeHashVerify.mjs.map +1 -1
- package/dist/lib/access/accessPaths.d.mts +18 -0
- package/dist/lib/access/accessPaths.mjs.map +1 -1
- package/dist/lib/access/createMailThrottle.d.mts +34 -0
- package/dist/lib/access/createMailThrottle.mjs +45 -0
- package/dist/lib/access/createMailThrottle.mjs.map +1 -0
- package/dist/lib/access/createVerifyEmailFlow.d.mts +37 -4
- package/dist/lib/access/createVerifyEmailFlow.mjs +33 -10
- package/dist/lib/access/createVerifyEmailFlow.mjs.map +1 -1
- package/dist/lib/access/verifyEmailMailer.d.mts +54 -0
- package/dist/lib/access/verifyEmailMailer.mjs +48 -0
- package/dist/lib/access/verifyEmailMailer.mjs.map +1 -0
- package/dist/private/lib/access/assertVerifyEmailAllowed.d.mts +13 -1
- package/dist/private/lib/access/assertVerifyEmailAllowed.mjs +7 -4
- package/dist/private/lib/access/assertVerifyEmailAllowed.mjs.map +1 -1
- package/dist/private/lib/access/db/abandonUser.d.mts +25 -0
- package/dist/private/lib/access/db/abandonUser.mjs +26 -0
- package/dist/private/lib/access/db/abandonUser.mjs.map +1 -0
- package/dist/private/lib/access/db/deleteUserByEmail.d.mts +7 -0
- package/dist/private/lib/access/db/deleteUserByEmail.mjs +15 -4
- package/dist/private/lib/access/db/deleteUserByEmail.mjs.map +1 -1
- package/dist/private/lib/access/db/enableEmailAccess.d.mts +9 -1
- package/dist/private/lib/access/db/enableEmailAccess.mjs +11 -5
- package/dist/private/lib/access/db/enableEmailAccess.mjs.map +1 -1
- package/dist/private/lib/access/handleBadDB.d.mts +11 -0
- package/dist/private/lib/access/handleBadDB.mjs +13 -1
- package/dist/private/lib/access/handleBadDB.mjs.map +1 -1
- package/dist/private/lib/access/handleIfAccountDeleted.d.mts +16 -1
- package/dist/private/lib/access/handleIfAccountDeleted.mjs +16 -5
- package/dist/private/lib/access/handleIfAccountDeleted.mjs.map +1 -1
- package/dist/private/lib/access/handleIfAccountDisabled.d.mts +15 -1
- package/dist/private/lib/access/handleIfAccountDisabled.mjs +15 -5
- package/dist/private/lib/access/handleIfAccountDisabled.mjs.map +1 -1
- package/dist/private/lib/access/handleIfEmailAlreadyValid.d.mts +18 -1
- package/dist/private/lib/access/handleIfEmailAlreadyValid.mjs +18 -5
- package/dist/private/lib/access/handleIfEmailAlreadyValid.mjs.map +1 -1
- package/dist/private/lib/access/handleIfHashBad.d.mts +5 -1
- package/dist/private/lib/access/handleIfHashBad.mjs +7 -5
- package/dist/private/lib/access/handleIfHashBad.mjs.map +1 -1
- package/dist/private/lib/access/handleIfMoreThan3DaysPassed.d.mts +8 -4
- package/dist/private/lib/access/handleIfMoreThan3DaysPassed.mjs +10 -8
- package/dist/private/lib/access/handleIfMoreThan3DaysPassed.mjs.map +1 -1
- package/dist/private/lib/access/handleIfTooMuchRequestsTimes.d.mts +7 -4
- package/dist/private/lib/access/handleIfTooMuchRequestsTimes.mjs +9 -8
- package/dist/private/lib/access/handleIfTooMuchRequestsTimes.mjs.map +1 -1
- package/package.json +9 -1
package/README.md
CHANGED
|
@@ -98,12 +98,21 @@ const { resetPwd, updatePassword } = createResetPwdFlow({
|
|
|
98
98
|
}
|
|
99
99
|
})
|
|
100
100
|
|
|
101
|
-
const verify = createVerifyEmailFlow({
|
|
101
|
+
const verify = createVerifyEmailFlow({
|
|
102
|
+
model: Account,
|
|
103
|
+
paths: { email: 'mail', valid: 'verified' },
|
|
104
|
+
onAbandon: 'soft-delete', // 'delete' (default) | 'soft-delete' | 'keep'
|
|
105
|
+
deletedValue: () => new Date() // what 'soft-delete' writes; default true
|
|
106
|
+
})
|
|
102
107
|
router.get('/check/verify-email/:email/:hash', verify.routerVerifyEmail())
|
|
103
108
|
```
|
|
104
109
|
|
|
105
110
|
Every `paths` key is optional and falls back to the `UserBase` layout, so the package-level exports are exactly these factories with no overrides. See [docs/code/lib-access.md](./docs/code/lib-access.md).
|
|
106
111
|
|
|
112
|
+
`onAbandon` decides what the two disposal guards — the fifth wrong hash and a link older than 3 days — do to a pending registration. The default `'delete'` removes the row; use `'soft-delete'` or `'keep'` when other collections depend on it, since mongo has no cascade, or pass `deleteUserByEmail` to replace the writer outright. The link is rejected either way.
|
|
113
|
+
|
|
114
|
+
Guard notifications are debounced per address per template (15 minutes) so an unauthenticated `GET /check/verify-email/…` cannot be looped into a mail bomb aimed at a registered address. Pass `mailThrottle` for a different window or a Redis-backed one, `mailThrottle: ALWAYS_MAIL` to opt out, or `mailer` to replace the sender entirely (any object with the six `IVerifyEmailMailer` methods).
|
|
115
|
+
|
|
107
116
|
### GraphQL error helpers
|
|
108
117
|
|
|
109
118
|
```ts
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { IVerifyEmailPaths, TAccessModel } from "../../../lib/access/accessPaths.mjs";
|
|
2
|
+
import { IVerifyEmailMailer } from "../../../lib/access/verifyEmailMailer.mjs";
|
|
2
3
|
import { TConfirmNewEmail } from "../../../private/lib/access/db/confirmNewEmail.mjs";
|
|
3
4
|
import { TIncReqTimes } from "../../../private/lib/access/db/incReqTimes.mjs";
|
|
4
5
|
import { GraphQLNonNull } from 'graphql';
|
|
@@ -13,6 +14,12 @@ export interface IEmailChangeHashVerifyDeps {
|
|
|
13
14
|
paths: IVerifyEmailPaths;
|
|
14
15
|
confirmNewEmail: TConfirmNewEmail;
|
|
15
16
|
incReqTimes: TIncReqTimes;
|
|
17
|
+
/**
|
|
18
|
+
* Who sends the three notifications this resolver can trigger. Optional, defaulting to the debounced
|
|
19
|
+
* SocketLabs binding — the client used to be constructed in `resolve`, so no caller could exercise a
|
|
20
|
+
* branch without a real send.
|
|
21
|
+
*/
|
|
22
|
+
mailer?: IVerifyEmailMailer;
|
|
16
23
|
}
|
|
17
24
|
/**
|
|
18
25
|
* Change email - Verify match between email and hash
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { SocketLabsLib } from "../../../email/SocketLabsLib.mjs";
|
|
2
1
|
import { DEFAULT_VERIFY_EMAIL_PATHS } from "../../../lib/access/accessPaths.mjs";
|
|
2
|
+
import { defaultVerifyEmailMailer } from "../../../lib/access/verifyEmailMailer.mjs";
|
|
3
3
|
import { StringLib } from "../../../lib/StringLib.mjs";
|
|
4
4
|
import { UserBase } from "../../models/MongoDB/UserBase.mjs";
|
|
5
5
|
import confirmNewEmail from "../../../private/lib/access/db/confirmNewEmail.mjs";
|
|
@@ -18,7 +18,7 @@ async function handleHashMismatch(ctx, uId, requestTimes) {
|
|
|
18
18
|
}
|
|
19
19
|
await ctx.deps.incReqTimes(uId);
|
|
20
20
|
// noinspection ES6MissingAwait
|
|
21
|
-
ctx.
|
|
21
|
+
ctx.mailer.wrongHash(ctx.uEmail, requestTimes);
|
|
22
22
|
return false;
|
|
23
23
|
}
|
|
24
24
|
/**
|
|
@@ -26,7 +26,7 @@ async function handleHashMismatch(ctx, uId, requestTimes) {
|
|
|
26
26
|
* free, accept it. Extracted from resolve() only to keep it inside the max-lines-per-function budget.
|
|
27
27
|
*/
|
|
28
28
|
async function handleValidHash(ctx, uId, dateLastReq) {
|
|
29
|
-
const { deps, user, uEmail,
|
|
29
|
+
const { deps, user, uEmail, mailer } = ctx;
|
|
30
30
|
const { paths } = deps;
|
|
31
31
|
if (typeof dateLastReq === 'undefined') {
|
|
32
32
|
// @fixme sentry 'dateLastReq is undefined'
|
|
@@ -39,7 +39,7 @@ async function handleValidHash(ctx, uId, dateLastReq) {
|
|
|
39
39
|
if (StrLibObj.isoToTimestamp(day3ago) > StrLibObj.isoToTimestamp(dateLastReq)) {
|
|
40
40
|
// dateLastReq too old then 3 days
|
|
41
41
|
// noinspection ES6MissingAwait
|
|
42
|
-
|
|
42
|
+
mailer.hashReqTooOld(uEmail);
|
|
43
43
|
return false;
|
|
44
44
|
}
|
|
45
45
|
// account is deleted -> maybe by admin for any reason
|
|
@@ -52,7 +52,7 @@ async function handleValidHash(ctx, uId, dateLastReq) {
|
|
|
52
52
|
// if account is disabled, for any reason
|
|
53
53
|
if (readPath(user, paths.disabled)) {
|
|
54
54
|
// noinspection ES6MissingAwait
|
|
55
|
-
|
|
55
|
+
mailer.accountDisabled(uEmail);
|
|
56
56
|
return false;
|
|
57
57
|
}
|
|
58
58
|
// valid request. meanwhile, has some user registered with this email address ??
|
|
@@ -71,37 +71,40 @@ async function handleValidHash(ctx, uId, dateLastReq) {
|
|
|
71
71
|
* The projection is built from the same map the reads use, which is what keeps a read field from going
|
|
72
72
|
* missing — the exact bug that made every wrong hash answer 500 through 5.1.0.
|
|
73
73
|
*/
|
|
74
|
-
export const createEmailChangeHashVerifyMutation = (deps) =>
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
return
|
|
74
|
+
export const createEmailChangeHashVerifyMutation = (deps) => {
|
|
75
|
+
const mailer = deps.mailer ?? defaultVerifyEmailMailer;
|
|
76
|
+
return {
|
|
77
|
+
description: 'Change email - Verify match between email and hash',
|
|
78
|
+
type: new GraphQLNonNull(GraphQLBoolean),
|
|
79
|
+
args: {
|
|
80
|
+
email: { type: new GraphQLNonNull(GraphQLString) },
|
|
81
|
+
hash: { type: new GraphQLNonNull(GraphQLString) }
|
|
82
|
+
},
|
|
83
|
+
async resolve(_, args) {
|
|
84
|
+
const { paths } = deps;
|
|
85
|
+
const uEmail = args.email.toLowerCase();
|
|
86
|
+
// search if the email exists
|
|
87
|
+
// Every field this resolver reads must be listed. account.email.requestTimes was missing, and
|
|
88
|
+
// because this is a .lean() read the absent key made handleHashMismatch throw 500 on *every*
|
|
89
|
+
// wrong hash: the strike counter never advanced and the owner never got the wrongHash warning.
|
|
90
|
+
const user = await deps.model
|
|
91
|
+
.findOne({ [paths.newEmailTmp]: uEmail })
|
|
92
|
+
.select(buildProjection([paths.hash, paths.dateLastReq, paths.requestTimes, paths.deleted, paths.disabled]))
|
|
93
|
+
.lean();
|
|
94
|
+
// if email not found, return (do not tell the user the real problem !)
|
|
95
|
+
if (user === null) {
|
|
96
|
+
return false; // @fixme throw
|
|
97
|
+
}
|
|
98
|
+
const ctx = { deps, user, uEmail, mailer };
|
|
99
|
+
const uId = readPath(user, '_id');
|
|
100
|
+
const dateLastReq = readPath(user, paths.dateLastReq);
|
|
101
|
+
if (args.hash === readPath(user, paths.hash)) {
|
|
102
|
+
return handleValidHash(ctx, uId, dateLastReq);
|
|
103
|
+
}
|
|
104
|
+
return handleHashMismatch(ctx, uId, readPath(user, paths.requestTimes));
|
|
95
105
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
const dateLastReq = readPath(user, paths.dateLastReq);
|
|
99
|
-
if (args.hash === readPath(user, paths.hash)) {
|
|
100
|
-
return handleValidHash(ctx, uId, dateLastReq);
|
|
101
|
-
}
|
|
102
|
-
return handleHashMismatch(ctx, uId, readPath(user, paths.requestTimes));
|
|
103
|
-
}
|
|
104
|
-
});
|
|
106
|
+
};
|
|
107
|
+
};
|
|
105
108
|
/** `UserBase`-bound default — the mutation every existing consumer already imports. */
|
|
106
109
|
export const emailChangeHashVerify = createEmailChangeHashVerifyMutation({
|
|
107
110
|
model: UserBase,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"emailChangeHashVerify.mjs","sourceRoot":"","sources":["../../../../src/graphQL/schema/mutations/emailChangeHashVerify.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,yCAAgC;AACxD,OAAO,EAAE,0BAA0B,EAAmC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AC,CAAA;IAC9F,CAAC;CACD,CAAC,CAAA;AAKF,uFAAuF;AACvF,MAAM,CAAC,MAAM,qBAAqB,GAAmC,mCAAmC,CAAC;IACxG,KAAK,EAAE,QAAQ;IACf,KAAK,EAAE,0BAA0B;IACjC,eAAe;IACf,WAAW;CACX,CAAC,CAAA","sourcesContent":["import { SocketLabsLib } from '@email/SocketLabsLib.mjs'\nimport { DEFAULT_VERIFY_EMAIL_PATHS, IVerifyEmailPaths, TAccessModel } from '@lib/access/accessPaths.mjs'\nimport { StringLib } from '@lib/StringLib.mjs'\nimport { UserBase } from '@models/MongoDB/UserBase.mjs'\nimport confirmNewEmail, { TConfirmNewEmail } from '@private/lib/access/db/confirmNewEmail.mjs'\nimport { incReqTimes, TIncReqTimes } from '@private/lib/access/db/incReqTimes.mjs'\nimport { buildProjection, readPath } from '@private/lib/access/pathTools.mjs'\nimport { throwInternalError } from '@throw/throwInternalError.mjs'\nimport { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql'\nimport { Types } from 'mongoose'\n\n/** Arguments accepted by the `emailChangeHashVerify` mutation. Exported so a consumer re-exporting the bound mutation can name its type. */\nexport interface IEmailChangeHashVerifyArgs {\n\temail: string\n\thash: string\n}\n\n/** Model, field map and writers the resolver needs, all bound together by the caller. */\nexport interface IEmailChangeHashVerifyDeps {\n\tmodel: TAccessModel\n\tpaths: IVerifyEmailPaths\n\tconfirmNewEmail: TConfirmNewEmail\n\tincReqTimes: TIncReqTimes\n}\n\n/**\n * Everything the extracted branch handlers need, bundled so each stays within the max-params budget:\n * the bound deps, the lean document just read, the lowercased email and one shared SocketLabs client.\n */\ninterface IVerifyContext {\n\tdeps: IEmailChangeHashVerifyDeps\n\tuser: unknown\n\tuEmail: string\n\tsocketLabs: SocketLabsLib\n}\n\n/**\n * The submitted hash does not match the stored one: count the attempt and warn the account owner.\n * Extracted from resolve() only to keep it inside the max-lines-per-function budget — behaviour unchanged.\n */\nasync function handleHashMismatch(ctx: IVerifyContext, uId: Types.ObjectId, requestTimes: number | undefined) {\n\t// hash failed\n\n\tif (typeof requestTimes === 'undefined') {\n\t\tthrow throwInternalError()\n\t}\n\n\tawait ctx.deps.incReqTimes(uId)\n\t// noinspection ES6MissingAwait\n\tctx.socketLabs.wrongHash(ctx.uEmail, requestTimes)\n\treturn false\n}\n\n/**\n * The submitted hash matches: enforce the freshness/account guards and, if the target email is still\n * free, accept it. Extracted from resolve() only to keep it inside the max-lines-per-function budget.\n */\nasync function handleValidHash(ctx: IVerifyContext, uId: Types.ObjectId, dateLastReq: Date | undefined) {\n\tconst { deps, user, uEmail, socketLabs } = ctx\n\tconst { paths } = deps\n\n\tif (typeof dateLastReq === 'undefined') {\n\t\t// @fixme sentry 'dateLastReq is undefined'\n\t\tthrow throwInternalError()\n\t}\n\n\t// if dateLastReq is older than 3 days, warn and stop\n\tconst StrLibObj = new StringLib()\n\tconst now = new Date()\n\tconst day3ago = new Date(now.setDate(now.getDate() - 3))\n\n\tif (StrLibObj.isoToTimestamp(day3ago) > StrLibObj.isoToTimestamp(dateLastReq)) {\n\t\t// dateLastReq too old then 3 days\n\n\t\t// noinspection ES6MissingAwait\n\t\tsocketLabs.hashReqTooOld(uEmail)\n\t\treturn false\n\t}\n\n\t// account is deleted -> maybe by admin for any reason\n\t// Read raw: this is a .lean() query, so Mongoose casting never runs and these are real booleans\n\t// only on data that scripts/migrate-account-disabled-to-boolean.mjs has been through. A legacy\n\t// string 'false' is truthy and blocks here — migrate, don't coerce.\n\tif (readPath(user, paths.deleted)) {\n\t\treturn false\n\t}\n\t// if account is disabled, for any reason\n\tif (readPath(user, paths.disabled)) {\n\t\t// noinspection ES6MissingAwait\n\t\tsocketLabs.accountDisabled(uEmail)\n\t\treturn false\n\t}\n\n\t// valid request. meanwhile, has some user registered with this email address ??\n\tconst qty = await deps.model.countDocuments({ [paths.email]: uEmail })\n\tif (qty > 0) {\n\t\treturn false\n\t}\n\n\t// accept new email\n\tawait deps.confirmNewEmail(uId, uEmail)\n\treturn true\n}\n\n/**\n * Change email - Verify match between email and hash\n *\n * The collection and every field path come from `deps`, so the same resolver serves any account model.\n * The projection is built from the same map the reads use, which is what keeps a read field from going\n * missing — the exact bug that made every wrong hash answer 500 through 5.1.0.\n */\nexport const createEmailChangeHashVerifyMutation = (deps: IEmailChangeHashVerifyDeps) => ({\n\tdescription: 'Change email - Verify match between email and hash',\n\ttype: new GraphQLNonNull(GraphQLBoolean),\n\targs: {\n\t\temail: { type: new GraphQLNonNull(GraphQLString) },\n\t\thash: { type: new GraphQLNonNull(GraphQLString) }\n\t},\n\tasync resolve(_: unknown, args: IEmailChangeHashVerifyArgs) {\n\t\tconst { paths } = deps\n\t\tconst uEmail = args.email.toLowerCase()\n\n\t\t// search if the email exists\n\t\t// Every field this resolver reads must be listed. account.email.requestTimes was missing, and\n\t\t// because this is a .lean() read the absent key made handleHashMismatch throw 500 on *every*\n\t\t// wrong hash: the strike counter never advanced and the owner never got the wrongHash warning.\n\t\tconst user = await deps.model\n\t\t\t.findOne({ [paths.newEmailTmp]: uEmail })\n\t\t\t.select(buildProjection([paths.hash, paths.dateLastReq, paths.requestTimes, paths.deleted, paths.disabled]))\n\t\t\t.lean()\n\n\t\t// if email not found, return (do not tell the user the real problem !)\n\t\tif (user === null) {\n\t\t\treturn false // @fixme throw\n\t\t}\n\n\t\tconst ctx: IVerifyContext = { deps, user, uEmail, socketLabs: new SocketLabsLib() }\n\n\t\tconst uId = readPath(user, '_id') as Types.ObjectId\n\t\tconst dateLastReq = readPath(user, paths.dateLastReq) as Date | undefined\n\n\t\tif (args.hash === readPath(user, paths.hash)) {\n\t\t\treturn handleValidHash(ctx, uId, dateLastReq)\n\t\t}\n\t\treturn handleHashMismatch(ctx, uId, readPath(user, paths.requestTimes) as number | undefined)\n\t}\n})\n\n/** Shape of the bound mutation, for the modules that take it as a dependency. */\nexport type TEmailChangeHashVerifyMutation = ReturnType<typeof createEmailChangeHashVerifyMutation>\n\n/** `UserBase`-bound default — the mutation every existing consumer already imports. */\nexport const emailChangeHashVerify: TEmailChangeHashVerifyMutation = createEmailChangeHashVerifyMutation({\n\tmodel: UserBase,\n\tpaths: DEFAULT_VERIFY_EMAIL_PATHS,\n\tconfirmNewEmail,\n\tincReqTimes\n})\n"]}
|
|
1
|
+
{"version":3,"file":"emailChangeHashVerify.mjs","sourceRoot":"","sources":["../../../../src/graphQL/schema/mutations/emailChangeHashVerify.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAmC,4CAAmC;AACzG,OAAO,EAAE,wBAAwB,EAAsB,kDAAyC;AAChG,OAAO,EAAE,SAAS,EAAE,mCAA0B;AAC9C,OAAO,EAAE,QAAQ,EAAE,0CAAoC;AACvD,OAAO,eAAqC,2DAAkD;AAC9F,OAAO,EAAE,WAAW,EAAgB,uDAA8C;AAClF,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,kDAAyC;AAC7E,OAAO,EAAE,kBAAkB,EAAE,2CAAqC;AAClE,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAkCvE;;;GAGG;AACH,KAAK,UAAU,kBAAkB,CAAC,GAAmB,EAAE,GAAmB,EAAE,YAAgC;IAC3G,cAAc;IAEd,IAAI,OAAO,YAAY,KAAK,WAAW,EAAE,CAAC;QACzC,MAAM,kBAAkB,EAAE,CAAA;IAC3B,CAAC;IAED,MAAM,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAA;IAC/B,+BAA+B;IAC/B,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAA;IAC9C,OAAO,KAAK,CAAA;AACb,CAAC;AAED;;;GAGG;AACH,KAAK,UAAU,eAAe,CAAC,GAAmB,EAAE,GAAmB,EAAE,WAA6B;IACrG,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAA;IAC1C,MAAM,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AI,EAAE,KAAK,CAAmB,CAAA;YACnD,MAAM,WAAW,GAAG,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC,WAAW,CAAqB,CAAA;YAEzE,IAAI,IAAI,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC9C,OAAO,eAAe,CAAC,GAAG,EAAE,GAAG,EAAE,WAAW,CAAC,CAAA;YAC9C,CAAC;YACD,OAAO,kBAAkB,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC,YAAY,CAAuB,CAAC,CAAA;QAC9F,CAAC;KACD,CAAA;AACF,CAAC,CAAA;AAKD,uFAAuF;AACvF,MAAM,CAAC,MAAM,qBAAqB,GAAmC,mCAAmC,CAAC;IACxG,KAAK,EAAE,QAAQ;IACf,KAAK,EAAE,0BAA0B;IACjC,eAAe;IACf,WAAW;CACX,CAAC,CAAA","sourcesContent":["import { DEFAULT_VERIFY_EMAIL_PATHS, IVerifyEmailPaths, TAccessModel } from '@lib/access/accessPaths.mjs'\nimport { defaultVerifyEmailMailer, IVerifyEmailMailer } from '@lib/access/verifyEmailMailer.mjs'\nimport { StringLib } from '@lib/StringLib.mjs'\nimport { UserBase } from '@models/MongoDB/UserBase.mjs'\nimport confirmNewEmail, { TConfirmNewEmail } from '@private/lib/access/db/confirmNewEmail.mjs'\nimport { incReqTimes, TIncReqTimes } from '@private/lib/access/db/incReqTimes.mjs'\nimport { buildProjection, readPath } from '@private/lib/access/pathTools.mjs'\nimport { throwInternalError } from '@throw/throwInternalError.mjs'\nimport { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql'\nimport { Types } from 'mongoose'\n\n/** Arguments accepted by the `emailChangeHashVerify` mutation. Exported so a consumer re-exporting the bound mutation can name its type. */\nexport interface IEmailChangeHashVerifyArgs {\n\temail: string\n\thash: string\n}\n\n/** Model, field map and writers the resolver needs, all bound together by the caller. */\nexport interface IEmailChangeHashVerifyDeps {\n\tmodel: TAccessModel\n\tpaths: IVerifyEmailPaths\n\tconfirmNewEmail: TConfirmNewEmail\n\tincReqTimes: TIncReqTimes\n\t/**\n\t * Who sends the three notifications this resolver can trigger. Optional, defaulting to the debounced\n\t * SocketLabs binding — the client used to be constructed in `resolve`, so no caller could exercise a\n\t * branch without a real send.\n\t */\n\tmailer?: IVerifyEmailMailer\n}\n\n/**\n * Everything the extracted branch handlers need, bundled so each stays within the max-params budget:\n * the bound deps, the lean document just read, the lowercased email and the resolved mailer.\n */\ninterface IVerifyContext {\n\tdeps: IEmailChangeHashVerifyDeps\n\tuser: unknown\n\tuEmail: string\n\tmailer: IVerifyEmailMailer\n}\n\n/**\n * The submitted hash does not match the stored one: count the attempt and warn the account owner.\n * Extracted from resolve() only to keep it inside the max-lines-per-function budget — behaviour unchanged.\n */\nasync function handleHashMismatch(ctx: IVerifyContext, uId: Types.ObjectId, requestTimes: number | undefined) {\n\t// hash failed\n\n\tif (typeof requestTimes === 'undefined') {\n\t\tthrow throwInternalError()\n\t}\n\n\tawait ctx.deps.incReqTimes(uId)\n\t// noinspection ES6MissingAwait\n\tctx.mailer.wrongHash(ctx.uEmail, requestTimes)\n\treturn false\n}\n\n/**\n * The submitted hash matches: enforce the freshness/account guards and, if the target email is still\n * free, accept it. Extracted from resolve() only to keep it inside the max-lines-per-function budget.\n */\nasync function handleValidHash(ctx: IVerifyContext, uId: Types.ObjectId, dateLastReq: Date | undefined) {\n\tconst { deps, user, uEmail, mailer } = ctx\n\tconst { paths } = deps\n\n\tif (typeof dateLastReq === 'undefined') {\n\t\t// @fixme sentry 'dateLastReq is undefined'\n\t\tthrow throwInternalError()\n\t}\n\n\t// if dateLastReq is older than 3 days, warn and stop\n\tconst StrLibObj = new StringLib()\n\tconst now = new Date()\n\tconst day3ago = new Date(now.setDate(now.getDate() - 3))\n\n\tif (StrLibObj.isoToTimestamp(day3ago) > StrLibObj.isoToTimestamp(dateLastReq)) {\n\t\t// dateLastReq too old then 3 days\n\n\t\t// noinspection ES6MissingAwait\n\t\tmailer.hashReqTooOld(uEmail)\n\t\treturn false\n\t}\n\n\t// account is deleted -> maybe by admin for any reason\n\t// Read raw: this is a .lean() query, so Mongoose casting never runs and these are real booleans\n\t// only on data that scripts/migrate-account-disabled-to-boolean.mjs has been through. A legacy\n\t// string 'false' is truthy and blocks here — migrate, don't coerce.\n\tif (readPath(user, paths.deleted)) {\n\t\treturn false\n\t}\n\t// if account is disabled, for any reason\n\tif (readPath(user, paths.disabled)) {\n\t\t// noinspection ES6MissingAwait\n\t\tmailer.accountDisabled(uEmail)\n\t\treturn false\n\t}\n\n\t// valid request. meanwhile, has some user registered with this email address ??\n\tconst qty = await deps.model.countDocuments({ [paths.email]: uEmail })\n\tif (qty > 0) {\n\t\treturn false\n\t}\n\n\t// accept new email\n\tawait deps.confirmNewEmail(uId, uEmail)\n\treturn true\n}\n\n/**\n * Change email - Verify match between email and hash\n *\n * The collection and every field path come from `deps`, so the same resolver serves any account model.\n * The projection is built from the same map the reads use, which is what keeps a read field from going\n * missing — the exact bug that made every wrong hash answer 500 through 5.1.0.\n */\nexport const createEmailChangeHashVerifyMutation = (deps: IEmailChangeHashVerifyDeps) => {\n\tconst mailer = deps.mailer ?? defaultVerifyEmailMailer\n\n\treturn {\n\t\tdescription: 'Change email - Verify match between email and hash',\n\t\ttype: new GraphQLNonNull(GraphQLBoolean),\n\t\targs: {\n\t\t\temail: { type: new GraphQLNonNull(GraphQLString) },\n\t\t\thash: { type: new GraphQLNonNull(GraphQLString) }\n\t\t},\n\t\tasync resolve(_: unknown, args: IEmailChangeHashVerifyArgs) {\n\t\t\tconst { paths } = deps\n\t\t\tconst uEmail = args.email.toLowerCase()\n\n\t\t\t// search if the email exists\n\t\t\t// Every field this resolver reads must be listed. account.email.requestTimes was missing, and\n\t\t\t// because this is a .lean() read the absent key made handleHashMismatch throw 500 on *every*\n\t\t\t// wrong hash: the strike counter never advanced and the owner never got the wrongHash warning.\n\t\t\tconst user = await deps.model\n\t\t\t\t.findOne({ [paths.newEmailTmp]: uEmail })\n\t\t\t\t.select(buildProjection([paths.hash, paths.dateLastReq, paths.requestTimes, paths.deleted, paths.disabled]))\n\t\t\t\t.lean()\n\n\t\t\t// if email not found, return (do not tell the user the real problem !)\n\t\t\tif (user === null) {\n\t\t\t\treturn false // @fixme throw\n\t\t\t}\n\n\t\t\tconst ctx: IVerifyContext = { deps, user, uEmail, mailer }\n\n\t\t\tconst uId = readPath(user, '_id') as Types.ObjectId\n\t\t\tconst dateLastReq = readPath(user, paths.dateLastReq) as Date | undefined\n\n\t\t\tif (args.hash === readPath(user, paths.hash)) {\n\t\t\t\treturn handleValidHash(ctx, uId, dateLastReq)\n\t\t\t}\n\t\t\treturn handleHashMismatch(ctx, uId, readPath(user, paths.requestTimes) as number | undefined)\n\t\t}\n\t}\n}\n\n/** Shape of the bound mutation, for the modules that take it as a dependency. */\nexport type TEmailChangeHashVerifyMutation = ReturnType<typeof createEmailChangeHashVerifyMutation>\n\n/** `UserBase`-bound default — the mutation every existing consumer already imports. */\nexport const emailChangeHashVerify: TEmailChangeHashVerifyMutation = createEmailChangeHashVerifyMutation({\n\tmodel: UserBase,\n\tpaths: DEFAULT_VERIFY_EMAIL_PATHS,\n\tconfirmNewEmail,\n\tincReqTimes\n})\n"]}
|
|
@@ -94,3 +94,21 @@ export declare const DEFAULT_VERIFY_EMAIL_PATHS: IVerifyEmailPaths;
|
|
|
94
94
|
* `undefined`, so pass only the keys being changed.
|
|
95
95
|
*/
|
|
96
96
|
export declare function resolveVerifyEmailPaths(paths?: Partial<IVerifyEmailPaths>): IVerifyEmailPaths;
|
|
97
|
+
/**
|
|
98
|
+
* What the verify-email guards do with an abandoned pending registration — a link older than 3 days, or a
|
|
99
|
+
* fifth wrong hash.
|
|
100
|
+
*
|
|
101
|
+
* `'delete'` removes the row. It is the behaviour through 5.6.1, the only one the chain had, and it is safe
|
|
102
|
+
* for `UserBase`, whose rows own nothing. It is not safe for a model at the head of a hierarchy the package
|
|
103
|
+
* cannot see: once the factory accepts an arbitrary model, the package no longer knows what deleting a row
|
|
104
|
+
* costs, and with no foreign keys and no cascade in Mongo it takes the children with it in effect while
|
|
105
|
+
* leaving them behind in fact.
|
|
106
|
+
*
|
|
107
|
+
* `'soft-delete'` writes `paths.deleted` instead — the one tombstone convention {@link IVerifyEmailPaths}
|
|
108
|
+
* already declares and the chain otherwise only ever read. The guards test it for truthiness, so the value
|
|
109
|
+
* written is the caller's (`deletedValue`), boolean or timestamp alike.
|
|
110
|
+
*
|
|
111
|
+
* `'keep'` leaves the document alone. The guard still throws, so the link is still refused; only the row
|
|
112
|
+
* survives, and disposing of it becomes the caller's job.
|
|
113
|
+
*/
|
|
114
|
+
export type TOnAbandon = 'delete' | 'soft-delete' | 'keep';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accessPaths.mjs","sourceRoot":"","sources":["../../../src/lib/access/accessPaths.mts"],"names":[],"mappings":"AAmDA,8FAA8F;AAC9F,MAAM,CAAC,MAAM,uBAAuB,GAAmB,MAAM,CAAC,MAAM,CAAC;IACpE,KAAK,EAAE,aAAa;IACpB,QAAQ,EAAE,gBAAgB;IAC1B,IAAI,EAAE,mBAAmB;IACzB,YAAY,EAAE,sBAAsB;IACpC,SAAS,EAAE,mBAAmB;IAC9B,OAAO,EAAE,iBAAiB;IAC1B,QAAQ,EAAE,kBAAkB;IAC5B,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,sBAAsB,EAAE,mBAAmB,CAAC,CAAC;CACxE,CAAC,CAAA;AAEF;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,KAA+B;IACnE,OAAO,EAAE,GAAG,uBAAuB,EAAE,GAAG,KAAK,EAAE,CAAA;AAChD,CAAC;AAkCD,8FAA8F;AAC9F,MAAM,CAAC,MAAM,0BAA0B,GAAsB,MAAM,CAAC,MAAM,CAAC;IAC1E,KAAK,EAAE,aAAa;IACpB,KAAK,EAAE,qBAAqB;IAC5B,IAAI,EAAE,oBAAoB;IAC1B,WAAW,EAAE,2BAA2B;IACxC,YAAY,EAAE,4BAA4B;IAC1C,WAAW,EAAE,2BAA2B;IACxC,OAAO,EAAE,iBAAiB;IAC1B,QAAQ,EAAE,kBAAkB;IAC5B,WAAW,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,oBAAoB,EAAE,2BAA2B,EAAE,4BAA4B,CAAC,CAAC;IAC7G,gBAAgB,EAAE,MAAM,CAAC,MAAM,CAAC;QAC/B,oBAAoB;QACpB,2BAA2B;QAC3B,4BAA4B;QAC5B,2BAA2B;KAC3B,CAAC;CACF,CAAC,CAAA;AAEF;;;;;GAKG;AACH,MAAM,UAAU,uBAAuB,CAAC,KAAkC;IACzE,OAAO,EAAE,GAAG,0BAA0B,EAAE,GAAG,KAAK,EAAE,CAAA;AACnD,CAAC","sourcesContent":["import { Model } from 'mongoose'\n\n/**\n * Any mongoose model an access flow can be pointed at.\n *\n * Deliberately `Model<any>`: the flows only ever call `findOne`, `updateOne`, `countDocuments` and\n * `deleteOne` with computed field paths, so nothing here can be typed against a concrete document\n * shape without forcing every consumer to describe theirs. The `paths` map below is what pins the\n * contract instead — a wrong path is a runtime no-op, which is why the defaults are exported and the\n * flows are tested against them.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type TAccessModel = Model<any>\n\n/**\n * Field paths the password-reset flow reads and writes.\n *\n * Every value is a dotted mongo path into the account document. They are supplied as data rather\n * than hard-coded because `UserBase` is only one possible layout: a consumer whose accounts live in\n * another collection, or under another field tree, could not use `resetPwd` / `updatePassword` at\n * all while the paths were baked in.\n */\nexport interface IResetPwdPaths {\n\t/** Login address. Used as the lookup filter by `getResetPwd` and `removeResetReq`. */\n\temail: string\n\t/** Bcrypt hash slot `updatePassword` overwrites. */\n\tpassword: string\n\t/** Display name passed to the reset / confirmation emails. Missing value ⇒ empty string. */\n\tname: string\n\t/** When the pending reset was requested. Drives the 10-minute throttle and the 60-minute expiry. */\n\tresetDateReq: string\n\t/** Password-reset token. Must stay disjoint from the email-verification hash slot. */\n\tresetHash: string\n\t/** Account tombstone flag. A set value makes `getResetPwd` answer `null`, as for an unknown address. */\n\tdeleted: string\n\t/** Account lockout flag. A set value makes `getResetPwd` answer `null`, as for an unknown address. */\n\tdisabled: string\n\t/**\n\t * Paths `removeResetReq` `$unset`s once a reset has been consumed.\n\t *\n\t * Kept separate from `resetDateReq` / `resetHash` on purpose — it is NOT always the same list.\n\t * A layout that stores the request as one all-or-nothing subdocument, e.g.\n\t * `resetPwd: { resetDateReq, resetHash }` under `validationLevel: 'strict'` +\n\t * `validationAction: 'error'`, rejects a write that unsets a single member: the leftover document\n\t * fails validation. The only legal cleanup there is `$unset: { resetPwd: '' }` — one container\n\t * path, not two leaf paths. Deriving this list from the leaves would make that layout impossible\n\t * to express, and the flat default hides the problem completely.\n\t */\n\tresetClear: readonly string[]\n}\n\n/** The layout of `UserBase` — i.e. the behaviour of the flow before it took a `paths` map. */\nexport const DEFAULT_RESET_PWD_PATHS: IResetPwdPaths = Object.freeze({\n\temail: 'login.email',\n\tpassword: 'login.password',\n\tname: 'personalData.name',\n\tresetDateReq: 'account.resetDateReq',\n\tresetHash: 'account.resetHash',\n\tdeleted: 'account.deleted',\n\tdisabled: 'account.disabled',\n\tresetClear: Object.freeze(['account.resetDateReq', 'account.resetHash'])\n})\n\n/**\n * Merge a partial override over {@link DEFAULT_RESET_PWD_PATHS}.\n *\n * Plain spread: a key present with an explicit `undefined` value overrides the default with\n * `undefined`, so pass only the keys being changed.\n */\nexport function resolveResetPwdPaths(paths?: Partial<IResetPwdPaths>): IResetPwdPaths {\n\treturn { ...DEFAULT_RESET_PWD_PATHS, ...paths }\n}\n\n/**\n * Field paths the email-verification and email-change flows read and write.\n *\n * Same rationale as {@link IResetPwdPaths}. Note that `hash` here is the inbox-proof token\n * (activation and email change, 3-day life, `requestTimes` throttle) and must never be pointed at\n * the same field as `IResetPwdPaths.resetHash`: while the two shared one slot, a hash issued by\n * either flow authenticated the other, and an unauthenticated reset request killed pending\n * activation links.\n */\nexport interface IVerifyEmailPaths {\n\t/** Live login address — lookup filter, and the field `confirmNewEmail` writes on an email change. */\n\temail: string\n\t/** Boolean flag `enableEmailAccess` flips once a verification link is honoured. */\n\tvalid: string\n\t/** Verification / email-change token. Never the password-reset slot. */\n\thash: string\n\t/** When the current token was issued. Drives the 3-day link window. */\n\tdateLastReq: string\n\t/** Strike counter. Five wrong hashes delete the account. */\n\trequestTimes: string\n\t/** Address awaiting confirmation during an email change. */\n\tnewEmailTmp: string\n\t/** Account tombstone flag. */\n\tdeleted: string\n\t/** Account lockout flag. */\n\tdisabled: string\n\t/** Paths `enableEmailAccess` `$unset`s once a verification link is honoured. */\n\tverifyClear: readonly string[]\n\t/** Paths `confirmNewEmail` `$unset`s once a new address is accepted. */\n\temailChangeClear: readonly string[]\n}\n\n/** The layout of `UserBase` — i.e. the behaviour of the flow before it took a `paths` map. */\nexport const DEFAULT_VERIFY_EMAIL_PATHS: IVerifyEmailPaths = Object.freeze({\n\temail: 'login.email',\n\tvalid: 'account.email.valid',\n\thash: 'account.email.hash',\n\tdateLastReq: 'account.email.dateLastReq',\n\trequestTimes: 'account.email.requestTimes',\n\tnewEmailTmp: 'account.email.newEmailTmp',\n\tdeleted: 'account.deleted',\n\tdisabled: 'account.disabled',\n\tverifyClear: Object.freeze(['account.email.hash', 'account.email.dateLastReq', 'account.email.requestTimes']),\n\temailChangeClear: Object.freeze([\n\t\t'account.email.hash',\n\t\t'account.email.dateLastReq',\n\t\t'account.email.requestTimes',\n\t\t'account.email.newEmailTmp'\n\t])\n})\n\n/**\n * Merge a partial override over {@link DEFAULT_VERIFY_EMAIL_PATHS}.\n *\n * Plain spread: a key present with an explicit `undefined` value overrides the default with\n * `undefined`, so pass only the keys being changed.\n */\nexport function resolveVerifyEmailPaths(paths?: Partial<IVerifyEmailPaths>): IVerifyEmailPaths {\n\treturn { ...DEFAULT_VERIFY_EMAIL_PATH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AAE,GAAG,KAAK,EAAE,CAAA;AACnD,CAAC","sourcesContent":["import { Model } from 'mongoose'\n\n/**\n * Any mongoose model an access flow can be pointed at.\n *\n * Deliberately `Model<any>`: the flows only ever call `findOne`, `updateOne`, `countDocuments` and\n * `deleteOne` with computed field paths, so nothing here can be typed against a concrete document\n * shape without forcing every consumer to describe theirs. The `paths` map below is what pins the\n * contract instead — a wrong path is a runtime no-op, which is why the defaults are exported and the\n * flows are tested against them.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type TAccessModel = Model<any>\n\n/**\n * Field paths the password-reset flow reads and writes.\n *\n * Every value is a dotted mongo path into the account document. They are supplied as data rather\n * than hard-coded because `UserBase` is only one possible layout: a consumer whose accounts live in\n * another collection, or under another field tree, could not use `resetPwd` / `updatePassword` at\n * all while the paths were baked in.\n */\nexport interface IResetPwdPaths {\n\t/** Login address. Used as the lookup filter by `getResetPwd` and `removeResetReq`. */\n\temail: string\n\t/** Bcrypt hash slot `updatePassword` overwrites. */\n\tpassword: string\n\t/** Display name passed to the reset / confirmation emails. Missing value ⇒ empty string. */\n\tname: string\n\t/** When the pending reset was requested. Drives the 10-minute throttle and the 60-minute expiry. */\n\tresetDateReq: string\n\t/** Password-reset token. Must stay disjoint from the email-verification hash slot. */\n\tresetHash: string\n\t/** Account tombstone flag. A set value makes `getResetPwd` answer `null`, as for an unknown address. */\n\tdeleted: string\n\t/** Account lockout flag. A set value makes `getResetPwd` answer `null`, as for an unknown address. */\n\tdisabled: string\n\t/**\n\t * Paths `removeResetReq` `$unset`s once a reset has been consumed.\n\t *\n\t * Kept separate from `resetDateReq` / `resetHash` on purpose — it is NOT always the same list.\n\t * A layout that stores the request as one all-or-nothing subdocument, e.g.\n\t * `resetPwd: { resetDateReq, resetHash }` under `validationLevel: 'strict'` +\n\t * `validationAction: 'error'`, rejects a write that unsets a single member: the leftover document\n\t * fails validation. The only legal cleanup there is `$unset: { resetPwd: '' }` — one container\n\t * path, not two leaf paths. Deriving this list from the leaves would make that layout impossible\n\t * to express, and the flat default hides the problem completely.\n\t */\n\tresetClear: readonly string[]\n}\n\n/** The layout of `UserBase` — i.e. the behaviour of the flow before it took a `paths` map. */\nexport const DEFAULT_RESET_PWD_PATHS: IResetPwdPaths = Object.freeze({\n\temail: 'login.email',\n\tpassword: 'login.password',\n\tname: 'personalData.name',\n\tresetDateReq: 'account.resetDateReq',\n\tresetHash: 'account.resetHash',\n\tdeleted: 'account.deleted',\n\tdisabled: 'account.disabled',\n\tresetClear: Object.freeze(['account.resetDateReq', 'account.resetHash'])\n})\n\n/**\n * Merge a partial override over {@link DEFAULT_RESET_PWD_PATHS}.\n *\n * Plain spread: a key present with an explicit `undefined` value overrides the default with\n * `undefined`, so pass only the keys being changed.\n */\nexport function resolveResetPwdPaths(paths?: Partial<IResetPwdPaths>): IResetPwdPaths {\n\treturn { ...DEFAULT_RESET_PWD_PATHS, ...paths }\n}\n\n/**\n * Field paths the email-verification and email-change flows read and write.\n *\n * Same rationale as {@link IResetPwdPaths}. Note that `hash` here is the inbox-proof token\n * (activation and email change, 3-day life, `requestTimes` throttle) and must never be pointed at\n * the same field as `IResetPwdPaths.resetHash`: while the two shared one slot, a hash issued by\n * either flow authenticated the other, and an unauthenticated reset request killed pending\n * activation links.\n */\nexport interface IVerifyEmailPaths {\n\t/** Live login address — lookup filter, and the field `confirmNewEmail` writes on an email change. */\n\temail: string\n\t/** Boolean flag `enableEmailAccess` flips once a verification link is honoured. */\n\tvalid: string\n\t/** Verification / email-change token. Never the password-reset slot. */\n\thash: string\n\t/** When the current token was issued. Drives the 3-day link window. */\n\tdateLastReq: string\n\t/** Strike counter. Five wrong hashes delete the account. */\n\trequestTimes: string\n\t/** Address awaiting confirmation during an email change. */\n\tnewEmailTmp: string\n\t/** Account tombstone flag. */\n\tdeleted: string\n\t/** Account lockout flag. */\n\tdisabled: string\n\t/** Paths `enableEmailAccess` `$unset`s once a verification link is honoured. */\n\tverifyClear: readonly string[]\n\t/** Paths `confirmNewEmail` `$unset`s once a new address is accepted. */\n\temailChangeClear: readonly string[]\n}\n\n/** The layout of `UserBase` — i.e. the behaviour of the flow before it took a `paths` map. */\nexport const DEFAULT_VERIFY_EMAIL_PATHS: IVerifyEmailPaths = Object.freeze({\n\temail: 'login.email',\n\tvalid: 'account.email.valid',\n\thash: 'account.email.hash',\n\tdateLastReq: 'account.email.dateLastReq',\n\trequestTimes: 'account.email.requestTimes',\n\tnewEmailTmp: 'account.email.newEmailTmp',\n\tdeleted: 'account.deleted',\n\tdisabled: 'account.disabled',\n\tverifyClear: Object.freeze(['account.email.hash', 'account.email.dateLastReq', 'account.email.requestTimes']),\n\temailChangeClear: Object.freeze([\n\t\t'account.email.hash',\n\t\t'account.email.dateLastReq',\n\t\t'account.email.requestTimes',\n\t\t'account.email.newEmailTmp'\n\t])\n})\n\n/**\n * Merge a partial override over {@link DEFAULT_VERIFY_EMAIL_PATHS}.\n *\n * Plain spread: a key present with an explicit `undefined` value overrides the default with\n * `undefined`, so pass only the keys being changed.\n */\nexport function resolveVerifyEmailPaths(paths?: Partial<IVerifyEmailPaths>): IVerifyEmailPaths {\n\treturn { ...DEFAULT_VERIFY_EMAIL_PATHS, ...paths }\n}\n\n/**\n * What the verify-email guards do with an abandoned pending registration — a link older than 3 days, or a\n * fifth wrong hash.\n *\n * `'delete'` removes the row. It is the behaviour through 5.6.1, the only one the chain had, and it is safe\n * for `UserBase`, whose rows own nothing. It is not safe for a model at the head of a hierarchy the package\n * cannot see: once the factory accepts an arbitrary model, the package no longer knows what deleting a row\n * costs, and with no foreign keys and no cascade in Mongo it takes the children with it in effect while\n * leaving them behind in fact.\n *\n * `'soft-delete'` writes `paths.deleted` instead — the one tombstone convention {@link IVerifyEmailPaths}\n * already declares and the chain otherwise only ever read. The guards test it for truthiness, so the value\n * written is the caller's (`deletedValue`), boolean or timestamp alike.\n *\n * `'keep'` leaves the document alone. The guard still throws, so the link is still refused; only the row\n * survives, and disposing of it becomes the caller's job.\n */\nexport type TOnAbandon = 'delete' | 'soft-delete' | 'keep'\n"]}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Answers "may this notification be sent?" for a key. `true` sends, `false` drops silently.
|
|
3
|
+
*
|
|
4
|
+
* Every `handleIf*` guard in the verify-email chain is reachable from an unauthenticated
|
|
5
|
+
* `GET /check/verify-email/:email/:hash`, and three of them have no counter to lean on:
|
|
6
|
+
* `handleIfEmailAlreadyValid`, `handleIfAccountDeleted` and `handleIfAccountDisabled` mailed the address
|
|
7
|
+
* on *every* request through 5.6.1. Anyone who knew a registered address could make the platform's own
|
|
8
|
+
* SocketLabs account mail its owner once per request — a mail bomb aimed at a third party, plus a
|
|
9
|
+
* sending-reputation problem, out of a GET nobody had to authenticate.
|
|
10
|
+
*
|
|
11
|
+
* The contract is one function so a deployment can replace it. A Redis `SET key NX PX <window>` returning
|
|
12
|
+
* whether the key was created is the obvious cross-instance implementation, and is a one-liner here.
|
|
13
|
+
*/
|
|
14
|
+
export type TMailThrottle = (key: string) => boolean | Promise<boolean>;
|
|
15
|
+
/** Options of {@link createMailThrottle}. */
|
|
16
|
+
export interface ICreateMailThrottleArgs {
|
|
17
|
+
/** How long a key stays blocked after a send. Default 15 minutes. */
|
|
18
|
+
windowMs?: number;
|
|
19
|
+
/** Cap on tracked keys, so an attacker cycling addresses cannot grow the map without bound. Default 5000. */
|
|
20
|
+
maxKeys?: number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* In-process debounce: one send per key per `windowMs`.
|
|
24
|
+
*
|
|
25
|
+
* In-process on purpose — no runtime dependency, nothing to configure, and the amplification it has to
|
|
26
|
+
* stop arrives through one process. Behind several instances it degrades to one mail per instance per
|
|
27
|
+
* window, which is a cap rather than the unbounded fan-out it replaces; pass your own `TMailThrottle`
|
|
28
|
+
* when one mail per address across the fleet matters.
|
|
29
|
+
*
|
|
30
|
+
* State is per instance. `createVerifyEmailFlow` builds one per flow, so two flows never share a window.
|
|
31
|
+
*/
|
|
32
|
+
export declare const createMailThrottle: ({ windowMs, maxKeys }?: ICreateMailThrottleArgs) => TMailThrottle;
|
|
33
|
+
/** Never debounce — one mail per request, as 5.6.1 and earlier did. Pass as `mailThrottle` to opt out. */
|
|
34
|
+
export declare const ALWAYS_MAIL: TMailThrottle;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-process debounce: one send per key per `windowMs`.
|
|
3
|
+
*
|
|
4
|
+
* In-process on purpose — no runtime dependency, nothing to configure, and the amplification it has to
|
|
5
|
+
* stop arrives through one process. Behind several instances it degrades to one mail per instance per
|
|
6
|
+
* window, which is a cap rather than the unbounded fan-out it replaces; pass your own `TMailThrottle`
|
|
7
|
+
* when one mail per address across the fleet matters.
|
|
8
|
+
*
|
|
9
|
+
* State is per instance. `createVerifyEmailFlow` builds one per flow, so two flows never share a window.
|
|
10
|
+
*/
|
|
11
|
+
export const createMailThrottle = ({ windowMs = 15 * 60 * 1000, maxKeys = 5000 } = {}) => {
|
|
12
|
+
/** key → epoch ms of the send that blocked it. Insertion-ordered, which is what makes the eviction cheap. */
|
|
13
|
+
const sentAt = new Map();
|
|
14
|
+
return function maySend(key) {
|
|
15
|
+
const now = Date.now();
|
|
16
|
+
const previous = sentAt.get(key);
|
|
17
|
+
if (previous !== undefined && now - previous < windowMs) {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
// Delete before the set below so the map stays ordered by send time, oldest first.
|
|
21
|
+
sentAt.delete(key);
|
|
22
|
+
if (sentAt.size >= maxKeys) {
|
|
23
|
+
for (const [tracked, at] of sentAt) {
|
|
24
|
+
if (now - at >= windowMs) {
|
|
25
|
+
sentAt.delete(tracked);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if (sentAt.size >= maxKeys) {
|
|
30
|
+
// Still full, so every tracked key is inside its window: drop the oldest — the first key the
|
|
31
|
+
// insertion-ordered map yields. Refusing to send instead would let a flood of fresh addresses
|
|
32
|
+
// mute the notifications of real ones. `done` is only true for a `maxKeys` of 0, which caps
|
|
33
|
+
// nothing and so has nothing to evict.
|
|
34
|
+
const oldest = sentAt.keys().next();
|
|
35
|
+
if (!oldest.done) {
|
|
36
|
+
sentAt.delete(oldest.value);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
sentAt.set(key, now);
|
|
40
|
+
return true;
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
/** Never debounce — one mail per request, as 5.6.1 and earlier did. Pass as `mailThrottle` to opt out. */
|
|
44
|
+
export const ALWAYS_MAIL = () => true;
|
|
45
|
+
//# sourceMappingURL=createMailThrottle.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createMailThrottle.mjs","sourceRoot":"","sources":["../../../src/lib/access/createMailThrottle.mts"],"names":[],"mappings":"AAuBA;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,EAClC,QAAQ,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,EACzB,OAAO,GAAG,IAAI,KACc,EAAE,EAAiB,EAAE;IACjD,6GAA6G;IAC7G,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAA;IAExC,OAAO,SAAS,OAAO,CAAC,GAAW;QAClC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;QACtB,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QAEhC,IAAI,QAAQ,KAAK,SAAS,IAAI,GAAG,GAAG,QAAQ,GAAG,QAAQ,EAAE,CAAC;YACzD,OAAO,KAAK,CAAA;QACb,CAAC;QAED,mFAAmF;QACnF,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;QAElB,IAAI,MAAM,CAAC,IAAI,IAAI,OAAO,EAAE,CAAC;YAC5B,KAAK,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC;gBACpC,IAAI,GAAG,GAAG,EAAE,IAAI,QAAQ,EAAE,CAAC;oBAC1B,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;gBACvB,CAAC;YACF,CAAC;QACF,CAAC;QAED,IAAI,MAAM,CAAC,IAAI,IAAI,OAAO,EAAE,CAAC;YAC5B,6FAA6F;YAC7F,8FAA8F;YAC9F,4FAA4F;YAC5F,uCAAuC;YACvC,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAA;YAEnC,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;gBAClB,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YAC5B,CAAC;QACF,CAAC;QAED,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;QACpB,OAAO,IAAI,CAAA;IACZ,CAAC,CAAA;AACF,CAAC,CAAA;AAED,0GAA0G;AAC1G,MAAM,CAAC,MAAM,WAAW,GAAkB,GAAG,EAAE,CAAC,IAAI,CAAA","sourcesContent":["/**\n * Answers \"may this notification be sent?\" for a key. `true` sends, `false` drops silently.\n *\n * Every `handleIf*` guard in the verify-email chain is reachable from an unauthenticated\n * `GET /check/verify-email/:email/:hash`, and three of them have no counter to lean on:\n * `handleIfEmailAlreadyValid`, `handleIfAccountDeleted` and `handleIfAccountDisabled` mailed the address\n * on *every* request through 5.6.1. Anyone who knew a registered address could make the platform's own\n * SocketLabs account mail its owner once per request — a mail bomb aimed at a third party, plus a\n * sending-reputation problem, out of a GET nobody had to authenticate.\n *\n * The contract is one function so a deployment can replace it. A Redis `SET key NX PX <window>` returning\n * whether the key was created is the obvious cross-instance implementation, and is a one-liner here.\n */\nexport type TMailThrottle = (key: string) => boolean | Promise<boolean>\n\n/** Options of {@link createMailThrottle}. */\nexport interface ICreateMailThrottleArgs {\n\t/** How long a key stays blocked after a send. Default 15 minutes. */\n\twindowMs?: number\n\t/** Cap on tracked keys, so an attacker cycling addresses cannot grow the map without bound. Default 5000. */\n\tmaxKeys?: number\n}\n\n/**\n * In-process debounce: one send per key per `windowMs`.\n *\n * In-process on purpose — no runtime dependency, nothing to configure, and the amplification it has to\n * stop arrives through one process. Behind several instances it degrades to one mail per instance per\n * window, which is a cap rather than the unbounded fan-out it replaces; pass your own `TMailThrottle`\n * when one mail per address across the fleet matters.\n *\n * State is per instance. `createVerifyEmailFlow` builds one per flow, so two flows never share a window.\n */\nexport const createMailThrottle = ({\n\twindowMs = 15 * 60 * 1000,\n\tmaxKeys = 5000\n}: ICreateMailThrottleArgs = {}): TMailThrottle => {\n\t/** key → epoch ms of the send that blocked it. Insertion-ordered, which is what makes the eviction cheap. */\n\tconst sentAt = new Map<string, number>()\n\n\treturn function maySend(key: string): boolean {\n\t\tconst now = Date.now()\n\t\tconst previous = sentAt.get(key)\n\n\t\tif (previous !== undefined && now - previous < windowMs) {\n\t\t\treturn false\n\t\t}\n\n\t\t// Delete before the set below so the map stays ordered by send time, oldest first.\n\t\tsentAt.delete(key)\n\n\t\tif (sentAt.size >= maxKeys) {\n\t\t\tfor (const [tracked, at] of sentAt) {\n\t\t\t\tif (now - at >= windowMs) {\n\t\t\t\t\tsentAt.delete(tracked)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (sentAt.size >= maxKeys) {\n\t\t\t// Still full, so every tracked key is inside its window: drop the oldest — the first key the\n\t\t\t// insertion-ordered map yields. Refusing to send instead would let a flood of fresh addresses\n\t\t\t// mute the notifications of real ones. `done` is only true for a `maxKeys` of 0, which caps\n\t\t\t// nothing and so has nothing to evict.\n\t\t\tconst oldest = sentAt.keys().next()\n\n\t\t\tif (!oldest.done) {\n\t\t\t\tsentAt.delete(oldest.value)\n\t\t\t}\n\t\t}\n\n\t\tsentAt.set(key, now)\n\t\treturn true\n\t}\n}\n\n/** Never debounce — one mail per request, as 5.6.1 and earlier did. Pass as `mailThrottle` to opt out. */\nexport const ALWAYS_MAIL: TMailThrottle = () => true\n"]}
|
|
@@ -7,11 +7,32 @@ import { TSetEmailHash } from "../../private/lib/access/db/setEmailHash.mjs";
|
|
|
7
7
|
import { TUserData4VerifyEmail } from "../../private/lib/access/db/userData4VerifyEmail.mjs";
|
|
8
8
|
import { TEmailChangeHashVerifyMutation } from '../../graphQL/schema/mutations/emailChangeHashVerify.mjs';
|
|
9
9
|
import { TVerifyEmailRouter } from '../../koa/router/verifyEmail.mjs';
|
|
10
|
-
import { IVerifyEmailPaths, TAccessModel } from './accessPaths.mjs';
|
|
11
|
-
|
|
10
|
+
import { IVerifyEmailPaths, TAccessModel, TOnAbandon } from './accessPaths.mjs';
|
|
11
|
+
import { TMailThrottle } from './createMailThrottle.mjs';
|
|
12
|
+
import { IVerifyEmailMailer } from './verifyEmailMailer.mjs';
|
|
13
|
+
/** What the factory needs: the account model, plus any path or policy that differs from the default. */
|
|
12
14
|
export interface ICreateVerifyEmailFlowArgs {
|
|
13
15
|
model: TAccessModel;
|
|
14
16
|
paths?: Partial<IVerifyEmailPaths>;
|
|
17
|
+
/** How an abandoned/expired registration is disposed of. Default `'delete'` — current behaviour. */
|
|
18
|
+
onAbandon?: TOnAbandon;
|
|
19
|
+
/**
|
|
20
|
+
* Value `'soft-delete'` writes to `paths.deleted`. A function is called once per write, so a layout
|
|
21
|
+
* storing a timestamp passes `() => new Date()`. Default `true`, matching `UserBase`. Ignored by the
|
|
22
|
+
* other two modes.
|
|
23
|
+
*/
|
|
24
|
+
deletedValue?: unknown;
|
|
25
|
+
/** Full override of the disposal writer; wins over `onAbandon` and `deletedValue`. */
|
|
26
|
+
deleteUserByEmail?: TDeleteUserByEmail;
|
|
27
|
+
/** Who sends the verify-email notifications. Default: SocketLabs, debounced by `mailThrottle`. */
|
|
28
|
+
mailer?: IVerifyEmailMailer;
|
|
29
|
+
/**
|
|
30
|
+
* Debounce applied to every notification an unauthenticated request can trigger. Default: a 15 minute
|
|
31
|
+
* per-address, per-template window. Pass `ALWAYS_MAIL` for the send-every-time behaviour of 5.6.1 and earlier, or a
|
|
32
|
+
* Redis-backed one to share the window across instances. Ignored when `mailer` is supplied — wrap it
|
|
33
|
+
* yourself with `throttleMailer` if you want both.
|
|
34
|
+
*/
|
|
35
|
+
mailThrottle?: TMailThrottle;
|
|
15
36
|
}
|
|
16
37
|
/** Everything the verify-email chain exposes, bound to the model and paths passed in. */
|
|
17
38
|
export interface IVerifyEmailFlow {
|
|
@@ -37,12 +58,24 @@ export interface IVerifyEmailFlow {
|
|
|
37
58
|
* flow reads: a schema storing the verification state as one required-members subdocument is left
|
|
38
59
|
* invalid by unsetting a single member. Pass the container path in that case. See `IVerifyEmailPaths`.
|
|
39
60
|
*
|
|
61
|
+
* Two guards dispose of an abandoned registration — the fifth wrong hash and a link older than 3 days.
|
|
62
|
+
* Through 5.6.1 that always meant `deleteOne`, which is wrong for any row other rows depend on: the
|
|
63
|
+
* package has no idea what a delete costs in a schema it was handed, and a mongo collection has no
|
|
64
|
+
* cascade to lean on. `onAbandon` picks the policy; `deleteUserByEmail` replaces the writer outright.
|
|
65
|
+
* Whatever it does, both guards still throw — disposal never decides whether the link is honoured.
|
|
66
|
+
*
|
|
67
|
+
* Replacing `flow.deleteUserByEmail` on the returned object does nothing, by design: the guards close
|
|
68
|
+
* over the writer at construction time. The value returned is the same one they hold, so it reports the
|
|
69
|
+
* policy rather than setting it.
|
|
70
|
+
*
|
|
40
71
|
* ```ts
|
|
41
72
|
* const flow = createVerifyEmailFlow({
|
|
42
73
|
* model: Account,
|
|
43
|
-
* paths: { email: 'mail', valid: 'verified', verifyClear: ['verification'] }
|
|
74
|
+
* paths: { email: 'mail', valid: 'verified', verifyClear: ['verification'] },
|
|
75
|
+
* onAbandon: 'soft-delete',
|
|
76
|
+
* deletedValue: () => new Date()
|
|
44
77
|
* })
|
|
45
78
|
* router.get('/check/verify-email/:email/:hash', flow.routerVerifyEmail())
|
|
46
79
|
* ```
|
|
47
80
|
*/
|
|
48
|
-
export declare const createVerifyEmailFlow: ({ model, paths }: ICreateVerifyEmailFlowArgs) => IVerifyEmailFlow;
|
|
81
|
+
export declare const createVerifyEmailFlow: ({ model, paths, onAbandon, deletedValue, deleteUserByEmail, mailer, mailThrottle }: ICreateVerifyEmailFlowArgs) => IVerifyEmailFlow;
|
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
import { createAssertVerifyEmailAllowed } from "../../private/lib/access/assertVerifyEmailAllowed.mjs";
|
|
2
|
+
import { createAbandonUser } from "../../private/lib/access/db/abandonUser.mjs";
|
|
2
3
|
import { createConfirmNewEmail } from "../../private/lib/access/db/confirmNewEmail.mjs";
|
|
3
|
-
import { createDeleteUserByEmail } from "../../private/lib/access/db/deleteUserByEmail.mjs";
|
|
4
4
|
import { createEnableEmailAccess } from "../../private/lib/access/db/enableEmailAccess.mjs";
|
|
5
5
|
import { createIncReqTimes } from "../../private/lib/access/db/incReqTimes.mjs";
|
|
6
6
|
import { createSetEmailHash } from "../../private/lib/access/db/setEmailHash.mjs";
|
|
7
7
|
import { createUserData4VerifyEmail } from "../../private/lib/access/db/userData4VerifyEmail.mjs";
|
|
8
|
+
import { createHandleIfAccountDeleted } from "../../private/lib/access/handleIfAccountDeleted.mjs";
|
|
9
|
+
import { createHandleIfAccountDisabled } from "../../private/lib/access/handleIfAccountDisabled.mjs";
|
|
10
|
+
import { createHandleIfEmailAlreadyValid } from "../../private/lib/access/handleIfEmailAlreadyValid.mjs";
|
|
8
11
|
import { createHandleIfHashBad } from "../../private/lib/access/handleIfHashBad.mjs";
|
|
9
12
|
import { createHandleIfMoreThan3DaysPassed } from "../../private/lib/access/handleIfMoreThan3DaysPassed.mjs";
|
|
10
13
|
import { createHandleIfTooMuchRequestsTimes } from "../../private/lib/access/handleIfTooMuchRequestsTimes.mjs";
|
|
11
14
|
import { createEmailChangeHashVerifyMutation } from '../../graphQL/schema/mutations/emailChangeHashVerify.mjs';
|
|
12
15
|
import { createVerifyEmailRouter } from '../../koa/router/verifyEmail.mjs';
|
|
13
16
|
import { resolveVerifyEmailPaths } from './accessPaths.mjs';
|
|
17
|
+
import { createMailThrottle } from './createMailThrottle.mjs';
|
|
18
|
+
import { socketLabsVerifyEmailMailer, throttleMailer } from './verifyEmailMailer.mjs';
|
|
14
19
|
/**
|
|
15
20
|
* Build the whole email-verification chain against any mongoose model.
|
|
16
21
|
*
|
|
@@ -23,40 +28,58 @@ import { resolveVerifyEmailPaths } from './accessPaths.mjs';
|
|
|
23
28
|
* flow reads: a schema storing the verification state as one required-members subdocument is left
|
|
24
29
|
* invalid by unsetting a single member. Pass the container path in that case. See `IVerifyEmailPaths`.
|
|
25
30
|
*
|
|
31
|
+
* Two guards dispose of an abandoned registration — the fifth wrong hash and a link older than 3 days.
|
|
32
|
+
* Through 5.6.1 that always meant `deleteOne`, which is wrong for any row other rows depend on: the
|
|
33
|
+
* package has no idea what a delete costs in a schema it was handed, and a mongo collection has no
|
|
34
|
+
* cascade to lean on. `onAbandon` picks the policy; `deleteUserByEmail` replaces the writer outright.
|
|
35
|
+
* Whatever it does, both guards still throw — disposal never decides whether the link is honoured.
|
|
36
|
+
*
|
|
37
|
+
* Replacing `flow.deleteUserByEmail` on the returned object does nothing, by design: the guards close
|
|
38
|
+
* over the writer at construction time. The value returned is the same one they hold, so it reports the
|
|
39
|
+
* policy rather than setting it.
|
|
40
|
+
*
|
|
26
41
|
* ```ts
|
|
27
42
|
* const flow = createVerifyEmailFlow({
|
|
28
43
|
* model: Account,
|
|
29
|
-
* paths: { email: 'mail', valid: 'verified', verifyClear: ['verification'] }
|
|
44
|
+
* paths: { email: 'mail', valid: 'verified', verifyClear: ['verification'] },
|
|
45
|
+
* onAbandon: 'soft-delete',
|
|
46
|
+
* deletedValue: () => new Date()
|
|
30
47
|
* })
|
|
31
48
|
* router.get('/check/verify-email/:email/:hash', flow.routerVerifyEmail())
|
|
32
49
|
* ```
|
|
33
50
|
*/
|
|
34
|
-
export const createVerifyEmailFlow = ({ model, paths }) => {
|
|
51
|
+
export const createVerifyEmailFlow = ({ model, paths, onAbandon = 'delete', deletedValue, deleteUserByEmail, mailer, mailThrottle }) => {
|
|
35
52
|
const resolved = resolveVerifyEmailPaths(paths);
|
|
53
|
+
const resolvedMailer = mailer ?? throttleMailer(socketLabsVerifyEmailMailer, mailThrottle ?? createMailThrottle());
|
|
36
54
|
const userData4VerifyEmail = createUserData4VerifyEmail(model, resolved);
|
|
37
|
-
const enableEmailAccess = createEnableEmailAccess(model, resolved);
|
|
55
|
+
const enableEmailAccess = createEnableEmailAccess(model, resolved, resolvedMailer);
|
|
38
56
|
const confirmNewEmail = createConfirmNewEmail(model, resolved);
|
|
39
|
-
|
|
57
|
+
// One writer, used by the guards and handed back — the returned member cannot disagree with what runs.
|
|
58
|
+
const abandonUser = deleteUserByEmail ?? createAbandonUser({ model, paths: resolved, mode: onAbandon, deletedValue });
|
|
40
59
|
const incReqTimes = createIncReqTimes(model, resolved);
|
|
41
60
|
const assertVerifyEmailAllowed = createAssertVerifyEmailAllowed({
|
|
42
61
|
paths: resolved,
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
62
|
+
handleIfEmailAlreadyValid: createHandleIfEmailAlreadyValid(resolvedMailer),
|
|
63
|
+
handleIfHashBad: createHandleIfHashBad(incReqTimes, resolvedMailer),
|
|
64
|
+
handleIfMoreThan3DaysPassed: createHandleIfMoreThan3DaysPassed(abandonUser, resolvedMailer),
|
|
65
|
+
handleIfTooMuchRequestsTimes: createHandleIfTooMuchRequestsTimes(abandonUser, resolvedMailer),
|
|
66
|
+
handleIfAccountDeleted: createHandleIfAccountDeleted(resolvedMailer),
|
|
67
|
+
handleIfAccountDisabled: createHandleIfAccountDisabled(resolvedMailer)
|
|
46
68
|
});
|
|
47
69
|
return {
|
|
48
70
|
userData4VerifyEmail,
|
|
49
71
|
setEmailHash: createSetEmailHash(model, resolved),
|
|
50
72
|
enableEmailAccess,
|
|
51
73
|
confirmNewEmail,
|
|
52
|
-
deleteUserByEmail,
|
|
74
|
+
deleteUserByEmail: abandonUser,
|
|
53
75
|
incReqTimes,
|
|
54
76
|
assertVerifyEmailAllowed,
|
|
55
77
|
emailChangeHashVerify: createEmailChangeHashVerifyMutation({
|
|
56
78
|
model,
|
|
57
79
|
paths: resolved,
|
|
58
80
|
confirmNewEmail,
|
|
59
|
-
incReqTimes
|
|
81
|
+
incReqTimes,
|
|
82
|
+
mailer: resolvedMailer
|
|
60
83
|
}),
|
|
61
84
|
routerVerifyEmail: createVerifyEmailRouter({
|
|
62
85
|
userData4VerifyEmail,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createVerifyEmailFlow.mjs","sourceRoot":"","sources":["../../../src/lib/access/createVerifyEmailFlow.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,8BAA8B,EAA6B,8DAAwD;AAC5H,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"createVerifyEmailFlow.mjs","sourceRoot":"","sources":["../../../src/lib/access/createVerifyEmailFlow.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,8BAA8B,EAA6B,8DAAwD;AAC5H,OAAO,EAAE,iBAAiB,EAAE,oDAA8C;AAC1E,OAAO,EAAE,qBAAqB,EAAoB,wDAAkD;AAEpG,OAAO,EAAE,uBAAuB,EAAsB,0DAAoD;AAC1G,OAAO,EAAE,iBAAiB,EAAgB,oDAA8C;AACxF,OAAO,EAAE,kBAAkB,EAAiB,qDAA+C;AAC3F,OAAO,EAAE,0BAA0B,EAAyB,6DAAuD;AACnH,OAAO,EAAE,4BAA4B,EAAE,4DAAsD;AAC7F,OAAO,EAAE,6BAA6B,EAAE,6DAAuD;AAC/F,OAAO,EAAE,+BAA+B,EAAE,+DAAyD;AACnG,OAAO,EAAE,qBAAqB,EAAE,qDAA+C;AAC/E,OAAO,EAAE,iCAAiC,EAAE,iEAA2D;AACvG,OAAO,EAAE,kCAAkC,EAAE,kEAA4D;AAEzG,OAAO,EACN,mCAAmC,EAEnC,MAAM,0DAA0D,CAAA;AACjE,OAAO,EAAE,uBAAuB,EAAsB,MAAM,kCA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E,cAAc,CAAC;QAC3F,4BAA4B,EAAE,kCAAkC,CAAC,WAAW,EAAE,cAAc,CAAC;QAC7F,sBAAsB,EAAE,4BAA4B,CAAC,cAAc,CAAC;QACpE,uBAAuB,EAAE,6BAA6B,CAAC,cAAc,CAAC;KACtE,CAAC,CAAA;IAEF,OAAO;QACN,oBAAoB;QACpB,YAAY,EAAE,kBAAkB,CAAC,KAAK,EAAE,QAAQ,CAAC;QACjD,iBAAiB;QACjB,eAAe;QACf,iBAAiB,EAAE,WAAW;QAC9B,WAAW;QACX,wBAAwB;QACxB,qBAAqB,EAAE,mCAAmC,CAAC;YAC1D,KAAK;YACL,KAAK,EAAE,QAAQ;YACf,eAAe;YACf,WAAW;YACX,MAAM,EAAE,cAAc;SACtB,CAAC;QACF,iBAAiB,EAAE,uBAAuB,CAAC;YAC1C,oBAAoB;YACpB,wBAAwB;YACxB,iBAAiB;SACjB,CAAC;KACF,CAAA;AACF,CAAC,CAAA","sourcesContent":["import { createAssertVerifyEmailAllowed, TAssertVerifyEmailAllowed } from '@private/lib/access/assertVerifyEmailAllowed.mjs'\nimport { createAbandonUser } from '@private/lib/access/db/abandonUser.mjs'\nimport { createConfirmNewEmail, TConfirmNewEmail } from '@private/lib/access/db/confirmNewEmail.mjs'\nimport { TDeleteUserByEmail } from '@private/lib/access/db/deleteUserByEmail.mjs'\nimport { createEnableEmailAccess, TEnableEmailAccess } from '@private/lib/access/db/enableEmailAccess.mjs'\nimport { createIncReqTimes, TIncReqTimes } from '@private/lib/access/db/incReqTimes.mjs'\nimport { createSetEmailHash, TSetEmailHash } from '@private/lib/access/db/setEmailHash.mjs'\nimport { createUserData4VerifyEmail, TUserData4VerifyEmail } from '@private/lib/access/db/userData4VerifyEmail.mjs'\nimport { createHandleIfAccountDeleted } from '@private/lib/access/handleIfAccountDeleted.mjs'\nimport { createHandleIfAccountDisabled } from '@private/lib/access/handleIfAccountDisabled.mjs'\nimport { createHandleIfEmailAlreadyValid } from '@private/lib/access/handleIfEmailAlreadyValid.mjs'\nimport { createHandleIfHashBad } from '@private/lib/access/handleIfHashBad.mjs'\nimport { createHandleIfMoreThan3DaysPassed } from '@private/lib/access/handleIfMoreThan3DaysPassed.mjs'\nimport { createHandleIfTooMuchRequestsTimes } from '@private/lib/access/handleIfTooMuchRequestsTimes.mjs'\n\nimport {\n\tcreateEmailChangeHashVerifyMutation,\n\tTEmailChangeHashVerifyMutation\n} from '../../graphQL/schema/mutations/emailChangeHashVerify.mjs'\nimport { createVerifyEmailRouter, TVerifyEmailRouter } from '../../koa/router/verifyEmail.mjs'\nimport { IVerifyEmailPaths, resolveVerifyEmailPaths, TAccessModel, TOnAbandon } from './accessPaths.mjs'\nimport { createMailThrottle, TMailThrottle } from './createMailThrottle.mjs'\nimport { IVerifyEmailMailer, socketLabsVerifyEmailMailer, throttleMailer } from './verifyEmailMailer.mjs'\n\n/** What the factory needs: the account model, plus any path or policy that differs from the default. */\nexport interface ICreateVerifyEmailFlowArgs {\n\tmodel: TAccessModel\n\tpaths?: Partial<IVerifyEmailPaths>\n\t/** How an abandoned/expired registration is disposed of. Default `'delete'` — current behaviour. */\n\tonAbandon?: TOnAbandon\n\t/**\n\t * Value `'soft-delete'` writes to `paths.deleted`. A function is called once per write, so a layout\n\t * storing a timestamp passes `() => new Date()`. Default `true`, matching `UserBase`. Ignored by the\n\t * other two modes.\n\t */\n\tdeletedValue?: unknown\n\t/** Full override of the disposal writer; wins over `onAbandon` and `deletedValue`. */\n\tdeleteUserByEmail?: TDeleteUserByEmail\n\t/** Who sends the verify-email notifications. Default: SocketLabs, debounced by `mailThrottle`. */\n\tmailer?: IVerifyEmailMailer\n\t/**\n\t * Debounce applied to every notification an unauthenticated request can trigger. Default: a 15 minute\n\t * per-address, per-template window. Pass `ALWAYS_MAIL` for the send-every-time behaviour of 5.6.1 and earlier, or a\n\t * Redis-backed one to share the window across instances. Ignored when `mailer` is supplied — wrap it\n\t * yourself with `throttleMailer` if you want both.\n\t */\n\tmailThrottle?: TMailThrottle\n}\n\n/** Everything the verify-email chain exposes, bound to the model and paths passed in. */\nexport interface IVerifyEmailFlow {\n\tuserData4VerifyEmail: TUserData4VerifyEmail\n\tsetEmailHash: TSetEmailHash\n\tenableEmailAccess: TEnableEmailAccess\n\tconfirmNewEmail: TConfirmNewEmail\n\tdeleteUserByEmail: TDeleteUserByEmail\n\tincReqTimes: TIncReqTimes\n\tassertVerifyEmailAllowed: TAssertVerifyEmailAllowed\n\temailChangeHashVerify: TEmailChangeHashVerifyMutation\n\trouterVerifyEmail: TVerifyEmailRouter\n}\n\n/**\n * Build the whole email-verification chain against any mongoose model.\n *\n * The package's own exports (`userData4VerifyEmail`, `setEmailHash`, `enableEmailAccess`,\n * `confirmNewEmail`, `emailChangeHashVerify`, `routerVerifyEmail`) are this factory applied to\n * `UserBase` with `DEFAULT_VERIFY_EMAIL_PATHS`, so switching to it changes nothing until a path is\n * overridden.\n *\n * The two `*Clear` keys are lists of paths to `$unset`, and neither is derived from the leaf paths the\n * flow reads: a schema storing the verification state as one required-members subdocument is left\n * invalid by unsetting a single member. Pass the container path in that case. See `IVerifyEmailPaths`.\n *\n * Two guards dispose of an abandoned registration — the fifth wrong hash and a link older than 3 days.\n * Through 5.6.1 that always meant `deleteOne`, which is wrong for any row other rows depend on: the\n * package has no idea what a delete costs in a schema it was handed, and a mongo collection has no\n * cascade to lean on. `onAbandon` picks the policy; `deleteUserByEmail` replaces the writer outright.\n * Whatever it does, both guards still throw — disposal never decides whether the link is honoured.\n *\n * Replacing `flow.deleteUserByEmail` on the returned object does nothing, by design: the guards close\n * over the writer at construction time. The value returned is the same one they hold, so it reports the\n * policy rather than setting it.\n *\n * ```ts\n * const flow = createVerifyEmailFlow({\n * model: Account,\n * paths: { email: 'mail', valid: 'verified', verifyClear: ['verification'] },\n * onAbandon: 'soft-delete',\n * deletedValue: () => new Date()\n * })\n * router.get('/check/verify-email/:email/:hash', flow.routerVerifyEmail())\n * ```\n */\nexport const createVerifyEmailFlow = ({\n\tmodel,\n\tpaths,\n\tonAbandon = 'delete',\n\tdeletedValue,\n\tdeleteUserByEmail,\n\tmailer,\n\tmailThrottle\n}: ICreateVerifyEmailFlowArgs): IVerifyEmailFlow => {\n\tconst resolved = resolveVerifyEmailPaths(paths)\n\tconst resolvedMailer = mailer ?? throttleMailer(socketLabsVerifyEmailMailer, mailThrottle ?? createMailThrottle())\n\n\tconst userData4VerifyEmail = createUserData4VerifyEmail(model, resolved)\n\tconst enableEmailAccess = createEnableEmailAccess(model, resolved, resolvedMailer)\n\tconst confirmNewEmail = createConfirmNewEmail(model, resolved)\n\t// One writer, used by the guards and handed back — the returned member cannot disagree with what runs.\n\tconst abandonUser = deleteUserByEmail ?? createAbandonUser({ model, paths: resolved, mode: onAbandon, deletedValue })\n\tconst incReqTimes = createIncReqTimes(model, resolved)\n\n\tconst assertVerifyEmailAllowed = createAssertVerifyEmailAllowed({\n\t\tpaths: resolved,\n\t\thandleIfEmailAlreadyValid: createHandleIfEmailAlreadyValid(resolvedMailer),\n\t\thandleIfHashBad: createHandleIfHashBad(incReqTimes, resolvedMailer),\n\t\thandleIfMoreThan3DaysPassed: createHandleIfMoreThan3DaysPassed(abandonUser, resolvedMailer),\n\t\thandleIfTooMuchRequestsTimes: createHandleIfTooMuchRequestsTimes(abandonUser, resolvedMailer),\n\t\thandleIfAccountDeleted: createHandleIfAccountDeleted(resolvedMailer),\n\t\thandleIfAccountDisabled: createHandleIfAccountDisabled(resolvedMailer)\n\t})\n\n\treturn {\n\t\tuserData4VerifyEmail,\n\t\tsetEmailHash: createSetEmailHash(model, resolved),\n\t\tenableEmailAccess,\n\t\tconfirmNewEmail,\n\t\tdeleteUserByEmail: abandonUser,\n\t\tincReqTimes,\n\t\tassertVerifyEmailAllowed,\n\t\temailChangeHashVerify: createEmailChangeHashVerifyMutation({\n\t\t\tmodel,\n\t\t\tpaths: resolved,\n\t\t\tconfirmNewEmail,\n\t\t\tincReqTimes,\n\t\t\tmailer: resolvedMailer\n\t\t}),\n\t\trouterVerifyEmail: createVerifyEmailRouter({\n\t\t\tuserData4VerifyEmail,\n\t\t\tassertVerifyEmailAllowed,\n\t\t\tenableEmailAccess\n\t\t})\n\t}\n}\n"]}
|