@prosopo/client-example-server 2.7.171 → 2.7.172

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.
@@ -1,915 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import { CaptchaType, type ProcaptchaToken } from "@prosopo/types";
16
- import type { NextFunction } from "express";
17
- import jwt from "jsonwebtoken";
18
- import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
19
- import { isAuth, login, signup } from "../controllers/auth.js";
20
- import {
21
- SECRET,
22
- SITE_KEY,
23
- VERIFY_ENDPOINT,
24
- connectionWith,
25
- pairWithAddress,
26
- request,
27
- responseStub,
28
- serverConfig,
29
- signupBody,
30
- userModel,
31
- } from "./authHarness.js";
32
-
33
- /**
34
- * The controllers derive keyring pairs and verify tokens against a provider.
35
- * Both are replaced here: deriving is deterministic but slow, and verifying
36
- * would need a live provider. Everything else — zod parsing, the mongoose
37
- * calls, the response codes — is the real thing.
38
- */
39
- const mocks = vi.hoisted(() => ({
40
- // Maps a secret to the address the pair derived from it claims.
41
- addresses: new Map<string, string>(),
42
- isVerified: vi.fn(),
43
- constructions: [] as unknown[][],
44
- }));
45
-
46
- vi.mock("@prosopo/keyring", async (importOriginal) => {
47
- const actual = await importOriginal<typeof import("@prosopo/keyring")>();
48
- return {
49
- ...actual,
50
- getPair: (secret: string) => ({
51
- address: mocks.addresses.get(secret) ?? `derived:${secret}`,
52
- }),
53
- };
54
- });
55
-
56
- vi.mock("@prosopo/server", async (importOriginal) => {
57
- const actual = await importOriginal<typeof import("@prosopo/server")>();
58
- return {
59
- ...actual,
60
- ProsopoServer: class {
61
- constructor(...args: unknown[]) {
62
- mocks.constructions.push(args);
63
- }
64
- isVerified = mocks.isVerified;
65
- },
66
- };
67
- });
68
-
69
- const next: NextFunction = () => undefined;
70
-
71
- const fetchMock =
72
- vi.fn<
73
- (input: string | URL | Request, init?: RequestInit) => Promise<Response>
74
- >();
75
-
76
- beforeEach(() => {
77
- mocks.addresses.clear();
78
- mocks.addresses.set(SECRET, SITE_KEY);
79
- mocks.constructions.length = 0;
80
- mocks.isVerified.mockReset();
81
- mocks.isVerified.mockResolvedValue({ verified: true });
82
- fetchMock.mockReset();
83
- fetchMock.mockResolvedValue(new Response(JSON.stringify({ verified: true })));
84
- vi.stubGlobal("fetch", fetchMock);
85
- vi.spyOn(console, "error").mockImplementation(() => undefined);
86
- });
87
-
88
- afterEach(() => {
89
- vi.unstubAllGlobals();
90
- vi.restoreAllMocks();
91
- Reflect.deleteProperty(process.env, "NODE_ENV");
92
- process.env.NODE_ENV = "test";
93
- });
94
-
95
- describe("signup", () => {
96
- test("creates the user once the captcha verifies", async () => {
97
- const { connection, model } = connectionWith(userModel({}));
98
- const res = responseStub();
99
- await signup(
100
- connection,
101
- serverConfig(),
102
- VERIFY_ENDPOINT,
103
- "local",
104
- request({ body: signupBody() }),
105
- res.response,
106
- next,
107
- );
108
- expect(res.statuses).toEqual([200]);
109
- expect(res.bodies).toEqual([{ message: "user created" }]);
110
- const created = model.create.mock.calls[0]?.[0] as Record<string, string>;
111
- expect(created?.email).toBe("user@example.com");
112
- expect(created?.name).toBe("user");
113
- // The password is salted and hashed, never stored as typed.
114
- expect(created?.password).not.toBe("hunter2");
115
- expect(String(created?.password).startsWith("0x")).toBe(true);
116
- expect(created?.salt).toMatch(/^0x[0-9a-f]{64}$/);
117
- });
118
-
119
- test("salts every signup differently", async () => {
120
- const { connection, model } = connectionWith(userModel({}));
121
- for (let i = 0; i < 2; i++) {
122
- await signup(
123
- connection,
124
- serverConfig(),
125
- VERIFY_ENDPOINT,
126
- "local",
127
- request({ body: signupBody() }),
128
- responseStub().response,
129
- next,
130
- );
131
- }
132
- const [first, second] = model.create.mock.calls.map(
133
- (call) => (call[0] as Record<string, string>).salt,
134
- );
135
- expect(first).not.toBe(second);
136
- });
137
-
138
- test("rejects an email that is already registered, before verifying", async () => {
139
- const { connection, model } = connectionWith(
140
- userModel({ found: { password: "0xhash", salt: "0xsalt" } }),
141
- );
142
- const res = responseStub();
143
- await signup(
144
- connection,
145
- serverConfig(),
146
- VERIFY_ENDPOINT,
147
- "local",
148
- request({ body: signupBody() }),
149
- res.response,
150
- next,
151
- );
152
- expect(res.statuses).toEqual([409]);
153
- expect(res.bodies).toEqual([{ message: "email already exists" }]);
154
- expect(mocks.isVerified).not.toHaveBeenCalled();
155
- expect(model.create).not.toHaveBeenCalled();
156
- });
157
-
158
- test("refuses a signup that failed the captcha", async () => {
159
- mocks.isVerified.mockResolvedValue({ verified: false });
160
- const { connection, model } = connectionWith(userModel({}));
161
- const res = responseStub();
162
- await signup(
163
- connection,
164
- serverConfig(),
165
- VERIFY_ENDPOINT,
166
- "local",
167
- request({ body: signupBody() }),
168
- res.response,
169
- next,
170
- );
171
- expect(res.statuses).toEqual([401]);
172
- expect(res.bodies).toEqual([
173
- { message: "user has not completed a captcha", verified: false },
174
- ]);
175
- expect(model.create).not.toHaveBeenCalled();
176
- });
177
-
178
- test("treats a non-boolean verification result as a failure", async () => {
179
- // The API path returns whatever JSON the endpoint sent, so `verified`
180
- // can be a string, or missing entirely.
181
- mocks.isVerified.mockResolvedValue({ verified: "true" });
182
- const { connection, model } = connectionWith(userModel({}));
183
- const res = responseStub();
184
- await signup(
185
- connection,
186
- serverConfig(),
187
- VERIFY_ENDPOINT,
188
- "local",
189
- request({ body: signupBody() }),
190
- res.response,
191
- next,
192
- );
193
- expect(res.statuses).toEqual([401]);
194
- expect(model.create).not.toHaveBeenCalled();
195
- });
196
-
197
- test("reports a database write failure as a bad gateway", async () => {
198
- const { connection } = connectionWith(
199
- userModel({ createRejects: new Error("write concern failed") }),
200
- );
201
- const res = responseStub();
202
- await signup(
203
- connection,
204
- serverConfig(),
205
- VERIFY_ENDPOINT,
206
- "local",
207
- request({ body: signupBody() }),
208
- res.response,
209
- next,
210
- );
211
- expect(res.statuses).toEqual([502]);
212
- expect(res.bodies).toEqual([{ message: "error while creating the user" }]);
213
- });
214
-
215
- test("reports a database read failure as a server error", async () => {
216
- const { connection } = connectionWith(
217
- userModel({ findOneRejects: new Error("mongo unavailable") }),
218
- );
219
- const res = responseStub();
220
- await signup(
221
- connection,
222
- serverConfig(),
223
- VERIFY_ENDPOINT,
224
- "local",
225
- request({ body: signupBody() }),
226
- res.response,
227
- next,
228
- );
229
- expect(res.statuses).toEqual([500]);
230
- expect(res.bodies).toEqual([{ message: "mongo unavailable" }]);
231
- });
232
-
233
- test("refuses to run without a site private key", async () => {
234
- const { connection } = connectionWith(userModel({}));
235
- const res = responseStub();
236
- await signup(
237
- connection,
238
- serverConfig({}),
239
- VERIFY_ENDPOINT,
240
- "local",
241
- request({ body: signupBody() }),
242
- res.response,
243
- next,
244
- );
245
- expect(res.statuses).toEqual([500]);
246
- expect(mocks.isVerified).not.toHaveBeenCalled();
247
- });
248
-
249
- test("rejects a body that isn't a signup", async () => {
250
- const { connection } = connectionWith(userModel({}));
251
- const res = responseStub();
252
- await signup(
253
- connection,
254
- serverConfig(),
255
- VERIFY_ENDPOINT,
256
- "local",
257
- request({ body: signupBody({ email: "not-an-email" }) }),
258
- res.response,
259
- next,
260
- );
261
- expect(res.statuses).toEqual([500]);
262
- });
263
-
264
- test("rejects a token that isn't a procaptcha token", async () => {
265
- const { connection } = connectionWith(userModel({}));
266
- const res = responseStub();
267
- await signup(
268
- connection,
269
- serverConfig(),
270
- VERIFY_ENDPOINT,
271
- "local",
272
- request({ body: signupBody({ "procaptcha-response": "token" }) }),
273
- res.response,
274
- next,
275
- );
276
- expect(res.statuses).toEqual([500]);
277
- });
278
-
279
- test("falls back to a message when the failure carries none", async () => {
280
- const { connection } = connectionWith(
281
- userModel({ findOneRejects: new Error("") }),
282
- );
283
- const res = responseStub();
284
- await signup(
285
- connection,
286
- serverConfig(),
287
- VERIFY_ENDPOINT,
288
- "local",
289
- request({ body: signupBody() }),
290
- res.response,
291
- next,
292
- );
293
- expect(res.bodies).toEqual([{ message: "internal server error" }]);
294
- });
295
-
296
- test("passes the caller's IP to the verifier", async () => {
297
- const { connection } = connectionWith(userModel({}));
298
- await signup(
299
- connection,
300
- serverConfig(),
301
- VERIFY_ENDPOINT,
302
- "local",
303
- request({
304
- body: signupBody(),
305
- headers: { "x-client-ip": "203.0.113.9" },
306
- }),
307
- responseStub().response,
308
- next,
309
- );
310
- expect(mocks.isVerified).toHaveBeenCalledWith(
311
- "0xtoken",
312
- "203.0.113.9",
313
- "user@example.com",
314
- undefined,
315
- );
316
- });
317
-
318
- test("falls back to localhost when no IP header is present", async () => {
319
- const { connection } = connectionWith(userModel({}));
320
- await signup(
321
- connection,
322
- serverConfig(),
323
- VERIFY_ENDPOINT,
324
- "local",
325
- request({ body: signupBody() }),
326
- responseStub().response,
327
- next,
328
- );
329
- expect(mocks.isVerified).toHaveBeenCalledWith(
330
- "0xtoken",
331
- "127.0.0.1",
332
- "user@example.com",
333
- undefined,
334
- );
335
- });
336
- });
337
-
338
- describe("signup: matching the site key to a keyring pair", () => {
339
- test("uses the bare secret when it derives the site key", async () => {
340
- const { connection } = connectionWith(userModel({}));
341
- await signup(
342
- connection,
343
- serverConfig(),
344
- VERIFY_ENDPOINT,
345
- "local",
346
- request({ body: signupBody() }),
347
- responseStub().response,
348
- next,
349
- );
350
- expect(mocks.constructions[0]?.[1]).toEqual({ address: SITE_KEY });
351
- });
352
-
353
- test("tries the captcha-type suffixes when the bare secret doesn't match", async () => {
354
- mocks.addresses.clear();
355
- mocks.addresses.set(`${SECRET}//${CaptchaType.frictionless}`, SITE_KEY);
356
- const { connection } = connectionWith(userModel({}));
357
- const res = responseStub();
358
- await signup(
359
- connection,
360
- serverConfig(),
361
- VERIFY_ENDPOINT,
362
- "api",
363
- request({ body: signupBody() }),
364
- res.response,
365
- next,
366
- );
367
- expect(res.statuses).toEqual([200]);
368
- // The suffixed secret is what gets sent for verification, not the base.
369
- const body: Record<string, string> = JSON.parse(
370
- String(fetchMock.mock.calls[0]?.[1]?.body),
371
- );
372
- expect(body.secret).toBe(`${SECRET}//${CaptchaType.frictionless}`);
373
- });
374
-
375
- test("gives up when no captcha type derives the site key", async () => {
376
- mocks.addresses.clear();
377
- const { connection } = connectionWith(userModel({}));
378
- const res = responseStub();
379
- await signup(
380
- connection,
381
- serverConfig(),
382
- VERIFY_ENDPOINT,
383
- "local",
384
- request({ body: signupBody() }),
385
- res.response,
386
- next,
387
- );
388
- expect(res.statuses).toEqual([500]);
389
- expect(res.bodies[0]).toMatchObject({ message: expect.any(String) });
390
- expect(mocks.isVerified).not.toHaveBeenCalled();
391
- });
392
- });
393
-
394
- describe("signup: verifying through the API endpoint", () => {
395
- test("posts the token and secret to the configured endpoint", async () => {
396
- const { connection } = connectionWith(userModel({}));
397
- const res = responseStub();
398
- await signup(
399
- connection,
400
- serverConfig(),
401
- VERIFY_ENDPOINT,
402
- "api",
403
- request({
404
- body: signupBody(),
405
- headers: { "x-client-ip": "203.0.113.9" },
406
- }),
407
- res.response,
408
- next,
409
- );
410
- expect(res.statuses).toEqual([200]);
411
- expect(fetchMock.mock.calls[0]?.[0]).toBe(VERIFY_ENDPOINT);
412
- expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");
413
- const body: Record<string, string> = JSON.parse(
414
- String(fetchMock.mock.calls[0]?.[1]?.body),
415
- );
416
- expect(body).toEqual({
417
- token: "0xtoken",
418
- secret: SECRET,
419
- email: "user@example.com",
420
- ip: "203.0.113.9",
421
- });
422
- expect(mocks.isVerified).not.toHaveBeenCalled();
423
- });
424
-
425
- test("does not log the site secret, but still posts it", async () => {
426
- const infoSpy = vi
427
- .spyOn(console, "info")
428
- .mockImplementation(() => undefined);
429
- const { connection } = connectionWith(userModel({}));
430
- await signup(
431
- connection,
432
- serverConfig(),
433
- VERIFY_ENDPOINT,
434
- "api",
435
- request({
436
- body: signupBody(),
437
- headers: { "x-client-ip": "203.0.113.9" },
438
- }),
439
- responseStub().response,
440
- next,
441
- );
442
- const logged = infoSpy.mock.calls
443
- .map((call) => call.map((arg) => String(arg)).join(" "))
444
- .join("\n");
445
- expect(logged).not.toContain(SECRET);
446
- const postedBody: Record<string, string> = JSON.parse(
447
- String(fetchMock.mock.calls[0]?.[1]?.body),
448
- );
449
- expect(postedBody.secret).toBe(SECRET);
450
- });
451
-
452
- test("withholds the IP in development", async () => {
453
- process.env.NODE_ENV = "development";
454
- const { connection } = connectionWith(userModel({}));
455
- await signup(
456
- connection,
457
- serverConfig(),
458
- VERIFY_ENDPOINT,
459
- "api",
460
- request({
461
- body: signupBody(),
462
- headers: { "x-client-ip": "203.0.113.9" },
463
- }),
464
- responseStub().response,
465
- next,
466
- );
467
- const body: Record<string, string> = JSON.parse(
468
- String(fetchMock.mock.calls[0]?.[1]?.body),
469
- );
470
- expect(body.ip).toBeUndefined();
471
- });
472
-
473
- test("refuses the signup when the endpoint says unverified", async () => {
474
- fetchMock.mockResolvedValue(
475
- new Response(JSON.stringify({ verified: false })),
476
- );
477
- const { connection, model } = connectionWith(userModel({}));
478
- const res = responseStub();
479
- await signup(
480
- connection,
481
- serverConfig(),
482
- VERIFY_ENDPOINT,
483
- "api",
484
- request({ body: signupBody() }),
485
- res.response,
486
- next,
487
- );
488
- expect(res.statuses).toEqual([401]);
489
- expect(model.create).not.toHaveBeenCalled();
490
- });
491
-
492
- test("reports a verification endpoint that is unreachable", async () => {
493
- fetchMock.mockRejectedValue(new Error("ECONNREFUSED"));
494
- const { connection } = connectionWith(userModel({}));
495
- const res = responseStub();
496
- await signup(
497
- connection,
498
- serverConfig(),
499
- VERIFY_ENDPOINT,
500
- "api",
501
- request({ body: signupBody() }),
502
- res.response,
503
- next,
504
- );
505
- expect(res.statuses).toEqual([500]);
506
- expect(res.bodies).toEqual([{ message: "ECONNREFUSED" }]);
507
- });
508
-
509
- test("reports a verification endpoint that returns garbage", async () => {
510
- fetchMock.mockResolvedValue(new Response("<html>502</html>"));
511
- const { connection } = connectionWith(userModel({}));
512
- const res = responseStub();
513
- await signup(
514
- connection,
515
- serverConfig(),
516
- VERIFY_ENDPOINT,
517
- "api",
518
- request({ body: signupBody() }),
519
- res.response,
520
- next,
521
- );
522
- expect(res.statuses).toEqual([500]);
523
- });
524
-
525
- test("any verify type other than api uses the library", async () => {
526
- const { connection } = connectionWith(userModel({}));
527
- await signup(
528
- connection,
529
- serverConfig(),
530
- VERIFY_ENDPOINT,
531
- "anything-else",
532
- request({ body: signupBody() }),
533
- responseStub().response,
534
- next,
535
- );
536
- expect(mocks.isVerified).toHaveBeenCalledTimes(1);
537
- expect(fetchMock).not.toHaveBeenCalled();
538
- });
539
- });
540
-
541
- describe("login", () => {
542
- const salt = "0xsalt";
543
- // The stored hash for password "hunter2" with the salt above, produced by
544
- // the same hashPassword the controller uses.
545
- const storedUser = async (): Promise<{ password: string; salt: string }> => {
546
- const { connection, model } = connectionWith(userModel({}));
547
- await signup(
548
- connection,
549
- serverConfig(),
550
- VERIFY_ENDPOINT,
551
- "local",
552
- request({ body: signupBody() }),
553
- responseStub().response,
554
- next,
555
- );
556
- const created = model.create.mock.calls[0]?.[0] as Record<string, string>;
557
- return { password: String(created.password), salt: String(created.salt) };
558
- };
559
-
560
- test("issues a token for the right password", async () => {
561
- const user = await storedUser();
562
- const { connection } = connectionWith(userModel({ found: user }));
563
- const res = responseStub();
564
- await login(
565
- connection,
566
- serverConfig(),
567
- VERIFY_ENDPOINT,
568
- "local",
569
- request({ body: signupBody() }),
570
- res.response,
571
- );
572
- expect(res.statuses).toEqual([200]);
573
- const body = res.bodies[0] as { message: string; token: string };
574
- expect(body.message).toBe("user logged in");
575
- const decoded = jwt.verify(body.token, "secret") as { email: string };
576
- expect(decoded.email).toBe("user@example.com");
577
- });
578
-
579
- test("rejects the wrong password", async () => {
580
- const user = await storedUser();
581
- const { connection } = connectionWith(userModel({ found: user }));
582
- const res = responseStub();
583
- await login(
584
- connection,
585
- serverConfig(),
586
- VERIFY_ENDPOINT,
587
- "local",
588
- request({ body: signupBody({ password: "not-hunter2" }) }),
589
- res.response,
590
- );
591
- expect(res.statuses).toEqual([401]);
592
- expect(res.bodies).toEqual([{ message: "invalid credentials" }]);
593
- });
594
-
595
- test("rejects a password that hashes right against the wrong salt", async () => {
596
- const user = await storedUser();
597
- const { connection } = connectionWith(
598
- userModel({ found: { password: user.password, salt: "0xdifferent" } }),
599
- );
600
- const res = responseStub();
601
- await login(
602
- connection,
603
- serverConfig(),
604
- VERIFY_ENDPOINT,
605
- "local",
606
- request({ body: signupBody() }),
607
- res.response,
608
- );
609
- expect(res.statuses).toEqual([401]);
610
- });
611
-
612
- test("reports an unknown email as not found", async () => {
613
- const { connection } = connectionWith(userModel({ found: null }));
614
- const res = responseStub();
615
- await login(
616
- connection,
617
- serverConfig(),
618
- VERIFY_ENDPOINT,
619
- "local",
620
- request({ body: signupBody() }),
621
- res.response,
622
- );
623
- expect(res.statuses).toEqual([404]);
624
- expect(res.bodies).toEqual([{ message: "user not found" }]);
625
- // No captcha verification for an account that doesn't exist.
626
- expect(mocks.isVerified).not.toHaveBeenCalled();
627
- });
628
-
629
- test("refuses a login that failed the captcha", async () => {
630
- const user = await storedUser();
631
- mocks.isVerified.mockResolvedValue({ verified: false });
632
- const { connection } = connectionWith(userModel({ found: user }));
633
- const res = responseStub();
634
- await login(
635
- connection,
636
- serverConfig(),
637
- VERIFY_ENDPOINT,
638
- "local",
639
- request({ body: signupBody() }),
640
- res.response,
641
- );
642
- expect(res.statuses).toEqual([401]);
643
- expect(res.bodies).toEqual([
644
- { message: "user has not completed a captcha", verified: false },
645
- ]);
646
- });
647
-
648
- test("does not send the email to the verifier", async () => {
649
- // Unlike signup, login verifies the token alone — the provider has no
650
- // signup record to match an email against.
651
- const user = await storedUser();
652
- const { connection } = connectionWith(userModel({ found: user }));
653
- await login(
654
- connection,
655
- serverConfig(),
656
- VERIFY_ENDPOINT,
657
- "local",
658
- request({ body: signupBody() }),
659
- responseStub().response,
660
- );
661
- expect(mocks.isVerified).toHaveBeenLastCalledWith(
662
- "0xtoken",
663
- "NO_IP",
664
- undefined,
665
- undefined,
666
- );
667
- });
668
-
669
- test("passes the caller's IP through", async () => {
670
- const user = await storedUser();
671
- const { connection } = connectionWith(userModel({ found: user }));
672
- await login(
673
- connection,
674
- serverConfig(),
675
- VERIFY_ENDPOINT,
676
- "local",
677
- request({
678
- body: signupBody(),
679
- headers: { "x-client-ip": "203.0.113.9" },
680
- }),
681
- responseStub().response,
682
- );
683
- expect(mocks.isVerified).toHaveBeenLastCalledWith(
684
- "0xtoken",
685
- "203.0.113.9",
686
- undefined,
687
- undefined,
688
- );
689
- });
690
-
691
- test("forwards the caller's clientSessionId to the provider", async () => {
692
- const user = await storedUser();
693
- const { connection } = connectionWith(userModel({ found: user }));
694
- await login(
695
- connection,
696
- serverConfig(),
697
- VERIFY_ENDPOINT,
698
- "local",
699
- request({
700
- body: { ...signupBody(), clientSessionId: "bumblebee-abc" },
701
- headers: { "x-client-ip": "203.0.113.9" },
702
- }),
703
- responseStub().response,
704
- );
705
- // Positional: isVerified(token, ip, email, clientSessionId). Without
706
- // this the widget can be rendered with data-sessionid and the dapp
707
- // server silently drops it at verify, so no correlation happens.
708
- expect(mocks.isVerified).toHaveBeenLastCalledWith(
709
- "0xtoken",
710
- "203.0.113.9",
711
- undefined,
712
- "bumblebee-abc",
713
- );
714
- });
715
-
716
- test("refuses to run without a site private key", async () => {
717
- const user = await storedUser();
718
- const { connection } = connectionWith(userModel({ found: user }));
719
- const res = responseStub();
720
- await login(
721
- connection,
722
- serverConfig({}),
723
- VERIFY_ENDPOINT,
724
- "local",
725
- request({ body: signupBody() }),
726
- res.response,
727
- );
728
- expect(res.statuses).toEqual([500]);
729
- });
730
-
731
- test("reports a database failure as a server error", async () => {
732
- const { connection } = connectionWith(
733
- userModel({ findOneRejects: new Error("mongo unavailable") }),
734
- );
735
- const res = responseStub();
736
- await login(
737
- connection,
738
- serverConfig(),
739
- VERIFY_ENDPOINT,
740
- "local",
741
- request({ body: signupBody() }),
742
- res.response,
743
- );
744
- expect(res.statuses).toEqual([500]);
745
- expect(res.bodies).toEqual([{ message: "mongo unavailable" }]);
746
- });
747
-
748
- test("falls back to a message when the failure carries none", async () => {
749
- const { connection } = connectionWith(
750
- userModel({ findOneRejects: new Error("") }),
751
- );
752
- const res = responseStub();
753
- await login(
754
- connection,
755
- serverConfig(),
756
- VERIFY_ENDPOINT,
757
- "local",
758
- request({ body: signupBody() }),
759
- res.response,
760
- );
761
- expect(res.bodies).toEqual([{ message: "internal server error" }]);
762
- });
763
-
764
- test("rejects a body that isn't a login", async () => {
765
- const user = await storedUser();
766
- const { connection } = connectionWith(userModel({ found: user }));
767
- const res = responseStub();
768
- await login(
769
- connection,
770
- serverConfig(),
771
- VERIFY_ENDPOINT,
772
- "local",
773
- request({ body: signupBody({ siteKey: undefined }) }),
774
- res.response,
775
- );
776
- expect(res.statuses).toEqual([500]);
777
- });
778
-
779
- test("verifies through the API endpoint when asked to", async () => {
780
- const user = await storedUser();
781
- const { connection } = connectionWith(userModel({ found: user }));
782
- const res = responseStub();
783
- await login(
784
- connection,
785
- serverConfig(),
786
- VERIFY_ENDPOINT,
787
- "api",
788
- request({ body: signupBody() }),
789
- res.response,
790
- );
791
- expect(res.statuses).toEqual([200]);
792
- const body: Record<string, string> = JSON.parse(
793
- String(fetchMock.mock.calls[0]?.[1]?.body),
794
- );
795
- expect(body.email).toBeUndefined();
796
- });
797
- });
798
-
799
- describe("isAuth", () => {
800
- const bearer = (token: string): string => `Bearer ${token}`;
801
-
802
- test("lets a valid token through", () => {
803
- const res = responseStub();
804
- isAuth(
805
- request({
806
- authorization: bearer(jwt.sign({ email: "a@b.c" }, "secret")),
807
- }),
808
- res.response,
809
- );
810
- expect(res.statuses).toEqual([200]);
811
- expect(res.bodies).toEqual([{ message: "here is your resource" }]);
812
- });
813
-
814
- test("refuses a request with no Authorization header", () => {
815
- // The header check used to fall through to splitting the empty string,
816
- // which threw before any response was sent.
817
- const res = responseStub();
818
- isAuth(request({}), res.response);
819
- expect(res.statuses).toEqual([401]);
820
- expect(res.bodies).toEqual([{ message: "not authenticated" }]);
821
- });
822
-
823
- test("refuses an Authorization header with no token", () => {
824
- const res = responseStub();
825
- isAuth(request({ authorization: "Bearer" }), res.response);
826
- expect(res.statuses).toEqual([401]);
827
- });
828
-
829
- test("refuses a Bearer header whose token is empty", () => {
830
- // "Bearer " splits into two parts, so the length check passes and the
831
- // empty token reached jwt.verify, which threw and read as a 500.
832
- const res = responseStub();
833
- isAuth(request({ authorization: "Bearer " }), res.response);
834
- expect(res.statuses).toEqual([401]);
835
- expect(res.bodies).toEqual([{ message: "not authenticated" }]);
836
- });
837
-
838
- test("reports a token it cannot decode, and only once", () => {
839
- // A failed verify used to send a 500 and then a 401 on the same
840
- // response, which express rejects as headers-already-sent.
841
- const res = responseStub();
842
- isAuth(request({ authorization: bearer("not-a-jwt") }), res.response);
843
- expect(res.statuses).toEqual([500]);
844
- expect(res.bodies).toHaveLength(1);
845
- });
846
-
847
- test("rejects a token signed with a different secret", () => {
848
- const res = responseStub();
849
- isAuth(
850
- request({
851
- authorization: bearer(jwt.sign({ email: "a@b.c" }, "other-secret")),
852
- }),
853
- res.response,
854
- );
855
- expect(res.statuses).toEqual([500]);
856
- });
857
-
858
- test("rejects an expired token", () => {
859
- const res = responseStub();
860
- isAuth(
861
- request({
862
- authorization: bearer(
863
- jwt.sign({ email: "a@b.c" }, "secret", { expiresIn: -10 }),
864
- ),
865
- }),
866
- res.response,
867
- );
868
- expect(res.statuses).toEqual([500]);
869
- expect(res.bodies).toEqual([{ message: "jwt expired" }]);
870
- });
871
-
872
- test("describes a decode failure that carries no message", () => {
873
- vi.spyOn(jwt, "verify").mockImplementation((): string => {
874
- throw new Error("");
875
- });
876
- const res = responseStub();
877
- isAuth(request({ authorization: bearer("whatever") }), res.response);
878
- expect(res.statuses).toEqual([500]);
879
- expect(res.bodies).toEqual([{ message: "could not decode the token" }]);
880
- });
881
-
882
- test("treats an empty decode as unauthorized", () => {
883
- // jwt.verify resolves to a payload or throws; the guard is defensive,
884
- // and this pins what it does if a future jwt version returns nothing.
885
- vi.spyOn(jwt, "verify").mockImplementation((): string => "");
886
- const res = responseStub();
887
- isAuth(request({ authorization: bearer("whatever") }), res.response);
888
- expect(res.statuses).toEqual([401]);
889
- expect(res.bodies).toEqual([{ message: "unauthorized" }]);
890
- });
891
-
892
- test("ignores anything after the token", () => {
893
- const res = responseStub();
894
- isAuth(
895
- request({
896
- authorization: `Bearer ${jwt.sign({ email: "a@b.c" }, "secret")} extra`,
897
- }),
898
- res.response,
899
- );
900
- expect(res.statuses).toEqual([200]);
901
- });
902
- });
903
-
904
- describe("the exported surface", () => {
905
- test("keeps the token type the handlers accept", () => {
906
- // A compile-time reminder that the request token is the shared type,
907
- // not a bare string the controllers invent.
908
- const token: ProcaptchaToken = "0xtoken";
909
- expect(token.startsWith("0x")).toBe(true);
910
- });
911
-
912
- test("the pair helper only ever sees the address", () => {
913
- expect(pairWithAddress(SITE_KEY).address).toBe(SITE_KEY);
914
- });
915
- });