create-tigra 3.3.0 → 4.0.1
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/CHANGELOG.md +151 -0
- package/README.md +264 -56
- package/bin/create-tigra.js +497 -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 +5 -3
- 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/README.md +79 -0
- 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/README.md +92 -21
- 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/README.md +108 -0
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +66 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +81 -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,10 +1,27 @@
|
|
|
1
1
|
import axios from 'axios';
|
|
2
|
+
import { toast } from 'sonner';
|
|
2
3
|
|
|
3
4
|
import type { InternalAxiosRequestConfig } from 'axios';
|
|
4
5
|
|
|
6
|
+
import { hardRedirect } from '@/lib/api/hard-redirect';
|
|
7
|
+
import { emitSessionEnded } from '@/lib/api/session-events';
|
|
5
8
|
import { API_ENDPOINTS } from '@/lib/constants/api-endpoints';
|
|
6
9
|
import { ROUTES } from '@/lib/constants/routes';
|
|
7
10
|
import { env } from '@/lib/env';
|
|
11
|
+
import { ERROR_CODES, getLimitInfo, isErrorCode, isLimitError } from '@/lib/utils/error';
|
|
12
|
+
|
|
13
|
+
declare module 'axios' {
|
|
14
|
+
interface AxiosRequestConfig {
|
|
15
|
+
/**
|
|
16
|
+
* Skip the global "too many requests" toast for this request because the
|
|
17
|
+
* caller shows the message itself (the auth forms show it inline).
|
|
18
|
+
*/
|
|
19
|
+
skipLimitToast?: boolean;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// One fixed toast id: a burst of limited requests updates one toast instead of stacking many.
|
|
24
|
+
const LIMIT_TOAST_ID = 'rate-limit';
|
|
8
25
|
|
|
9
26
|
const apiClient = axios.create({
|
|
10
27
|
baseURL: env.NEXT_PUBLIC_API_BASE_URL,
|
|
@@ -43,11 +60,71 @@ const resetRefreshState = (): void => {
|
|
|
43
60
|
refreshTimestamp = 0;
|
|
44
61
|
};
|
|
45
62
|
|
|
63
|
+
// Calls that do not carry a session, so their 401 or 403 says nothing about one:
|
|
64
|
+
// a 401 there is wrong credentials or a bad token, and sign-in answers a banned
|
|
65
|
+
// account with 403 ACCOUNT_DEACTIVATED (the forms show that). Logout is here so
|
|
66
|
+
// ending a session never re-enters the session rules below.
|
|
67
|
+
const SESSIONLESS_ENDPOINTS: string[] = [
|
|
68
|
+
API_ENDPOINTS.AUTH.LOGIN,
|
|
69
|
+
API_ENDPOINTS.AUTH.REGISTER,
|
|
70
|
+
API_ENDPOINTS.AUTH.REFRESH,
|
|
71
|
+
API_ENDPOINTS.AUTH.RESET_PASSWORD,
|
|
72
|
+
API_ENDPOINTS.AUTH.LOGOUT,
|
|
73
|
+
];
|
|
74
|
+
|
|
75
|
+
// One logout for a burst of calls that all found the account banned.
|
|
76
|
+
let endingDeactivatedSession: Promise<void> | null = null;
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The account was banned while signed in: every authenticated call now answers
|
|
80
|
+
* 403 ACCOUNT_DEACTIVATED, and so would a refresh. End the session the way a
|
|
81
|
+
* logout does (the server clears the cookies, auth_session with its cookie
|
|
82
|
+
* domain included), then tell the app, which clears the user and says why.
|
|
83
|
+
* Best effort: the user is signed out locally even if the logout call fails.
|
|
84
|
+
*/
|
|
85
|
+
const endDeactivatedSession = (): Promise<void> => {
|
|
86
|
+
endingDeactivatedSession ??= apiClient
|
|
87
|
+
.post(API_ENDPOINTS.AUTH.LOGOUT)
|
|
88
|
+
.then(
|
|
89
|
+
() => undefined,
|
|
90
|
+
() => undefined
|
|
91
|
+
)
|
|
92
|
+
.then(() => {
|
|
93
|
+
emitSessionEnded('deactivated');
|
|
94
|
+
})
|
|
95
|
+
.finally(() => {
|
|
96
|
+
endingDeactivatedSession = null;
|
|
97
|
+
});
|
|
98
|
+
return endingDeactivatedSession;
|
|
99
|
+
};
|
|
100
|
+
|
|
46
101
|
apiClient.interceptors.response.use(
|
|
47
102
|
(response) => response,
|
|
48
103
|
async (error) => {
|
|
49
104
|
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
|
|
50
105
|
|
|
106
|
+
// "Slow down" answers (429 rate limit / login lock / email cap, 403 IP_BLOCKED):
|
|
107
|
+
// tell the person once, with the wait time, and never treat them as an auth
|
|
108
|
+
// failure. They are rejected as-is; React Query does not retry them (providers.tsx).
|
|
109
|
+
const limit = getLimitInfo(error);
|
|
110
|
+
if (limit) {
|
|
111
|
+
if (!originalRequest?.skipLimitToast && typeof window !== 'undefined') {
|
|
112
|
+
toast.error(limit.message, { id: LIMIT_TOAST_ID });
|
|
113
|
+
}
|
|
114
|
+
return Promise.reject(error);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const isSessionless = SESSIONLESS_ENDPOINTS.includes(originalRequest?.url ?? '');
|
|
118
|
+
|
|
119
|
+
if (
|
|
120
|
+
error.response?.status === 403 &&
|
|
121
|
+
isErrorCode(error, ERROR_CODES.ACCOUNT_DEACTIVATED) &&
|
|
122
|
+
!isSessionless
|
|
123
|
+
) {
|
|
124
|
+
await endDeactivatedSession();
|
|
125
|
+
return Promise.reject(error);
|
|
126
|
+
}
|
|
127
|
+
|
|
51
128
|
if (error.response?.status !== 401 || originalRequest._retry) {
|
|
52
129
|
return Promise.reject(error);
|
|
53
130
|
}
|
|
@@ -60,13 +137,7 @@ apiClient.interceptors.response.use(
|
|
|
60
137
|
|
|
61
138
|
// Don't retry auth endpoints that don't use tokens —
|
|
62
139
|
// a 401 here means wrong credentials, not an expired token.
|
|
63
|
-
|
|
64
|
-
API_ENDPOINTS.AUTH.LOGIN,
|
|
65
|
-
API_ENDPOINTS.AUTH.REGISTER,
|
|
66
|
-
API_ENDPOINTS.AUTH.REFRESH,
|
|
67
|
-
API_ENDPOINTS.AUTH.RESET_PASSWORD,
|
|
68
|
-
];
|
|
69
|
-
if (noRetryEndpoints.includes(originalRequest.url ?? '')) {
|
|
140
|
+
if (isSessionless) {
|
|
70
141
|
return Promise.reject(error);
|
|
71
142
|
}
|
|
72
143
|
|
|
@@ -97,15 +168,29 @@ apiClient.interceptors.response.use(
|
|
|
97
168
|
// Retry original request — new cookie is set automatically
|
|
98
169
|
return apiClient(originalRequest);
|
|
99
170
|
} catch (refreshError) {
|
|
171
|
+
// Lost a race with another tab: both refreshed at once with the same
|
|
172
|
+
// token, the other one won, and the server kept the cookies, so this
|
|
173
|
+
// browser already holds the winner's fresh ones (401
|
|
174
|
+
// REFRESH_TOKEN_ROTATED, server auth.controller.ts). Not a dead session:
|
|
175
|
+
// release the queue and replay the request once with the new cookies.
|
|
176
|
+
// `_retry` is already set, so a second 401 is rejected, never looped.
|
|
177
|
+
if (isErrorCode(refreshError, ERROR_CODES.REFRESH_TOKEN_ROTATED)) {
|
|
178
|
+
processQueue(null);
|
|
179
|
+
return apiClient(originalRequest);
|
|
180
|
+
}
|
|
181
|
+
|
|
100
182
|
processQueue(refreshError);
|
|
101
183
|
|
|
102
184
|
// Only logout on definitive auth failures (server responded with 4xx).
|
|
103
|
-
// Network errors (server unreachable, timeout) should NOT destroy the session
|
|
185
|
+
// Network errors (server unreachable, timeout) should NOT destroy the session,
|
|
186
|
+
// and neither should a rate-limited or blocked refresh: the session is still
|
|
187
|
+
// valid, the caller just has to wait (the toast says how long).
|
|
104
188
|
const isAuthFailure =
|
|
105
189
|
axios.isAxiosError(refreshError) &&
|
|
106
190
|
refreshError.response != null &&
|
|
107
191
|
refreshError.response.status >= 400 &&
|
|
108
|
-
refreshError.response.status < 500
|
|
192
|
+
refreshError.response.status < 500 &&
|
|
193
|
+
!isLimitError(refreshError);
|
|
109
194
|
|
|
110
195
|
if (isAuthFailure) {
|
|
111
196
|
// The bootstrap probe (AuthInitializer's getMe) runs on EVERY page,
|
|
@@ -127,15 +212,16 @@ apiClient.interceptors.response.use(
|
|
|
127
212
|
isSessionDead = true;
|
|
128
213
|
}
|
|
129
214
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
store.dispatch(logout());
|
|
215
|
+
// AuthInitializer clears the signed-in user on this event.
|
|
216
|
+
emitSessionEnded(isBootstrapProbe ? 'signed-out' : 'expired');
|
|
133
217
|
|
|
134
218
|
if (!isBootstrapProbe && typeof window !== 'undefined') {
|
|
135
|
-
// Clear session
|
|
136
|
-
//
|
|
219
|
+
// Clear the session marker so the proxy won't let the user through to
|
|
220
|
+
// protected pages (prevents redirect loops). The server already
|
|
221
|
+
// cleared it, with its cookie domain, when it refused the refresh;
|
|
222
|
+
// this covers a host-only marker too.
|
|
137
223
|
document.cookie = 'auth_session=; Max-Age=0; path=/; SameSite=Strict';
|
|
138
|
-
|
|
224
|
+
hardRedirect(ROUTES.LOGIN);
|
|
139
225
|
}
|
|
140
226
|
}
|
|
141
227
|
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A full page load to `path`, used when the session is dead: it drops every
|
|
3
|
+
* in-memory state (React Query cache, the API client's refresh state) at once.
|
|
4
|
+
* Its own module so tests can replace it (jsdom cannot navigate).
|
|
5
|
+
*/
|
|
6
|
+
export function hardRedirect(path: string): void {
|
|
7
|
+
window.location.href = path;
|
|
8
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the API client tells the app that the session ended. The client never
|
|
3
|
+
* imports the Redux store (each visitor gets their own store, see
|
|
4
|
+
* store/index.ts); AuthInitializer listens here and clears the signed-in user.
|
|
5
|
+
*
|
|
6
|
+
* Reasons:
|
|
7
|
+
* - 'expired': a real call found the session dead (the refresh was refused).
|
|
8
|
+
* The API client also sends the browser to the sign-in page.
|
|
9
|
+
* - 'signed-out': the start-up "who am I" check found no live session.
|
|
10
|
+
* - 'deactivated': the account was banned while signed in (403
|
|
11
|
+
* ACCOUNT_DEACTIVATED); the cookies were cleared through the logout route.
|
|
12
|
+
*/
|
|
13
|
+
export type SessionEndReason = 'expired' | 'signed-out' | 'deactivated';
|
|
14
|
+
|
|
15
|
+
type Listener = (reason: SessionEndReason) => void;
|
|
16
|
+
|
|
17
|
+
const listeners = new Set<Listener>();
|
|
18
|
+
|
|
19
|
+
/** Subscribe; returns the unsubscribe function (fits a useEffect cleanup). */
|
|
20
|
+
export function onSessionEnded(listener: Listener): () => void {
|
|
21
|
+
listeners.add(listener);
|
|
22
|
+
return () => {
|
|
23
|
+
listeners.delete(listener);
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function emitSessionEnded(reason: SessionEndReason): void {
|
|
28
|
+
for (const listener of [...listeners]) listener(reason);
|
|
29
|
+
}
|
|
@@ -13,3 +13,15 @@ export const ROUTES = {
|
|
|
13
13
|
SESSIONS: '/admin/sessions',
|
|
14
14
|
},
|
|
15
15
|
} as const;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Pages only a signed-in visitor may open, each with everything under it
|
|
19
|
+
* (/admin also covers /admin/users, never /administrator; lib/utils/paths.ts).
|
|
20
|
+
* The proxy sends a visitor with no session marker to sign-in, and
|
|
21
|
+
* AuthInitializer does the same when the session turns out to be dead. The
|
|
22
|
+
* template ships no pages: add your own protected areas here.
|
|
23
|
+
*/
|
|
24
|
+
export const PROTECTED_PATHS: readonly string[] = [ROUTES.DASHBOARD, ROUTES.PROFILE, ROUTES.ADMIN.DASHBOARD];
|
|
25
|
+
|
|
26
|
+
/** The sign-in pages, where the start-up "who am I" check never runs (no session to read there yet). */
|
|
27
|
+
export const AUTH_PATHS: readonly string[] = [ROUTES.LOGIN, ROUTES.REGISTER, ROUTES.RESET_PASSWORD, ROUTES.VERIFY_ACCOUNT];
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
*/
|
|
16
16
|
import type { Event } from '@sentry/nextjs';
|
|
17
17
|
|
|
18
|
-
const SECRET_HEADERS = new Set(['cookie', 'set-cookie', 'authorization', 'proxy-authorization', 'x-api-key']);
|
|
18
|
+
const SECRET_HEADERS = new Set(['cookie', 'set-cookie', 'authorization', 'proxy-authorization', 'x-api-key', 'x-origin-verify']);
|
|
19
19
|
const URL_HEADERS = new Set(['referer', 'referrer']);
|
|
20
20
|
|
|
21
21
|
/** Drop the query string and fragment: tokens travel there. */
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { AxiosError, AxiosHeaders } from 'axios';
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
formatWait,
|
|
6
|
+
getErrorCode,
|
|
7
|
+
getErrorMessage,
|
|
8
|
+
getFieldErrors,
|
|
9
|
+
getLimitInfo,
|
|
10
|
+
isLimitError,
|
|
11
|
+
} from '../error';
|
|
12
|
+
|
|
13
|
+
/** An axios error carrying the server's answer, as the API client sees it. */
|
|
14
|
+
function apiError(status: number, error?: Record<string, unknown>): AxiosError {
|
|
15
|
+
const config = { headers: new AxiosHeaders() };
|
|
16
|
+
return new AxiosError('Request failed', 'ERR_BAD_REQUEST', config, undefined, {
|
|
17
|
+
status,
|
|
18
|
+
statusText: '',
|
|
19
|
+
headers: {},
|
|
20
|
+
config,
|
|
21
|
+
data: error ? { success: false, error } : undefined,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe('getLimitInfo ("slow down" answers)', () => {
|
|
26
|
+
it('a bare 429 is a rate limit with a generic wait', () => {
|
|
27
|
+
expect(getLimitInfo(apiError(429))).toEqual({
|
|
28
|
+
code: 'RATE_LIMIT_EXCEEDED',
|
|
29
|
+
retryAfterSeconds: undefined,
|
|
30
|
+
message: 'Too many requests. Please wait a moment and try again.',
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('uses the server wait, rounded up to whole minutes', () => {
|
|
35
|
+
const info = getLimitInfo(apiError(429, { code: 'RATE_LIMIT_EXCEEDED', message: 'x', retryAfterSeconds: 90 }));
|
|
36
|
+
expect(info?.message).toBe('Too many requests. Try again in 2 minutes.');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('a login lock and the email cap have their own wording', () => {
|
|
40
|
+
expect(getLimitInfo(apiError(429, { code: 'LOGIN_LOCKED', message: 'x', retryAfterSeconds: 900 }))?.message).toBe(
|
|
41
|
+
'Too many failed sign-in attempts. Try again in 15 minutes.',
|
|
42
|
+
);
|
|
43
|
+
expect(getLimitInfo(apiError(429, { code: 'EMAIL_RATE_LIMITED', message: 'x', retryAfterSeconds: 30 }))?.message).toBe(
|
|
44
|
+
'Too many emails were sent to this address. Try again in 30 seconds.',
|
|
45
|
+
);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('an IP block says how long when it is automatic, and that it is blocked otherwise', () => {
|
|
49
|
+
expect(getLimitInfo(apiError(403, { code: 'IP_BLOCKED', message: 'x', retryAfterSeconds: 120 }))?.message).toBe(
|
|
50
|
+
'Too many requests from your network. Try again in 2 minutes.',
|
|
51
|
+
);
|
|
52
|
+
expect(getLimitInfo(apiError(403, { code: 'IP_BLOCKED', message: 'x' }))?.message).toBe(
|
|
53
|
+
'Access from your network is blocked.',
|
|
54
|
+
);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('anything else is not a limit', () => {
|
|
58
|
+
expect(getLimitInfo(apiError(401, { code: 'UNAUTHORIZED', message: 'x' }))).toBeNull();
|
|
59
|
+
expect(getLimitInfo(apiError(403, { code: 'ACCOUNT_DEACTIVATED', message: 'x' }))).toBeNull();
|
|
60
|
+
expect(getLimitInfo(new Error('boom'))).toBeNull();
|
|
61
|
+
expect(isLimitError(apiError(500))).toBe(false);
|
|
62
|
+
expect(isLimitError(apiError(429))).toBe(true);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
describe('formatWait', () => {
|
|
67
|
+
it.each([
|
|
68
|
+
[0, '1 second'],
|
|
69
|
+
[1, '1 second'],
|
|
70
|
+
[45, '45 seconds'],
|
|
71
|
+
[59.2, '1 minute'],
|
|
72
|
+
[60, '1 minute'],
|
|
73
|
+
[61, '2 minutes'],
|
|
74
|
+
])('%s s -> %s', (seconds, text) => {
|
|
75
|
+
expect(formatWait(seconds)).toBe(text);
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
describe('getFieldErrors (422 VALIDATION_FAILED)', () => {
|
|
80
|
+
it('maps each field to its first message', () => {
|
|
81
|
+
const error = apiError(422, {
|
|
82
|
+
code: 'VALIDATION_FAILED',
|
|
83
|
+
message: 'Please check these fields: firstName, email',
|
|
84
|
+
fields: [
|
|
85
|
+
{ field: 'firstName', message: 'First name must be at least 2 characters' },
|
|
86
|
+
{ field: 'firstName', message: 'second message is ignored' },
|
|
87
|
+
{ field: 'email', message: 'Invalid email address' },
|
|
88
|
+
],
|
|
89
|
+
});
|
|
90
|
+
expect(getFieldErrors(error)).toEqual({
|
|
91
|
+
firstName: 'First name must be at least 2 characters',
|
|
92
|
+
email: 'Invalid email address',
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it('is empty for any other error', () => {
|
|
97
|
+
expect(getFieldErrors(apiError(400, { code: 'BAD_REQUEST', message: 'x', fields: [{ field: 'a', message: 'b' }] }))).toEqual({});
|
|
98
|
+
expect(getFieldErrors(new Error('x'))).toEqual({});
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('field names become plain own keys, never prototype setters', () => {
|
|
102
|
+
const out = getFieldErrors(
|
|
103
|
+
apiError(422, { code: 'VALIDATION_FAILED', message: 'x', fields: [{ field: '__proto__', message: 'm' }] }),
|
|
104
|
+
);
|
|
105
|
+
expect(Object.prototype.hasOwnProperty.call(out, '__proto__')).toBe(true);
|
|
106
|
+
expect(({} as Record<string, unknown>).m).toBeUndefined();
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
describe('getErrorMessage and getErrorCode', () => {
|
|
111
|
+
it('prefers the server message, then a network hint, then the error message', () => {
|
|
112
|
+
expect(getErrorMessage(apiError(400, { code: 'X', message: 'Server says no' }))).toBe('Server says no');
|
|
113
|
+
expect(getErrorMessage(new AxiosError('Network Error', 'ERR_NETWORK'))).toBe('Network error. Check your connection.');
|
|
114
|
+
expect(getErrorMessage(new Error('plain'))).toBe('plain');
|
|
115
|
+
expect(getErrorMessage('?')).toBe('An unexpected error occurred');
|
|
116
|
+
expect(getErrorCode(apiError(403, { code: 'ACCOUNT_DEACTIVATED', message: 'x' }))).toBe('ACCOUNT_DEACTIVATED');
|
|
117
|
+
expect(getErrorCode(new Error('x'))).toBeUndefined();
|
|
118
|
+
});
|
|
119
|
+
});
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { AxiosError, AxiosHeaders } from 'axios';
|
|
2
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import { applyFieldErrors } from '../form';
|
|
5
|
+
|
|
6
|
+
function validationFailed(fields: { field: string; message: string }[]): AxiosError {
|
|
7
|
+
const config = { headers: new AxiosHeaders() };
|
|
8
|
+
return new AxiosError('Request failed', 'ERR_BAD_REQUEST', config, undefined, {
|
|
9
|
+
status: 422,
|
|
10
|
+
statusText: '',
|
|
11
|
+
headers: {},
|
|
12
|
+
config,
|
|
13
|
+
data: { success: false, error: { code: 'VALIDATION_FAILED', message: 'Please check these fields', fields } },
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
type Form = { firstName: string; email: string };
|
|
18
|
+
|
|
19
|
+
describe('applyFieldErrors', () => {
|
|
20
|
+
it("puts each server message on the form's own field", () => {
|
|
21
|
+
const setError = vi.fn();
|
|
22
|
+
const applied = applyFieldErrors<Form>(
|
|
23
|
+
validationFailed([
|
|
24
|
+
{ field: 'firstName', message: 'First name must be at least 2 characters' },
|
|
25
|
+
{ field: 'body', message: 'not a form field' },
|
|
26
|
+
]),
|
|
27
|
+
setError,
|
|
28
|
+
['firstName', 'email'],
|
|
29
|
+
);
|
|
30
|
+
expect(applied).toBe(true);
|
|
31
|
+
expect(setError).toHaveBeenCalledTimes(1);
|
|
32
|
+
expect(setError).toHaveBeenCalledWith('firstName', { type: 'server', message: 'First name must be at least 2 characters' });
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('sets nothing for fields the form does not have, or for any other error', () => {
|
|
36
|
+
const setError = vi.fn();
|
|
37
|
+
expect(applyFieldErrors<Form>(validationFailed([{ field: 'body', message: 'x' }]), setError, ['firstName'])).toBe(false);
|
|
38
|
+
expect(applyFieldErrors<Form>(new Error('boom'), setError, ['firstName'])).toBe(false);
|
|
39
|
+
expect(applyFieldErrors<Form>(null, setError, ['firstName'])).toBe(false);
|
|
40
|
+
expect(setError).not.toHaveBeenCalled();
|
|
41
|
+
});
|
|
42
|
+
});
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { isAuthPath, isProtectedPath, isUnderPath } from '../paths';
|
|
4
|
+
|
|
5
|
+
describe('isUnderPath (whole path segments)', () => {
|
|
6
|
+
it.each([
|
|
7
|
+
['/admin', '/admin', true],
|
|
8
|
+
['/admin/users', '/admin', true],
|
|
9
|
+
['/admin/users/1', '/admin', true],
|
|
10
|
+
['/administrator', '/admin', false],
|
|
11
|
+
['/admin-old', '/admin', false],
|
|
12
|
+
['/', '/admin', false],
|
|
13
|
+
['/anything', '/', true],
|
|
14
|
+
])('%s under %s -> %s', (pathname, base, expected) => {
|
|
15
|
+
expect(isUnderPath(pathname, base)).toBe(expected);
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
describe('the shipped lists', () => {
|
|
20
|
+
it.each([
|
|
21
|
+
['/dashboard', true],
|
|
22
|
+
['/dashboard/settings', true],
|
|
23
|
+
['/profile', true],
|
|
24
|
+
['/admin/sessions', true],
|
|
25
|
+
['/profile-public', false],
|
|
26
|
+
['/dashboards', false],
|
|
27
|
+
['/', false],
|
|
28
|
+
['/login', false],
|
|
29
|
+
])('protected %s -> %s', (pathname, expected) => {
|
|
30
|
+
expect(isProtectedPath(pathname)).toBe(expected);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it.each([
|
|
34
|
+
['/login', true],
|
|
35
|
+
['/register', true],
|
|
36
|
+
['/reset-password', true],
|
|
37
|
+
['/verify-account', true],
|
|
38
|
+
['/login-help', false],
|
|
39
|
+
['/dashboard', false],
|
|
40
|
+
])('sign-in page %s -> %s', (pathname, expected) => {
|
|
41
|
+
expect(isAuthPath(pathname)).toBe(expected);
|
|
42
|
+
});
|
|
43
|
+
});
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { getSafeRedirectPath, isSafeUrl } from '../security';
|
|
4
|
+
|
|
5
|
+
describe('getSafeRedirectPath (the ?from= value after sign-in)', () => {
|
|
6
|
+
it.each([
|
|
7
|
+
['/dashboard', '/dashboard'],
|
|
8
|
+
['/admin/users?page=2#top', '/admin/users?page=2#top'],
|
|
9
|
+
['/a/../b', '/b'],
|
|
10
|
+
])('keeps a same-site path: %s', (input, expected) => {
|
|
11
|
+
expect(getSafeRedirectPath(input)).toBe(expected);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it.each([
|
|
15
|
+
['nothing', undefined],
|
|
16
|
+
['empty', ''],
|
|
17
|
+
['no leading slash', 'dashboard'],
|
|
18
|
+
['protocol-relative', '//evil.com'],
|
|
19
|
+
['absolute URL', 'https://evil.com/x'],
|
|
20
|
+
['backslash (browsers read it as a slash)', '/\\evil.com'],
|
|
21
|
+
// Caught only by the character rule: the URL parse alone would quietly turn it into /foo/bar.
|
|
22
|
+
['backslash inside a path', '/foo\\bar'],
|
|
23
|
+
['tab inside', '/\t/evil.com'],
|
|
24
|
+
['newline inside', '/\n/evil.com'],
|
|
25
|
+
['dot segments that resolve to //', '/..//evil.com'],
|
|
26
|
+
['encoded dot segments', '/%2e%2e//evil.com'],
|
|
27
|
+
])('refuses %s', (_name, input) => {
|
|
28
|
+
expect(getSafeRedirectPath(input as string | undefined)).toBeUndefined();
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
describe('isSafeUrl', () => {
|
|
33
|
+
it.each(['https://example.com', 'http://example.com/a', 'mailto:a@example.com'])('allows %s', (url) => {
|
|
34
|
+
expect(isSafeUrl(url)).toBe(true);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it.each(['javascript:alert(1)', 'data:text/html,<b>x</b>', 'not a url', 'vbscript:x'])('refuses %s', (url) => {
|
|
38
|
+
expect(isSafeUrl(url)).toBe(false);
|
|
39
|
+
});
|
|
40
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import { hasSessionMarker } from '../session-marker';
|
|
5
|
+
|
|
6
|
+
describe('hasSessionMarker', () => {
|
|
7
|
+
afterEach(() => {
|
|
8
|
+
document.cookie = 'auth_session=; Max-Age=0; path=/';
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it.each([
|
|
12
|
+
['auth_session=1', true],
|
|
13
|
+
['theme=dark; auth_session=1; other=x', true],
|
|
14
|
+
['auth_session=', false],
|
|
15
|
+
['xauth_session=1', false],
|
|
16
|
+
['auth_session_old=1', false],
|
|
17
|
+
['', false],
|
|
18
|
+
])('%j -> %s', (cookies, expected) => {
|
|
19
|
+
expect(hasSessionMarker(cookies)).toBe(expected);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it("reads this browser's cookies by default", () => {
|
|
23
|
+
expect(hasSessionMarker()).toBe(false);
|
|
24
|
+
document.cookie = 'auth_session=1; path=/';
|
|
25
|
+
expect(hasSessionMarker()).toBe(true);
|
|
26
|
+
});
|
|
27
|
+
});
|
|
@@ -34,7 +34,88 @@ export const isErrorCode = (error: unknown, code: string): boolean => {
|
|
|
34
34
|
// Account-state codes from the server (src/libs/account-status.ts). They are
|
|
35
35
|
// separate on purpose: a deactivated (banned) account must never be steered to
|
|
36
36
|
// email verification, because verifying cannot lift a ban.
|
|
37
|
+
// RATE_LIMIT_EXCEEDED to IP_BLOCKED are the "wait and retry" answers (server
|
|
38
|
+
// docs/rate-limits.md). VALIDATION_FAILED is wrong input (see getFieldErrors).
|
|
39
|
+
// REFRESH_TOKEN_ROTATED: this tab lost a refresh race with another tab, which
|
|
40
|
+
// already set fresh cookies; not a dead session (lib/api/axios.config.ts).
|
|
41
|
+
// Keep this an object literal: the email-verification patcher appends to it.
|
|
37
42
|
export const ERROR_CODES = {
|
|
38
43
|
ACCOUNT_DEACTIVATED: 'ACCOUNT_DEACTIVATED',
|
|
39
44
|
EMAIL_NOT_VERIFIED: 'EMAIL_NOT_VERIFIED',
|
|
45
|
+
REFRESH_TOKEN_ROTATED: 'REFRESH_TOKEN_ROTATED',
|
|
46
|
+
RATE_LIMIT_EXCEEDED: 'RATE_LIMIT_EXCEEDED',
|
|
47
|
+
LOGIN_LOCKED: 'LOGIN_LOCKED',
|
|
48
|
+
EMAIL_RATE_LIMITED: 'EMAIL_RATE_LIMITED',
|
|
49
|
+
IP_BLOCKED: 'IP_BLOCKED',
|
|
50
|
+
VALIDATION_FAILED: 'VALIDATION_FAILED',
|
|
40
51
|
} as const;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The server's verdict per field on a 422 VALIDATION_FAILED answer, as
|
|
55
|
+
* { email: 'Invalid email address', ... } (first message per field). Empty for
|
|
56
|
+
* any other error. Forms can pass these to react-hook-form's setError; the
|
|
57
|
+
* error's message already names the fields for a toast.
|
|
58
|
+
*/
|
|
59
|
+
export const getFieldErrors = (error: unknown): Record<string, string> => {
|
|
60
|
+
if (!axios.isAxiosError(error)) return {};
|
|
61
|
+
const data = error.response?.data as ApiError | undefined;
|
|
62
|
+
if (data?.error?.code !== ERROR_CODES.VALIDATION_FAILED) return {};
|
|
63
|
+
// A Map, then fromEntries: field names become own keys only, whatever they are.
|
|
64
|
+
const firsts = new Map<string, string>();
|
|
65
|
+
for (const { field, message } of data.error.fields ?? []) {
|
|
66
|
+
if (!firsts.has(field)) firsts.set(field, message);
|
|
67
|
+
}
|
|
68
|
+
return Object.fromEntries(firsts);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/** "45 seconds", "1 minute", "15 minutes": minutes round up, so nobody retries too early. */
|
|
72
|
+
export const formatWait = (seconds: number): string => {
|
|
73
|
+
const s = Math.max(1, Math.ceil(seconds));
|
|
74
|
+
if (s < 60) return `${s} ${s === 1 ? 'second' : 'seconds'}`;
|
|
75
|
+
const m = Math.ceil(s / 60);
|
|
76
|
+
return `${m} ${m === 1 ? 'minute' : 'minutes'}`;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export interface LimitInfo {
|
|
80
|
+
code: string;
|
|
81
|
+
retryAfterSeconds?: number;
|
|
82
|
+
/** Plain message for the person, with the wait time when the server sent one. */
|
|
83
|
+
message: string;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Recognise a "slow down" answer: a route rate limit, a login lock, the
|
|
88
|
+
* per-address email cap or a blocked network. Returns null for any other
|
|
89
|
+
* error. Wording lives here (not in the server's message) so every screen
|
|
90
|
+
* says the same thing.
|
|
91
|
+
*/
|
|
92
|
+
export const getLimitInfo = (error: unknown): LimitInfo | null => {
|
|
93
|
+
if (!axios.isAxiosError(error)) return null;
|
|
94
|
+
const status = error.response?.status;
|
|
95
|
+
const data = error.response?.data as ApiError | undefined;
|
|
96
|
+
const code = data?.error?.code ?? (status === 429 ? ERROR_CODES.RATE_LIMIT_EXCEEDED : undefined);
|
|
97
|
+
const seconds = data?.error?.retryAfterSeconds;
|
|
98
|
+
const wait = seconds ? ` Try again in ${formatWait(seconds)}.` : ' Please wait a moment and try again.';
|
|
99
|
+
|
|
100
|
+
switch (code) {
|
|
101
|
+
case ERROR_CODES.RATE_LIMIT_EXCEEDED:
|
|
102
|
+
return { code, retryAfterSeconds: seconds, message: `Too many requests.${wait}` };
|
|
103
|
+
case ERROR_CODES.LOGIN_LOCKED:
|
|
104
|
+
return { code, retryAfterSeconds: seconds, message: `Too many failed sign-in attempts.${wait}` };
|
|
105
|
+
case ERROR_CODES.EMAIL_RATE_LIMITED:
|
|
106
|
+
return { code, retryAfterSeconds: seconds, message: `Too many emails were sent to this address.${wait}` };
|
|
107
|
+
case ERROR_CODES.IP_BLOCKED:
|
|
108
|
+
return {
|
|
109
|
+
code,
|
|
110
|
+
retryAfterSeconds: seconds,
|
|
111
|
+
message: seconds
|
|
112
|
+
? `Too many requests from your network. Try again in ${formatWait(seconds)}.`
|
|
113
|
+
: 'Access from your network is blocked.',
|
|
114
|
+
};
|
|
115
|
+
default:
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
/** True for the answers getLimitInfo recognises. Such requests must not be retried. */
|
|
121
|
+
export const isLimitError = (error: unknown): boolean => getLimitInfo(error) !== null;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { FieldValues, Path, UseFormSetError } from 'react-hook-form';
|
|
2
|
+
|
|
3
|
+
import { getFieldErrors } from '@/lib/utils/error';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Put the server's verdict on wrong input (422 VALIDATION_FAILED, one message
|
|
7
|
+
* per field) onto the form's own fields, so it shows where the client rules
|
|
8
|
+
* show theirs. The client rules mirror the server's, but the server is the one
|
|
9
|
+
* that decides: whatever slips through (a rule changed on one side only) still
|
|
10
|
+
* lands under the right field instead of only in a toast.
|
|
11
|
+
*
|
|
12
|
+
* Only the form's own `fields` are set; anything else (a field the form does
|
|
13
|
+
* not have) stays in the toast the auth hooks show. Returns whether any field
|
|
14
|
+
* got a message. Call it from an effect on the request's error.
|
|
15
|
+
*/
|
|
16
|
+
export function applyFieldErrors<T extends FieldValues>(
|
|
17
|
+
error: unknown,
|
|
18
|
+
setError: UseFormSetError<T>,
|
|
19
|
+
fields: readonly Path<T>[]
|
|
20
|
+
): boolean {
|
|
21
|
+
const byField = getFieldErrors(error);
|
|
22
|
+
let applied = false;
|
|
23
|
+
for (const field of fields) {
|
|
24
|
+
const message = byField[field];
|
|
25
|
+
if (message) {
|
|
26
|
+
setError(field, { type: 'server', message });
|
|
27
|
+
applied = true;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return applied;
|
|
31
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { AUTH_PATHS, PROTECTED_PATHS } from '@/lib/constants/routes';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Whether `pathname` is `base` itself or a page under it, by whole path
|
|
5
|
+
* segments: '/admin' covers '/admin' and '/admin/users', never '/administrator'
|
|
6
|
+
* (a plain startsWith would treat that unrelated page as protected).
|
|
7
|
+
*/
|
|
8
|
+
export function isUnderPath(pathname: string, base: string): boolean {
|
|
9
|
+
if (pathname === base) return true;
|
|
10
|
+
return pathname.startsWith(base.endsWith('/') ? base : `${base}/`);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** A page that needs a signed-in visitor (PROTECTED_PATHS). */
|
|
14
|
+
export const isProtectedPath = (pathname: string): boolean =>
|
|
15
|
+
PROTECTED_PATHS.some((base) => isUnderPath(pathname, base));
|
|
16
|
+
|
|
17
|
+
/** A sign-in page (AUTH_PATHS). */
|
|
18
|
+
export const isAuthPath = (pathname: string): boolean => AUTH_PATHS.some((base) => isUnderPath(pathname, base));
|