@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.
Files changed (68) hide show
  1. package/CHANGELOG.md +22 -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/index.d.ts +2 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +8 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/src/authentication/EmailVerificationToken.d.ts +23 -0
  10. package/dist/src/authentication/EmailVerificationToken.d.ts.map +1 -0
  11. package/dist/src/authentication/EmailVerificationToken.js +90 -0
  12. package/dist/src/authentication/EmailVerificationToken.js.map +1 -0
  13. package/dist/src/authentication/MailedToken.d.ts +91 -0
  14. package/dist/src/authentication/MailedToken.d.ts.map +1 -0
  15. package/dist/src/authentication/MailedToken.js +221 -0
  16. package/dist/src/authentication/MailedToken.js.map +1 -0
  17. package/dist/src/authentication/PasswordResetToken.d.ts +7 -61
  18. package/dist/src/authentication/PasswordResetToken.d.ts.map +1 -1
  19. package/dist/src/authentication/PasswordResetToken.js +25 -140
  20. package/dist/src/authentication/PasswordResetToken.js.map +1 -1
  21. package/dist/src/routes/signup.d.ts +8 -3
  22. package/dist/src/routes/signup.d.ts.map +1 -1
  23. package/dist/src/routes/signup.js +55 -15
  24. package/dist/src/routes/signup.js.map +1 -1
  25. package/dist/src/routes/verifyEmail.d.ts +21 -0
  26. package/dist/src/routes/verifyEmail.d.ts.map +1 -0
  27. package/dist/src/routes/verifyEmail.js +107 -0
  28. package/dist/src/routes/verifyEmail.js.map +1 -0
  29. package/dist/src/services/DisposableEmailDomains.d.ts +24 -0
  30. package/dist/src/services/DisposableEmailDomains.d.ts.map +1 -0
  31. package/dist/src/services/DisposableEmailDomains.js +129 -0
  32. package/dist/src/services/DisposableEmailDomains.js.map +1 -0
  33. package/dist/src/services/Signup.d.ts +27 -1
  34. package/dist/src/services/Signup.d.ts.map +1 -1
  35. package/dist/src/services/Signup.js +166 -30
  36. package/dist/src/services/Signup.js.map +1 -1
  37. package/dist/src/services/SignupGuard.d.ts +55 -0
  38. package/dist/src/services/SignupGuard.d.ts.map +1 -0
  39. package/dist/src/services/SignupGuard.js +13 -0
  40. package/dist/src/services/SignupGuard.js.map +1 -0
  41. package/dist/test/EmailVerification.test.d.ts +2 -0
  42. package/dist/test/EmailVerification.test.d.ts.map +1 -0
  43. package/dist/test/EmailVerification.test.js +451 -0
  44. package/dist/test/EmailVerification.test.js.map +1 -0
  45. package/dist/test/Signup.test.js +8 -0
  46. package/dist/test/Signup.test.js.map +1 -1
  47. package/dist/test/SignupGuardSeam.test.d.ts +2 -0
  48. package/dist/test/SignupGuardSeam.test.d.ts.map +1 -0
  49. package/dist/test/SignupGuardSeam.test.js +474 -0
  50. package/dist/test/SignupGuardSeam.test.js.map +1 -0
  51. package/dist/test/UserServerTestEnvironment.d.ts.map +1 -1
  52. package/dist/test/UserServerTestEnvironment.js +4 -0
  53. package/dist/test/UserServerTestEnvironment.js.map +1 -1
  54. package/generated/index.ts +3 -1
  55. package/index.ts +10 -0
  56. package/package.json +4 -4
  57. package/src/authentication/EmailVerificationToken.ts +32 -0
  58. package/src/authentication/MailedToken.ts +171 -0
  59. package/src/authentication/PasswordResetToken.ts +13 -131
  60. package/src/routes/signup.ts +58 -9
  61. package/src/routes/verifyEmail.ts +64 -0
  62. package/src/services/DisposableEmailDomains.ts +125 -0
  63. package/src/services/Signup.ts +111 -10
  64. package/src/services/SignupGuard.ts +58 -0
  65. package/test/EmailVerification.test.ts +297 -0
  66. package/test/Signup.test.ts +11 -1
  67. package/test/SignupGuardSeam.test.ts +299 -0
  68. package/test/UserServerTestEnvironment.ts +4 -0
@@ -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 { createHash, randomBytes, timingSafeEqual } from 'crypto';
2
- import moment, { Moment } from 'moment';
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's one owner: its shape, its mint, the lookup that maps a presented
14
- * value back to the user it was issued to, and its single-use redemption.
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
- * A token is 32 bytes from the platform CSPRNG, hex-encoded (64 lowercase hex characters). The
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
- * Issue a token to `user`: store its digest and its expiry on the row, replacing any token
42
- * outstanding, and return the token — the only time it exists outside the mailed link.
43
- */
44
- async mint(user: User): Promise<string> {
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
- const updated = await getDbAsSystem().update(
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
  }
@@ -3,10 +3,26 @@ import { Logger } from '@proteinjs/logger';
3
3
  import { RequestDigests } from '@proteinjs/util-node';
4
4
  import { UserSignup, routes } from '@proteinjs/user';
5
5
  import { establishSession } from '../authentication/establishSession';
6
+ import { DisposableEmailDomains } from '../services/DisposableEmailDomains';
6
7
  import { Signup } from '../services/Signup';
8
+ import { getDefaultSignupGuard, SignupGuardFacts } from '../services/SignupGuard';
9
+ import { ClientAddress } from '../throttle/ClientAddress';
7
10
 
8
11
  const logger = new Logger({ name: 'signup' });
9
12
 
13
+ /**
14
+ * The request body: `UserSignup` (+ an optional invite `token`; the invite carries the email on
15
+ * that path), and the two fields a form may carry for the consumer's guard — read here, judged
16
+ * by the guard, never by this route.
17
+ */
18
+ type SignupSubmission = Partial<UserSignup> & {
19
+ token?: string;
20
+ /** The honeypot field — no person sees it, so a value in it is bot-shaped. */
21
+ website?: unknown;
22
+ /** The render-moment token a form carries when the consumer's posture mints one. */
23
+ formToken?: unknown;
24
+ };
25
+
10
26
  /**
11
27
  * `POST /user/signup` — create the account AND establish its session in the same request
12
28
  * (auto-login), so a new user lands in the app instead of being bounced to the login form to
@@ -14,37 +30,61 @@ const logger = new Logger({ name: 'signup' });
14
30
  * because session establishment is a request-level concern services never see; the domain flow
15
31
  * (invite validation, account creation, notification emails) stays owned by `Signup.createUser`.
16
32
  *
17
- * Body: `UserSignup` (+ optional invite `token`; the invite carries the email on that path).
18
- * Response mirrors the login route's contract: 200 with `{}` on success, `{ error }` with
19
- * user-readable copy otherwise.
33
+ * Body: `SignupSubmission`. Response mirrors the login route's contract: 200 with `{}` on
34
+ * success, `{ error }` with user-readable copy otherwise.
20
35
  *
21
36
  * When the email is already registered the response is byte-identical to success but NO session
22
37
  * is minted — auto-login must never hand out a session for an account the caller didn't just
23
38
  * create; the caller falls through to the login screen exactly as before. Existence is reported
24
39
  * to the mailbox owner by email, never to the caller.
40
+ *
41
+ * The NO-INVITE road passes two doors before any write, in this order: the throwaway-mail list
42
+ * (`DisposableEmailDomains`, refused with its one sentence) and the consumer's registered
43
+ * `DefaultSignupGuard`, handed the submission's facts (`SignupGuardFacts`) — `refuse` answers
44
+ * `{ error: sentence }`, `drop` answers exactly as success, and neither writes an account or
45
+ * mints a session. The invite road passes neither: an invited address was chosen by an admin.
25
46
  */
26
47
  export const signup: Route = {
27
48
  path: routes.signup.path,
28
49
  method: routes.signup.method,
29
50
  onRequest: async (request: any, response): Promise<void> => {
30
- const body: Partial<UserSignup> & { token?: string } = request.body ?? {};
51
+ const body: SignupSubmission = request.body ?? {};
31
52
  if (!body.name || !body.password) {
32
53
  response.send({ error: 'Name and password cannot be blank' });
33
54
  return;
34
55
  }
35
56
 
57
+ const digests = new RequestDigests();
58
+ const email = typeof body.email === 'string' ? body.email.trim() : undefined;
59
+ if (!body.token && email) {
60
+ if (new DisposableEmailDomains().isDisposable(email)) {
61
+ logger.info({ message: 'Signup refused: throwaway-mail domain', obj: { account: digests.account(email) } });
62
+ response.send({ error: DisposableEmailDomains.REFUSAL });
63
+ return;
64
+ }
65
+
66
+ const facts = signupFacts(request, body, email);
67
+ const verdict = await getDefaultSignupGuard().check(facts);
68
+ if (verdict.verdict !== 'allow') {
69
+ logger.info({
70
+ message: `Signup ${verdict.verdict === 'refuse' ? 'refused' : 'dropped'} by the guard`,
71
+ obj: { account: digests.account(email), device: facts.clientDevice },
72
+ });
73
+ // A drop answers exactly as success: the caller learns nothing it can iterate against.
74
+ response.send(verdict.verdict === 'refuse' ? { error: verdict.sentence } : {});
75
+ return;
76
+ }
77
+ }
78
+
36
79
  let result;
37
80
  try {
38
- result = await new Signup().createUser(
39
- { name: body.name, email: body.email, password: body.password },
40
- body.token
41
- );
81
+ result = await new Signup().createUser({ name: body.name, email, password: body.password }, body.token);
42
82
  } catch (error: any) {
43
83
  // createUser throws plain-words errors deliberately (invite expired / invite required /
44
84
  // email missing); the message is the user-facing contract, same as the RPC layer's. The log
45
85
  // gets the error through the digest door: a concurrent double sign-up's unique-index refusal
46
86
  // names the address in the database's own words.
47
- logger.error({ message: 'Signup failed', error: new RequestDigests().redactError(error) });
87
+ logger.error({ message: 'Signup failed', error: digests.redactError(error) });
48
88
  response.send({ error: error instanceof Error ? error.message : 'Sign up failed.' });
49
89
  return;
50
90
  }
@@ -56,3 +96,12 @@ export const signup: Route = {
56
96
  response.send({});
57
97
  },
58
98
  };
99
+
100
+ /** The facts the guard judges — the address lowercased, the form's two optional fields as sent, the device as a digest. */
101
+ const signupFacts = (request: any, body: SignupSubmission, email: string): SignupGuardFacts => ({
102
+ email: email.toLowerCase(),
103
+ honeypot: typeof body.website === 'string' ? body.website : undefined,
104
+ formToken: typeof body.formToken === 'string' ? body.formToken : undefined,
105
+ clientDevice: new RequestDigests().coarseIp(new ClientAddress().of(request)),
106
+ hasUserAgent: Boolean(request.headers?.['user-agent']),
107
+ });
@@ -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
+ };
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The common throwaway-mail domains — inboxes anyone can open or that are minted on demand with
3
+ * nobody behind them — so a sign-up from one is an account whose mail no one reads. A short list
4
+ * in code, no vendor, applied on the no-invite road before the guard: a deliverability check
5
+ * refuses only a domain that takes no mail, and a throwaway on a real domain passes it; this list
6
+ * is the other half. Written 2026-10-28.
7
+ *
8
+ * The rule for adding a domain: it goes on the list when its service describes itself as
9
+ * temporary, disposable or anonymous mail — addresses with no owner, read by whoever asks — and
10
+ * never when people hold their own mailboxes there (a webmail, a school, a company, a forwarding
11
+ * service with an owner behind each alias). Keep it short: the list carries the names that
12
+ * actually show up at the door, and a consumer's guard bounds the rest. Entries are lowercase
13
+ * registrable domains, one per line; a subdomain of a listed domain is refused with it.
14
+ */
15
+ export class DisposableEmailDomains {
16
+ /** The one sentence a refused address is told — read by the person, shown in full. */
17
+ static readonly REFUSAL = 'Use an email address you can read mail at.';
18
+
19
+ private static readonly DOMAINS: ReadonlySet<string> = new Set([
20
+ '10minemail.com',
21
+ '10minutemail.com',
22
+ '10minutemail.net',
23
+ 'anonbox.net',
24
+ 'burnermail.io',
25
+ 'cool.fr.nf',
26
+ 'courriel.fr.nf',
27
+ 'crazymailing.com',
28
+ 'discard.email',
29
+ 'dispostable.com',
30
+ 'dropmail.me',
31
+ 'emailfake.com',
32
+ 'emailondeck.com',
33
+ 'fakeinbox.com',
34
+ 'fakemail.net',
35
+ 'generator.email',
36
+ 'getairmail.com',
37
+ 'getnada.com',
38
+ 'grr.la',
39
+ 'guerrillamail.biz',
40
+ 'guerrillamail.com',
41
+ 'guerrillamail.de',
42
+ 'guerrillamail.net',
43
+ 'guerrillamail.org',
44
+ 'guerrillamailblock.com',
45
+ 'harakirimail.com',
46
+ 'inboxkitten.com',
47
+ 'jetable.fr.nf',
48
+ 'jetable.org',
49
+ 'mail-temp.com',
50
+ 'mail7.io',
51
+ 'mailcatch.com',
52
+ 'maildrop.cc',
53
+ 'mailexpire.com',
54
+ 'mailin8r.com',
55
+ 'mailinater.com',
56
+ 'mailinator.com',
57
+ 'mailinator2.com',
58
+ 'mailnesia.com',
59
+ 'mailpoof.com',
60
+ 'mailsac.com',
61
+ 'mailtemp.net',
62
+ 'mega.zik.dj',
63
+ 'meltmail.com',
64
+ 'mintemail.com',
65
+ 'mohmal.com',
66
+ 'moncourrier.fr.nf',
67
+ 'monemail.fr.nf',
68
+ 'monmail.fr.nf',
69
+ 'mytemp.email',
70
+ 'nomail.xl.cx',
71
+ 'nospam.ze.tc',
72
+ 'pokemail.net',
73
+ 'sharklasers.com',
74
+ 'sogetthis.com',
75
+ 'spam4.me',
76
+ 'spambox.us',
77
+ 'speed.1s.fr',
78
+ 'temp-mail.io',
79
+ 'temp-mail.org',
80
+ 'tempail.com',
81
+ 'tempinbox.com',
82
+ 'tempmail.com',
83
+ 'tempmail.dev',
84
+ 'tempmailo.com',
85
+ 'tempr.email',
86
+ 'throwawaymail.com',
87
+ 'trashmail.com',
88
+ 'trashmail.me',
89
+ 'trashmail.net',
90
+ 'yopmail.com',
91
+ 'yopmail.fr',
92
+ 'yopmail.net',
93
+ ]);
94
+
95
+ /** Whether the address's domain is a listed domain or a subdomain of one; the case of the address does not matter. */
96
+ isDisposable(email: string): boolean {
97
+ const domain = this.domainOf(email);
98
+ if (!domain) {
99
+ return false;
100
+ }
101
+
102
+ // `mail.mailinator.com` is refused with `mailinator.com`: every suffix at a label boundary
103
+ // is looked up, so a domain that merely ends with a listed name (`notmailinator.com`) is not.
104
+ const labels = domain.split('.');
105
+ for (let start = 0; start < labels.length - 1; start++) {
106
+ if (DisposableEmailDomains.DOMAINS.has(labels.slice(start).join('.'))) {
107
+ return true;
108
+ }
109
+ }
110
+ return false;
111
+ }
112
+
113
+ /** The part after the last `@`, trimmed and lowercased; undefined when there is none. */
114
+ private domainOf(email: string): string | undefined {
115
+ const at = email.lastIndexOf('@');
116
+ if (at < 0) {
117
+ return undefined;
118
+ }
119
+ const domain = email
120
+ .slice(at + 1)
121
+ .trim()
122
+ .toLowerCase();
123
+ return domain || undefined;
124
+ }
125
+ }