@proteinjs/user-server 1.27.0 → 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.
Files changed (39) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/generated/index.d.ts.map +1 -1
  3. package/dist/generated/index.js +3 -1
  4. package/dist/generated/index.js.map +1 -1
  5. package/dist/src/authentication/EmailVerificationToken.d.ts +23 -0
  6. package/dist/src/authentication/EmailVerificationToken.d.ts.map +1 -0
  7. package/dist/src/authentication/EmailVerificationToken.js +90 -0
  8. package/dist/src/authentication/EmailVerificationToken.js.map +1 -0
  9. package/dist/src/authentication/MailedToken.d.ts +91 -0
  10. package/dist/src/authentication/MailedToken.d.ts.map +1 -0
  11. package/dist/src/authentication/MailedToken.js +221 -0
  12. package/dist/src/authentication/MailedToken.js.map +1 -0
  13. package/dist/src/authentication/PasswordResetToken.d.ts +7 -61
  14. package/dist/src/authentication/PasswordResetToken.d.ts.map +1 -1
  15. package/dist/src/authentication/PasswordResetToken.js +25 -140
  16. package/dist/src/authentication/PasswordResetToken.js.map +1 -1
  17. package/dist/src/routes/verifyEmail.d.ts +21 -0
  18. package/dist/src/routes/verifyEmail.d.ts.map +1 -0
  19. package/dist/src/routes/verifyEmail.js +107 -0
  20. package/dist/src/routes/verifyEmail.js.map +1 -0
  21. package/dist/src/services/Signup.d.ts +27 -1
  22. package/dist/src/services/Signup.d.ts.map +1 -1
  23. package/dist/src/services/Signup.js +166 -30
  24. package/dist/src/services/Signup.js.map +1 -1
  25. package/dist/test/EmailVerification.test.d.ts +2 -0
  26. package/dist/test/EmailVerification.test.d.ts.map +1 -0
  27. package/dist/test/EmailVerification.test.js +451 -0
  28. package/dist/test/EmailVerification.test.js.map +1 -0
  29. package/dist/test/Signup.test.js +8 -0
  30. package/dist/test/Signup.test.js.map +1 -1
  31. package/generated/index.ts +3 -1
  32. package/package.json +4 -4
  33. package/src/authentication/EmailVerificationToken.ts +32 -0
  34. package/src/authentication/MailedToken.ts +171 -0
  35. package/src/authentication/PasswordResetToken.ts +13 -131
  36. package/src/routes/verifyEmail.ts +64 -0
  37. package/src/services/Signup.ts +111 -10
  38. package/test/EmailVerification.test.ts +297 -0
  39. package/test/Signup.test.ts +11 -1
@@ -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
+ });
@@ -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
  });