@proteinjs/user-server 1.22.3 → 1.23.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 (76) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/generated/index.js +1 -1
  3. package/dist/generated/index.js.map +1 -1
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js.map +1 -1
  7. package/dist/src/routes/executePasswordReset.js +3 -1
  8. package/dist/src/routes/executePasswordReset.js.map +1 -1
  9. package/dist/src/routes/initiatePasswordReset.d.ts.map +1 -1
  10. package/dist/src/routes/initiatePasswordReset.js +14 -12
  11. package/dist/src/routes/initiatePasswordReset.js.map +1 -1
  12. package/dist/src/routes/login.js +18 -14
  13. package/dist/src/routes/login.js.map +1 -1
  14. package/dist/src/services/Signup.d.ts +10 -0
  15. package/dist/src/services/Signup.d.ts.map +1 -1
  16. package/dist/src/services/Signup.js +51 -21
  17. package/dist/src/services/Signup.js.map +1 -1
  18. package/dist/src/throttle/MemoryThrottleWindowStore.d.ts +28 -0
  19. package/dist/src/throttle/MemoryThrottleWindowStore.d.ts.map +1 -0
  20. package/dist/src/throttle/MemoryThrottleWindowStore.js +108 -0
  21. package/dist/src/throttle/MemoryThrottleWindowStore.js.map +1 -0
  22. package/dist/src/throttle/PasswordResetThrottle.d.ts +9 -8
  23. package/dist/src/throttle/PasswordResetThrottle.d.ts.map +1 -1
  24. package/dist/src/throttle/PasswordResetThrottle.js +63 -15
  25. package/dist/src/throttle/PasswordResetThrottle.js.map +1 -1
  26. package/dist/src/throttle/SignInThrottle.d.ts +21 -15
  27. package/dist/src/throttle/SignInThrottle.d.ts.map +1 -1
  28. package/dist/src/throttle/SignInThrottle.js +94 -25
  29. package/dist/src/throttle/SignInThrottle.js.map +1 -1
  30. package/dist/src/throttle/SlidingWindow.d.ts +6 -4
  31. package/dist/src/throttle/SlidingWindow.d.ts.map +1 -1
  32. package/dist/src/throttle/SlidingWindow.js +6 -4
  33. package/dist/src/throttle/SlidingWindow.js.map +1 -1
  34. package/dist/src/throttle/StoredWindow.d.ts +59 -0
  35. package/dist/src/throttle/StoredWindow.d.ts.map +1 -0
  36. package/dist/src/throttle/StoredWindow.js +209 -0
  37. package/dist/src/throttle/StoredWindow.js.map +1 -0
  38. package/dist/src/throttle/ThrottleWindowStore.d.ts +38 -0
  39. package/dist/src/throttle/ThrottleWindowStore.d.ts.map +1 -0
  40. package/dist/src/throttle/ThrottleWindowStore.js +3 -0
  41. package/dist/src/throttle/ThrottleWindowStore.js.map +1 -0
  42. package/dist/test/MemoryThrottleWindowStore.test.d.ts +2 -0
  43. package/dist/test/MemoryThrottleWindowStore.test.d.ts.map +1 -0
  44. package/dist/test/MemoryThrottleWindowStore.test.js +210 -0
  45. package/dist/test/MemoryThrottleWindowStore.test.js.map +1 -0
  46. package/dist/test/NoAddressesInLogs.integration.test.js +13 -11
  47. package/dist/test/NoAddressesInLogs.integration.test.js.map +1 -1
  48. package/dist/test/SharedThrottleWindows.integration.test.d.ts +2 -0
  49. package/dist/test/SharedThrottleWindows.integration.test.d.ts.map +1 -0
  50. package/dist/test/SharedThrottleWindows.integration.test.js +756 -0
  51. package/dist/test/SharedThrottleWindows.integration.test.js.map +1 -0
  52. package/dist/test/SignupRace.integration.test.d.ts +2 -0
  53. package/dist/test/SignupRace.integration.test.d.ts.map +1 -0
  54. package/dist/test/SignupRace.integration.test.js +320 -0
  55. package/dist/test/SignupRace.integration.test.js.map +1 -0
  56. package/dist/test/UserServerTestEnvironment.d.ts.map +1 -1
  57. package/dist/test/UserServerTestEnvironment.js +3 -0
  58. package/dist/test/UserServerTestEnvironment.js.map +1 -1
  59. package/generated/index.ts +1 -1
  60. package/index.ts +4 -0
  61. package/package.json +5 -5
  62. package/src/routes/executePasswordReset.ts +1 -1
  63. package/src/routes/initiatePasswordReset.ts +2 -1
  64. package/src/routes/login.ts +2 -2
  65. package/src/services/Signup.ts +30 -11
  66. package/src/throttle/MemoryThrottleWindowStore.ts +60 -0
  67. package/src/throttle/PasswordResetThrottle.ts +14 -11
  68. package/src/throttle/SignInThrottle.ts +27 -19
  69. package/src/throttle/SlidingWindow.ts +6 -4
  70. package/src/throttle/StoredWindow.ts +132 -0
  71. package/src/throttle/ThrottleWindowStore.ts +41 -0
  72. package/test/MemoryThrottleWindowStore.test.ts +74 -0
  73. package/test/NoAddressesInLogs.integration.test.ts +9 -8
  74. package/test/SharedThrottleWindows.integration.test.ts +407 -0
  75. package/test/SignupRace.integration.test.ts +230 -0
  76. package/test/UserServerTestEnvironment.ts +3 -0
@@ -0,0 +1,407 @@
1
+ import { getDbAsSystem } from '@proteinjs/db';
2
+ import { MailSink } from '@proteinjs/email-server';
3
+ import { SourceRepository } from '@proteinjs/reflection';
4
+ import { tables } from '@proteinjs/user';
5
+ import { RequestDigests as UtilRequestDigests } from '@proteinjs/util-node';
6
+ import { login } from '../src/routes/login';
7
+ import { initiatePasswordReset } from '../src/routes/initiatePasswordReset';
8
+ import { PasswordHasher } from '../src/authentication/PasswordHasher';
9
+ import { PasswordResetToken } from '../src/authentication/PasswordResetToken';
10
+ import { RequestDigests } from '../src/throttle/RequestDigests';
11
+ import { SignInThrottle } from '../src/throttle/SignInThrottle';
12
+ import { PasswordResetThrottle } from '../src/throttle/PasswordResetThrottle';
13
+ import { createPassportRequest } from './passportSessionHarness';
14
+ import { UserServerTestEnvironment } from './UserServerTestEnvironment';
15
+ import { LogCapture } from './LogCapture';
16
+
17
+ const testEnv = new UserServerTestEnvironment();
18
+
19
+ /**
20
+ * The windows keyed on something other than the device — the sign-in door's per-account window
21
+ * and the reset door's per-address window — counted in ONE store that every server process shares
22
+ * (a store registered through `@proteinjs/user-server/DefaultThrottleWindowStoreFactory`), so the
23
+ * count is one across replicas and survives a deploy. Against the Spanner emulator, outcomes only:
24
+ * - two "pods" (the door in this process, and a second process's throttle) count as one: ten wrong
25
+ * passwords through the door, and the second pod refuses the eleventh;
26
+ * - a deploy (a new process with a new store instance over the same backing store) sees the old
27
+ * count, and the window's expiry (its TTL — equal to the window: 15 minutes per account, an hour
28
+ * per reset address) clears it;
29
+ * - a success on one pod clears the account's window for every pod;
30
+ * - the reset door's per-address window is one count across pods;
31
+ * - the store failing or stalling is the NAMED FALLBACK: the door counts in this process's memory
32
+ * window until the store answers again — ten wrong passwords are judged wrong and the eleventh is
33
+ * refused, the right password signs in, a stalled store is judged within its deadline, the reset
34
+ * door still mints and mails — and the outage is one WARN line per window saying so, once however
35
+ * many tries meet it, and one INFO line when the store answers again;
36
+ * - an outage's boundary continues from this process's own count (every try the store answered was
37
+ * counted in memory too): nine wrong in the store, then the store fails, and the eleventh is
38
+ * refused; on recovery the store counts from what it holds (the outage's tries were this
39
+ * process's own and never reach it).
40
+ *
41
+ * The backing store here is a stand-in for the shared one (a map every instance reads and writes,
42
+ * the way every process reads and writes one Redis), with its own clock for the TTL.
43
+ */
44
+
45
+ const WRONG = 'User name or password incorrect';
46
+ const THROTTLED = 'Too many attempts. Try again in a few minutes.';
47
+ const RIGHT_PASSWORD = 'the right horse battery';
48
+ const MINUTE = 60 * 1000;
49
+ const FACTORY = '@proteinjs/user-server/DefaultThrottleWindowStoreFactory';
50
+
51
+ /** Every instance reads and writes one backing map: a new instance is a new process on the same store. */
52
+ class SharedBackingStore {
53
+ static readonly backing = new Map<string, { count: number; expiresAt: number }>();
54
+ /** key → the window (TTL) its first count was given. */
55
+ static readonly windows = new Map<string, number>();
56
+ static now = () => Date.now();
57
+
58
+ async increment(key: string, windowMs: number): Promise<number> {
59
+ const live = this.live(key);
60
+ const entry = live ?? { count: 0, expiresAt: SharedBackingStore.now() + windowMs };
61
+ if (!live) {
62
+ SharedBackingStore.windows.set(key, windowMs);
63
+ }
64
+ entry.count++;
65
+ SharedBackingStore.backing.set(key, entry);
66
+ return entry.count;
67
+ }
68
+
69
+ async read(key: string): Promise<number> {
70
+ return this.live(key)?.count ?? 0;
71
+ }
72
+
73
+ async clear(key: string): Promise<void> {
74
+ SharedBackingStore.backing.delete(key);
75
+ }
76
+
77
+ private live(key: string) {
78
+ const entry = SharedBackingStore.backing.get(key);
79
+ if (entry && entry.expiresAt <= SharedBackingStore.now()) {
80
+ SharedBackingStore.backing.delete(key);
81
+ return undefined;
82
+ }
83
+ return entry;
84
+ }
85
+ }
86
+
87
+ /** A store that is down: every call fails the way a lost connection does. */
88
+ class DownStore {
89
+ async increment(): Promise<number> {
90
+ throw new Error('Connection is closed.');
91
+ }
92
+ async read(): Promise<number> {
93
+ throw new Error('Connection is closed.');
94
+ }
95
+ async clear(): Promise<void> {
96
+ throw new Error('Connection is closed.');
97
+ }
98
+ }
99
+
100
+ /** A store that never answers (a client queueing commands while it reconnects). */
101
+ class StalledStore {
102
+ increment(): Promise<number> {
103
+ return new Promise(() => undefined);
104
+ }
105
+ read(): Promise<number> {
106
+ return new Promise(() => undefined);
107
+ }
108
+ clear(): Promise<void> {
109
+ return new Promise(() => undefined);
110
+ }
111
+ }
112
+
113
+ type SourceRepositoryInternals = { objectCache: Record<string, unknown[]> };
114
+ const register = (store: () => unknown) => {
115
+ (SourceRepository.get() as unknown as SourceRepositoryInternals).objectCache[FACTORY] = [{ getStore: store }];
116
+ };
117
+
118
+ let run = 0;
119
+ /** A fresh address per test, so the counts of one test never meet another's. */
120
+ const address = (label: string) => `shared-${label}-${Date.now()}-${++run}@test.local`;
121
+ let ipSeed = 0;
122
+ /** A fresh client address per try, so the per-device window (per pod, by design) never decides. */
123
+ const freshIp = () => {
124
+ ipSeed++;
125
+ return `10.${(ipSeed >> 16) & 255}.${(ipSeed >> 8) & 255}.${ipSeed & 255}`;
126
+ };
127
+
128
+ type Attempt = { sent: any; signedInAs?: string };
129
+
130
+ /** One sign-in try through pod A's door (this process's `POST /user/login`). */
131
+ const signIn = async (email: string, password: string, ip = freshIp()): Promise<Attempt> => {
132
+ let sent: any;
133
+ const response: any = {
134
+ send: (body: any) => {
135
+ sent = body;
136
+ },
137
+ status: () => response,
138
+ };
139
+ const { request } = await createPassportRequest({
140
+ body: { email, password },
141
+ headers: {},
142
+ socket: { remoteAddress: ip },
143
+ app: { get: () => false },
144
+ });
145
+ await login.onRequest(request, response);
146
+ return { sent, signedInAs: request.session.passport?.user };
147
+ };
148
+
149
+ const wrongTries = async (count: number, email: string) => {
150
+ const answers: string[] = [];
151
+ for (let i = 0; i < count; i++) {
152
+ answers.push((await signIn(email, 'wrong guess')).sent?.error);
153
+ }
154
+ return answers;
155
+ };
156
+
157
+ /** One reset request through pod A's door (`POST /user/initiate-password-reset`). */
158
+ const requestReset = async (email: string, ip = freshIp()) => {
159
+ let sent: any;
160
+ const response: any = {
161
+ send: (body: any) => {
162
+ sent = body;
163
+ },
164
+ status: () => response,
165
+ };
166
+ await initiatePasswordReset.onRequest(
167
+ { body: { email }, headers: {}, socket: { remoteAddress: ip }, app: { get: () => false } } as never,
168
+ response
169
+ );
170
+ // The door answers first and works after; let the work settle before reading the row.
171
+ await new Promise((resolve) => setTimeout(resolve, 300));
172
+ return sent;
173
+ };
174
+
175
+ const createAccount = async (email: string) => {
176
+ const user = await testEnv.createUser({ name: 'Shared Window User', email });
177
+ await getDbAsSystem().update(tables.User, { id: user.id, password: await new PasswordHasher().hash(RIGHT_PASSWORD) });
178
+ return user;
179
+ };
180
+
181
+ const coarseIp = () => new RequestDigests().coarseIp(freshIp());
182
+
183
+ describe('the account and reset-address windows, one count across server processes', () => {
184
+ const originalTransport = process.env.EMAIL_TRANSPORT;
185
+
186
+ beforeAll(async () => {
187
+ await testEnv.beforeAll();
188
+ const objectCache = (SourceRepository.get() as unknown as SourceRepositoryInternals).objectCache;
189
+ objectCache['@proteinjs/email-server/DefaultEmailConfigFactory'] = [
190
+ {
191
+ getEmailConfig: () => ({
192
+ host: 'smtp.test.local',
193
+ port: 465,
194
+ secure: true,
195
+ from: '"Example" <hi@example.com>',
196
+ }),
197
+ },
198
+ ];
199
+ objectCache['@proteinjs/email-server/DefaultPasswordResetEmailConfigFactory'] = [
200
+ { getConfig: () => ({ getEmailContent: (path: string) => ({ text: `Reset: https://app.test.local/${path}` }) }) },
201
+ ];
202
+ process.env.EMAIL_TRANSPORT = 'sink';
203
+ }, 120000);
204
+
205
+ beforeEach(() => {
206
+ SharedBackingStore.now = () => Date.now();
207
+ register(() => new SharedBackingStore());
208
+ });
209
+
210
+ afterAll(async () => {
211
+ delete (SourceRepository.get() as unknown as SourceRepositoryInternals).objectCache[FACTORY];
212
+ if (originalTransport === undefined) {
213
+ delete process.env.EMAIL_TRANSPORT;
214
+ } else {
215
+ process.env.EMAIL_TRANSPORT = originalTransport;
216
+ }
217
+ await testEnv.afterAll();
218
+ });
219
+
220
+ it('two pods count as one: ten wrong passwords through the door, and the second pod refuses the eleventh', async () => {
221
+ const email = address('two-pods');
222
+ await createAccount(email);
223
+ const podB = new SignInThrottle();
224
+
225
+ expect(await wrongTries(10, email)).toEqual(Array(10).fill(WRONG));
226
+
227
+ expect(await podB.admit(coarseIp(), new RequestDigests().account(email))).toBe('account');
228
+ // And back through the door: the right password is refused too, and no session is made.
229
+ const right = await signIn(email, RIGHT_PASSWORD);
230
+ expect(right.sent).toEqual({ error: THROTTLED });
231
+ expect(right.signedInAs).toBeUndefined();
232
+ });
233
+
234
+ it('interleaved across two pods, the eleventh wrong password is refused wherever it lands', async () => {
235
+ const email = address('interleaved');
236
+ const account = new RequestDigests().account(email);
237
+ const podB = new SignInThrottle();
238
+
239
+ for (let i = 0; i < 5; i++) {
240
+ expect((await signIn(email, 'wrong guess')).sent).toEqual({ error: WRONG });
241
+ expect(await podB.admit(coarseIp(), account)).toBeUndefined();
242
+ }
243
+
244
+ expect((await signIn(email, 'wrong guess')).sent).toEqual({ error: THROTTLED });
245
+ });
246
+
247
+ it('a deploy sees the old count (a new process, a new store instance, the same store) — and the window’s expiry clears it', async () => {
248
+ const email = address('deploy');
249
+ const account = new RequestDigests().account(email);
250
+ expect(await wrongTries(10, email)).toEqual(Array(10).fill(WRONG));
251
+
252
+ const afterDeploy = new SignInThrottle();
253
+ expect(await afterDeploy.admit(coarseIp(), account)).toBe('account');
254
+
255
+ // The TTL is the window: fifteen minutes after the first counted try, the count is gone.
256
+ const counted = Array.from(SharedBackingStore.windows.entries()).filter(([key]) => key.includes(account));
257
+ expect(counted.map(([, windowMs]) => windowMs)).toEqual([15 * MINUTE]);
258
+ const start = Date.now();
259
+ SharedBackingStore.now = () => start + 15 * MINUTE + 1;
260
+ expect(await afterDeploy.admit(coarseIp(), account)).toBeUndefined();
261
+ });
262
+
263
+ it("a success on one pod clears the account's window for every pod", async () => {
264
+ const email = address('cleared');
265
+ await createAccount(email);
266
+ const account = new RequestDigests().account(email);
267
+ const podB = new SignInThrottle();
268
+ expect(await wrongTries(9, email)).toEqual(Array(9).fill(WRONG));
269
+
270
+ // Pod B sees the account prove itself (a sign-in there, or a reset link redeemed there).
271
+ await podB.recordSuccess(account);
272
+
273
+ expect(await wrongTries(10, email)).toEqual(Array(10).fill(WRONG));
274
+ expect((await signIn(email, 'wrong guess')).sent).toEqual({ error: THROTTLED });
275
+ });
276
+
277
+ it("the reset door's per-address window is one count across pods, with the hour as its TTL", async () => {
278
+ const email = address('reset');
279
+ await createAccount(email);
280
+ const account = new UtilRequestDigests().account(email);
281
+ const podB = new PasswordResetThrottle();
282
+
283
+ for (let i = 0; i < 3; i++) {
284
+ await requestReset(email);
285
+ }
286
+
287
+ expect(await podB.admit(new UtilRequestDigests().coarseIp(freshIp()), account)).toBe('account');
288
+ const counted = Array.from(SharedBackingStore.windows.entries()).filter(([key]) => key.includes(account));
289
+ expect(counted.map(([, windowMs]) => windowMs)).toEqual([60 * MINUTE]);
290
+ });
291
+
292
+ it('windows sharing one store never meet: three reset requests for an address leave its ten sign-in tries whole', async () => {
293
+ const email = address('never-meet');
294
+ await createAccount(email);
295
+
296
+ for (let i = 0; i < 3; i++) {
297
+ await requestReset(email);
298
+ }
299
+
300
+ expect(await wrongTries(10, email)).toEqual(Array(10).fill(WRONG));
301
+ expect((await signIn(email, 'wrong guess')).sent).toEqual({ error: THROTTLED });
302
+ });
303
+
304
+ describe("when the store fails, the counted doors count in this process's memory until it answers", () => {
305
+ it('a store that is down: the right password signs in, ten wrong passwords are judged wrong, the eleventh is refused (the right password too, no session) — one WARN saying so until the store answers again', async () => {
306
+ const email = address('down');
307
+ await createAccount(email);
308
+ register(() => new DownStore());
309
+
310
+ const log = await LogCapture.during(async () => {
311
+ const first = await signIn(email, RIGHT_PASSWORD);
312
+ expect(first.sent).toEqual({});
313
+ expect(first.signedInAs).toBe(email);
314
+ expect(await wrongTries(10, email)).toEqual(Array(10).fill(WRONG));
315
+ const eleventh = await signIn(email, RIGHT_PASSWORD);
316
+ expect(eleventh.sent).toEqual({ error: THROTTLED });
317
+ expect(eleventh.signedInAs).toBeUndefined();
318
+ });
319
+ const unavailable = log.linesContaining('Throttle window store unavailable');
320
+ expect(unavailable.lines).toHaveLength(1);
321
+ expect(unavailable.text).toContain("counting in this process's memory until it answers");
322
+ expect(unavailable.text).toContain('sign-in-account');
323
+ expect(log.addresses).toEqual([]);
324
+
325
+ // The store answers again: the door counts there again (the outage's tries were this process's
326
+ // own), the right password signs in — and its success clears the memory window too.
327
+ register(() => new SharedBackingStore());
328
+ const recovered = await LogCapture.during(async () => {
329
+ const right = await signIn(email, RIGHT_PASSWORD);
330
+ expect(right.sent).toEqual({});
331
+ expect(right.signedInAs).toBe(email);
332
+ });
333
+ expect(recovered.linesContaining('Throttle window store answering again').lines).toHaveLength(1);
334
+
335
+ // The next outage is its own line, and the memory window starts clean.
336
+ register(() => new DownStore());
337
+ const again = await LogCapture.during(async () => {
338
+ expect((await signIn(email, 'wrong guess')).sent).toEqual({ error: WRONG });
339
+ });
340
+ expect(again.linesContaining('Throttle window store unavailable').lines).toHaveLength(1);
341
+ });
342
+
343
+ it("the store fails after nine wrong tries: the memory window continues from this process's own nine — the tenth is judged wrong, the eleventh refused; one WARN", async () => {
344
+ const email = address('boundary');
345
+ await createAccount(email);
346
+ expect(await wrongTries(9, email)).toEqual(Array(9).fill(WRONG));
347
+
348
+ register(() => new DownStore());
349
+ const log = await LogCapture.during(async () => {
350
+ expect(await wrongTries(2, email)).toEqual([WRONG, THROTTLED]);
351
+ const right = await signIn(email, RIGHT_PASSWORD);
352
+ expect(right.sent).toEqual({ error: THROTTLED });
353
+ expect(right.signedInAs).toBeUndefined();
354
+ });
355
+ expect(log.linesContaining('Throttle window store unavailable').lines).toHaveLength(1);
356
+ expect(log.addresses).toEqual([]);
357
+ });
358
+
359
+ it("on recovery the store counts from what it holds: the outage's five wrong tries never reach the shared count (ten fresh before the refusal, one INFO) — and this process's own count, kept all along, refuses at once in the next outage", async () => {
360
+ const email = address('recovery');
361
+ await createAccount(email);
362
+ register(() => new DownStore());
363
+ expect(await wrongTries(5, email)).toEqual(Array(5).fill(WRONG));
364
+
365
+ register(() => new SharedBackingStore());
366
+ const recovered = await LogCapture.during(async () => {
367
+ expect(await wrongTries(11, email)).toEqual([...Array(10).fill(WRONG), THROTTLED]);
368
+ });
369
+ expect(recovered.linesContaining('Throttle window store answering again').lines).toHaveLength(1);
370
+
371
+ // Sixteen tries met this process within the window (five in the outage, eleven while the store
372
+ // answered): when the store fails again, memory judges from all sixteen.
373
+ register(() => new DownStore());
374
+ expect((await signIn(email, 'wrong guess')).sent).toEqual({ error: THROTTLED });
375
+ });
376
+
377
+ it('a store that never answers: the door judges the try within the store deadline — not never, and not a refusal', async () => {
378
+ const email = address('stalled');
379
+ register(() => new StalledStore());
380
+
381
+ const started = Date.now();
382
+ const answer = await signIn(email, 'wrong guess');
383
+
384
+ expect(answer.sent).toEqual({ error: WRONG });
385
+ expect(Date.now() - started).toBeLessThan(5000);
386
+ });
387
+
388
+ it('the reset door with the store down: the one answer as always, AND the link minted and mailed', async () => {
389
+ const email = address('reset-down');
390
+ const user = await createAccount(email);
391
+ register(() => new DownStore());
392
+ MailSink.get().clear();
393
+
394
+ expect(await requestReset(email)).toEqual({
395
+ message: 'If that address has an account, a reset link is on its way.',
396
+ });
397
+
398
+ const row = await getDbAsSystem().get(tables.User, { id: user.id });
399
+ expect(new PasswordResetToken().mintedAt(row)).toBeDefined();
400
+ expect(
401
+ MailSink.get()
402
+ .list()
403
+ .map((mail) => mail.to)
404
+ ).toEqual([[email]]);
405
+ });
406
+ });
407
+ });
@@ -0,0 +1,230 @@
1
+ import { randomBytes } from 'crypto';
2
+ import { getDbAsSystem } from '@proteinjs/db';
3
+ import { MailSink, MailSinkRecord } from '@proteinjs/email-server';
4
+ import { SourceRepository } from '@proteinjs/reflection';
5
+ import { tables } from '@proteinjs/user';
6
+ import { PasswordHasher } from '../src/authentication/PasswordHasher';
7
+ import { signup } from '../src/routes/signup';
8
+ import { Signup } from '../src/services/Signup';
9
+ import { RequestDigests } from '../src/throttle/RequestDigests';
10
+ import { LogCapture } from './LogCapture';
11
+ import { createPassportRequest } from './passportSessionHarness';
12
+ import { UserServerTestEnvironment } from './UserServerTestEnvironment';
13
+
14
+ /**
15
+ * Two sign-ups for one address at the same moment. The signup door has one rule for an address
16
+ * that already has an account: the caller gets the response a new account gets, byte for byte, no
17
+ * session is minted, the address's owner is told by mail, and no log line names the address. A
18
+ * race used to break it: both requests passed the existence check before either wrote, the unique
19
+ * index on the address refused the second insert, and the database's sentence — which names the
20
+ * address — came back as the loser's response and its log line.
21
+ *
22
+ * Driven end to end against the Spanner emulator: the real route, the real passport session
23
+ * machinery, the real mail sink (`EMAIL_TRANSPORT=sink`), the log captured as the default writer
24
+ * emits it. Each create's password hash is held until both creates have arrived, so both have
25
+ * passed the existence check and both inserts race.
26
+ */
27
+
28
+ const testEnv = new UserServerTestEnvironment();
29
+
30
+ type SourceRepositoryInternals = { objectCache: Record<string, unknown[]> };
31
+ const objectCache = () => (SourceRepository.get() as unknown as SourceRepositoryInternals).objectCache;
32
+
33
+ const CONFIG_KEYS = [
34
+ '@proteinjs/email-server/DefaultEmailConfigFactory',
35
+ '@proteinjs/email-server/DefaultSignupConfirmationEmailConfigFactory',
36
+ '@proteinjs/user-server/DefaultInviteConfigFactory',
37
+ ];
38
+
39
+ const WELCOME_SUBJECT = 'Welcome';
40
+ const EXISTS_SUBJECT = 'Account already exists';
41
+
42
+ type SignupOutcome = {
43
+ status: number;
44
+ /** The body as the wire carries it (express serializes an object body as JSON). */
45
+ bytes: string;
46
+ loggedInAs?: string;
47
+ sessionEvents: string[];
48
+ };
49
+
50
+ /** One sign-up through the route, the session read back off the request as passport left it. */
51
+ const signUp = async (body: Record<string, unknown>): Promise<SignupOutcome> => {
52
+ const { request, events } = await createPassportRequest({ body });
53
+ const outcome: SignupOutcome = { status: 200, bytes: '', sessionEvents: events };
54
+ const response = {
55
+ status(code: number) {
56
+ outcome.status = code;
57
+ return this;
58
+ },
59
+ send(sent?: unknown) {
60
+ outcome.bytes = JSON.stringify(sent);
61
+ },
62
+ };
63
+ await signup.onRequest(request as never, response as never);
64
+ outcome.loggedInAs = request.session.passport?.user;
65
+ return outcome;
66
+ };
67
+
68
+ /**
69
+ * Runs `run` with every account creation's password hash held until `count` hashes have started —
70
+ * each create has passed the existence check by then, so their inserts race.
71
+ */
72
+ const withCreatesHeldTogether = async <T>(count: number, run: () => Promise<T>): Promise<T> => {
73
+ const hash = PasswordHasher.prototype.hash;
74
+ let arrived = 0;
75
+ let release!: () => void;
76
+ const allArrived = new Promise<void>((resolve) => (release = resolve));
77
+ const held = jest.spyOn(PasswordHasher.prototype, 'hash').mockImplementation(async function (
78
+ this: PasswordHasher,
79
+ password: string
80
+ ) {
81
+ const hashed = await hash.call(this, password);
82
+ if (++arrived === count) {
83
+ release();
84
+ }
85
+ await allArrived;
86
+ return hashed;
87
+ });
88
+ try {
89
+ return await run();
90
+ } finally {
91
+ held.mockRestore();
92
+ }
93
+ };
94
+
95
+ /** The mail the sink holds for `address`, oldest first. */
96
+ const mailTo = (address: string): MailSinkRecord[] =>
97
+ MailSink.get()
98
+ .list()
99
+ .filter((record) => record.to.includes(address))
100
+ .reverse();
101
+
102
+ describe('two sign-ups for one address at once', () => {
103
+ let originalTransport: string | undefined;
104
+
105
+ beforeAll(async () => {
106
+ await testEnv.beforeAll();
107
+ originalTransport = process.env.EMAIL_TRANSPORT;
108
+ process.env.EMAIL_TRANSPORT = 'sink';
109
+ const cache = objectCache();
110
+ cache['@proteinjs/email-server/DefaultEmailConfigFactory'] = [
111
+ {
112
+ getEmailConfig: () => ({
113
+ host: 'smtp.test.local',
114
+ port: 465,
115
+ secure: true,
116
+ from: '"Example" <hi@example.com>',
117
+ }),
118
+ },
119
+ ];
120
+ cache['@proteinjs/email-server/DefaultSignupConfirmationEmailConfigFactory'] = [
121
+ {
122
+ getConfig: () => ({
123
+ newUserSubject: WELCOME_SUBJECT,
124
+ existingUserSubject: EXISTS_SUBJECT,
125
+ getNewUserEmailContent: () => ({ text: 'welcome' }),
126
+ getExistingUserEmailContent: () => ({ text: 'someone tried to sign up with your address' }),
127
+ }),
128
+ },
129
+ ];
130
+ // Invite-optional, the library default — the suites load src, never the generated source graph.
131
+ cache['@proteinjs/user-server/DefaultInviteConfigFactory'] = [{ getConfig: () => ({ isInviteOnly: false }) }];
132
+ }, 120000);
133
+
134
+ afterAll(async () => {
135
+ const cache = objectCache();
136
+ for (const key of CONFIG_KEYS) {
137
+ delete cache[key];
138
+ }
139
+ if (originalTransport === undefined) {
140
+ delete process.env.EMAIL_TRANSPORT;
141
+ } else {
142
+ process.env.EMAIL_TRANSPORT = originalTransport;
143
+ }
144
+ await testEnv.afterAll();
145
+ });
146
+
147
+ beforeEach(() => {
148
+ MailSink.get().clear();
149
+ });
150
+
151
+ it('the loser answers exactly as a plain existing address does: the same bytes, no session, one mail to the owner, no address in the log', async () => {
152
+ // Typed with capitals, stored lowercased — the address a person types.
153
+ const local = `race-${randomBytes(4).toString('hex')}`;
154
+ const address = `${local}@test.local`;
155
+ const body = { name: 'Racer', email: `${local.toUpperCase()}@Test.local`, password: 'a-password' };
156
+
157
+ let raced: SignupOutcome[] = [];
158
+ const log = await LogCapture.during(async () => {
159
+ raced = await withCreatesHeldTogether(2, () => Promise.all([signUp(body), signUp(body)]));
160
+ });
161
+ const racedMail = mailTo(address);
162
+
163
+ // A plain sign-up for the address that now exists: the response the rule promises.
164
+ const plain = await signUp(body);
165
+ expect(plain.loggedInAs).toBeUndefined();
166
+
167
+ // Both racers got that response, byte for byte.
168
+ expect(raced.map((outcome) => [outcome.status, outcome.bytes])).toEqual([
169
+ [plain.status, plain.bytes],
170
+ [plain.status, plain.bytes],
171
+ ]);
172
+ // One account; one session, for the racer that created it; the loser none at all.
173
+ expect((await getDbAsSystem().query(tables.User, { email: address })).length).toBe(1);
174
+ expect(raced.filter((outcome) => outcome.loggedInAs === address)).toHaveLength(1);
175
+ const loser = raced.find((outcome) => outcome.loggedInAs === undefined);
176
+ expect(loser?.sessionEvents).toEqual([]);
177
+ // The owner's mail: the winner's welcome and ONE notice that someone tried the address again.
178
+ expect(racedMail.map((record) => record.subject).sort()).toEqual([EXISTS_SUBJECT, WELCOME_SUBJECT].sort());
179
+
180
+ // No line this process wrote names the address (its local part, in any case or encoding) except the database
181
+ // driver's own line for the refused statement: the driver's version (the one a package lock
182
+ // pins) decides whether that line prints bound values; it is the driver's to keep clean.
183
+ const lines = log.lines.filter((line) => !line.includes('[SpannerDriver]'));
184
+ expect(lines.length).toBeGreaterThan(0);
185
+ expect(lines.filter((line) => line.toLowerCase().includes(local))).toEqual([]);
186
+ // The account lines name the account by its digest: the winner's `Created user` and the
187
+ // loser's `already exists`, each carrying the same digest for the one address.
188
+ const digest = new RequestDigests().account(address);
189
+ expect(lines.filter((line) => line.includes('Created user') && line.includes(digest))).toHaveLength(1);
190
+ expect(lines.filter((line) => line.includes('already exists') && line.includes(digest))).toHaveLength(1);
191
+ });
192
+
193
+ it('a create that loses the race to the same address reports it as existing, the account row the winner wrote untouched', async () => {
194
+ const local = `race-${randomBytes(4).toString('hex')}`;
195
+ const address = `${local}@test.local`;
196
+ // Both creates carry the address as typed (capitals): the row is stored lowercased, and the
197
+ // loser's re-read must ask for the address the way the row holds it.
198
+ const account = (name: string) => ({
199
+ name,
200
+ email: `${local.toUpperCase()}@Test.local`,
201
+ password: 'a-password',
202
+ emailVerified: false,
203
+ invitedBy: null,
204
+ });
205
+
206
+ const outcomes = await withCreatesHeldTogether(2, () =>
207
+ Promise.all([new Signup().createAccount(account('First')), new Signup().createAccount(account('Second'))])
208
+ );
209
+
210
+ expect(outcomes.slice().sort()).toEqual(['created', 'exists']);
211
+ const rows = await getDbAsSystem().query(tables.User, { email: address });
212
+ expect(rows).toHaveLength(1);
213
+ expect(rows[0].name).toBe(outcomes[0] === 'created' ? 'First' : 'Second');
214
+ });
215
+
216
+ it('an insert the database refuses while the address has no account is a real failure: it throws, never "exists"', async () => {
217
+ const address = `race-${randomBytes(4).toString('hex')}@test.local`;
218
+ // The name column holds 255 characters; the database refuses a longer one.
219
+ const create = new Signup().createAccount({
220
+ name: 'n'.repeat(300),
221
+ email: address,
222
+ password: 'a-password',
223
+ emailVerified: false,
224
+ invitedBy: null,
225
+ });
226
+
227
+ await expect(create).rejects.toThrow();
228
+ expect(await getDbAsSystem().query(tables.User, { email: address })).toHaveLength(0);
229
+ });
230
+ });
@@ -50,6 +50,9 @@ export class UserServerTestEnvironment {
50
50
  const objectCache = (SourceRepository.get() as unknown as SourceRepositoryInternals).objectCache;
51
51
  objectCache['@proteinjs/server-api/SessionDataStorage'] = [new TestSessionDataStorage()];
52
52
  objectCache['@proteinjs/db/DefaultDbDriverFactory'] = [{ getDbDriver: () => this.spannerDriver }];
53
+ // No shared window store registered: the counted throttle windows use the library's own
54
+ // per-process store (the suites load src, never the generated source graph).
55
+ objectCache['@proteinjs/user-server/DefaultThrottleWindowStoreFactory'] = [];
53
56
  Session.setData({
54
57
  sessionId: 'test-session',
55
58
  user: 'guest',