@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.
- package/CHANGELOG.md +11 -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/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/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/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/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/generated/index.ts +3 -1
- 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/verifyEmail.ts +64 -0
- package/src/services/Signup.ts +111 -10
- package/test/EmailVerification.test.ts +297 -0
- package/test/Signup.test.ts +11 -1
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from 'crypto';
|
|
2
|
+
import moment, { Moment } from 'moment';
|
|
3
|
+
import { getDbAsSystem } from '@proteinjs/db';
|
|
4
|
+
import { tables, User } from '@proteinjs/user';
|
|
5
|
+
|
|
6
|
+
export type MailedTokenResolution =
|
|
7
|
+
| { status: 'malformed' }
|
|
8
|
+
| { status: 'unknown' }
|
|
9
|
+
| { status: 'expired'; user: User }
|
|
10
|
+
| { status: 'live'; user: User; token: string };
|
|
11
|
+
|
|
12
|
+
/** The two cells a token kind keeps on the user row: the stored digest and when it lapses. */
|
|
13
|
+
export type MailedTokenCells = {
|
|
14
|
+
token: 'passwordResetToken' | 'emailVerificationToken';
|
|
15
|
+
expiration: 'passwordResetTokenExpiration' | 'emailVerificationTokenExpiration';
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** How long a token stays live after its mint. */
|
|
19
|
+
export type MailedTokenLifetime = { amount: number; unit: 'minutes' | 'days' };
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A single-use token mailed to an account as a link — the one owner of the mechanism every kind
|
|
23
|
+
* shares: its shape, its mint, the lookup that maps a presented value back to the user it was
|
|
24
|
+
* issued to, its withdrawal, and the conditional write that spends it once. A kind (the password
|
|
25
|
+
* reset, the email verification) names its two cells on the user row, its lifetime, and what
|
|
26
|
+
* spending it writes.
|
|
27
|
+
*
|
|
28
|
+
* A token is 32 bytes from the platform CSPRNG, hex-encoded (64 lowercase hex characters). The
|
|
29
|
+
* token itself exists only in the link mailed to the account: the user row stores its SHA-256
|
|
30
|
+
* digest (hex) beside the expiry, never the token, so a read of the table yields nothing that
|
|
31
|
+
* can be presented. A digest is not a token — presenting one is hashed again and matches no row.
|
|
32
|
+
* A fast unsalted hash is enough here because the input is 256 bits of CSPRNG output, not a
|
|
33
|
+
* human-chosen secret.
|
|
34
|
+
*
|
|
35
|
+
* Resolution refuses anything that is not a value of the token's shape BEFORE any lookup. A
|
|
36
|
+
* query filter built from a request value that is not a token does not compare the way a token
|
|
37
|
+
* does: `null` renders as `IS NULL` and would match every account with no pending token, an
|
|
38
|
+
* empty string matches an emptied column, and other types reach the driver. The presented token
|
|
39
|
+
* is then hashed, the row is looked up by that digest, and the row the lookup returns is
|
|
40
|
+
* re-checked in code — its stored digest must be a string equal to the presented token's digest
|
|
41
|
+
* (compared in constant time) and its expiry a real timestamp still in the future — so the
|
|
42
|
+
* outcome never rests on how the storage compares.
|
|
43
|
+
*/
|
|
44
|
+
export abstract class MailedToken {
|
|
45
|
+
private static readonly SHAPE = /^[0-9a-f]{64}$/;
|
|
46
|
+
|
|
47
|
+
protected constructor(
|
|
48
|
+
private readonly cells: MailedTokenCells,
|
|
49
|
+
private readonly lifetime: MailedTokenLifetime
|
|
50
|
+
) {}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Issue a token to `user`: store its digest and its expiry on the row, replacing any token
|
|
54
|
+
* outstanding, and return the token — the only time it exists outside the mailed link.
|
|
55
|
+
*/
|
|
56
|
+
async mint(user: User): Promise<string> {
|
|
57
|
+
const token = randomBytes(32).toString('hex');
|
|
58
|
+
await getDbAsSystem().update(tables.User, {
|
|
59
|
+
id: user.id,
|
|
60
|
+
...this.cellsWrite(this.digest(token), moment().add(this.lifetime.amount, this.lifetime.unit)),
|
|
61
|
+
});
|
|
62
|
+
return token;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async resolve(presented: unknown): Promise<MailedTokenResolution> {
|
|
66
|
+
const token = this.parse(presented);
|
|
67
|
+
if (token === undefined) {
|
|
68
|
+
return { status: 'malformed' };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const digest = this.digest(token);
|
|
72
|
+
const user = await getDbAsSystem().get(tables.User, this.cellsLookup(digest));
|
|
73
|
+
if (!user || !this.matches(user[this.cells.token], digest)) {
|
|
74
|
+
return { status: 'unknown' };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (!this.isLive(user[this.cells.expiration])) {
|
|
78
|
+
return { status: 'expired', user };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return { status: 'live', user, token };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Withdraw a token that never reached its owner (the mail carrying it failed to send): the row
|
|
86
|
+
* is cleared only while it still carries this token's digest, so a newer token is left alone.
|
|
87
|
+
*/
|
|
88
|
+
async revoke(user: User, token: string): Promise<void> {
|
|
89
|
+
await getDbAsSystem().update(tables.User, this.cellsWrite(null, null), {
|
|
90
|
+
id: user.id,
|
|
91
|
+
...this.cellsLookup(this.digest(token)),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** When the token outstanding on `user` was minted, or undefined when the row carries none. */
|
|
96
|
+
mintedAt(user: User): Moment | undefined {
|
|
97
|
+
const expiration = user[this.cells.expiration];
|
|
98
|
+
if (!user[this.cells.token] || !expiration) {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return moment(expiration).subtract(this.lifetime.amount, this.lifetime.unit);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* A log-safe reference to a presented token: a short prefix of a well-formed one's digest,
|
|
107
|
+
* never the value itself and never a part of it. The routes log it only for a token that
|
|
108
|
+
* resolved `unknown` — one no row carries — so it never lines up with a digest a row holds.
|
|
109
|
+
* What it is for is telling refusals apart in the log: one stale link presented again reads
|
|
110
|
+
* the same each time, a run of different values reads differently. 48 bits of the SHA-256 of
|
|
111
|
+
* 256 random bits identify nothing and can be presented nowhere.
|
|
112
|
+
*/
|
|
113
|
+
fingerprint(presented: unknown): string | undefined {
|
|
114
|
+
const token = this.parse(presented);
|
|
115
|
+
if (token === undefined) {
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return this.digest(token).slice(0, 12);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Spend the token: `effect` is written and the token cleared in one conditional update — the
|
|
124
|
+
* row must still carry this token's digest at write time, so two presentations of the same
|
|
125
|
+
* token cannot both succeed. Resolves false when the token was already spent.
|
|
126
|
+
*/
|
|
127
|
+
protected async spend(user: User, token: string, effect: Partial<User>): Promise<boolean> {
|
|
128
|
+
const updated = await getDbAsSystem().update(
|
|
129
|
+
tables.User,
|
|
130
|
+
{ ...effect, ...this.cellsWrite(null, null) },
|
|
131
|
+
{ id: user.id, ...this.cellsLookup(this.digest(token)) }
|
|
132
|
+
);
|
|
133
|
+
return updated === 1;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
private parse(presented: unknown): string | undefined {
|
|
137
|
+
return typeof presented === 'string' && MailedToken.SHAPE.test(presented) ? presented : undefined;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** What the row stores in place of a token: its SHA-256, hex-encoded. */
|
|
141
|
+
private digest(token: string): string {
|
|
142
|
+
return createHash('sha256').update(token).digest('hex');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private matches(storedDigest: string | null | undefined, presentedDigest: string): boolean {
|
|
146
|
+
if (typeof storedDigest !== 'string' || storedDigest.length !== presentedDigest.length) {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return timingSafeEqual(Buffer.from(storedDigest), Buffer.from(presentedDigest));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
private isLive(expiration: Moment | null | undefined): boolean {
|
|
154
|
+
if (!expiration) {
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const expiresAt = moment(expiration);
|
|
159
|
+
return expiresAt.isValid() && moment().isBefore(expiresAt);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The kind's two cells as a write: a digest and its expiry, or nulls to clear them. */
|
|
163
|
+
private cellsWrite(digest: string | null, expiration: Moment | null): Partial<User> {
|
|
164
|
+
return { [this.cells.token]: digest, [this.cells.expiration]: expiration };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The filter that finds the row carrying `digest` in the kind's token cell. */
|
|
168
|
+
private cellsLookup(digest: string): Partial<User> {
|
|
169
|
+
return { [this.cells.token]: digest };
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -1,73 +1,24 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import { getDbAsSystem } from '@proteinjs/db';
|
|
4
|
-
import { tables, User } from '@proteinjs/user';
|
|
1
|
+
import { User } from '@proteinjs/user';
|
|
2
|
+
import { MailedToken, MailedTokenResolution } from './MailedToken';
|
|
5
3
|
|
|
6
|
-
export type PasswordResetResolution =
|
|
7
|
-
| { status: 'malformed' }
|
|
8
|
-
| { status: 'unknown' }
|
|
9
|
-
| { status: 'expired'; user: User }
|
|
10
|
-
| { status: 'live'; user: User; token: string };
|
|
4
|
+
export type PasswordResetResolution = MailedTokenResolution;
|
|
11
5
|
|
|
12
6
|
/**
|
|
13
|
-
* The password-reset token
|
|
14
|
-
*
|
|
7
|
+
* The password-reset token: a `MailedToken` on the row's `passwordResetToken` /
|
|
8
|
+
* `passwordResetTokenExpiration` cells, live for an hour, spent by the password write.
|
|
15
9
|
*
|
|
16
|
-
*
|
|
17
|
-
* token itself exists only in the link mailed to the account: the user row stores its SHA-256
|
|
18
|
-
* digest (hex) beside the expiry, never the token, so a read of the table yields nothing that
|
|
19
|
-
* can be presented. A digest is not a token — presenting one is hashed again and matches no row.
|
|
20
|
-
* A fast unsalted hash is enough here because the input is 256 bits of CSPRNG output, not a
|
|
21
|
-
* human-chosen secret.
|
|
22
|
-
*
|
|
23
|
-
* Resolution refuses anything that is not a value of the token's shape BEFORE any lookup. A
|
|
24
|
-
* query filter built from a request value that is not a token does not compare the way a token
|
|
25
|
-
* does: `null` renders as `IS NULL` and would match every account with no pending reset, an
|
|
26
|
-
* empty string matches an emptied column, and other types reach the driver. The presented token
|
|
27
|
-
* is then hashed, the row is looked up by that digest, and the row the lookup returns is
|
|
28
|
-
* re-checked in code — its stored digest must be a string equal to the presented token's digest
|
|
29
|
-
* (compared in constant time) and its expiry a real timestamp still in the future — so the
|
|
30
|
-
* outcome never rests on how the storage compares.
|
|
31
|
-
*
|
|
32
|
-
* No migration accompanies the move from a stored token to a stored digest: a row that still
|
|
10
|
+
* No migration accompanied the move from a stored token to a stored digest: a row that still
|
|
33
11
|
* holds a token minted before it never equals the digest of anything presented, so that token
|
|
34
12
|
* fails validation for what remains of its hour and the person asks for a new link.
|
|
35
13
|
*/
|
|
36
|
-
export class PasswordResetToken {
|
|
37
|
-
private static readonly SHAPE = /^[0-9a-f]{64}$/;
|
|
14
|
+
export class PasswordResetToken extends MailedToken {
|
|
38
15
|
private static readonly LIFETIME_MINUTES = 60;
|
|
39
16
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
const token = randomBytes(32).toString('hex');
|
|
46
|
-
await getDbAsSystem().update(tables.User, {
|
|
47
|
-
id: user.id,
|
|
48
|
-
passwordResetToken: this.digest(token),
|
|
49
|
-
passwordResetTokenExpiration: moment().add(PasswordResetToken.LIFETIME_MINUTES, 'minutes'),
|
|
50
|
-
});
|
|
51
|
-
return token;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
async resolve(presented: unknown): Promise<PasswordResetResolution> {
|
|
55
|
-
const token = this.parse(presented);
|
|
56
|
-
if (token === undefined) {
|
|
57
|
-
return { status: 'malformed' };
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const digest = this.digest(token);
|
|
61
|
-
const user = await getDbAsSystem().get(tables.User, { passwordResetToken: digest });
|
|
62
|
-
if (!user || !this.matches(user.passwordResetToken, digest)) {
|
|
63
|
-
return { status: 'unknown' };
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
if (!this.isLive(user.passwordResetTokenExpiration)) {
|
|
67
|
-
return { status: 'expired', user };
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
return { status: 'live', user, token };
|
|
17
|
+
constructor() {
|
|
18
|
+
super(
|
|
19
|
+
{ token: 'passwordResetToken', expiration: 'passwordResetTokenExpiration' },
|
|
20
|
+
{ amount: PasswordResetToken.LIFETIME_MINUTES, unit: 'minutes' }
|
|
21
|
+
);
|
|
71
22
|
}
|
|
72
23
|
|
|
73
24
|
/**
|
|
@@ -76,75 +27,6 @@ export class PasswordResetToken {
|
|
|
76
27
|
* succeed. Resolves false when the token was already redeemed.
|
|
77
28
|
*/
|
|
78
29
|
async redeem(user: User, token: string, hashedPassword: string): Promise<boolean> {
|
|
79
|
-
|
|
80
|
-
tables.User,
|
|
81
|
-
{ password: hashedPassword, passwordResetToken: null, passwordResetTokenExpiration: null },
|
|
82
|
-
{ id: user.id, passwordResetToken: this.digest(token) }
|
|
83
|
-
);
|
|
84
|
-
return updated === 1;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* Withdraw a token that never reached its owner (the mail carrying it failed to send): the row
|
|
89
|
-
* is cleared only while it still carries this token's digest, so a newer token is left alone.
|
|
90
|
-
*/
|
|
91
|
-
async revoke(user: User, token: string): Promise<void> {
|
|
92
|
-
await getDbAsSystem().update(
|
|
93
|
-
tables.User,
|
|
94
|
-
{ passwordResetToken: null, passwordResetTokenExpiration: null },
|
|
95
|
-
{ id: user.id, passwordResetToken: this.digest(token) }
|
|
96
|
-
);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/** When the token outstanding on `user` was minted, or undefined when the row carries none. */
|
|
100
|
-
mintedAt(user: User): Moment | undefined {
|
|
101
|
-
if (!user.passwordResetToken || !user.passwordResetTokenExpiration) {
|
|
102
|
-
return undefined;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
return moment(user.passwordResetTokenExpiration).subtract(PasswordResetToken.LIFETIME_MINUTES, 'minutes');
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
/**
|
|
109
|
-
* A log-safe reference to a presented token: a short prefix of a well-formed one's digest,
|
|
110
|
-
* never the value itself and never a part of it. The routes log it only for a token that
|
|
111
|
-
* resolved `unknown` — one no row carries — so it never lines up with a digest a row holds.
|
|
112
|
-
* What it is for is telling refusals apart in the log: one stale link presented again reads
|
|
113
|
-
* the same each time, a run of different values reads differently. 48 bits of the SHA-256 of
|
|
114
|
-
* 256 random bits identify nothing and can be presented nowhere.
|
|
115
|
-
*/
|
|
116
|
-
fingerprint(presented: unknown): string | undefined {
|
|
117
|
-
const token = this.parse(presented);
|
|
118
|
-
if (token === undefined) {
|
|
119
|
-
return undefined;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
return this.digest(token).slice(0, 12);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
private parse(presented: unknown): string | undefined {
|
|
126
|
-
return typeof presented === 'string' && PasswordResetToken.SHAPE.test(presented) ? presented : undefined;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
/** What the row stores in place of a token: its SHA-256, hex-encoded. */
|
|
130
|
-
private digest(token: string): string {
|
|
131
|
-
return createHash('sha256').update(token).digest('hex');
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
private matches(storedDigest: string | null | undefined, presentedDigest: string): boolean {
|
|
135
|
-
if (typeof storedDigest !== 'string' || storedDigest.length !== presentedDigest.length) {
|
|
136
|
-
return false;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
return timingSafeEqual(Buffer.from(storedDigest), Buffer.from(presentedDigest));
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
private isLive(expiration: Moment | null | undefined): boolean {
|
|
143
|
-
if (!expiration) {
|
|
144
|
-
return false;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
const expiresAt = moment(expiration);
|
|
148
|
-
return expiresAt.isValid() && moment().isBefore(expiresAt);
|
|
30
|
+
return await this.spend(user, token, { password: hashedPassword });
|
|
149
31
|
}
|
|
150
32
|
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { Route } from '@proteinjs/server-api';
|
|
2
|
+
import { routes } from '@proteinjs/user';
|
|
3
|
+
import { Logger } from '@proteinjs/logger';
|
|
4
|
+
import { RequestDigests } from '@proteinjs/util-node';
|
|
5
|
+
import { EmailVerificationToken } from '../authentication/EmailVerificationToken';
|
|
6
|
+
|
|
7
|
+
/** What the route answers, for the page that called it: `{ state }`. */
|
|
8
|
+
export type VerifyEmailState = 'confirmed' | 'expired' | 'invalid';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* `GET /user/verify-email?token=` — confirms an account's email address from the token in its
|
|
12
|
+
* mailed link. The link lands on the app's verify page (`uiRoutes.account.verifyEmail`), which
|
|
13
|
+
* calls this route with the token and shows the state it answers, the way the password-reset
|
|
14
|
+
* page calls its token routes: JSON, never a redirect.
|
|
15
|
+
*
|
|
16
|
+
* Resolves the presented token through `EmailVerificationToken` — which refuses anything but a
|
|
17
|
+
* well-formed token before any lookup — checks its expiry, and spends it: `emailVerified` is
|
|
18
|
+
* written and the token cleared in one conditional update, so a link confirms once.
|
|
19
|
+
* - 'confirmed': the address is now verified and the token spent;
|
|
20
|
+
* - 'expired': the link lapsed — the flag is unchanged; the account page's re-send mints a new one;
|
|
21
|
+
* - 'invalid': malformed, unknown, or already spent — the same word for all three, so the
|
|
22
|
+
* answer says nothing about whether a token ever existed.
|
|
23
|
+
* A request with no token at all is refused (400, 'invalid'). Nothing in any answer names an
|
|
24
|
+
* address, and the token itself never reaches the log.
|
|
25
|
+
*/
|
|
26
|
+
export const verifyEmail: Route = {
|
|
27
|
+
path: routes.verifyEmail.path,
|
|
28
|
+
method: routes.verifyEmail.method,
|
|
29
|
+
onRequest: async (request, response): Promise<void> => {
|
|
30
|
+
const logger = new Logger({ name: 'verifyEmail' });
|
|
31
|
+
const { token } = request.query ?? {};
|
|
32
|
+
if (!token) {
|
|
33
|
+
response.status(400).send({ state: 'invalid' satisfies VerifyEmailState });
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const verification = new EmailVerificationToken();
|
|
38
|
+
const resolution = await verification.resolve(token);
|
|
39
|
+
if (resolution.status === 'malformed' || resolution.status === 'unknown') {
|
|
40
|
+
logger.info({
|
|
41
|
+
message: `Invalid email verification token used`,
|
|
42
|
+
obj: { reason: resolution.status, token: verification.fingerprint(token) },
|
|
43
|
+
});
|
|
44
|
+
response.status(200).send({ state: 'invalid' satisfies VerifyEmailState });
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const account = new RequestDigests().account(resolution.user.email);
|
|
49
|
+
if (resolution.status === 'expired') {
|
|
50
|
+
logger.info({ message: `Expired email verification token used`, obj: { account } });
|
|
51
|
+
response.status(200).send({ state: 'expired' satisfies VerifyEmailState });
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (!(await verification.confirm(resolution.user, resolution.token))) {
|
|
56
|
+
logger.info({ message: `Email verification token already spent`, obj: { account } });
|
|
57
|
+
response.status(200).send({ state: 'invalid' satisfies VerifyEmailState });
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
logger.info({ message: `Email address verified`, obj: { account } });
|
|
62
|
+
response.status(200).send({ state: 'confirmed' satisfies VerifyEmailState });
|
|
63
|
+
},
|
|
64
|
+
};
|
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
|
}
|