create-tigra 3.3.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -12
- package/bin/create-tigra.js +495 -472
- package/lib/patchers/email-verification.patcher.js +72 -10
- package/modules/email-verification/client/hooks/useVerification.ts +4 -1
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
- package/modules/email-verification/server/verification.controller.ts +3 -1
- package/modules/email-verification/server/verification.service.ts +44 -13
- package/package.json +3 -2
- package/template/.github/dependabot.yml +47 -0
- package/template/.github/workflows/audit.yml +36 -0
- package/template/.github/workflows/ci.yml +79 -0
- package/template/AGENTS.md +18 -9
- package/template/client/.dockerignore +1 -0
- package/template/client/.env.example.production +13 -2
- package/template/client/AGENTS.md +13 -5
- package/template/client/Dockerfile +186 -14
- package/template/client/next.config.ts +1 -1
- package/template/client/package-lock.json +15983 -14181
- package/template/client/package.json +56 -48
- package/template/client/scripts/check-sharp.mjs +53 -0
- package/template/client/scripts/next-dev.cjs +5 -1
- package/template/client/src/__tests__/proxy.test.ts +92 -0
- package/template/client/src/app/healthz/route.ts +16 -0
- package/template/client/src/app/layout.tsx +9 -3
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/app/providers.tsx +23 -4
- package/template/client/src/components/layout/Header.tsx +7 -3
- package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
- package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
- package/template/client/src/features/admin/types/admin.types.ts +2 -3
- package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
- package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
- package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
- package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
- package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
- package/template/client/src/features/auth/services/auth.service.ts +8 -3
- package/template/client/src/features/auth/store/authSlice.ts +7 -2
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
- package/template/client/src/lib/api/api.types.ts +14 -0
- package/template/client/src/lib/api/axios.config.ts +101 -15
- package/template/client/src/lib/api/hard-redirect.ts +8 -0
- package/template/client/src/lib/api/session-events.ts +29 -0
- package/template/client/src/lib/constants/routes.ts +12 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
- package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
- package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
- package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
- package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
- package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
- package/template/client/src/lib/utils/error.ts +81 -0
- package/template/client/src/lib/utils/form.ts +31 -0
- package/template/client/src/lib/utils/paths.ts +18 -0
- package/template/client/src/lib/utils/session-marker.ts +24 -0
- package/template/client/src/{middleware.ts → proxy.ts} +25 -11
- package/template/client/src/store/__tests__/store.test.ts +44 -0
- package/template/client/src/store/index.ts +26 -8
- package/template/client/vitest.config.mts +48 -0
- package/template/server/.env.example +280 -270
- package/template/server/.env.example.production +283 -242
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +176 -14
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +52 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +63 -0
- package/template/server/eslint.config.mjs +19 -0
- package/template/server/package-lock.json +8784 -8743
- package/template/server/package.json +79 -75
- package/template/server/prisma/migrations/0_init/migration.sql +82 -0
- package/template/server/prisma/migrations/migration_lock.toml +3 -0
- package/template/server/prisma/schema.prisma +0 -3
- package/template/server/scripts/check-heic.mjs +40 -0
- package/template/server/scripts/check-sharp.mjs +53 -0
- package/template/server/src/__tests__/routes.integration.test.ts +280 -0
- package/template/server/src/app.ts +248 -346
- package/template/server/src/config/__tests__/env.test.ts +219 -0
- package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
- package/template/server/src/config/env.ts +326 -182
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
- package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
- package/template/server/src/jobs/index.ts +12 -2
- package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
- package/template/server/src/jobs/schedule.ts +50 -0
- package/template/server/src/libs/__tests__/auth.test.ts +98 -7
- package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
- package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
- package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
- package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
- package/template/server/src/libs/__tests__/email.test.ts +68 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
- package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
- package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
- package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
- package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
- package/template/server/src/libs/__tests__/http.test.ts +74 -2
- package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
- package/template/server/src/libs/__tests__/logger.test.ts +50 -0
- package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
- package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
- package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
- package/template/server/src/libs/__tests__/redis.test.ts +38 -2
- package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
- package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
- package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
- package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
- package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
- package/template/server/src/libs/auth.ts +39 -10
- package/template/server/src/libs/client-ip.ts +158 -77
- package/template/server/src/libs/cloudflare-ranges.ts +132 -0
- package/template/server/src/libs/cookies.ts +53 -14
- package/template/server/src/libs/email-quota.ts +74 -0
- package/template/server/src/libs/email.ts +46 -9
- package/template/server/src/libs/error-handler.ts +111 -0
- package/template/server/src/libs/health-routes.ts +53 -0
- package/template/server/src/libs/http.ts +139 -47
- package/template/server/src/libs/ip-address.ts +37 -0
- package/template/server/src/libs/ip-block.ts +284 -221
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +127 -41
- package/template/server/src/libs/observability/sentry.ts +1 -1
- package/template/server/src/libs/origin-check.ts +9 -7
- package/template/server/src/libs/prisma.ts +47 -4
- package/template/server/src/libs/query-counter.ts +71 -59
- package/template/server/src/libs/rate-limiting.ts +110 -0
- package/template/server/src/libs/redis-required.ts +28 -0
- package/template/server/src/libs/redis.ts +27 -1
- package/template/server/src/libs/request-id.ts +18 -0
- package/template/server/src/libs/requestLogger.ts +112 -17
- package/template/server/src/libs/safe-http.ts +101 -0
- package/template/server/src/libs/shutdown.ts +87 -0
- package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
- package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
- package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
- package/template/server/src/libs/storage/file-storage.service.ts +94 -84
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
- package/template/server/src/libs/token-hash.ts +18 -0
- package/template/server/src/libs/url-safety.ts +127 -121
- package/template/server/src/libs/validation-errors.ts +86 -0
- package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
- package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
- package/template/server/src/modules/admin/admin.controller.ts +66 -49
- package/template/server/src/modules/admin/admin.repo.ts +49 -10
- package/template/server/src/modules/admin/admin.routes.ts +48 -2
- package/template/server/src/modules/admin/admin.schemas.ts +18 -6
- package/template/server/src/modules/admin/admin.service.ts +66 -4
- package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
- package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
- package/template/server/src/modules/auth/auth.controller.ts +133 -128
- package/template/server/src/modules/auth/auth.repo.ts +44 -44
- package/template/server/src/modules/auth/auth.schemas.ts +4 -2
- package/template/server/src/modules/auth/auth.service.ts +167 -96
- package/template/server/src/modules/auth/session.repo.ts +12 -0
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
- package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
- package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
- package/template/server/src/modules/users/users.controller.ts +9 -38
- package/template/server/src/modules/users/users.repo.ts +23 -7
- package/template/server/src/modules/users/users.routes.ts +3 -22
- package/template/server/src/modules/users/users.schemas.ts +15 -9
- package/template/server/src/modules/users/users.service.ts +105 -93
- package/template/server/src/scripts/make-admin.ts +48 -0
- package/template/server/src/server.ts +48 -26
- package/template/server/src/shared/errors/AppError.ts +27 -1
- package/template/server/src/shared/errors/errors.ts +42 -5
- package/template/server/src/shared/responses/successResponse.ts +22 -3
- package/template/server/src/shared/types/index.ts +7 -0
- package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
- package/template/server/src/test/integration-helpers.ts +343 -0
- package/template/server/src/test/integration-services.ts +74 -0
- package/template/server/src/test/integration.global-setup.ts +144 -0
- package/template/server/src/test/integration.setup.ts +35 -158
- package/template/server/src/test/setup.ts +3 -10
- package/template/server/tsconfig.build.json +1 -1
- package/template/server/tsconfig.json +1 -0
- package/template/server/vitest.config.ts +17 -4
- package/template/server/vitest.integration.config.ts +18 -13
- package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
|
@@ -1,121 +1,257 @@
|
|
|
1
|
-
import { describe, it, expect,
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
});
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
});
|
|
1
|
+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
|
2
|
+
import Fastify, { type FastifyInstance } from 'fastify';
|
|
3
|
+
import { env } from '@config/env.js';
|
|
4
|
+
import { logger } from '@libs/logger.js';
|
|
5
|
+
import {
|
|
6
|
+
normalizeIp,
|
|
7
|
+
resolveClientIp,
|
|
8
|
+
getClientIp,
|
|
9
|
+
TRUSTED_PROXY_RANGES,
|
|
10
|
+
UNVERIFIED_CLOUDFLARE_KEY,
|
|
11
|
+
UNVERIFIED_WARNING_INTERVAL_MS,
|
|
12
|
+
resetUnverifiedWarningForTests,
|
|
13
|
+
} from '../client-ip.js';
|
|
14
|
+
|
|
15
|
+
// Real Fastify with the app's own trustProxy setting, so proxy-addr walks X-Forwarded-For exactly
|
|
16
|
+
// as in production. `remoteAddress` is the TCP peer: a public address = a direct visitor,
|
|
17
|
+
// 10.0.1.5 = Coolify's Traefik on the Docker network, 173.245.48.10 = a Cloudflare edge server.
|
|
18
|
+
const TRAEFIK = '10.0.1.5';
|
|
19
|
+
const CF_EDGE = '173.245.48.10';
|
|
20
|
+
const CF_EDGE_V6 = '2400:cb00::1';
|
|
21
|
+
const VISITOR = '203.0.113.7';
|
|
22
|
+
const OTHER_VISITOR = '198.51.100.20';
|
|
23
|
+
const FORGED = '6.6.6.6';
|
|
24
|
+
|
|
25
|
+
let app: FastifyInstance;
|
|
26
|
+
|
|
27
|
+
beforeAll(async () => {
|
|
28
|
+
app = Fastify({ trustProxy: TRUSTED_PROXY_RANGES });
|
|
29
|
+
app.get('/ip', async (request) => ({ ...resolveClientIp(request), key: getClientIp(request) }));
|
|
30
|
+
await app.ready();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
afterAll(async () => {
|
|
34
|
+
await app.close();
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
async function resolve(remoteAddress: string, headers: Record<string, string | string[]> = {}): Promise<{ ip: string; source: string; key: string }> {
|
|
38
|
+
const res = await app.inject({ method: 'GET', url: '/ip', remoteAddress, headers });
|
|
39
|
+
return res.json();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
describe('resolveClientIp — a visitor that reaches the app directly (no trusted proxy)', () => {
|
|
43
|
+
it('uses the TCP peer', async () => {
|
|
44
|
+
expect(await resolve(VISITOR)).toEqual({ ip: VISITOR, source: 'socket', key: VISITOR });
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('ignores X-Forwarded-For and CF-Connecting-IP written by that visitor', async () => {
|
|
48
|
+
const r = await resolve(VISITOR, { 'x-forwarded-for': FORGED, 'cf-connecting-ip': OTHER_VISITOR });
|
|
49
|
+
expect(r).toMatchObject({ ip: VISITOR, source: 'socket' });
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
describe('resolveClientIp — behind our own proxy (Traefik), no Cloudflare', () => {
|
|
54
|
+
it('uses the address the proxy recorded', async () => {
|
|
55
|
+
expect(await resolve(TRAEFIK, { 'x-forwarded-for': VISITOR })).toMatchObject({ ip: VISITOR, source: 'proxy' });
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('ignores entries the visitor wrote to the left of it (the old spoofing hole)', async () => {
|
|
59
|
+
const r = await resolve(TRAEFIK, { 'x-forwarded-for': `${FORGED}, 10.0.0.9, ${VISITOR}` });
|
|
60
|
+
expect(r).toMatchObject({ ip: VISITOR, source: 'proxy' });
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('ignores a forged CF-Connecting-IP when the hop is not Cloudflare (sslip.io, grey cloud, server IP)', async () => {
|
|
64
|
+
const r = await resolve(TRAEFIK, { 'x-forwarded-for': VISITOR, 'cf-connecting-ip': FORGED });
|
|
65
|
+
expect(r).toMatchObject({ ip: VISITOR, source: 'proxy' });
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('skips further trusted internal hops to the right', async () => {
|
|
69
|
+
const r = await resolve(TRAEFIK, { 'x-forwarded-for': `${VISITOR}, 10.0.0.9` });
|
|
70
|
+
expect(r).toMatchObject({ ip: VISITOR, source: 'proxy' });
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('gives two visitors two different keys (no shared counter through one proxy)', async () => {
|
|
74
|
+
const a = await resolve(TRAEFIK, { 'x-forwarded-for': VISITOR });
|
|
75
|
+
const b = await resolve(TRAEFIK, { 'x-forwarded-for': OTHER_VISITOR });
|
|
76
|
+
expect(a.key).not.toBe(b.key);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('falls back to the proxy address when the proxy sent no X-Forwarded-For', async () => {
|
|
80
|
+
expect(await resolve(TRAEFIK)).toMatchObject({ ip: TRAEFIK, source: 'socket' });
|
|
81
|
+
expect(await resolve(TRAEFIK, { 'x-forwarded-for': '' })).toMatchObject({ ip: TRAEFIK });
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
describe('resolveClientIp — through Cloudflare', () => {
|
|
86
|
+
it('Cloudflare then our proxy: uses CF-Connecting-IP, never the edge address', async () => {
|
|
87
|
+
const r = await resolve(TRAEFIK, { 'x-forwarded-for': `${FORGED}, ${OTHER_VISITOR}, ${CF_EDGE}`, 'cf-connecting-ip': OTHER_VISITOR });
|
|
88
|
+
expect(r).toEqual({ ip: OTHER_VISITOR, source: 'cloudflare', key: OTHER_VISITOR });
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('two visitors behind the same Cloudflare edge get two keys (the old shared lockout)', async () => {
|
|
92
|
+
const a = await resolve(TRAEFIK, { 'x-forwarded-for': `${VISITOR}, ${CF_EDGE}`, 'cf-connecting-ip': VISITOR });
|
|
93
|
+
const b = await resolve(TRAEFIK, { 'x-forwarded-for': `${OTHER_VISITOR}, ${CF_EDGE}`, 'cf-connecting-ip': OTHER_VISITOR });
|
|
94
|
+
expect([a.key, b.key]).toEqual([VISITOR, OTHER_VISITOR]);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('Cloudflare connecting to the app directly also works', async () => {
|
|
98
|
+
expect(await resolve(CF_EDGE, { 'cf-connecting-ip': VISITOR })).toMatchObject({ ip: VISITOR, source: 'cloudflare' });
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('works for an IPv6 edge and an IPv6 visitor', async () => {
|
|
102
|
+
const r = await resolve(TRAEFIK, { 'x-forwarded-for': `2001:db8::5, ${CF_EDGE_V6}`, 'cf-connecting-ip': '2001:DB8::5' });
|
|
103
|
+
expect(r).toMatchObject({ ip: '2001:db8::5', source: 'cloudflare' });
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('a Cloudflare hop with a missing or invalid header stays on the edge address (strict, not spoofable)', async () => {
|
|
107
|
+
const variants: Record<string, string | string[]>[] = [{}, { 'cf-connecting-ip': '' }, { 'cf-connecting-ip': 'not-an-ip' }, { 'cf-connecting-ip': [VISITOR, FORGED] }];
|
|
108
|
+
for (const headers of variants) {
|
|
109
|
+
const r = await resolve(TRAEFIK, { 'x-forwarded-for': CF_EDGE, ...headers });
|
|
110
|
+
expect(r.ip).toBe(CF_EDGE);
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
describe('resolveClientIp — Cloudflare requests that are not genuine traffic of this zone', () => {
|
|
116
|
+
// A Cloudflare Worker (anyone's) fetching the app through a non-Cloudflare hostname leaves from
|
|
117
|
+
// Cloudflare's ranges and may set CF-Connecting-IP freely; Cloudflare stamps such requests with
|
|
118
|
+
// CF-Worker. They must land in one fixed bucket, whatever address they claim.
|
|
119
|
+
it('without a secret: a CF-Worker-stamped request is unverified and keyed on one fixed bucket', async () => {
|
|
120
|
+
const a = await resolve(TRAEFIK, { 'x-forwarded-for': CF_EDGE, 'cf-connecting-ip': FORGED, 'cf-worker': 'attacker.example' });
|
|
121
|
+
const b = await resolve(TRAEFIK, { 'x-forwarded-for': '104.16.0.9', 'cf-connecting-ip': OTHER_VISITOR, 'cf-worker': 'x' });
|
|
122
|
+
expect(a).toEqual({ ip: UNVERIFIED_CLOUDFLARE_KEY, source: 'cloudflare-unverified', key: UNVERIFIED_CLOUDFLARE_KEY });
|
|
123
|
+
expect(b.key).toBe(a.key);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
describe('with CLOUDFLARE_ORIGIN_SECRET set', () => {
|
|
127
|
+
const SECRET = 'a'.repeat(40);
|
|
128
|
+
beforeAll(() => {
|
|
129
|
+
env.CLOUDFLARE_ORIGIN_SECRET = SECRET;
|
|
130
|
+
});
|
|
131
|
+
afterAll(() => {
|
|
132
|
+
env.CLOUDFLARE_ORIGIN_SECRET = undefined;
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('believes CF-Connecting-IP only with the matching origin secret', async () => {
|
|
136
|
+
const ok = await resolve(TRAEFIK, { 'x-forwarded-for': CF_EDGE, 'cf-connecting-ip': VISITOR, 'x-origin-verify': SECRET });
|
|
137
|
+
expect(ok).toMatchObject({ ip: VISITOR, source: 'cloudflare' });
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('a missing, wrong, wrong-length or repeated secret is unverified (fixed bucket)', async () => {
|
|
141
|
+
const variants: Record<string, string | string[]>[] = [
|
|
142
|
+
{},
|
|
143
|
+
{ 'x-origin-verify': 'b'.repeat(40) },
|
|
144
|
+
{ 'x-origin-verify': 'short' },
|
|
145
|
+
{ 'x-origin-verify': [SECRET, SECRET] },
|
|
146
|
+
];
|
|
147
|
+
for (const extra of variants) {
|
|
148
|
+
const r = await resolve(TRAEFIK, { 'x-forwarded-for': CF_EDGE, 'cf-connecting-ip': FORGED, ...extra });
|
|
149
|
+
expect(r).toMatchObject({ ip: UNVERIFIED_CLOUDFLARE_KEY, source: 'cloudflare-unverified' });
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it('the owner\'s own zone traffic is believed even when stamped by one of the owner\'s Workers', async () => {
|
|
154
|
+
const r = await resolve(TRAEFIK, { 'x-forwarded-for': CF_EDGE, 'cf-connecting-ip': VISITOR, 'x-origin-verify': SECRET, 'cf-worker': 'owner.example' });
|
|
155
|
+
expect(r).toMatchObject({ ip: VISITOR, source: 'cloudflare' });
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it('a non-Cloudflare hop never uses CF-Connecting-IP, secret or not', async () => {
|
|
159
|
+
const r = await resolve(TRAEFIK, { 'x-forwarded-for': VISITOR, 'cf-connecting-ip': FORGED, 'x-origin-verify': SECRET });
|
|
160
|
+
expect(r).toMatchObject({ ip: VISITOR, source: 'proxy' });
|
|
161
|
+
});
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
describe('resolveClientIp — address forms and broken input', () => {
|
|
166
|
+
it('normalizes IPv4-mapped IPv6 and upper-case IPv6 so one visitor has one key', async () => {
|
|
167
|
+
expect(await resolve(`::ffff:${VISITOR}`)).toMatchObject({ ip: VISITOR, source: 'socket' });
|
|
168
|
+
expect(await resolve(TRAEFIK, { 'x-forwarded-for': '2001:DB8::1' })).toMatchObject({ ip: '2001:db8::1' });
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it('treats an IPv4-mapped proxy address as our proxy', async () => {
|
|
172
|
+
expect(await resolve(`::ffff:${TRAEFIK}`, { 'x-forwarded-for': VISITOR })).toMatchObject({ ip: VISITOR, source: 'proxy' });
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it('several X-Forwarded-For headers are read as one list, right-most first', async () => {
|
|
176
|
+
const r = await resolve(TRAEFIK, { 'x-forwarded-for': [FORGED, VISITOR] });
|
|
177
|
+
expect(r.ip).toBe(VISITOR);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it('always returns a non-empty key, whatever the headers contain', async () => {
|
|
181
|
+
for (const xff of ['garbage', ',,,', ' , 999.1.1.1', `${VISITOR}, garbage`]) {
|
|
182
|
+
const r = await resolve(TRAEFIK, { 'x-forwarded-for': xff });
|
|
183
|
+
expect(r.key.length).toBeGreaterThan(0);
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
describe('normalizeIp', () => {
|
|
189
|
+
it('accepts IPv4/IPv6 literals and rejects everything else', () => {
|
|
190
|
+
expect(normalizeIp(' 203.0.113.7 ')).toBe('203.0.113.7');
|
|
191
|
+
expect(normalizeIp('::FFFF:203.0.113.7')).toBe('203.0.113.7');
|
|
192
|
+
expect(normalizeIp('2001:DB8::1')).toBe('2001:db8::1');
|
|
193
|
+
expect(normalizeIp('::ffff:not-ip')).toBeUndefined();
|
|
194
|
+
expect(normalizeIp('')).toBeUndefined();
|
|
195
|
+
expect(normalizeIp(undefined)).toBeUndefined();
|
|
196
|
+
expect(normalizeIp('example.com')).toBeUndefined();
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it('gives every spelling of one address the same canonical form', () => {
|
|
200
|
+
expect(normalizeIp('2001:0DB8:0000::0001')).toBe('2001:db8::1');
|
|
201
|
+
expect(normalizeIp('2001:db8:0:0:0:0:0:1')).toBe('2001:db8::1');
|
|
202
|
+
expect(normalizeIp('::ffff:cb00:7107')).toBe('203.0.113.7'); // hex IPv4-mapped
|
|
203
|
+
expect(normalizeIp('::1')).toBe('::1');
|
|
204
|
+
expect(normalizeIp('FE80::1%ETH0')).toBe('fe80::1%eth0'); // zone id: lower-cased only
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
describe('TRUST_CLOUDFLARE is gone', () => {
|
|
209
|
+
it('a leftover TRUST_CLOUDFLARE value is ignored by the env schema', async () => {
|
|
210
|
+
vi.resetModules();
|
|
211
|
+
process.env.TRUST_CLOUDFLARE = 'true';
|
|
212
|
+
try {
|
|
213
|
+
const { env } = await import('@config/env.js');
|
|
214
|
+
expect('TRUST_CLOUDFLARE' in env).toBe(false);
|
|
215
|
+
} finally {
|
|
216
|
+
delete process.env.TRUST_CLOUDFLARE;
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
describe('warning when Cloudflare traffic lands in the shared bucket', () => {
|
|
222
|
+
// On a correctly set up zone this never happens, so the operator must hear about it:
|
|
223
|
+
// every such visitor shares ONE rate-limit counter.
|
|
224
|
+
const unverified = { 'x-forwarded-for': CF_EDGE, 'cf-connecting-ip': FORGED, 'cf-worker': 'someone.example' };
|
|
225
|
+
|
|
226
|
+
afterAll(() => {
|
|
227
|
+
vi.useRealTimers();
|
|
228
|
+
vi.restoreAllMocks();
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
it('logs one warning per interval, not one per request, and never the header values', async () => {
|
|
232
|
+
resetUnverifiedWarningForTests();
|
|
233
|
+
vi.useFakeTimers({ toFake: ['Date'] });
|
|
234
|
+
vi.setSystemTime(new Date('2026-10-19T10:00:00Z'));
|
|
235
|
+
const warn = vi.spyOn(logger, 'warn').mockImplementation(() => undefined as never);
|
|
236
|
+
|
|
237
|
+
for (let i = 0; i < 5; i++) await resolve(TRAEFIK, unverified);
|
|
238
|
+
expect(warn).toHaveBeenCalledTimes(1);
|
|
239
|
+
const message = String(warn.mock.calls[0]?.[0]);
|
|
240
|
+
expect(message).toContain('share one rate-limit bucket');
|
|
241
|
+
expect(message).not.toContain(FORGED);
|
|
242
|
+
expect(message).not.toContain('someone.example');
|
|
243
|
+
|
|
244
|
+
vi.setSystemTime(new Date(Date.now() + UNVERIFIED_WARNING_INTERVAL_MS + 1));
|
|
245
|
+
await resolve(TRAEFIK, unverified);
|
|
246
|
+
expect(warn).toHaveBeenCalledTimes(2);
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it('does not warn for verified Cloudflare traffic or for direct visitors', async () => {
|
|
250
|
+
resetUnverifiedWarningForTests();
|
|
251
|
+
const warn = vi.spyOn(logger, 'warn').mockImplementation(() => undefined as never);
|
|
252
|
+
warn.mockClear();
|
|
253
|
+
await resolve(TRAEFIK, { 'x-forwarded-for': CF_EDGE, 'cf-connecting-ip': VISITOR });
|
|
254
|
+
await resolve(VISITOR);
|
|
255
|
+
expect(warn).not.toHaveBeenCalled();
|
|
256
|
+
});
|
|
257
|
+
});
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
2
|
+
|
|
3
|
+
const { get } = vi.hoisted(() => ({ get: vi.fn() }));
|
|
4
|
+
vi.mock('@libs/http.js', () => ({ httpClient: { get } }));
|
|
5
|
+
vi.mock('@libs/logger.js', () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
BUNDLED_CLOUDFLARE_IPV4,
|
|
9
|
+
BUNDLED_CLOUDFLARE_IPV6,
|
|
10
|
+
CLOUDFLARE_IPV4_URL,
|
|
11
|
+
buildRangeList,
|
|
12
|
+
isCloudflareIp,
|
|
13
|
+
refreshCloudflareRanges,
|
|
14
|
+
resetCloudflareRangesForTests,
|
|
15
|
+
} from '../cloudflare-ranges.js';
|
|
16
|
+
|
|
17
|
+
/** Make the mocked HTTP client answer the two list URLs with these bodies. */
|
|
18
|
+
function serve(ipv4: string, ipv6: string): void {
|
|
19
|
+
get.mockImplementation(async (url: string) => ({ data: url === CLOUDFLARE_IPV4_URL ? ipv4 : ipv6 }));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const NEW_V4 = ['192.0.2.0/24', '198.18.0.0/15', '100.64.0.0/10', '233.252.0.0/24', '240.0.0.0/8'].join('\n');
|
|
23
|
+
const NEW_V6 = '2001:db8:cf::/48';
|
|
24
|
+
|
|
25
|
+
beforeEach(() => {
|
|
26
|
+
get.mockReset();
|
|
27
|
+
resetCloudflareRangesForTests();
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
describe('bundled ranges', () => {
|
|
31
|
+
it('build without error and recognise Cloudflare edges, IPv4 and IPv6', () => {
|
|
32
|
+
expect(buildRangeList(BUNDLED_CLOUDFLARE_IPV4, BUNDLED_CLOUDFLARE_IPV6)).not.toBeNull();
|
|
33
|
+
expect(isCloudflareIp('173.245.48.10')).toBe(true);
|
|
34
|
+
expect(isCloudflareIp('104.16.1.1')).toBe(true);
|
|
35
|
+
expect(isCloudflareIp('2606:4700::1')).toBe(true);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('do not contain ordinary, private or malformed addresses', () => {
|
|
39
|
+
for (const ip of ['8.8.8.8', '203.0.113.7', '10.0.1.5', '172.20.0.1', '::1', '2001:db8::1', 'garbage', '']) {
|
|
40
|
+
expect(isCloudflareIp(ip)).toBe(false);
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
describe('refreshCloudflareRanges', () => {
|
|
46
|
+
it('swaps in a complete downloaded list', async () => {
|
|
47
|
+
serve(NEW_V4, NEW_V6);
|
|
48
|
+
expect(await refreshCloudflareRanges()).toBe(true);
|
|
49
|
+
expect(isCloudflareIp('192.0.2.10')).toBe(true);
|
|
50
|
+
expect(isCloudflareIp('2001:db8:cf::1')).toBe(true);
|
|
51
|
+
expect(isCloudflareIp('173.245.48.10')).toBe(false);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('keeps the current list when the download fails', async () => {
|
|
55
|
+
get.mockRejectedValue(new Error('network down'));
|
|
56
|
+
expect(await refreshCloudflareRanges()).toBe(false);
|
|
57
|
+
expect(isCloudflareIp('173.245.48.10')).toBe(true);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('keeps the current list for an error page, a truncated list or a bad line', async () => {
|
|
61
|
+
for (const [v4, v6] of [
|
|
62
|
+
['<html>rate limited</html>', NEW_V6],
|
|
63
|
+
['192.0.2.0/24\n198.18.0.0/15', NEW_V6],
|
|
64
|
+
[`${NEW_V4}\n300.1.1.0/24`, NEW_V6],
|
|
65
|
+
[NEW_V4, ''],
|
|
66
|
+
[NEW_V4, '2001:db8::/200'],
|
|
67
|
+
]) {
|
|
68
|
+
serve(v4, v6);
|
|
69
|
+
expect(await refreshCloudflareRanges()).toBe(false);
|
|
70
|
+
expect(isCloudflareIp('173.245.48.10')).toBe(true);
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('tolerates Windows line endings and blank lines', async () => {
|
|
75
|
+
serve(`${NEW_V4.replace(/\n/g, '\r\n')}\r\n\r\n`, `${NEW_V6}\n`);
|
|
76
|
+
expect(await refreshCloudflareRanges()).toBe(true);
|
|
77
|
+
expect(isCloudflareIp('100.64.0.1')).toBe(true);
|
|
78
|
+
});
|
|
79
|
+
});
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { describe, it, expect, vi } from 'vitest';
|
|
2
2
|
import type { FastifyReply } from 'fastify';
|
|
3
|
-
import { setAuthCookies, clearAuthCookies } from '../cookies.js';
|
|
3
|
+
import { setAuthCookies, clearAuthCookies, resetPlainHttpWarningForTests } from '../cookies.js';
|
|
4
|
+
import { logger } from '@libs/logger.js';
|
|
4
5
|
|
|
5
6
|
// Production cross-subdomain setup: only the non-secret auth_session indicator
|
|
6
7
|
// may use COOKIE_DOMAIN; the bearer token cookies must stay host-only.
|
|
@@ -14,7 +15,9 @@ vi.mock('@config/env.js', () => ({
|
|
|
14
15
|
},
|
|
15
16
|
}));
|
|
16
17
|
|
|
17
|
-
|
|
18
|
+
vi.mock('@libs/logger.js', () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
|
|
19
|
+
|
|
20
|
+
type CookieOpts = { domain?: string; path?: string; httpOnly?: boolean; secure?: boolean; sameSite?: string };
|
|
18
21
|
|
|
19
22
|
function fakeReply(): { reply: FastifyReply; set: Map<string, CookieOpts>; cleared: Array<[string, CookieOpts]> } {
|
|
20
23
|
const set = new Map<string, CookieOpts>();
|
|
@@ -50,6 +53,28 @@ describe('setAuthCookies', () => {
|
|
|
50
53
|
});
|
|
51
54
|
});
|
|
52
55
|
|
|
56
|
+
describe('SameSite (never None, even with COOKIE_DOMAIN in production)', () => {
|
|
57
|
+
it('sets the token cookies Strict and the auth_session marker Lax', () => {
|
|
58
|
+
const { reply, set } = fakeReply();
|
|
59
|
+
setAuthCookies(reply, 'access', 'refresh');
|
|
60
|
+
|
|
61
|
+
expect(set.get('access_token')?.sameSite).toBe('strict');
|
|
62
|
+
expect(set.get('refresh_token')?.sameSite).toBe('strict');
|
|
63
|
+
expect(set.get('auth_session')?.sameSite).toBe('lax');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('clears with the same policies, and nothing anywhere is None', () => {
|
|
67
|
+
const { reply, set, cleared } = fakeReply();
|
|
68
|
+
setAuthCookies(reply, 'access', 'refresh');
|
|
69
|
+
clearAuthCookies(reply);
|
|
70
|
+
|
|
71
|
+
for (const [name, opts] of cleared) {
|
|
72
|
+
expect(opts.sameSite, name).toBe(name === 'auth_session' ? 'lax' : 'strict');
|
|
73
|
+
}
|
|
74
|
+
expect([...set.values(), ...cleared.map(([, o]) => o)].some((o) => o.sameSite === 'none')).toBe(false);
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
53
78
|
describe('clearAuthCookies', () => {
|
|
54
79
|
it('clears both the host-only tokens and any legacy domain-wide copies', () => {
|
|
55
80
|
const { reply, cleared } = fakeReply();
|
|
@@ -60,3 +85,29 @@ describe('clearAuthCookies', () => {
|
|
|
60
85
|
expect(cleared).toContainEqual(['auth_session', expect.objectContaining({ domain: '.example.test' })]);
|
|
61
86
|
});
|
|
62
87
|
});
|
|
88
|
+
|
|
89
|
+
describe('plain-http warning (production cookies are Secure)', () => {
|
|
90
|
+
function replyOver(protocol: string, hostname = 'api.example.test'): FastifyReply {
|
|
91
|
+
const { reply } = fakeReply();
|
|
92
|
+
(reply as unknown as { request: unknown }).request = { protocol, hostname };
|
|
93
|
+
return reply;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
it('warns once when the API is reached over http', () => {
|
|
97
|
+
resetPlainHttpWarningForTests();
|
|
98
|
+
vi.mocked(logger.warn).mockClear();
|
|
99
|
+
setAuthCookies(replyOver('http'), 'a', 'r');
|
|
100
|
+
setAuthCookies(replyOver('http'), 'a', 'r');
|
|
101
|
+
expect(logger.warn).toHaveBeenCalledTimes(1);
|
|
102
|
+
expect(vi.mocked(logger.warn).mock.calls[0]?.[0]).toContain('plain http');
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('stays quiet over https, on localhost, and when the request is unknown', () => {
|
|
106
|
+
resetPlainHttpWarningForTests();
|
|
107
|
+
vi.mocked(logger.warn).mockClear();
|
|
108
|
+
setAuthCookies(replyOver('https'), 'a', 'r');
|
|
109
|
+
setAuthCookies(replyOver('http', 'localhost'), 'a', 'r');
|
|
110
|
+
setAuthCookies(fakeReply().reply, 'a', 'r');
|
|
111
|
+
expect(logger.warn).not.toHaveBeenCalled();
|
|
112
|
+
});
|
|
113
|
+
});
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
2
|
+
import { getRedis } from '@libs/redis.js';
|
|
3
|
+
import { consumeEmailQuota, emailQuotaKey } from '../email-quota.js';
|
|
4
|
+
|
|
5
|
+
vi.mock('@libs/redis.js');
|
|
6
|
+
vi.mock('@libs/logger.js', () => ({
|
|
7
|
+
logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() },
|
|
8
|
+
}));
|
|
9
|
+
|
|
10
|
+
const redisMock = {
|
|
11
|
+
incr: vi.fn(),
|
|
12
|
+
pexpire: vi.fn(),
|
|
13
|
+
pttl: vi.fn(),
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
describe('consumeEmailQuota — 3 emails per address per hour', () => {
|
|
17
|
+
beforeEach(() => {
|
|
18
|
+
vi.clearAllMocks();
|
|
19
|
+
vi.mocked(getRedis).mockReturnValue(redisMock as never);
|
|
20
|
+
redisMock.pexpire.mockResolvedValue(1);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('starts the one-hour window on the first email', async () => {
|
|
24
|
+
redisMock.incr.mockResolvedValue(1);
|
|
25
|
+
await expect(consumeEmailQuota('user@example.com')).resolves.toBeUndefined();
|
|
26
|
+
expect(redisMock.pexpire).toHaveBeenCalledWith(emailQuotaKey('user@example.com'), 3_600_000);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('allows the third email to the same address', async () => {
|
|
30
|
+
redisMock.incr.mockResolvedValue(3);
|
|
31
|
+
await expect(consumeEmailQuota('user@example.com')).resolves.toBeUndefined();
|
|
32
|
+
expect(redisMock.pexpire).not.toHaveBeenCalled();
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('refuses the fourth with 429 EMAIL_RATE_LIMITED and the time left in the window', async () => {
|
|
36
|
+
redisMock.incr.mockResolvedValue(4);
|
|
37
|
+
redisMock.pttl.mockResolvedValue(30 * 60 * 1000);
|
|
38
|
+
await expect(consumeEmailQuota('user@example.com')).rejects.toMatchObject({
|
|
39
|
+
statusCode: 429,
|
|
40
|
+
code: 'EMAIL_RATE_LIMITED',
|
|
41
|
+
retryAfterSeconds: 1800,
|
|
42
|
+
message: 'Too many emails were sent to this address. Try again in 30 minutes.',
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('restarts a window whose expiry was lost instead of blocking forever', async () => {
|
|
47
|
+
redisMock.incr.mockResolvedValue(9);
|
|
48
|
+
redisMock.pttl.mockResolvedValue(-1);
|
|
49
|
+
await expect(consumeEmailQuota('user@example.com')).rejects.toMatchObject({ retryAfterSeconds: 3600 });
|
|
50
|
+
expect(redisMock.pexpire).toHaveBeenCalledWith(emailQuotaKey('user@example.com'), 3_600_000);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('keys on a hash of the normalized address, never the raw email', () => {
|
|
54
|
+
const key = emailQuotaKey('User@Example.com ');
|
|
55
|
+
expect(key).toBe(emailQuotaKey('user@example.com'));
|
|
56
|
+
expect(key).toMatch(/^email-quota:[0-9a-f]{64}$/);
|
|
57
|
+
expect(key).not.toContain('example');
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('keeps the sign-in re-send on its own counter, so anonymous requests cannot use it up', async () => {
|
|
61
|
+
redisMock.incr.mockResolvedValue(1);
|
|
62
|
+
await consumeEmailQuota('user@example.com', 'sign-in');
|
|
63
|
+
expect(redisMock.incr).toHaveBeenCalledWith(emailQuotaKey('user@example.com', 'sign-in'));
|
|
64
|
+
expect(emailQuotaKey('user@example.com', 'sign-in')).not.toBe(emailQuotaKey('user@example.com'));
|
|
65
|
+
expect(emailQuotaKey('user@example.com', 'sign-in')).toMatch(/^email-quota:sign-in:[0-9a-f]{64}$/);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('caps the sign-in counter too (whoever registered an address knows its password)', async () => {
|
|
69
|
+
redisMock.incr.mockResolvedValue(4);
|
|
70
|
+
redisMock.pttl.mockResolvedValue(60_000);
|
|
71
|
+
await expect(consumeEmailQuota('user@example.com', 'sign-in')).rejects.toMatchObject({
|
|
72
|
+
code: 'EMAIL_RATE_LIMITED',
|
|
73
|
+
retryAfterSeconds: 60,
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('lets the email through when Redis is down (fail open)', async () => {
|
|
78
|
+
redisMock.incr.mockRejectedValue(new Error('Connection is closed'));
|
|
79
|
+
await expect(consumeEmailQuota('user@example.com')).resolves.toBeUndefined();
|
|
80
|
+
});
|
|
81
|
+
});
|