create-tigra 4.0.1 → 5.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/CHANGELOG.md +43 -0
- package/README.md +21 -3
- package/bin/create-tigra.js +131 -65
- package/lib/installer-transaction.js +275 -0
- package/lib/patchers/diagnostics.patcher.js +123 -0
- package/lib/patchers/email-verification.patcher.js +86 -92
- package/lib/patchers/metrics.patcher.js +145 -0
- package/lib/project-files.js +99 -0
- package/modules/diagnostics/diagnostics.md +75 -0
- package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
- package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
- package/modules/diagnostics/prisma/migration.sql +20 -0
- package/modules/diagnostics/server/__tests__/diagnostics.collector.test.ts +72 -0
- package/modules/diagnostics/server/__tests__/diagnostics.context.test.ts +51 -0
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +123 -0
- package/modules/diagnostics/server/__tests__/diagnostics.service.test.ts +31 -0
- package/modules/diagnostics/server/diagnostics.collector.ts +95 -0
- package/modules/diagnostics/server/diagnostics.context.ts +73 -0
- package/modules/diagnostics/server/diagnostics.repo.ts +79 -0
- package/modules/diagnostics/server/diagnostics.routes.ts +16 -0
- package/modules/diagnostics/server/diagnostics.sample.ts +92 -0
- package/modules/diagnostics/server/diagnostics.schemas.ts +33 -0
- package/modules/diagnostics/server/diagnostics.service.ts +44 -0
- package/modules/email-verification/client/hooks/useVerification.ts +4 -7
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
- package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
- package/modules/email-verification/server/verification.service.ts +102 -157
- package/modules/metrics/client/WebVitalsReporter.tsx +37 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +66 -0
- package/modules/metrics/client/metrics.pages.ts +5 -0
- package/modules/metrics/performance.md +56 -0
- package/modules/metrics/prisma/metric-bucket.prisma +18 -0
- package/modules/metrics/prisma/migration.sql +17 -0
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +97 -0
- package/modules/metrics/server/__tests__/metrics.integration.test.ts +88 -0
- package/modules/metrics/server/__tests__/metrics.schemas.test.ts +36 -0
- package/modules/metrics/server/__tests__/metrics.service.test.ts +84 -0
- package/modules/metrics/server/metrics.collector.ts +133 -0
- package/modules/metrics/server/metrics.pages.ts +3 -0
- package/modules/metrics/server/metrics.repo.ts +45 -0
- package/modules/metrics/server/metrics.routes.ts +45 -0
- package/modules/metrics/server/metrics.schemas.ts +57 -0
- package/modules/metrics/server/metrics.service.ts +104 -0
- package/package.json +1 -1
- package/template/AGENTS.md +18 -10
- package/template/client/.dockerignore +2 -5
- package/template/client/gitignore +43 -0
- package/template/client/src/app/focus-rings.policy.test.ts +88 -0
- package/template/client/src/app/globals.css +46 -0
- package/template/client/src/app/layout.tsx +5 -0
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/components/common/InputModalityTracker.tsx +12 -0
- package/template/client/src/components/ui/input.tsx +3 -2
- package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
- package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
- package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
- package/template/client/src/features/auth/services/auth.service.ts +3 -2
- package/template/client/src/features/auth/store/authSlice.ts +11 -8
- package/template/client/src/features/auth/types/auth.types.ts +1 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
- package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
- package/template/client/src/lib/api/axios.config.ts +24 -6
- package/template/client/src/lib/api/session-events.ts +54 -0
- package/template/client/src/lib/input-modality.test.ts +79 -0
- package/template/client/src/lib/input-modality.ts +52 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
- package/template/client/src/store/__tests__/store.test.ts +1 -0
- package/template/gitignore +3 -2
- package/template/server/.dockerignore +2 -5
- package/template/server/.env.example +1 -0
- package/template/server/.env.example.production +1 -0
- package/template/server/README.md +7 -2
- package/template/server/docs/deployment.md +66 -0
- package/template/server/docs/logging.md +9 -8
- package/template/server/docs/rate-limits.md +6 -4
- package/template/server/gitignore +33 -0
- package/template/server/prisma/migrations/0_init/migration.sql +25 -0
- package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
- package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
- package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
- package/template/server/prisma/schema.prisma +25 -1
- package/template/server/src/__tests__/routes.integration.test.ts +5 -2
- package/template/server/src/app.ts +14 -5
- package/template/server/src/config/env.ts +8 -0
- package/template/server/src/config/rate-limit.config.ts +1 -1
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
- package/template/server/src/jobs/index.ts +8 -2
- package/template/server/src/libs/__tests__/auth.test.ts +1 -1
- package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
- package/template/server/src/libs/__tests__/http.test.ts +10 -10
- package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
- package/template/server/src/libs/__tests__/logger.test.ts +10 -1
- package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
- package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
- package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
- package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
- package/template/server/src/libs/account-mutation.ts +77 -0
- package/template/server/src/libs/auth.ts +37 -3
- package/template/server/src/libs/cookies.ts +25 -13
- package/template/server/src/libs/email-quota.ts +11 -7
- package/template/server/src/libs/email.ts +11 -8
- package/template/server/src/libs/error-handler.ts +16 -12
- package/template/server/src/libs/http.ts +37 -13
- package/template/server/src/libs/ip-block.ts +56 -34
- package/template/server/src/libs/logger.ts +23 -8
- package/template/server/src/libs/monitoring.ts +57 -31
- package/template/server/src/libs/observability/sentry.ts +65 -49
- package/template/server/src/libs/prisma.ts +1 -1
- package/template/server/src/libs/private-cache.ts +6 -0
- package/template/server/src/libs/rate-limiting.ts +4 -0
- package/template/server/src/libs/requestLogger.ts +3 -3
- package/template/server/src/libs/safe-http.ts +58 -18
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
- package/template/server/src/libs/storage/file-storage.service.ts +59 -109
- package/template/server/src/libs/storage/file-validator.ts +2 -1
- package/template/server/src/libs/url-safety.ts +10 -2
- package/template/server/src/libs/validation-errors.ts +11 -8
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
- package/template/server/src/modules/admin/admin.controller.ts +4 -4
- package/template/server/src/modules/admin/admin.repo.ts +37 -54
- package/template/server/src/modules/admin/admin.routes.ts +3 -5
- package/template/server/src/modules/admin/admin.schemas.ts +3 -6
- package/template/server/src/modules/admin/admin.service.ts +61 -62
- package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
- package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
- package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
- package/template/server/src/modules/auth/auth-link-store.ts +64 -0
- package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
- package/template/server/src/modules/auth/auth.controller.ts +16 -5
- package/template/server/src/modules/auth/auth.repo.ts +152 -61
- package/template/server/src/modules/auth/auth.routes.ts +4 -0
- package/template/server/src/modules/auth/auth.schemas.ts +7 -3
- package/template/server/src/modules/auth/auth.service.ts +33 -237
- package/template/server/src/modules/auth/recovery.queue.ts +44 -0
- package/template/server/src/modules/auth/recovery.store.ts +7 -0
- package/template/server/src/modules/auth/session.repo.ts +5 -4
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
- package/template/server/src/modules/files/files.controller.ts +2 -2
- package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
- package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
- package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
- package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
- package/template/server/src/modules/users/users.controller.ts +28 -25
- package/template/server/src/modules/users/users.repo.ts +12 -51
- package/template/server/src/modules/users/users.service.ts +109 -234
- package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
- package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
- package/template/server/src/test/setup.ts +4 -0
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import { useRef } from 'react';
|
|
4
4
|
|
|
5
|
-
import { useMutation
|
|
5
|
+
import { useMutation } from '@tanstack/react-query';
|
|
6
6
|
import { toast } from 'sonner';
|
|
7
7
|
|
|
8
|
-
import {
|
|
8
|
+
import { useAppSelector } from '@/store/hooks';
|
|
9
9
|
import { useAppRouter } from '@/hooks/useAppRouter';
|
|
10
10
|
import { getErrorMessage, isErrorCode, isLimitError, ERROR_CODES } from '@/lib/utils/error';
|
|
11
11
|
import { ROUTES } from '@/lib/constants/routes';
|
|
12
12
|
import { getSafeRedirectPath } from '@/lib/utils/security';
|
|
13
13
|
import { authService } from '../services/auth.service';
|
|
14
|
-
import {
|
|
14
|
+
import { useSessionTransition } from './useSessionTransition';
|
|
15
15
|
|
|
16
16
|
import type { ILoginRequest, IRegisterRequest, IUser } from '../types/auth.types';
|
|
17
17
|
|
|
@@ -32,19 +32,15 @@ interface UseAuthReturn {
|
|
|
32
32
|
}
|
|
33
33
|
|
|
34
34
|
export const useAuth = (): UseAuthReturn => {
|
|
35
|
-
const dispatch = useAppDispatch();
|
|
36
35
|
const router = useAppRouter();
|
|
37
|
-
const
|
|
36
|
+
const { completeSessionChange, signOut } = useSessionTransition();
|
|
38
37
|
const { user, isAuthenticated, isInitializing, isLoggingOut } = useAppSelector((state) => state.auth);
|
|
39
38
|
const pendingRedirectRef = useRef<string>(ROUTES.DASHBOARD);
|
|
40
39
|
|
|
41
40
|
const loginMutation = useMutation({
|
|
42
41
|
mutationFn: (data: ILoginRequest) => authService.login(data),
|
|
43
|
-
onSuccess: (
|
|
44
|
-
|
|
45
|
-
dispatch(setUser(data.user));
|
|
46
|
-
toast.success('Signed in successfully');
|
|
47
|
-
router.push(pendingRedirectRef.current);
|
|
42
|
+
onSuccess: () => {
|
|
43
|
+
completeSessionChange(pendingRedirectRef.current);
|
|
48
44
|
},
|
|
49
45
|
onError: (error) => {
|
|
50
46
|
// Rate limit / login lock: LoginForm shows it inline (with the wait), no toast.
|
|
@@ -71,10 +67,7 @@ export const useAuth = (): UseAuthReturn => {
|
|
|
71
67
|
router.push(ROUTES.VERIFY_ACCOUNT);
|
|
72
68
|
return;
|
|
73
69
|
}
|
|
74
|
-
|
|
75
|
-
dispatch(setUser(data.user));
|
|
76
|
-
toast.success('Account created successfully');
|
|
77
|
-
router.push(ROUTES.DASHBOARD);
|
|
70
|
+
completeSessionChange(ROUTES.DASHBOARD);
|
|
78
71
|
},
|
|
79
72
|
onError: (error) => {
|
|
80
73
|
// Rate limit / email cap: RegisterForm shows it inline (with the wait), no toast.
|
|
@@ -83,19 +76,6 @@ export const useAuth = (): UseAuthReturn => {
|
|
|
83
76
|
},
|
|
84
77
|
});
|
|
85
78
|
|
|
86
|
-
const logout = useCallback(async (): Promise<void> => {
|
|
87
|
-
dispatch(setLoggingOut(true));
|
|
88
|
-
try {
|
|
89
|
-
await authService.logout();
|
|
90
|
-
} catch {
|
|
91
|
-
// Proceed with local logout even if server call fails
|
|
92
|
-
} finally {
|
|
93
|
-
queryClient.clear();
|
|
94
|
-
dispatch(logoutAction());
|
|
95
|
-
router.push(ROUTES.LOGIN);
|
|
96
|
-
}
|
|
97
|
-
}, [dispatch, router, queryClient]);
|
|
98
|
-
|
|
99
79
|
return {
|
|
100
80
|
user,
|
|
101
81
|
isAuthenticated,
|
|
@@ -103,14 +83,11 @@ export const useAuth = (): UseAuthReturn => {
|
|
|
103
83
|
login: (data: ILoginRequest, redirectTo?: string) => {
|
|
104
84
|
// Validate again at the sink: whatever a caller passes, router.push after
|
|
105
85
|
// login only ever receives a same-site path.
|
|
106
|
-
|
|
107
|
-
if (safeRedirect) {
|
|
108
|
-
pendingRedirectRef.current = safeRedirect;
|
|
109
|
-
}
|
|
86
|
+
pendingRedirectRef.current = getSafeRedirectPath(redirectTo) ?? ROUTES.DASHBOARD;
|
|
110
87
|
loginMutation.mutate(data);
|
|
111
88
|
},
|
|
112
89
|
register: registerMutation.mutate,
|
|
113
|
-
logout,
|
|
90
|
+
logout: signOut,
|
|
114
91
|
isLoggingIn: loginMutation.isPending,
|
|
115
92
|
isRegistering: registerMutation.isPending,
|
|
116
93
|
isLoggingOut,
|
|
@@ -32,15 +32,15 @@ export const useCurrentUser = (
|
|
|
32
32
|
|
|
33
33
|
const { data, isLoading, error } = useQuery({
|
|
34
34
|
queryKey: authKeys.me(),
|
|
35
|
-
queryFn: () => authService.getMe(),
|
|
35
|
+
queryFn: ({ signal }) => authService.getMe(signal),
|
|
36
36
|
enabled,
|
|
37
37
|
staleTime: 30 * 1000,
|
|
38
38
|
retry: false,
|
|
39
39
|
});
|
|
40
40
|
|
|
41
41
|
useEffect(() => {
|
|
42
|
-
if (data) dispatch(setUser(data));
|
|
43
|
-
}, [data, dispatch]);
|
|
42
|
+
if (enabled && data) dispatch(setUser(data));
|
|
43
|
+
}, [enabled, data, dispatch]);
|
|
44
44
|
|
|
45
45
|
useEffect(() => {
|
|
46
46
|
if (!enabled || error) dispatch(setInitialized());
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { useCallback } from 'react';
|
|
4
|
+
import { useQueryClient } from '@tanstack/react-query';
|
|
5
|
+
import type { QueryClient } from '@tanstack/react-query';
|
|
6
|
+
|
|
7
|
+
import { hardRedirect } from '@/lib/api/hard-redirect';
|
|
8
|
+
import { publishSessionChange, sessionRevision } from '@/lib/api/session-events';
|
|
9
|
+
import { ROUTES } from '@/lib/constants/routes';
|
|
10
|
+
import { useAppDispatch } from '@/store/hooks';
|
|
11
|
+
import type { AppDispatch } from '@/store';
|
|
12
|
+
import { authService } from '../services/auth.service';
|
|
13
|
+
import { blockSession, logout, markLogoutFailed } from '../store/authSlice';
|
|
14
|
+
|
|
15
|
+
/** Clear all account data before the next protected screen can mount. */
|
|
16
|
+
export function clearSessionState(dispatch: AppDispatch, queries: QueryClient, block = false): void {
|
|
17
|
+
void queries.cancelQueries();
|
|
18
|
+
queries.clear();
|
|
19
|
+
dispatch(block ? blockSession() : logout());
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function useSessionTransition(): {
|
|
23
|
+
completeSessionChange: (path: string) => void;
|
|
24
|
+
signOut: () => Promise<void>;
|
|
25
|
+
} {
|
|
26
|
+
const dispatch = useAppDispatch();
|
|
27
|
+
const queries = useQueryClient();
|
|
28
|
+
|
|
29
|
+
const completeSessionChange = useCallback((path: string): void => {
|
|
30
|
+
clearSessionState(dispatch, queries, true);
|
|
31
|
+
publishSessionChange();
|
|
32
|
+
// The new document boots from the shared cookies. This also discards
|
|
33
|
+
// the Next.js route cache for the previous account.
|
|
34
|
+
hardRedirect(path);
|
|
35
|
+
}, [dispatch, queries]);
|
|
36
|
+
|
|
37
|
+
const signOut = useCallback(async (): Promise<void> => {
|
|
38
|
+
const revision = sessionRevision();
|
|
39
|
+
clearSessionState(dispatch, queries, true);
|
|
40
|
+
try {
|
|
41
|
+
await authService.logout();
|
|
42
|
+
if (revision === sessionRevision()) completeSessionChange(ROUTES.LOGIN);
|
|
43
|
+
} catch {
|
|
44
|
+
// A network failure cannot revoke HttpOnly cookies. Keep this tab
|
|
45
|
+
// blocked and let the user retry before notifying its peers.
|
|
46
|
+
if (revision === sessionRevision()) dispatch(markLogoutFailed());
|
|
47
|
+
}
|
|
48
|
+
}, [completeSessionChange, dispatch, queries]);
|
|
49
|
+
|
|
50
|
+
return { completeSessionChange, signOut };
|
|
51
|
+
}
|
|
@@ -33,9 +33,10 @@ class AuthService {
|
|
|
33
33
|
await apiClient.post(API_ENDPOINTS.AUTH.LOGOUT);
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
async getMe(): Promise<IUser> {
|
|
36
|
+
async getMe(signal?: AbortSignal): Promise<IUser> {
|
|
37
37
|
const response = await apiClient.get<ApiResponse<IUser>>(
|
|
38
|
-
API_ENDPOINTS.AUTH.ME
|
|
38
|
+
API_ENDPOINTS.AUTH.ME,
|
|
39
|
+
{ signal },
|
|
39
40
|
);
|
|
40
41
|
return response.data.data;
|
|
41
42
|
}
|
|
@@ -13,6 +13,7 @@ export const initialAuthState: IAuthState = {
|
|
|
13
13
|
isAuthenticated: false,
|
|
14
14
|
isInitializing: true,
|
|
15
15
|
isLoggingOut: false,
|
|
16
|
+
logoutFailed: false,
|
|
16
17
|
};
|
|
17
18
|
|
|
18
19
|
const authSlice = createSlice({
|
|
@@ -24,20 +25,22 @@ const authSlice = createSlice({
|
|
|
24
25
|
state.isAuthenticated = true;
|
|
25
26
|
state.isInitializing = false;
|
|
26
27
|
state.isLoggingOut = false;
|
|
28
|
+
state.logoutFailed = false;
|
|
27
29
|
},
|
|
28
30
|
setInitialized: (state) => {
|
|
29
31
|
state.isInitializing = false;
|
|
30
32
|
},
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
state.
|
|
33
|
+
blockSession: () => ({
|
|
34
|
+
...initialAuthState,
|
|
35
|
+
isInitializing: false,
|
|
36
|
+
isLoggingOut: true,
|
|
37
|
+
}),
|
|
38
|
+
markLogoutFailed: (state) => {
|
|
39
|
+
state.logoutFailed = true;
|
|
38
40
|
},
|
|
41
|
+
logout: () => ({ ...initialAuthState, isInitializing: false }),
|
|
39
42
|
},
|
|
40
43
|
});
|
|
41
44
|
|
|
42
|
-
export const { setUser, setInitialized,
|
|
45
|
+
export const { setUser, setInitialized, blockSession, markLogoutFailed, logout } = authSlice.actions;
|
|
43
46
|
export default authSlice.reducer;
|
|
@@ -48,9 +48,26 @@ const count = (calls: string[], call: string): number => calls.filter((c) => c =
|
|
|
48
48
|
beforeEach(() => {
|
|
49
49
|
// Module mocks survive vi.resetModules(): forget the previous test's calls.
|
|
50
50
|
vi.clearAllMocks();
|
|
51
|
+
localStorage.clear();
|
|
51
52
|
document.cookie = 'auth_session=1; path=/';
|
|
52
53
|
});
|
|
53
54
|
|
|
55
|
+
it('discards an old successful response after another tab changes session', async () => {
|
|
56
|
+
const t = await load(() => ({ status: 200 }));
|
|
57
|
+
let finish!: () => void;
|
|
58
|
+
let started!: () => void;
|
|
59
|
+
const sent = new Promise<void>(resolve => { started = resolve; });
|
|
60
|
+
t.apiClient.defaults.adapter = async config => {
|
|
61
|
+
await new Promise<void>(resolve => { finish = resolve; started(); });
|
|
62
|
+
return respond(config, 200, { profile: 'previous fixture account' });
|
|
63
|
+
};
|
|
64
|
+
const response = t.apiClient.get('/auth/me');
|
|
65
|
+
await sent;
|
|
66
|
+
localStorage.setItem('tigra:session-revision', 'next-session');
|
|
67
|
+
finish();
|
|
68
|
+
await expect(response).rejects.toMatchObject({ code: 'ERR_CANCELED' });
|
|
69
|
+
});
|
|
70
|
+
|
|
54
71
|
describe('expired access token', () => {
|
|
55
72
|
it('parallel 401s share ONE refresh, then every request is replayed', async () => {
|
|
56
73
|
let refreshed = false;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { expect, it, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import { onPeerSessionChange, sessionRevision } from '../session-events';
|
|
5
|
+
|
|
6
|
+
it('detects peer changes and a missed revision when the tab returns', () => {
|
|
7
|
+
localStorage.clear();
|
|
8
|
+
const changed = vi.fn();
|
|
9
|
+
const stop = onPeerSessionChange(changed);
|
|
10
|
+
const key = 'tigra:session-revision';
|
|
11
|
+
localStorage.setItem(key, 'first-change');
|
|
12
|
+
window.dispatchEvent(new StorageEvent('storage', { key }));
|
|
13
|
+
window.dispatchEvent(new StorageEvent('storage', { key }));
|
|
14
|
+
expect(changed).toHaveBeenCalledTimes(1);
|
|
15
|
+
localStorage.setItem(key, 'missed-change');
|
|
16
|
+
window.dispatchEvent(new Event('pageshow'));
|
|
17
|
+
expect(changed).toHaveBeenCalledTimes(2);
|
|
18
|
+
expect(sessionRevision()).toBe('missed-change');
|
|
19
|
+
stop();
|
|
20
|
+
localStorage.setItem(key, 'after-cleanup');
|
|
21
|
+
window.dispatchEvent(new Event('focus'));
|
|
22
|
+
expect(changed).toHaveBeenCalledTimes(2);
|
|
23
|
+
});
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import axios from 'axios';
|
|
1
|
+
import axios, { CanceledError } from 'axios';
|
|
2
2
|
import { toast } from 'sonner';
|
|
3
3
|
|
|
4
4
|
import type { InternalAxiosRequestConfig } from 'axios';
|
|
5
5
|
|
|
6
6
|
import { hardRedirect } from '@/lib/api/hard-redirect';
|
|
7
|
-
import { emitSessionEnded } from '@/lib/api/session-events';
|
|
7
|
+
import { emitSessionEnded, sessionRevision } from '@/lib/api/session-events';
|
|
8
8
|
import { API_ENDPOINTS } from '@/lib/constants/api-endpoints';
|
|
9
9
|
import { ROUTES } from '@/lib/constants/routes';
|
|
10
10
|
import { env } from '@/lib/env';
|
|
@@ -17,6 +17,8 @@ declare module 'axios' {
|
|
|
17
17
|
* caller shows the message itself (the auth forms show it inline).
|
|
18
18
|
*/
|
|
19
19
|
skipLimitToast?: boolean;
|
|
20
|
+
/** Session revision captured before the first send, including retries. */
|
|
21
|
+
sessionRevision?: string | null;
|
|
20
22
|
}
|
|
21
23
|
}
|
|
22
24
|
|
|
@@ -29,7 +31,12 @@ const apiClient = axios.create({
|
|
|
29
31
|
withCredentials: true, // Send cookies with every request
|
|
30
32
|
});
|
|
31
33
|
|
|
32
|
-
|
|
34
|
+
apiClient.interceptors.request.use((config) => {
|
|
35
|
+
const revision = sessionRevision();
|
|
36
|
+
if (config.sessionRevision === undefined) config.sessionRevision = revision;
|
|
37
|
+
if (config.sessionRevision !== revision) throw new CanceledError('Session changed');
|
|
38
|
+
return config;
|
|
39
|
+
});
|
|
33
40
|
|
|
34
41
|
let isRefreshing = false;
|
|
35
42
|
let refreshTimestamp = 0;
|
|
@@ -83,6 +90,7 @@ let endingDeactivatedSession: Promise<void> | null = null;
|
|
|
83
90
|
* Best effort: the user is signed out locally even if the logout call fails.
|
|
84
91
|
*/
|
|
85
92
|
const endDeactivatedSession = (): Promise<void> => {
|
|
93
|
+
const revision = sessionRevision();
|
|
86
94
|
endingDeactivatedSession ??= apiClient
|
|
87
95
|
.post(API_ENDPOINTS.AUTH.LOGOUT)
|
|
88
96
|
.then(
|
|
@@ -90,7 +98,7 @@ const endDeactivatedSession = (): Promise<void> => {
|
|
|
90
98
|
() => undefined
|
|
91
99
|
)
|
|
92
100
|
.then(() => {
|
|
93
|
-
emitSessionEnded('deactivated');
|
|
101
|
+
if (revision === sessionRevision()) emitSessionEnded('deactivated');
|
|
94
102
|
})
|
|
95
103
|
.finally(() => {
|
|
96
104
|
endingDeactivatedSession = null;
|
|
@@ -99,9 +107,15 @@ const endDeactivatedSession = (): Promise<void> => {
|
|
|
99
107
|
};
|
|
100
108
|
|
|
101
109
|
apiClient.interceptors.response.use(
|
|
102
|
-
(response) =>
|
|
110
|
+
(response) => {
|
|
111
|
+
if (response.config.sessionRevision !== sessionRevision()) throw new CanceledError('Session changed');
|
|
112
|
+
return response;
|
|
113
|
+
},
|
|
103
114
|
async (error) => {
|
|
104
115
|
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
|
|
116
|
+
if (originalRequest && originalRequest.sessionRevision !== sessionRevision()) {
|
|
117
|
+
throw new CanceledError('Session changed');
|
|
118
|
+
}
|
|
105
119
|
|
|
106
120
|
// "Slow down" answers (429 rate limit / login lock / email cap, 403 IP_BLOCKED):
|
|
107
121
|
// tell the person once, with the wait time, and never treat them as an auth
|
|
@@ -161,13 +175,17 @@ apiClient.interceptors.response.use(
|
|
|
161
175
|
|
|
162
176
|
try {
|
|
163
177
|
// Refresh — cookie is sent automatically
|
|
164
|
-
await apiClient.post(API_ENDPOINTS.AUTH.REFRESH);
|
|
178
|
+
await apiClient.post(API_ENDPOINTS.AUTH.REFRESH, undefined, { sessionRevision: originalRequest.sessionRevision });
|
|
165
179
|
|
|
166
180
|
processQueue(null);
|
|
167
181
|
|
|
168
182
|
// Retry original request — new cookie is set automatically
|
|
169
183
|
return apiClient(originalRequest);
|
|
170
184
|
} catch (refreshError) {
|
|
185
|
+
if (originalRequest.sessionRevision !== sessionRevision()) {
|
|
186
|
+
processQueue(refreshError);
|
|
187
|
+
throw new CanceledError('Session changed');
|
|
188
|
+
}
|
|
171
189
|
// Lost a race with another tab: both refreshed at once with the same
|
|
172
190
|
// token, the other one won, and the server kept the cookies, so this
|
|
173
191
|
// browser already holds the winner's fresh ones (401
|
|
@@ -16,6 +16,60 @@ type Listener = (reason: SessionEndReason) => void;
|
|
|
16
16
|
|
|
17
17
|
const listeners = new Set<Listener>();
|
|
18
18
|
|
|
19
|
+
const REVISION_KEY = 'tigra:session-revision';
|
|
20
|
+
let inMemoryRevision: string | null = null;
|
|
21
|
+
let useMemoryRevision = false;
|
|
22
|
+
|
|
23
|
+
/** An opaque notification only. The API remains the source of identity. */
|
|
24
|
+
export function sessionRevision(): string | null {
|
|
25
|
+
if (typeof window === 'undefined') return null;
|
|
26
|
+
if (useMemoryRevision) return inMemoryRevision;
|
|
27
|
+
try {
|
|
28
|
+
return window.localStorage.getItem(REVISION_KEY) ?? inMemoryRevision;
|
|
29
|
+
} catch {
|
|
30
|
+
return inMemoryRevision;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Call after credentials have changed, before navigating away. */
|
|
35
|
+
export function publishSessionChange(): void {
|
|
36
|
+
const revision = crypto.randomUUID?.() ?? Date.now().toString(36) + Math.random().toString(36);
|
|
37
|
+
inMemoryRevision = revision;
|
|
38
|
+
try {
|
|
39
|
+
window.localStorage.setItem(REVISION_KEY, revision);
|
|
40
|
+
} catch {
|
|
41
|
+
// Same-tab response cancellation still works when storage is disabled.
|
|
42
|
+
useMemoryRevision = true;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Storage covers active tabs. Checking on return covers suspended tabs. */
|
|
47
|
+
export function onPeerSessionChange(listener: () => void): () => void {
|
|
48
|
+
let seen = sessionRevision();
|
|
49
|
+
const check = (): void => {
|
|
50
|
+
const current = sessionRevision();
|
|
51
|
+
if (current === seen) return;
|
|
52
|
+
seen = current;
|
|
53
|
+
listener();
|
|
54
|
+
};
|
|
55
|
+
const onStorage = (event: StorageEvent): void => {
|
|
56
|
+
if (event.key === REVISION_KEY) check();
|
|
57
|
+
};
|
|
58
|
+
const onVisible = (): void => {
|
|
59
|
+
if (document.visibilityState === 'visible') check();
|
|
60
|
+
};
|
|
61
|
+
window.addEventListener('storage', onStorage);
|
|
62
|
+
window.addEventListener('focus', check);
|
|
63
|
+
window.addEventListener('pageshow', check);
|
|
64
|
+
document.addEventListener('visibilitychange', onVisible);
|
|
65
|
+
return () => {
|
|
66
|
+
window.removeEventListener('storage', onStorage);
|
|
67
|
+
window.removeEventListener('focus', check);
|
|
68
|
+
window.removeEventListener('pageshow', check);
|
|
69
|
+
document.removeEventListener('visibilitychange', onVisible);
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
19
73
|
/** Subscribe; returns the unsubscribe function (fits a useEffect cleanup). */
|
|
20
74
|
export function onSessionEnded(listener: Listener): () => void {
|
|
21
75
|
listeners.add(listener);
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import { installInputModality } from './input-modality';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Focus rings are for keyboard users. Radix menus and selects move focus by script after a mouse click
|
|
8
|
+
* whose default they cancel, so Chrome reports `:focus-visible` and every keyboard ring showed for mouse users. The
|
|
9
|
+
* page records how the owner last interacted (`<html data-input>`) and the CSS hides focus rings in "pointer" mode.
|
|
10
|
+
*/
|
|
11
|
+
let uninstall: () => void;
|
|
12
|
+
const mode = (): string | null => document.documentElement.getAttribute('data-input');
|
|
13
|
+
const key = (target: Element, keyName: string, init: KeyboardEventInit = {}): void => {
|
|
14
|
+
target.dispatchEvent(new KeyboardEvent('keydown', { key: keyName, bubbles: true, ...init }));
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
beforeEach(() => {
|
|
18
|
+
document.body.innerHTML = '<button id="b">B</button><textarea id="t"></textarea><input id="i" type="text">'
|
|
19
|
+
+ '<input id="c" type="checkbox"><div id="e" contenteditable="true"></div>';
|
|
20
|
+
document.documentElement.removeAttribute('data-input');
|
|
21
|
+
uninstall = installInputModality(document);
|
|
22
|
+
});
|
|
23
|
+
afterEach(() => { uninstall(); });
|
|
24
|
+
|
|
25
|
+
describe('installInputModality', () => {
|
|
26
|
+
it('starts in pointer mode, so nothing shows a ring before the first key press', () => {
|
|
27
|
+
expect(mode()).toBe('pointer');
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('switches to keyboard on Tab and on navigation keys outside text fields', () => {
|
|
31
|
+
key(document.getElementById('b')!, 'Tab');
|
|
32
|
+
expect(mode()).toBe('keyboard');
|
|
33
|
+
document.getElementById('b')!.dispatchEvent(new Event('pointerdown', { bubbles: true }));
|
|
34
|
+
expect(mode()).toBe('pointer');
|
|
35
|
+
for (const name of ['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown', 'Escape']) {
|
|
36
|
+
document.documentElement.setAttribute('data-input', 'pointer');
|
|
37
|
+
key(document.getElementById('b')!, name);
|
|
38
|
+
expect(mode(), name).toBe('keyboard');
|
|
39
|
+
}
|
|
40
|
+
// A checkbox is not a text field: arrows there are focus navigation.
|
|
41
|
+
document.documentElement.setAttribute('data-input', 'pointer');
|
|
42
|
+
key(document.getElementById('c')!, 'ArrowDown');
|
|
43
|
+
expect(mode()).toBe('keyboard');
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('typing, arrows and Enter inside a text field never switch to keyboard', () => {
|
|
47
|
+
for (const id of ['t', 'i', 'e']) {
|
|
48
|
+
for (const name of ['a', 'Enter', ' ', 'ArrowLeft', 'ArrowDown', 'Home', 'Escape', 'Backspace']) {
|
|
49
|
+
key(document.getElementById(id)!, name);
|
|
50
|
+
expect(mode(), `${id} ${name}`).toBe('pointer');
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
// Tab moves focus out of the field: that is keyboard navigation.
|
|
54
|
+
key(document.getElementById('t')!, 'Tab');
|
|
55
|
+
expect(mode()).toBe('keyboard');
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('ignores shortcuts with Ctrl, Alt or Meta and lone modifier keys', () => {
|
|
59
|
+
for (const init of [{ ctrlKey: true }, { altKey: true }, { metaKey: true }]) {
|
|
60
|
+
key(document.getElementById('b')!, 'ArrowDown', init);
|
|
61
|
+
expect(mode()).toBe('pointer');
|
|
62
|
+
}
|
|
63
|
+
for (const name of ['Shift', 'Control', 'Alt', 'Meta']) key(document.getElementById('b')!, name);
|
|
64
|
+
expect(mode()).toBe('pointer');
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('a pointer press anywhere returns to pointer mode (mouse, touch or pen)', () => {
|
|
68
|
+
key(document.getElementById('b')!, 'Tab');
|
|
69
|
+
document.body.dispatchEvent(new Event('pointerdown', { bubbles: true }));
|
|
70
|
+
expect(mode()).toBe('pointer');
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('uninstall removes the listeners', () => {
|
|
74
|
+
uninstall();
|
|
75
|
+
key(document.getElementById('b')!, 'Tab');
|
|
76
|
+
expect(mode()).toBe('pointer');
|
|
77
|
+
uninstall = (): void => undefined;
|
|
78
|
+
});
|
|
79
|
+
});
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the visitor last interacted with the page, kept on `<html data-input="pointer" | "keyboard">`, so focus rings
|
|
3
|
+
* show only for keyboard users (globals.css "Focus rings").
|
|
4
|
+
*
|
|
5
|
+
* Why the browser's own `:focus-visible` is not enough: Radix menus and selects cancel the default of the mouse press
|
|
6
|
+
* on their trigger and then move focus by script (into the menu, then to the item under the pointer). Chrome then has
|
|
7
|
+
* no record of mouse use and reports `:focus-visible`, so every keyboard ring appeared for mouse users until their
|
|
8
|
+
* first ordinary click on the page (reproduced in Chrome, also on a blank page without Radix).
|
|
9
|
+
*
|
|
10
|
+
* Rules:
|
|
11
|
+
* - Any pointer press (mouse, touch, pen) means "pointer".
|
|
12
|
+
* - Tab means "keyboard" everywhere; arrows, Home/End, PageUp/PageDown and Escape mean "keyboard" outside text fields,
|
|
13
|
+
* where they navigate focus (menus, tabs, radio groups). Typing, Enter and caret keys in a text field do not: the
|
|
14
|
+
* owner is writing, not navigating. Shortcuts with Ctrl/Alt/Meta and lone modifier keys change nothing.
|
|
15
|
+
* - The server renders "pointer" (app/layout.tsx), so nothing shows a ring before the first key press; a keyboard
|
|
16
|
+
* user's first Tab switches the mode before focus moves (keydown precedes the focus change).
|
|
17
|
+
*/
|
|
18
|
+
export type InputModality = 'pointer' | 'keyboard';
|
|
19
|
+
|
|
20
|
+
const NAVIGATION_KEYS = new Set(['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown', 'Escape']);
|
|
21
|
+
/** Input types that are not text fields: arrows there move focus or a value, like any other control. */
|
|
22
|
+
const NON_TEXT_INPUTS = new Set(['button', 'submit', 'reset', 'checkbox', 'radio', 'range', 'file', 'color', 'image']);
|
|
23
|
+
|
|
24
|
+
/** True for elements where keys type or move a caret (they keep their focus look in every mode). */
|
|
25
|
+
function isTextField(target: EventTarget | null): boolean {
|
|
26
|
+
if (!(target instanceof Element)) return false;
|
|
27
|
+
if (target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement) return true;
|
|
28
|
+
if (target instanceof HTMLInputElement) return !NON_TEXT_INPUTS.has(target.type);
|
|
29
|
+
// The attribute, not `isContentEditable` (missing in jsdom); `closest` also covers keys from inside an editor.
|
|
30
|
+
return target.closest('[contenteditable]:not([contenteditable="false"])') !== null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Starts tracking on `doc` (capture phase, so a component that stops propagation cannot hide the interaction) and
|
|
34
|
+
* returns a function that stops it. Sets "pointer" at once. */
|
|
35
|
+
export function installInputModality(doc: Document): () => void {
|
|
36
|
+
const root = doc.documentElement;
|
|
37
|
+
const set = (mode: InputModality): void => {
|
|
38
|
+
if (root.getAttribute('data-input') !== mode) root.setAttribute('data-input', mode);
|
|
39
|
+
};
|
|
40
|
+
const onPointerDown = (): void => set('pointer');
|
|
41
|
+
const onKeyDown = (event: KeyboardEvent): void => {
|
|
42
|
+
if (event.ctrlKey || event.altKey || event.metaKey) return;
|
|
43
|
+
if (event.key === 'Tab' || (NAVIGATION_KEYS.has(event.key) && !isTextField(event.target))) set('keyboard');
|
|
44
|
+
};
|
|
45
|
+
set('pointer');
|
|
46
|
+
doc.addEventListener('pointerdown', onPointerDown, true);
|
|
47
|
+
doc.addEventListener('keydown', onKeyDown, true);
|
|
48
|
+
return () => {
|
|
49
|
+
doc.removeEventListener('pointerdown', onPointerDown, true);
|
|
50
|
+
doc.removeEventListener('keydown', onKeyDown, true);
|
|
51
|
+
};
|
|
52
|
+
}
|