@proteinjs/user-server 1.26.1 → 1.28.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/CHANGELOG.md +22 -0
- package/dist/generated/index.d.ts.map +1 -1
- package/dist/generated/index.js +3 -1
- package/dist/generated/index.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/dist/src/authentication/EmailVerificationToken.d.ts +23 -0
- package/dist/src/authentication/EmailVerificationToken.d.ts.map +1 -0
- package/dist/src/authentication/EmailVerificationToken.js +90 -0
- package/dist/src/authentication/EmailVerificationToken.js.map +1 -0
- package/dist/src/authentication/MailedToken.d.ts +91 -0
- package/dist/src/authentication/MailedToken.d.ts.map +1 -0
- package/dist/src/authentication/MailedToken.js +221 -0
- package/dist/src/authentication/MailedToken.js.map +1 -0
- package/dist/src/authentication/PasswordResetToken.d.ts +7 -61
- package/dist/src/authentication/PasswordResetToken.d.ts.map +1 -1
- package/dist/src/authentication/PasswordResetToken.js +25 -140
- package/dist/src/authentication/PasswordResetToken.js.map +1 -1
- package/dist/src/routes/signup.d.ts +8 -3
- package/dist/src/routes/signup.d.ts.map +1 -1
- package/dist/src/routes/signup.js +55 -15
- package/dist/src/routes/signup.js.map +1 -1
- package/dist/src/routes/verifyEmail.d.ts +21 -0
- package/dist/src/routes/verifyEmail.d.ts.map +1 -0
- package/dist/src/routes/verifyEmail.js +107 -0
- package/dist/src/routes/verifyEmail.js.map +1 -0
- package/dist/src/services/DisposableEmailDomains.d.ts +24 -0
- package/dist/src/services/DisposableEmailDomains.d.ts.map +1 -0
- package/dist/src/services/DisposableEmailDomains.js +129 -0
- package/dist/src/services/DisposableEmailDomains.js.map +1 -0
- package/dist/src/services/Signup.d.ts +27 -1
- package/dist/src/services/Signup.d.ts.map +1 -1
- package/dist/src/services/Signup.js +166 -30
- package/dist/src/services/Signup.js.map +1 -1
- package/dist/src/services/SignupGuard.d.ts +55 -0
- package/dist/src/services/SignupGuard.d.ts.map +1 -0
- package/dist/src/services/SignupGuard.js +13 -0
- package/dist/src/services/SignupGuard.js.map +1 -0
- package/dist/test/EmailVerification.test.d.ts +2 -0
- package/dist/test/EmailVerification.test.d.ts.map +1 -0
- package/dist/test/EmailVerification.test.js +451 -0
- package/dist/test/EmailVerification.test.js.map +1 -0
- package/dist/test/Signup.test.js +8 -0
- package/dist/test/Signup.test.js.map +1 -1
- package/dist/test/SignupGuardSeam.test.d.ts +2 -0
- package/dist/test/SignupGuardSeam.test.d.ts.map +1 -0
- package/dist/test/SignupGuardSeam.test.js +474 -0
- package/dist/test/SignupGuardSeam.test.js.map +1 -0
- package/dist/test/UserServerTestEnvironment.d.ts.map +1 -1
- package/dist/test/UserServerTestEnvironment.js +4 -0
- package/dist/test/UserServerTestEnvironment.js.map +1 -1
- package/generated/index.ts +3 -1
- package/index.ts +10 -0
- package/package.json +4 -4
- package/src/authentication/EmailVerificationToken.ts +32 -0
- package/src/authentication/MailedToken.ts +171 -0
- package/src/authentication/PasswordResetToken.ts +13 -131
- package/src/routes/signup.ts +58 -9
- package/src/routes/verifyEmail.ts +64 -0
- package/src/services/DisposableEmailDomains.ts +125 -0
- package/src/services/Signup.ts +111 -10
- package/src/services/SignupGuard.ts +58 -0
- package/test/EmailVerification.test.ts +297 -0
- package/test/Signup.test.ts +11 -1
- package/test/SignupGuardSeam.test.ts +299 -0
- package/test/UserServerTestEnvironment.ts +4 -0
package/src/services/Signup.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getDbAsSystem, Reference } from '@proteinjs/db';
|
|
2
2
|
import {
|
|
3
3
|
SendInviteResponse,
|
|
4
|
+
ResendEmailVerificationResponse,
|
|
4
5
|
tables,
|
|
5
6
|
UserAuth,
|
|
6
7
|
uiRoutes,
|
|
@@ -22,8 +23,11 @@ import {
|
|
|
22
23
|
getDefaultInviteEmailConfigFactory,
|
|
23
24
|
getDefaultSignupConfirmationEmailConfigFactory,
|
|
24
25
|
InviteEmailConfig,
|
|
26
|
+
SignupConfirmationEmailConfig,
|
|
27
|
+
SignupConfirmationEmailContext,
|
|
25
28
|
} from '@proteinjs/email-server';
|
|
26
29
|
import { Loadable, SourceRepository } from '@proteinjs/reflection';
|
|
30
|
+
import { EmailVerificationToken } from '../authentication/EmailVerificationToken';
|
|
27
31
|
import { PasswordHasher } from '../authentication/PasswordHasher';
|
|
28
32
|
|
|
29
33
|
/**
|
|
@@ -33,6 +37,13 @@ import { PasswordHasher } from '../authentication/PasswordHasher';
|
|
|
33
37
|
*/
|
|
34
38
|
export const INVITE_TOKEN_TTL_DAYS = 90;
|
|
35
39
|
|
|
40
|
+
/**
|
|
41
|
+
* The gap between two verification mails to one account — the password reset's five minutes:
|
|
42
|
+
* long enough that a double tap sends one mail, short enough that a mistyped-looking inbox wait
|
|
43
|
+
* ends soon.
|
|
44
|
+
*/
|
|
45
|
+
export const EMAIL_VERIFICATION_RESEND_GAP_MINUTES = 5;
|
|
46
|
+
|
|
36
47
|
export interface InviteConfig {
|
|
37
48
|
isInviteOnly: boolean;
|
|
38
49
|
}
|
|
@@ -82,6 +93,12 @@ export class Signup implements SignupService {
|
|
|
82
93
|
return UserAuth.hasPermission(USER_PERMISSIONS.users);
|
|
83
94
|
}
|
|
84
95
|
|
|
96
|
+
// The re-send is the signed-in account's own act: it reads the session's user and mails
|
|
97
|
+
// that account, nobody else's.
|
|
98
|
+
if (methodName === 'resendEmailVerification') {
|
|
99
|
+
return UserAuth.isLoggedIn();
|
|
100
|
+
}
|
|
101
|
+
|
|
85
102
|
return true;
|
|
86
103
|
},
|
|
87
104
|
},
|
|
@@ -114,8 +131,7 @@ export class Signup implements SignupService {
|
|
|
114
131
|
throw new Error('Email is required when there is no invite');
|
|
115
132
|
}
|
|
116
133
|
|
|
117
|
-
const
|
|
118
|
-
const config = defaultEmailConfigFactory.getConfig();
|
|
134
|
+
const config = this.signupConfirmationEmailConfig();
|
|
119
135
|
const emailSender = new EmailSender();
|
|
120
136
|
|
|
121
137
|
const creation = await this.createAccount({
|
|
@@ -143,18 +159,66 @@ export class Signup implements SignupService {
|
|
|
143
159
|
return { outcome: 'exists', email };
|
|
144
160
|
}
|
|
145
161
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
162
|
+
// An invited address was proved by the invite mail; a plain sign-up's welcome carries the
|
|
163
|
+
// link that confirms it (the account works meanwhile — nothing waits on the tap).
|
|
164
|
+
const verification = invite ? undefined : await this.mintEmailVerification(email);
|
|
165
|
+
try {
|
|
166
|
+
await this.emailWelcome(emailSender, email, config, verification && { verifyEmailLink: verification.link });
|
|
167
|
+
} catch (error) {
|
|
168
|
+
// The link never reached the account: withdraw the token, so the account page's re-send
|
|
169
|
+
// is not held by the gap between mails.
|
|
170
|
+
if (verification) {
|
|
171
|
+
await new EmailVerificationToken().revoke(verification.user, verification.token);
|
|
172
|
+
}
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
154
175
|
logger.info({ message: `Created user`, obj: { account: new RequestDigests().account(email) } });
|
|
155
176
|
return { outcome: 'created', email };
|
|
156
177
|
}
|
|
157
178
|
|
|
179
|
+
/**
|
|
180
|
+
* The signed-in account's own re-send: a fresh token replaces the one outstanding (the earlier
|
|
181
|
+
* link stops working) and the welcome-shaped mail goes out again with the new link, through the
|
|
182
|
+
* same config as the sign-up's. Refused without a word — `{ sent: false }` — when the address is
|
|
183
|
+
* already verified, when the last mint is inside the gap, or when the mail fails to send (the
|
|
184
|
+
* token is withdrawn then, so the next tap is not held by the gap). The account is the
|
|
185
|
+
* session's, read fresh from its row: a verification completed on another device is seen here.
|
|
186
|
+
*/
|
|
187
|
+
async resendEmailVerification(): Promise<ResendEmailVerificationResponse> {
|
|
188
|
+
const logger = new Logger({ name: 'Signup.resendEmailVerification' });
|
|
189
|
+
const digests = new RequestDigests();
|
|
190
|
+
const user = await getDbAsSystem().get(tables.User, { id: new UserRepo().getUser().id });
|
|
191
|
+
if (!user || user.emailVerified) {
|
|
192
|
+
return { sent: false };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const fields = { account: digests.account(user.email) };
|
|
196
|
+
const verification = new EmailVerificationToken();
|
|
197
|
+
const mintedAt = verification.mintedAt(user);
|
|
198
|
+
if (mintedAt && moment().diff(mintedAt, 'minutes') < EMAIL_VERIFICATION_RESEND_GAP_MINUTES) {
|
|
199
|
+
logger.info({ message: `Email verification re-send requested too soon`, obj: fields });
|
|
200
|
+
return { sent: false };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const token = await verification.mint(user);
|
|
204
|
+
try {
|
|
205
|
+
await this.emailWelcome(new EmailSender(), user.email, this.signupConfirmationEmailConfig(), {
|
|
206
|
+
verifyEmailLink: this.verifyEmailLink(token),
|
|
207
|
+
});
|
|
208
|
+
} catch (error: any) {
|
|
209
|
+
logger.error({
|
|
210
|
+
message: `Failed to send the email verification mail`,
|
|
211
|
+
obj: fields,
|
|
212
|
+
error: digests.redactError(error),
|
|
213
|
+
});
|
|
214
|
+
await verification.revoke(user, token);
|
|
215
|
+
return { sent: false };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
logger.info({ message: `Email verification link mailed`, obj: fields });
|
|
219
|
+
return { sent: true };
|
|
220
|
+
}
|
|
221
|
+
|
|
158
222
|
async sendInvite(email: string): Promise<SendInviteResponse> {
|
|
159
223
|
const logger = new Logger({ name: 'Signup.sendInvite' });
|
|
160
224
|
const caseInsensitiveEmail = email.toLowerCase();
|
|
@@ -417,4 +481,41 @@ export class Signup implements SignupService {
|
|
|
417
481
|
...config.options,
|
|
418
482
|
});
|
|
419
483
|
}
|
|
484
|
+
|
|
485
|
+
/** The sign-up mails' content factory: the consumer's registration, or the library's default. */
|
|
486
|
+
private signupConfirmationEmailConfig(): SignupConfirmationEmailConfig {
|
|
487
|
+
return getDefaultSignupConfirmationEmailConfigFactory().getConfig();
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* The welcome mail — the new-user content from the config, handed the confirm link when the
|
|
492
|
+
* address is unverified (an invited account's welcome carries no context).
|
|
493
|
+
*/
|
|
494
|
+
private async emailWelcome(
|
|
495
|
+
emailSender: EmailSender,
|
|
496
|
+
email: string,
|
|
497
|
+
config: SignupConfirmationEmailConfig,
|
|
498
|
+
context?: SignupConfirmationEmailContext
|
|
499
|
+
): Promise<void> {
|
|
500
|
+
const { text, html } = config.getNewUserEmailContent(context);
|
|
501
|
+
await emailSender.sendEmail({
|
|
502
|
+
to: email,
|
|
503
|
+
subject: config.newUserSubject || config.options?.subject || 'Welcome!',
|
|
504
|
+
text,
|
|
505
|
+
html,
|
|
506
|
+
...config.options,
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** A fresh verification token on the account's row, with the confirm link that carries it. */
|
|
511
|
+
private async mintEmailVerification(email: string): Promise<{ user: User; token: string; link: string }> {
|
|
512
|
+
const user = await getDbAsSystem().get(tables.User, { email });
|
|
513
|
+
const token = await new EmailVerificationToken().mint(user);
|
|
514
|
+
return { user, token, link: this.verifyEmailLink(token) };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** The partial path a confirm link carries — the app's verify page with the token (not a full URL). */
|
|
518
|
+
private verifyEmailLink(token: string): string {
|
|
519
|
+
return `${uiRoutes.account.verifyEmail}?token=${token}`;
|
|
520
|
+
}
|
|
420
521
|
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { Loadable, SourceRepository } from '@proteinjs/reflection';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* What the signup route hands the guard about a no-invite submission: request facts only the
|
|
5
|
+
* route can read, reduced to what an abuse posture needs and never anything that identifies the
|
|
6
|
+
* client on its own.
|
|
7
|
+
*/
|
|
8
|
+
export type SignupGuardFacts = {
|
|
9
|
+
/** The address the form carries, trimmed and lowercased — the account's address if the signup goes through. */
|
|
10
|
+
email: string;
|
|
11
|
+
/**
|
|
12
|
+
* The form's honeypot field (`website`) when the form carries one — a field no person sees, so
|
|
13
|
+
* a value in it is bot-shaped. Undefined when the form has no such field.
|
|
14
|
+
*/
|
|
15
|
+
honeypot?: string;
|
|
16
|
+
/** The render-moment token the form carries, when it carries one — a consumer's time trap verifies it. */
|
|
17
|
+
formToken?: string;
|
|
18
|
+
/**
|
|
19
|
+
* The coarse hash of the client's address (`RequestDigests.coarseIp` of the address `ClientAddress`
|
|
20
|
+
* reads): the key a per-device window counts on and the name a log line gives a device. Never
|
|
21
|
+
* the address itself.
|
|
22
|
+
*/
|
|
23
|
+
clientDevice: string;
|
|
24
|
+
/** Whether the request carried a User-Agent header at all. */
|
|
25
|
+
hasUserAgent: boolean;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The guard's answer, one of three:
|
|
30
|
+
* - `allow` — the signup continues: the account is created and its session established;
|
|
31
|
+
* - `refuse` — the route answers `{ error: sentence }` with no account and no session; the
|
|
32
|
+
* sentence is read by the person, so it is plain words in full;
|
|
33
|
+
* - `drop` — the route answers exactly as it answers success (`{}`) with no account and no
|
|
34
|
+
* session, and the caller cannot tell: the silent drop for a bot-shaped submission, which gets
|
|
35
|
+
* nothing to iterate against.
|
|
36
|
+
*/
|
|
37
|
+
export type SignupGuardVerdict = { verdict: 'allow' } | { verdict: 'refuse'; sentence: string } | { verdict: 'drop' };
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The seam a consumer plugs its sign-up abuse posture into — a honeypot, a time trap, a
|
|
41
|
+
* per-device throttle, a daily breaker, whatever it holds — by registering a class that
|
|
42
|
+
* implements this interface (the `DefaultInviteConfigFactory` pattern; the first registration
|
|
43
|
+
* found is the guard). The signup route consults it on the NO-INVITE road only: an invited
|
|
44
|
+
* address was chosen by an admin, and the invite road is unchanged. With no registration every
|
|
45
|
+
* submission is allowed.
|
|
46
|
+
*/
|
|
47
|
+
export interface DefaultSignupGuard extends Loadable {
|
|
48
|
+
check(facts: SignupGuardFacts): SignupGuardVerdict | Promise<SignupGuardVerdict>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const getDefaultSignupGuard = (): DefaultSignupGuard => {
|
|
52
|
+
const allowEvery: DefaultSignupGuard = {
|
|
53
|
+
check: (): SignupGuardVerdict => ({ verdict: 'allow' }),
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const guard = SourceRepository.get().object<DefaultSignupGuard>('@proteinjs/user-server/DefaultSignupGuard');
|
|
57
|
+
return guard || allowEvery;
|
|
58
|
+
};
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
import moment from 'moment';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Email verification after sign-up — the library half, outcomes only, against the Spanner
|
|
6
|
+
* emulator (rows written, the context the config was handed, the mails sent, the states
|
|
7
|
+
* answered):
|
|
8
|
+
* - a plain sign-up's account works at once; its row stores the verification pair (the token's
|
|
9
|
+
* digest, an expiry a week out) and the welcome mail's config is handed the link that carries
|
|
10
|
+
* the token — the digest never rides the mail;
|
|
11
|
+
* - an invited sign-up stores no pair and the config is handed no context: the invite mail proved
|
|
12
|
+
* the address (the regression guard on the invite road);
|
|
13
|
+
* - `GET /user/verify-email?token=` spends the link once: 'confirmed' with `emailVerified` set
|
|
14
|
+
* and the pair cleared; the same token again is 'invalid' (cleared is unknown); a lapsed link
|
|
15
|
+
* is 'expired' with the flag unchanged; an unknown, malformed or missing token is 'invalid';
|
|
16
|
+
* no answer names an address;
|
|
17
|
+
* - the signed-in account's re-send mints a fresh pair (the earlier link stops working) and sends
|
|
18
|
+
* one mail; inside the gap it sends nothing and the pair stands; a verified account gets
|
|
19
|
+
* `{ sent: false }` and no mail.
|
|
20
|
+
* The mail transport and the config are doubled at the module boundary (SignupRoute.test.ts
|
|
21
|
+
* pattern) — the config double records every context it is handed; the db stays real.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const sendEmail = jest.fn();
|
|
25
|
+
/** Every context `getNewUserEmailContent` was handed, in call order — `undefined` when none. */
|
|
26
|
+
const newUserContexts: unknown[] = [];
|
|
27
|
+
|
|
28
|
+
jest.mock('@proteinjs/email-server', () => ({
|
|
29
|
+
EmailSender: jest.fn().mockImplementation(() => ({ sendEmail })),
|
|
30
|
+
getDefaultInviteEmailConfigFactory: () => ({
|
|
31
|
+
getConfig: () => ({ getEmailContent: () => ({ text: 'invite', html: '<p>invite</p>' }) }),
|
|
32
|
+
}),
|
|
33
|
+
getDefaultSignupConfirmationEmailConfigFactory: () => ({
|
|
34
|
+
getConfig: () => ({
|
|
35
|
+
newUserSubject: 'Welcome aboard',
|
|
36
|
+
getNewUserEmailContent: (context?: { verifyEmailLink?: string }) => {
|
|
37
|
+
newUserContexts.push(context);
|
|
38
|
+
const confirm = context?.verifyEmailLink ? ` Confirm: https://app.test/${context.verifyEmailLink}` : '';
|
|
39
|
+
return { text: `welcome${confirm}`, html: '<p>welcome</p>' };
|
|
40
|
+
},
|
|
41
|
+
}),
|
|
42
|
+
}),
|
|
43
|
+
}));
|
|
44
|
+
|
|
45
|
+
import { getDbAsSystem, Reference } from '@proteinjs/db';
|
|
46
|
+
import { SourceRepository } from '@proteinjs/reflection';
|
|
47
|
+
import { tables, uiRoutes, User } from '@proteinjs/user';
|
|
48
|
+
import { EmailVerificationToken } from '../src/authentication/EmailVerificationToken';
|
|
49
|
+
import { verifyEmail } from '../src/routes/verifyEmail';
|
|
50
|
+
import { EMAIL_VERIFICATION_RESEND_GAP_MINUTES, Signup } from '../src/services/Signup';
|
|
51
|
+
import { UserServerTestEnvironment } from './UserServerTestEnvironment';
|
|
52
|
+
|
|
53
|
+
const testEnv = new UserServerTestEnvironment();
|
|
54
|
+
|
|
55
|
+
type ObjectCache = { objectCache: Record<string, unknown[]> };
|
|
56
|
+
type RouteOutcome = { status?: number; body?: { state?: string } };
|
|
57
|
+
|
|
58
|
+
const TOKEN_SHAPE = /^[0-9a-f]{64}$/;
|
|
59
|
+
const EXPECTED_LIFETIME_DAYS = 7;
|
|
60
|
+
/** Tolerance for the clock advancing between the mint and the assertion. */
|
|
61
|
+
const CLOCK_SKEW_TOLERANCE_SECONDS = 60;
|
|
62
|
+
|
|
63
|
+
const sha256Hex = (value: string) => createHash('sha256').update(value).digest('hex');
|
|
64
|
+
|
|
65
|
+
/** The same `moment().add(days, 'days')` arithmetic the mint uses, so a DST boundary inside the week cancels out. */
|
|
66
|
+
const secondsFromExpectedLifetime = (expiration: unknown, days: number) =>
|
|
67
|
+
Math.abs(moment(expiration as moment.MomentInput).diff(moment().add(days, 'days'), 'seconds'));
|
|
68
|
+
|
|
69
|
+
const userRow = async (email: string): Promise<User> => await getDbAsSystem().get(tables.User, { email });
|
|
70
|
+
|
|
71
|
+
/** The token a verify-email link carries. */
|
|
72
|
+
const tokenIn = (link: string | undefined): string => {
|
|
73
|
+
const token = /[?&]token=([0-9a-f]{64})$/.exec(link ?? '')?.[1];
|
|
74
|
+
if (!token) {
|
|
75
|
+
throw new Error('The link carries no verification token');
|
|
76
|
+
}
|
|
77
|
+
return token;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** The link the newest welcome mail's config was handed. */
|
|
81
|
+
const latestLink = (): string | undefined =>
|
|
82
|
+
(newUserContexts[newUserContexts.length - 1] as { verifyEmailLink?: string } | undefined)?.verifyEmailLink;
|
|
83
|
+
|
|
84
|
+
/** The token in the newest mail's text — what the account's inbox actually holds. */
|
|
85
|
+
const mailedToken = (): string =>
|
|
86
|
+
tokenIn(/https:\/\/app\.test\/(\S+)/.exec(sendEmail.mock.lastCall?.[0]?.text ?? '')?.[1]);
|
|
87
|
+
|
|
88
|
+
/** A plain (no-invite) sign-up; answers the row and the token its welcome mail carried. */
|
|
89
|
+
const signUp = async (email: string): Promise<{ user: User; token: string }> => {
|
|
90
|
+
const result = await new Signup().createUser({ name: 'Plain Signup', email, password: 'a password' });
|
|
91
|
+
expect(result.outcome).toBe('created');
|
|
92
|
+
return { user: await userRow(email), token: mailedToken() };
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const invokeVerify = async (query: Record<string, unknown>): Promise<RouteOutcome> => {
|
|
96
|
+
const outcome: RouteOutcome = {};
|
|
97
|
+
const response = {
|
|
98
|
+
status(code: number) {
|
|
99
|
+
outcome.status = code;
|
|
100
|
+
return this;
|
|
101
|
+
},
|
|
102
|
+
send(body?: unknown) {
|
|
103
|
+
outcome.body = body as RouteOutcome['body'];
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
await verifyEmail.onRequest({ query } as never, response as never);
|
|
107
|
+
return outcome;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/** Moves an account's last mint back past the re-send gap, so only the flag can refuse. */
|
|
111
|
+
const ageLastMint = async (user: User) => {
|
|
112
|
+
await getDbAsSystem().update(tables.User, {
|
|
113
|
+
id: user.id,
|
|
114
|
+
emailVerificationTokenExpiration: moment()
|
|
115
|
+
.add(EXPECTED_LIFETIME_DAYS, 'days')
|
|
116
|
+
.subtract(EMAIL_VERIFICATION_RESEND_GAP_MINUTES + 1, 'minutes'),
|
|
117
|
+
});
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
describe('email verification after sign-up', () => {
|
|
121
|
+
beforeAll(async () => {
|
|
122
|
+
await testEnv.beforeAll();
|
|
123
|
+
// Invite optional (the library's default): the no-invite road is open.
|
|
124
|
+
(SourceRepository.get() as unknown as ObjectCache).objectCache[
|
|
125
|
+
'@proteinjs/user-server/DefaultInviteConfigFactory'
|
|
126
|
+
] = [];
|
|
127
|
+
}, 120000);
|
|
128
|
+
|
|
129
|
+
afterAll(async () => {
|
|
130
|
+
await testEnv.afterAll();
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
beforeEach(() => {
|
|
134
|
+
sendEmail.mockClear();
|
|
135
|
+
newUserContexts.length = 0;
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('a plain sign-up stores the pair — the digest, a week out — and hands the config the link carrying the token', async () => {
|
|
139
|
+
const email = 'plain@test.local';
|
|
140
|
+
|
|
141
|
+
const result = await new Signup().createUser({ name: 'Plain Signup', email, password: 'a password' });
|
|
142
|
+
|
|
143
|
+
expect(result.outcome).toBe('created');
|
|
144
|
+
const row = await userRow(email);
|
|
145
|
+
expect(row.emailVerified).toBe(false);
|
|
146
|
+
expect(row.emailVerificationToken).toMatch(TOKEN_SHAPE);
|
|
147
|
+
expect(EmailVerificationToken.LIFETIME_DAYS).toBe(EXPECTED_LIFETIME_DAYS);
|
|
148
|
+
expect(secondsFromExpectedLifetime(row.emailVerificationTokenExpiration, EXPECTED_LIFETIME_DAYS)).toBeLessThan(
|
|
149
|
+
CLOCK_SKEW_TOLERANCE_SECONDS
|
|
150
|
+
);
|
|
151
|
+
|
|
152
|
+
// The context: the verify page's path carrying the token whose DIGEST the row holds.
|
|
153
|
+
expect(newUserContexts).toHaveLength(1);
|
|
154
|
+
const link = latestLink();
|
|
155
|
+
expect(link).toMatch(new RegExp(`^${uiRoutes.account.verifyEmail}\\?token=[0-9a-f]{64}$`));
|
|
156
|
+
expect(sha256Hex(tokenIn(link))).toBe(row.emailVerificationToken);
|
|
157
|
+
expect(link).not.toContain(row.emailVerificationToken);
|
|
158
|
+
|
|
159
|
+
// One mail: the welcome, under the config's new-user subject, carrying the link.
|
|
160
|
+
expect(sendEmail).toHaveBeenCalledTimes(1);
|
|
161
|
+
expect(sendEmail.mock.calls[0][0]).toMatchObject({ to: email, subject: 'Welcome aboard' });
|
|
162
|
+
expect(sendEmail.mock.calls[0][0].text).toContain(link);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it('an invited sign-up stores no pair and the config is handed no context (the invite proved the address)', async () => {
|
|
166
|
+
const inviter = await testEnv.createUser({ name: 'Inviter', email: 'inviter@test.local' });
|
|
167
|
+
const email = 'invited@test.local';
|
|
168
|
+
await getDbAsSystem().insert(tables.Invite, {
|
|
169
|
+
email,
|
|
170
|
+
token: 'invite-token-verify-1',
|
|
171
|
+
tokenExpiresAt: moment().add(1, 'day'),
|
|
172
|
+
invitedBy: new Reference(tables.User.name, inviter.id),
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
const result = await new Signup().createUser(
|
|
176
|
+
{ name: 'Invited Signup', password: 'a password' },
|
|
177
|
+
'invite-token-verify-1'
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
expect(result.outcome).toBe('created');
|
|
181
|
+
const row = await userRow(email);
|
|
182
|
+
expect(row.emailVerified).toBe(true);
|
|
183
|
+
expect(row.emailVerificationToken ?? null).toBeNull();
|
|
184
|
+
expect(row.emailVerificationTokenExpiration ?? null).toBeNull();
|
|
185
|
+
expect(newUserContexts).toEqual([undefined]);
|
|
186
|
+
expect(sendEmail).toHaveBeenCalledTimes(1);
|
|
187
|
+
expect(sendEmail.mock.calls[0][0].text).not.toContain('token=');
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it('the mailed token confirms the address once: emailVerified set, the pair cleared, confirmed answered; again is invalid', async () => {
|
|
191
|
+
const { user, token } = await signUp('confirm@test.local');
|
|
192
|
+
|
|
193
|
+
const first = await invokeVerify({ token });
|
|
194
|
+
|
|
195
|
+
expect(first).toEqual({ status: 200, body: { state: 'confirmed' } });
|
|
196
|
+
const confirmed = await userRow(user.email);
|
|
197
|
+
expect(confirmed.emailVerified).toBe(true);
|
|
198
|
+
expect(confirmed.emailVerificationToken).toBeNull();
|
|
199
|
+
expect(confirmed.emailVerificationTokenExpiration).toBeNull();
|
|
200
|
+
|
|
201
|
+
// Spent: the cleared row no longer answers to the token, so the same link reads as unknown.
|
|
202
|
+
const again = await invokeVerify({ token });
|
|
203
|
+
expect(again).toEqual({ status: 200, body: { state: 'invalid' } });
|
|
204
|
+
expect((await userRow(user.email)).emailVerified).toBe(true);
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it('a lapsed link answers expired and leaves the flag and the pair as they were', async () => {
|
|
208
|
+
const { user, token } = await signUp('lapsed@test.local');
|
|
209
|
+
const lapsed = moment().subtract(1, 'minute');
|
|
210
|
+
await getDbAsSystem().update(tables.User, { id: user.id, emailVerificationTokenExpiration: lapsed });
|
|
211
|
+
|
|
212
|
+
const outcome = await invokeVerify({ token });
|
|
213
|
+
|
|
214
|
+
expect(outcome).toEqual({ status: 200, body: { state: 'expired' } });
|
|
215
|
+
const row = await userRow(user.email);
|
|
216
|
+
expect(row.emailVerified).toBe(false);
|
|
217
|
+
expect(row.emailVerificationToken).toBe(sha256Hex(token));
|
|
218
|
+
expect(moment(row.emailVerificationTokenExpiration as moment.MomentInput).isSame(lapsed)).toBe(true);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it('an unknown, malformed or missing token is invalid, and no answer names an address', async () => {
|
|
222
|
+
const { user, token } = await signUp('unknown@test.local');
|
|
223
|
+
|
|
224
|
+
const unissued = await invokeVerify({ token: sha256Hex(`never issued ${Math.random()}`) });
|
|
225
|
+
const digestAsToken = await invokeVerify({ token: sha256Hex(token) });
|
|
226
|
+
const malformed = await invokeVerify({ token: 'not-a-token' });
|
|
227
|
+
const missing = await invokeVerify({});
|
|
228
|
+
const confirmed = await invokeVerify({ token });
|
|
229
|
+
|
|
230
|
+
expect(unissued).toEqual({ status: 200, body: { state: 'invalid' } });
|
|
231
|
+
expect(digestAsToken).toEqual({ status: 200, body: { state: 'invalid' } });
|
|
232
|
+
expect(malformed).toEqual({ status: 200, body: { state: 'invalid' } });
|
|
233
|
+
expect(missing).toEqual({ status: 400, body: { state: 'invalid' } });
|
|
234
|
+
expect(confirmed).toEqual({ status: 200, body: { state: 'confirmed' } });
|
|
235
|
+
for (const outcome of [unissued, digestAsToken, malformed, missing, confirmed]) {
|
|
236
|
+
expect(JSON.stringify(outcome.body)).not.toContain(user.email);
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it('the signed-in account re-sends: a fresh pair (the earlier link stops working) and one mail; inside the gap nothing; verified nothing', async () => {
|
|
241
|
+
const { user, token: first } = await signUp('resend@test.local');
|
|
242
|
+
testEnv.actAs(user);
|
|
243
|
+
|
|
244
|
+
// Inside the gap: no mail, the pair stands.
|
|
245
|
+
const tooSoon = await new Signup().resendEmailVerification();
|
|
246
|
+
expect(tooSoon).toEqual({ sent: false });
|
|
247
|
+
expect(sendEmail).toHaveBeenCalledTimes(1);
|
|
248
|
+
expect((await userRow(user.email)).emailVerificationToken).toBe(sha256Hex(first));
|
|
249
|
+
|
|
250
|
+
await ageLastMint(user);
|
|
251
|
+
const resent = await new Signup().resendEmailVerification();
|
|
252
|
+
|
|
253
|
+
expect(resent).toEqual({ sent: true });
|
|
254
|
+
expect(sendEmail).toHaveBeenCalledTimes(2);
|
|
255
|
+
expect(sendEmail.mock.calls[1][0]).toMatchObject({ to: user.email, subject: 'Welcome aboard' });
|
|
256
|
+
const second = mailedToken();
|
|
257
|
+
expect(second).not.toBe(first);
|
|
258
|
+
const row = await userRow(user.email);
|
|
259
|
+
expect(row.emailVerificationToken).toBe(sha256Hex(second));
|
|
260
|
+
expect(secondsFromExpectedLifetime(row.emailVerificationTokenExpiration, EXPECTED_LIFETIME_DAYS)).toBeLessThan(
|
|
261
|
+
CLOCK_SKEW_TOLERANCE_SECONDS
|
|
262
|
+
);
|
|
263
|
+
expect(newUserContexts).toEqual([
|
|
264
|
+
{ verifyEmailLink: `${uiRoutes.account.verifyEmail}?token=${first}` },
|
|
265
|
+
{ verifyEmailLink: `${uiRoutes.account.verifyEmail}?token=${second}` },
|
|
266
|
+
]);
|
|
267
|
+
|
|
268
|
+
// The earlier link is dead; the fresh one confirms.
|
|
269
|
+
expect(await invokeVerify({ token: first })).toEqual({ status: 200, body: { state: 'invalid' } });
|
|
270
|
+
expect(await invokeVerify({ token: second })).toEqual({ status: 200, body: { state: 'confirmed' } });
|
|
271
|
+
|
|
272
|
+
// Verified now: the re-send refuses without a word and sends nothing.
|
|
273
|
+
const verified = await new Signup().resendEmailVerification();
|
|
274
|
+
expect(verified).toEqual({ sent: false });
|
|
275
|
+
expect(sendEmail).toHaveBeenCalledTimes(2);
|
|
276
|
+
expect((await userRow(user.email)).emailVerificationToken).toBeNull();
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it('a re-send whose mail fails withdraws the token, so the next tap is not held by the gap', async () => {
|
|
280
|
+
const { user, token: first } = await signUp('resend-fails@test.local');
|
|
281
|
+
testEnv.actAs(user);
|
|
282
|
+
await ageLastMint(user);
|
|
283
|
+
sendEmail.mockRejectedValueOnce(new Error('transport refused'));
|
|
284
|
+
|
|
285
|
+
const failed = await new Signup().resendEmailVerification();
|
|
286
|
+
|
|
287
|
+
expect(failed).toEqual({ sent: false });
|
|
288
|
+
const withdrawn = await userRow(user.email);
|
|
289
|
+
expect(withdrawn.emailVerificationToken).toBeNull();
|
|
290
|
+
expect(withdrawn.emailVerified).toBe(false);
|
|
291
|
+
expect(await invokeVerify({ token: first })).toEqual({ status: 200, body: { state: 'invalid' } });
|
|
292
|
+
|
|
293
|
+
const retried = await new Signup().resendEmailVerification();
|
|
294
|
+
expect(retried).toEqual({ sent: true });
|
|
295
|
+
expect(await invokeVerify({ token: mailedToken() })).toEqual({ status: 200, body: { state: 'confirmed' } });
|
|
296
|
+
});
|
|
297
|
+
});
|
package/test/Signup.test.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { UserAuth } from '@proteinjs/user';
|
|
1
|
+
import { guestUser, UserAuth } from '@proteinjs/user';
|
|
2
2
|
import { Signup } from '../src/services/Signup';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -68,4 +68,14 @@ describe('Signup service auth', () => {
|
|
|
68
68
|
setUser([]);
|
|
69
69
|
expect(canAccess('initializeSignup')).toBe(true);
|
|
70
70
|
});
|
|
71
|
+
|
|
72
|
+
it(`admits resendEmailVerification for any signed-in account and refuses it to the guest (it mails the session's own account)`, () => {
|
|
73
|
+
setUser([]);
|
|
74
|
+
expect(canAccess('resendEmailVerification')).toBe(true);
|
|
75
|
+
|
|
76
|
+
(UserAuth as unknown as UserAuthInternals).userRepo = {
|
|
77
|
+
getUser: () => ({ email: guestUser.email, roles: [] }),
|
|
78
|
+
};
|
|
79
|
+
expect(canAccess('resendEmailVerification')).toBe(false);
|
|
80
|
+
});
|
|
71
81
|
});
|