create-tigra 3.2.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 +160 -44
- 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 +81 -21
- 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 +38 -19
- 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 +18 -4
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +27 -7
- 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/features/auth/types/auth.types.ts +3 -0
- package/template/client/src/instrumentation-client.ts +9 -1
- package/template/client/src/instrumentation.ts +6 -0
- 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 +71 -0
- 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 +86 -1
- 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/security.ts +37 -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 -269
- package/template/server/.env.example.production +283 -236
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +181 -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 +19 -6
- package/template/server/prisma/seed.ts +13 -5
- 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 -335
- 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 -171
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +110 -0
- 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 +81 -65
- 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 +168 -0
- 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 +113 -0
- 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 +59 -0
- 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 -0
- 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/account-status.ts +52 -0
- package/template/server/src/libs/auth.ts +51 -12
- 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 +91 -24
- 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 -220
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +131 -42
- package/template/server/src/libs/observability/sentry.ts +80 -0
- 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 +108 -18
- 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 +143 -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 +104 -83
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +78 -72
- 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 +56 -13
- 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 +73 -7
- 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 +332 -49
- 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 +60 -42
- package/template/server/src/modules/auth/auth.schemas.ts +5 -2
- package/template/server/src/modules/auth/auth.service.ts +197 -109
- package/template/server/src/modules/auth/session.repo.ts +12 -12
- 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 +25 -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 +23 -8
- 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
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Identity and sessions against a real MySQL and Redis: what must stay true
|
|
3
|
+
* about tokens and sessions (the layer 3 hardening).
|
|
4
|
+
* - Refresh and reset tokens are stored as fingerprints, never as issued.
|
|
5
|
+
* - Two refreshes with the same cookie at once: exactly one wins; the other
|
|
6
|
+
* gets 401 REFRESH_TOKEN_ROTATED and keeps its cookies.
|
|
7
|
+
* - An access token dies with its session (logout, logout-all, password
|
|
8
|
+
* reset, admin revoke), and a token without a session id is refused.
|
|
9
|
+
* - A reset link works once, even when used twice at the same moment.
|
|
10
|
+
* - Wrong passwords on change/delete answer 422, a ban stops refresh at once,
|
|
11
|
+
* 15 wrong sign-ins lock the email for this address, hostile cookies never
|
|
12
|
+
* cause a 500.
|
|
13
|
+
* Emails go to an in-process Resend stub; nothing is sent.
|
|
14
|
+
*/
|
|
15
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
16
|
+
import type { FastifyInstance } from 'fastify';
|
|
17
|
+
import {
|
|
18
|
+
PASSWORD,
|
|
19
|
+
call,
|
|
20
|
+
clearsCookies,
|
|
21
|
+
db,
|
|
22
|
+
redis,
|
|
23
|
+
registerAdmin,
|
|
24
|
+
registerUser,
|
|
25
|
+
signIn,
|
|
26
|
+
startEmailStub,
|
|
27
|
+
tokenOf,
|
|
28
|
+
uniqueEmail,
|
|
29
|
+
type CookieJar,
|
|
30
|
+
type EmailStub,
|
|
31
|
+
} from '@/test/integration-helpers.js';
|
|
32
|
+
|
|
33
|
+
let app: FastifyInstance;
|
|
34
|
+
let mail: EmailStub;
|
|
35
|
+
|
|
36
|
+
beforeAll(async () => {
|
|
37
|
+
mail = await startEmailStub();
|
|
38
|
+
const { buildTestApp } = await import('@/test/integration-helpers.js');
|
|
39
|
+
app = await buildTestApp();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
afterAll(async () => {
|
|
43
|
+
await app?.close();
|
|
44
|
+
await mail?.close();
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
/** Only the access token of a jar, as a Cookie header (so a refresh cannot rescue it). */
|
|
48
|
+
const accessOnly = (jar: CookieJar): string => `access_token=${jar.get('access_token')}`;
|
|
49
|
+
|
|
50
|
+
/** Requests a reset link for the address and returns its raw token. */
|
|
51
|
+
async function resetTokenFor(email: string): Promise<string> {
|
|
52
|
+
const r = await call(app, 'POST', '/auth/forgot-password', { payload: { email } });
|
|
53
|
+
expect(r.status).toBe(200);
|
|
54
|
+
return tokenOf(mail.to(email).filter((e) => /reset-password/.test(e.link ?? '')).at(-1)?.link ?? null);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
describe('tokens are stored as fingerprints', () => {
|
|
58
|
+
it('refresh tokens in the database are 64-hex SHA-256 fingerprints, never the cookie value', async () => {
|
|
59
|
+
const u = await registerUser(app, 'fp');
|
|
60
|
+
const rows = await (await db()).refreshToken.findMany({ where: { userId: u.id }, select: { token: true } });
|
|
61
|
+
const cookieValue = decodeURIComponent(u.jar.get('refresh_token') ?? '');
|
|
62
|
+
expect(rows.length).toBeGreaterThan(0);
|
|
63
|
+
expect(rows.every((r) => /^[0-9a-f]{64}$/.test(r.token))).toBe(true);
|
|
64
|
+
expect(cookieValue.length).toBeGreaterThan(0);
|
|
65
|
+
expect(rows.map((r) => r.token)).not.toContain(cookieValue);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('no reset key or pointer in Redis holds the raw reset token', async () => {
|
|
69
|
+
const u = await registerUser(app, 'resetkey');
|
|
70
|
+
const raw = await resetTokenFor(u.email);
|
|
71
|
+
const keys = await (await redis()).keys('pw-reset*');
|
|
72
|
+
expect(keys.length).toBeGreaterThan(0);
|
|
73
|
+
expect(keys.join('\n')).not.toContain(raw);
|
|
74
|
+
for (const key of keys) {
|
|
75
|
+
const type = await (await redis()).type(key);
|
|
76
|
+
const value = type === 'string' ? await (await redis()).get(key) : JSON.stringify(await (await redis()).hgetall(key));
|
|
77
|
+
expect(value ?? '').not.toContain(raw);
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
describe('parallel refresh', () => {
|
|
83
|
+
it('two refreshes with the same cookie: one 200, one 401 REFRESH_TOKEN_ROTATED that keeps its cookies', async () => {
|
|
84
|
+
const u = await registerUser(app, 'race');
|
|
85
|
+
const otherDevice = await signIn(app, u.email);
|
|
86
|
+
let raced: { winner: Awaited<ReturnType<typeof call>>; loser: Awaited<ReturnType<typeof call>> } | null = null;
|
|
87
|
+
// A real race: on a fast machine both can still land one after the other; try a few times.
|
|
88
|
+
for (let attempt = 0; attempt < 8 && !raced; attempt++) {
|
|
89
|
+
const device = await signIn(app, u.email);
|
|
90
|
+
const sameCookie = device.header();
|
|
91
|
+
const pair = await Promise.all([
|
|
92
|
+
call(app, 'POST', '/auth/refresh', { cookie: sameCookie }),
|
|
93
|
+
call(app, 'POST', '/auth/refresh', { cookie: sameCookie }),
|
|
94
|
+
]);
|
|
95
|
+
const winner = pair.find((r) => r.status === 200);
|
|
96
|
+
const loser = pair.find((r) => r.code === 'REFRESH_TOKEN_ROTATED');
|
|
97
|
+
if (winner && loser) raced = { winner, loser };
|
|
98
|
+
for (const r of pair) expect(r.status).not.toBe(500);
|
|
99
|
+
}
|
|
100
|
+
expect(raced, 'no attempt produced a real race').not.toBeNull();
|
|
101
|
+
expect(raced!.loser.status).toBe(401);
|
|
102
|
+
expect(clearsCookies(raced!.loser.res)).toBe(false);
|
|
103
|
+
|
|
104
|
+
// The winner's new refresh token works afterwards; another device was not touched.
|
|
105
|
+
const { CookieJar } = await import('@/test/integration-helpers.js');
|
|
106
|
+
const winnerJar = new CookieJar().absorb(raced!.winner.res);
|
|
107
|
+
expect((await call(app, 'POST', '/auth/refresh', { jar: winnerJar })).status).toBe(200);
|
|
108
|
+
expect((await call(app, 'GET', '/auth/me', { jar: otherDevice })).status).toBe(200);
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
describe('an access token ends with its session', () => {
|
|
113
|
+
it('logout: the old access token is refused at once (401 SESSION_EXPIRED, cookies cleared); another device stays in', async () => {
|
|
114
|
+
const u = await registerUser(app, 'logout');
|
|
115
|
+
const otherDevice = await signIn(app, u.email);
|
|
116
|
+
const token = accessOnly(u.jar);
|
|
117
|
+
expect((await call(app, 'GET', '/auth/me', { cookie: token })).status).toBe(200);
|
|
118
|
+
await call(app, 'POST', '/auth/logout', { jar: u.jar });
|
|
119
|
+
const after = await call(app, 'GET', '/auth/me', { cookie: token });
|
|
120
|
+
expect(after.status).toBe(401);
|
|
121
|
+
expect(after.code).toBe('SESSION_EXPIRED');
|
|
122
|
+
expect(clearsCookies(after.res)).toBe(true);
|
|
123
|
+
// The token is bound to ITS session, not to "some live session of this user".
|
|
124
|
+
expect((await call(app, 'GET', '/auth/me', { cookie: accessOnly(otherDevice) })).status).toBe(200);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("logout-all: another device's access token is refused at once", async () => {
|
|
128
|
+
const u = await registerUser(app, 'logoutall');
|
|
129
|
+
const other = await signIn(app, u.email);
|
|
130
|
+
await call(app, 'POST', '/auth/logout-all', { jar: u.jar });
|
|
131
|
+
const r = await call(app, 'GET', '/auth/me', { cookie: accessOnly(other) });
|
|
132
|
+
expect([r.status, r.code]).toEqual([401, 'SESSION_EXPIRED']);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('password reset: every earlier access token is refused at once', async () => {
|
|
136
|
+
const u = await registerUser(app, 'resetends');
|
|
137
|
+
const other = await signIn(app, u.email);
|
|
138
|
+
const token = await resetTokenFor(u.email);
|
|
139
|
+
expect((await call(app, 'POST', '/auth/reset-password', { payload: { token, newPassword: 'New-Passw0rd-456!' } })).status).toBe(200);
|
|
140
|
+
for (const jar of [u.jar, other]) {
|
|
141
|
+
const r = await call(app, 'GET', '/auth/me', { cookie: accessOnly(jar) });
|
|
142
|
+
expect([r.status, r.code]).toEqual([401, 'SESSION_EXPIRED']);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it("admin revoke: that session's access token is refused at once", async () => {
|
|
147
|
+
const admin = await registerAdmin(app, 'revoker');
|
|
148
|
+
const victim = await registerUser(app, 'revoked');
|
|
149
|
+
const sessions = await call(app, 'GET', '/auth/sessions', { jar: victim.jar });
|
|
150
|
+
const newest = [...(sessions.body?.data ?? [])].sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0];
|
|
151
|
+
const del = await call(app, 'DELETE', `/admin/sessions/${newest.id}`, { jar: admin.jar });
|
|
152
|
+
expect(del.status).toBe(200);
|
|
153
|
+
const r = await call(app, 'GET', '/auth/me', { cookie: accessOnly(victim.jar) });
|
|
154
|
+
expect([r.status, r.code]).toEqual([401, 'SESSION_EXPIRED']);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it('a validly signed token without a session id is refused (401 SESSION_EXPIRED, cookies cleared)', async () => {
|
|
158
|
+
const u = await registerUser(app, 'legacy');
|
|
159
|
+
const legacy = app.jwt.sign({ userId: u.id, role: 'USER' } as never, { expiresIn: '15m' });
|
|
160
|
+
const r = await call(app, 'GET', '/auth/me', { cookie: `access_token=${legacy}` });
|
|
161
|
+
expect([r.status, r.code]).toEqual([401, 'SESSION_EXPIRED']);
|
|
162
|
+
expect(clearsCookies(r.res)).toBe(true);
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
describe('reset links', () => {
|
|
167
|
+
it('the same link twice at once: exactly one 200, the other 400 INVALID_RESET_TOKEN', async () => {
|
|
168
|
+
const u = await registerUser(app, 'resettwice');
|
|
169
|
+
const token = await resetTokenFor(u.email);
|
|
170
|
+
const answers = await Promise.all([
|
|
171
|
+
call(app, 'POST', '/auth/reset-password', { payload: { token, newPassword: 'New-Passw0rd-456!' } }),
|
|
172
|
+
call(app, 'POST', '/auth/reset-password', { payload: { token, newPassword: 'New-Passw0rd-789!' } }),
|
|
173
|
+
]);
|
|
174
|
+
expect(answers.map((a) => `${a.status}${a.code ? ` ${a.code}` : ''}`).sort()).toEqual(['200', '400 INVALID_RESET_TOKEN']);
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
describe('passwords and sign-in answers', () => {
|
|
179
|
+
it('wrong current password on change → 422 INVALID_CURRENT_PASSWORD; on delete → 422 INVALID_PASSWORD', async () => {
|
|
180
|
+
const u = await registerUser(app, 'wrongpw');
|
|
181
|
+
const change = await call(app, 'PATCH', '/users/me/password', {
|
|
182
|
+
jar: u.jar,
|
|
183
|
+
payload: { currentPassword: 'Wrong-Passw0rd-1', newPassword: 'New-Passw0rd-456!' },
|
|
184
|
+
});
|
|
185
|
+
expect([change.status, change.code]).toEqual([422, 'INVALID_CURRENT_PASSWORD']);
|
|
186
|
+
const del = await call(app, 'DELETE', '/users/me', { jar: u.jar, payload: { password: 'Wrong-Passw0rd-1' } });
|
|
187
|
+
expect([del.status, del.code]).toEqual([422, 'INVALID_PASSWORD']);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it('the right current password changes it and keeps this device signed in', async () => {
|
|
191
|
+
const u = await registerUser(app, 'rightpw');
|
|
192
|
+
const change = await call(app, 'PATCH', '/users/me/password', {
|
|
193
|
+
jar: u.jar,
|
|
194
|
+
payload: { currentPassword: PASSWORD, newPassword: 'New-Passw0rd-456!' },
|
|
195
|
+
});
|
|
196
|
+
expect(change.status).toBe(200);
|
|
197
|
+
expect((await call(app, 'GET', '/auth/me', { jar: u.jar })).status).toBe(200);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it('login → me → refresh → me works; a wrong password is 401 INVALID_CREDENTIALS; bad input is 422 with fields', async () => {
|
|
201
|
+
const u = await registerUser(app, 'flow');
|
|
202
|
+
const jar = await signIn(app, u.email);
|
|
203
|
+
expect((await call(app, 'GET', '/auth/me', { jar })).status).toBe(200);
|
|
204
|
+
expect((await call(app, 'POST', '/auth/refresh', { jar })).status).toBe(200);
|
|
205
|
+
expect((await call(app, 'GET', '/auth/me', { jar })).status).toBe(200);
|
|
206
|
+
const wrong = await call(app, 'POST', '/auth/login', { payload: { email: u.email, password: 'Wrong-Passw0rd-1' } });
|
|
207
|
+
expect([wrong.status, wrong.code]).toEqual([401, 'INVALID_CREDENTIALS']);
|
|
208
|
+
const bad = await call(app, 'POST', '/auth/register', { payload: { email: 'not-an-email', password: 'x', firstName: '', lastName: '' } });
|
|
209
|
+
expect([bad.status, bad.code]).toEqual([422, 'VALIDATION_FAILED']);
|
|
210
|
+
expect(Array.isArray(bad.body?.error?.fields)).toBe(true);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
it("a ban stops the user's refresh and says ACCOUNT_DEACTIVATED on their access token at once", async () => {
|
|
214
|
+
const admin = await registerAdmin(app, 'banner');
|
|
215
|
+
const victim = await registerUser(app, 'banned');
|
|
216
|
+
expect((await call(app, 'GET', '/auth/me', { jar: victim.jar.copy() })).status).toBe(200);
|
|
217
|
+
const ban = await call(app, 'PATCH', `/admin/users/${victim.id}/status`, { jar: admin.jar, payload: { isActive: false } });
|
|
218
|
+
expect(ban.status).toBe(200);
|
|
219
|
+
const refresh = await call(app, 'POST', '/auth/refresh', { cookie: victim.jar.header() });
|
|
220
|
+
expect([refresh.status, refresh.code]).toEqual([401, 'INVALID_REFRESH_TOKEN']);
|
|
221
|
+
const me = await call(app, 'GET', '/auth/me', { cookie: victim.jar.header() });
|
|
222
|
+
expect([me.status, me.code]).toEqual([403, 'ACCOUNT_DEACTIVATED']);
|
|
223
|
+
expect(clearsCookies(me.res)).toBe(true);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it('15 wrong sign-ins for one email from one address lock it (429 LOGIN_LOCKED)', async () => {
|
|
227
|
+
const email = uniqueEmail('lock');
|
|
228
|
+
const codes: (string | undefined)[] = [];
|
|
229
|
+
for (let i = 0; i < 15; i++) {
|
|
230
|
+
codes.push((await call(app, 'POST', '/auth/login', { payload: { email, password: 'Wrong-Passw0rd-1' } })).code);
|
|
231
|
+
}
|
|
232
|
+
expect(codes.slice(0, 14).every((c) => c === 'INVALID_CREDENTIALS')).toBe(true);
|
|
233
|
+
expect(codes[14]).toBe('LOGIN_LOCKED');
|
|
234
|
+
});
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
describe('hostile refresh cookies', () => {
|
|
238
|
+
it.each([
|
|
239
|
+
['empty', ''],
|
|
240
|
+
['8 KB', 'x'.repeat(8192)],
|
|
241
|
+
['garbage', '%%%;;notatoken'],
|
|
242
|
+
])('a %s refresh cookie → 401, never 500', async (_label, value) => {
|
|
243
|
+
const r = await call(app, 'POST', '/auth/refresh', { cookie: `refresh_token=${encodeURIComponent(value)}` });
|
|
244
|
+
expect(r.status).toBe(401);
|
|
245
|
+
});
|
|
246
|
+
});
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tokens at rest are fingerprints only (libs/token-hash.ts): refresh tokens in
|
|
3
|
+
* MySQL, password-reset tokens in Redis. Callers keep passing the raw token;
|
|
4
|
+
* nothing that is stored equals it, so reading the database or Redis yields no
|
|
5
|
+
* usable login. (The email-verification module uses the same scheme.)
|
|
6
|
+
*/
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
|
9
|
+
import { hashToken } from '@libs/token-hash.js';
|
|
10
|
+
import { testUsers } from '@/test/setup.js';
|
|
11
|
+
|
|
12
|
+
const sha256 = (raw: string): string => createHash('sha256').update(raw).digest('hex');
|
|
13
|
+
|
|
14
|
+
const prismaMock = vi.hoisted(() => ({
|
|
15
|
+
refreshToken: { create: vi.fn(), findUnique: vi.fn(), delete: vi.fn(), deleteMany: vi.fn() },
|
|
16
|
+
session: { update: vi.fn() },
|
|
17
|
+
$transaction: vi.fn(),
|
|
18
|
+
}));
|
|
19
|
+
// rotateRefreshToken runs an interactive transaction: hand it the same mock as `tx`.
|
|
20
|
+
vi.mock('@libs/prisma.js', () => ({
|
|
21
|
+
prisma: prismaMock,
|
|
22
|
+
isPrismaNotFound: (): boolean => false,
|
|
23
|
+
isPrismaWriteConflict: (e: unknown): boolean => (e as { code?: string })?.code === 'P2034',
|
|
24
|
+
}));
|
|
25
|
+
|
|
26
|
+
const redisMock = vi.hoisted(() => ({ status: 'ready', get: vi.fn(), set: vi.fn(), del: vi.fn(), getdel: vi.fn() }));
|
|
27
|
+
vi.mock('@libs/redis.js', () => ({ getRedis: (): typeof redisMock => redisMock }));
|
|
28
|
+
|
|
29
|
+
const sentEmails = vi.hoisted(() => [] as Array<{ html: string }>);
|
|
30
|
+
vi.mock('@libs/email.js', () => ({ sendEmail: vi.fn(async (msg: { html: string }) => void sentEmails.push(msg)) }));
|
|
31
|
+
vi.mock('@libs/email-quota.js', () => ({ consumeEmailQuota: vi.fn() }));
|
|
32
|
+
vi.mock('@libs/password.js', () => ({ hashPassword: vi.fn(async () => 'new-hash'), verifyPassword: vi.fn() }));
|
|
33
|
+
vi.mock('../session.repo.js', () => ({ sessionRepository: { deleteAllUserSessions: vi.fn() } }));
|
|
34
|
+
|
|
35
|
+
// Imported after the mocks.
|
|
36
|
+
const authRepo = await import('../auth.repo.js');
|
|
37
|
+
const authService = await import('../auth.service.js');
|
|
38
|
+
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
vi.clearAllMocks();
|
|
41
|
+
sentEmails.length = 0;
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
describe('hashToken', () => {
|
|
45
|
+
it('is the SHA-256 hex of the token: 64 characters, deterministic, never the input', () => {
|
|
46
|
+
expect(hashToken('abc')).toBe(sha256('abc'));
|
|
47
|
+
expect(hashToken('abc')).toMatch(/^[0-9a-f]{64}$/);
|
|
48
|
+
expect(hashToken('abc')).not.toBe('abc');
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
describe('refresh tokens in MySQL', () => {
|
|
53
|
+
const raw = '3f2a9c1e-5b7d-4e8a-9c21-7d4e5f6a8b90';
|
|
54
|
+
|
|
55
|
+
it('stores only the fingerprint, and looks up and deletes by it', async () => {
|
|
56
|
+
await authRepo.createRefreshToken({ token: raw, userId: 'u1', sessionId: 's1', expiresAt: new Date() });
|
|
57
|
+
expect(prismaMock.refreshToken.create.mock.calls[0]?.[0].data.token).toBe(sha256(raw));
|
|
58
|
+
|
|
59
|
+
await authRepo.findRefreshToken(raw);
|
|
60
|
+
expect(prismaMock.refreshToken.findUnique).toHaveBeenCalledWith({ where: { token: sha256(raw) } });
|
|
61
|
+
|
|
62
|
+
await authRepo.deleteRefreshToken(raw);
|
|
63
|
+
expect(prismaMock.refreshToken.delete).toHaveBeenCalledWith({ where: { token: sha256(raw) } });
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const newData = { token: 'new-raw', userId: 'u1', sessionId: 's1', expiresAt: new Date() };
|
|
67
|
+
const runTx = (): void => {
|
|
68
|
+
prismaMock.$transaction.mockImplementation(async (fn: (tx: typeof prismaMock) => unknown) => fn(prismaMock));
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
it('rotation removes the old fingerprint with a counted delete and stores the new one', async () => {
|
|
72
|
+
runTx();
|
|
73
|
+
prismaMock.refreshToken.deleteMany.mockResolvedValue({ count: 1 });
|
|
74
|
+
await expect(authRepo.rotateRefreshToken(raw, newData)).resolves.toBe(true);
|
|
75
|
+
expect(prismaMock.refreshToken.deleteMany).toHaveBeenCalledWith({ where: { token: sha256(raw) } });
|
|
76
|
+
expect(prismaMock.refreshToken.create).toHaveBeenCalledWith({
|
|
77
|
+
data: expect.objectContaining({ token: sha256('new-raw') }),
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('exactly one parallel rotation wins: the one that removed nothing creates nothing', async () => {
|
|
82
|
+
runTx();
|
|
83
|
+
prismaMock.refreshToken.deleteMany.mockResolvedValue({ count: 0 }); // a parallel refresh removed it
|
|
84
|
+
await expect(authRepo.rotateRefreshToken(raw, newData)).resolves.toBe(false);
|
|
85
|
+
expect(prismaMock.refreshToken.create).not.toHaveBeenCalled();
|
|
86
|
+
expect(prismaMock.session.update).not.toHaveBeenCalled();
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('a write conflict with the parallel transaction counts as a lost race, not a 500', async () => {
|
|
90
|
+
prismaMock.$transaction.mockRejectedValue(Object.assign(new Error('write conflict'), { code: 'P2034' }));
|
|
91
|
+
await expect(authRepo.rotateRefreshToken(raw, newData)).resolves.toBe(false);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
describe('password-reset tokens in Redis', () => {
|
|
96
|
+
it('forgotPassword stores only the fingerprint; the raw token exists only in the email', async () => {
|
|
97
|
+
vi.spyOn(authRepo, 'findUserByEmail').mockResolvedValue(testUsers.validUser);
|
|
98
|
+
redisMock.get.mockResolvedValue(null);
|
|
99
|
+
|
|
100
|
+
await authService.forgotPassword(testUsers.validUser.email);
|
|
101
|
+
|
|
102
|
+
const raw = /token=([0-9a-f]{64})/.exec(sentEmails[0]?.html ?? '')?.[1];
|
|
103
|
+
expect(raw).toBeDefined();
|
|
104
|
+
const stored = JSON.stringify(redisMock.set.mock.calls);
|
|
105
|
+
expect(stored).not.toContain(raw as string);
|
|
106
|
+
expect(redisMock.set).toHaveBeenCalledWith(`pw-reset:${sha256(raw as string)}`, testUsers.validUser.id, 'EX', 3600);
|
|
107
|
+
expect(redisMock.set).toHaveBeenCalledWith(`pw-reset-user:${testUsers.validUser.id}`, sha256(raw as string), 'EX', 3600);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('resetPassword looks the emailed (raw) token up by its fingerprint', async () => {
|
|
111
|
+
redisMock.getdel.mockResolvedValue(testUsers.validUser.id);
|
|
112
|
+
vi.spyOn(authRepo, 'findUserById').mockResolvedValue(testUsers.validUser);
|
|
113
|
+
vi.spyOn(authRepo, 'updateUserPassword').mockResolvedValue(undefined);
|
|
114
|
+
vi.spyOn(authRepo, 'deleteRefreshTokensByUserId').mockResolvedValue(undefined);
|
|
115
|
+
|
|
116
|
+
await authService.resetPassword('raw-reset-token', 'New-Passw0rd-123!');
|
|
117
|
+
expect(redisMock.getdel).toHaveBeenCalledWith(`pw-reset:${sha256('raw-reset-token')}`);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
@@ -1,128 +1,133 @@
|
|
|
1
|
-
import type { FastifyRequest, FastifyReply } from 'fastify';
|
|
2
|
-
import { successResponse } from '@shared/responses/successResponse.js';
|
|
3
|
-
import { UnauthorizedError, ForbiddenError } from '@shared/errors/errors.js';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
reply
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
reply.
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
reply.
|
|
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
|
-
reply
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
request
|
|
96
|
-
reply
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
request
|
|
104
|
-
reply
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
reply
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
}
|
|
1
|
+
import type { FastifyRequest, FastifyReply } from 'fastify';
|
|
2
|
+
import { successResponse } from '@shared/responses/successResponse.js';
|
|
3
|
+
import { UnauthorizedError, ForbiddenError } from '@shared/errors/errors.js';
|
|
4
|
+
import { isAppError } from '@shared/errors/AppError.js';
|
|
5
|
+
import { setAuthCookies, clearAuthCookies } from '@libs/cookies.js';
|
|
6
|
+
import { getClientIp } from '@libs/client-ip.js';
|
|
7
|
+
import type {
|
|
8
|
+
RegisterInput,
|
|
9
|
+
LoginInput,
|
|
10
|
+
ForgotPasswordInput,
|
|
11
|
+
ResetPasswordInput,
|
|
12
|
+
} from './auth.schemas.js';
|
|
13
|
+
import * as authService from './auth.service.js';
|
|
14
|
+
|
|
15
|
+
export async function register(
|
|
16
|
+
request: FastifyRequest<{ Body: RegisterInput }>,
|
|
17
|
+
reply: FastifyReply,
|
|
18
|
+
): Promise<void> {
|
|
19
|
+
const deviceInfo = request.headers['user-agent'];
|
|
20
|
+
const ipAddress = getClientIp(request);
|
|
21
|
+
|
|
22
|
+
const result = await authService.register(request.body, deviceInfo, ipAddress);
|
|
23
|
+
|
|
24
|
+
if (result.requiresVerification) {
|
|
25
|
+
reply.status(201).send(
|
|
26
|
+
successResponse('Registration successful. Please verify your email address to continue.', { user: result.user }),
|
|
27
|
+
);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
setAuthCookies(reply, result.accessToken!, result.refreshToken!);
|
|
32
|
+
reply.status(201).send(successResponse('User registered successfully', { user: result.user }));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function login(
|
|
36
|
+
request: FastifyRequest<{ Body: LoginInput }>,
|
|
37
|
+
reply: FastifyReply,
|
|
38
|
+
): Promise<void> {
|
|
39
|
+
const deviceInfo = request.headers['user-agent'];
|
|
40
|
+
const ipAddress = getClientIp(request);
|
|
41
|
+
|
|
42
|
+
const result = await authService.login(request.body, deviceInfo, ipAddress);
|
|
43
|
+
|
|
44
|
+
setAuthCookies(reply, result.accessToken, result.refreshToken);
|
|
45
|
+
reply.send(successResponse('Logged in successfully', { user: result.user }));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function refresh(
|
|
49
|
+
request: FastifyRequest,
|
|
50
|
+
reply: FastifyReply,
|
|
51
|
+
): Promise<void> {
|
|
52
|
+
const refreshToken = request.cookies.refresh_token;
|
|
53
|
+
if (!refreshToken) {
|
|
54
|
+
clearAuthCookies(reply);
|
|
55
|
+
throw new UnauthorizedError('Refresh token not provided', 'MISSING_REFRESH_TOKEN');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
const tokens = await authService.refresh(refreshToken);
|
|
60
|
+
setAuthCookies(reply, tokens.accessToken, tokens.refreshToken);
|
|
61
|
+
reply.send(successResponse('Token refreshed successfully', null));
|
|
62
|
+
} catch (error) {
|
|
63
|
+
// Session is definitively dead (refresh token revoked, user gone, inactive).
|
|
64
|
+
// Clear all auth cookies so the browser stops replaying them — otherwise the
|
|
65
|
+
// client keeps retrying refresh and middleware keeps redirecting, producing
|
|
66
|
+
// an infinite loop that trips the rate limiter.
|
|
67
|
+
// Except a lost race with a parallel refresh (REFRESH_TOKEN_ROTATED): that
|
|
68
|
+
// browser already holds the winner's fresh cookies, and clearing them here
|
|
69
|
+
// would sign it out.
|
|
70
|
+
const lostRace = isAppError(error) && error.code === authService.REFRESH_TOKEN_ROTATED;
|
|
71
|
+
if (!lostRace && (error instanceof UnauthorizedError || error instanceof ForbiddenError)) {
|
|
72
|
+
clearAuthCookies(reply);
|
|
73
|
+
}
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function logout(
|
|
79
|
+
request: FastifyRequest,
|
|
80
|
+
reply: FastifyReply,
|
|
81
|
+
): Promise<void> {
|
|
82
|
+
const refreshToken = request.cookies.refresh_token;
|
|
83
|
+
if (refreshToken) {
|
|
84
|
+
await authService.logout(refreshToken);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
clearAuthCookies(reply);
|
|
88
|
+
reply.send(successResponse('Logged out successfully', null));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function me(
|
|
92
|
+
request: FastifyRequest,
|
|
93
|
+
reply: FastifyReply,
|
|
94
|
+
): Promise<void> {
|
|
95
|
+
const user = await authService.getCurrentUser(request.user.userId);
|
|
96
|
+
reply.send(successResponse('Current user retrieved', user));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export async function getSessions(
|
|
100
|
+
request: FastifyRequest,
|
|
101
|
+
reply: FastifyReply,
|
|
102
|
+
): Promise<void> {
|
|
103
|
+
const sessions = await authService.getUserSessions(request.user.userId);
|
|
104
|
+
reply.send(successResponse('User sessions retrieved', sessions));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function logoutAllSessions(
|
|
108
|
+
request: FastifyRequest,
|
|
109
|
+
reply: FastifyReply,
|
|
110
|
+
): Promise<void> {
|
|
111
|
+
const count = await authService.logoutAllSessions(request.user.userId);
|
|
112
|
+
clearAuthCookies(reply);
|
|
113
|
+
reply.send(
|
|
114
|
+
successResponse(`Successfully logged out from ${count} session(s)`, { count }),
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function forgotPassword(
|
|
119
|
+
request: FastifyRequest<{ Body: ForgotPasswordInput }>,
|
|
120
|
+
reply: FastifyReply,
|
|
121
|
+
): Promise<void> {
|
|
122
|
+
await authService.forgotPassword(request.body.email);
|
|
123
|
+
// Always return success to prevent email enumeration
|
|
124
|
+
reply.send(successResponse('If an account exists with that email, a reset link has been sent', null));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export async function resetPassword(
|
|
128
|
+
request: FastifyRequest<{ Body: ResetPasswordInput }>,
|
|
129
|
+
reply: FastifyReply,
|
|
130
|
+
): Promise<void> {
|
|
131
|
+
await authService.resetPassword(request.body.token, request.body.newPassword);
|
|
132
|
+
reply.send(successResponse('Password reset successfully', null));
|
|
133
|
+
}
|