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
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import type React from 'react';
|
|
4
|
+
import { useEffect } from 'react';
|
|
5
|
+
|
|
6
|
+
import { useForm } from 'react-hook-form';
|
|
7
|
+
import { zodResolver } from '@hookform/resolvers/zod';
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
import { Loader2 } from 'lucide-react';
|
|
10
|
+
|
|
11
|
+
import { Button } from '@/components/ui/button';
|
|
12
|
+
import { Input } from '@/components/ui/input';
|
|
13
|
+
import { Label } from '@/components/ui/label';
|
|
14
|
+
import { AppLink } from '@/components/common/AppLink';
|
|
15
|
+
import { useForgotPassword } from '../hooks/usePasswordReset';
|
|
16
|
+
import { LimitNotice } from './LimitNotice';
|
|
17
|
+
import { ROUTES } from '@/lib/constants/routes';
|
|
18
|
+
import { cn } from '@/lib/utils';
|
|
19
|
+
import { applyFieldErrors } from '@/lib/utils/form';
|
|
20
|
+
|
|
21
|
+
const forgotPasswordSchema = z.object({
|
|
22
|
+
email: z.string().min(1, 'Email is required').email('Invalid email address'),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
type ForgotPasswordFormData = z.infer<typeof forgotPasswordSchema>;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Request a password-reset link. The server answers the same way whether or not
|
|
29
|
+
* the email has an account (no enumeration), so success only says "check your
|
|
30
|
+
* email". Its limits (per IP, and 3 emails per hour per address) show inline,
|
|
31
|
+
* with the wait time.
|
|
32
|
+
*/
|
|
33
|
+
export const ForgotPasswordForm = (): React.ReactElement => {
|
|
34
|
+
const { forgotPassword, isPending, error } = useForgotPassword();
|
|
35
|
+
|
|
36
|
+
const {
|
|
37
|
+
register,
|
|
38
|
+
handleSubmit,
|
|
39
|
+
setError,
|
|
40
|
+
formState: { errors },
|
|
41
|
+
} = useForm<ForgotPasswordFormData>({
|
|
42
|
+
resolver: zodResolver(forgotPasswordSchema),
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
// The server's 422 verdict lands under its field (lib/utils/form.ts).
|
|
46
|
+
useEffect(() => {
|
|
47
|
+
applyFieldErrors(error, setError, ['email']);
|
|
48
|
+
}, [error, setError]);
|
|
49
|
+
|
|
50
|
+
const onSubmit = (data: ForgotPasswordFormData): void => {
|
|
51
|
+
forgotPassword(data.email);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
return (
|
|
55
|
+
<div className="mx-auto w-full max-w-sm space-y-6">
|
|
56
|
+
<div className="space-y-2 text-center">
|
|
57
|
+
<h1 className="text-2xl font-bold tracking-tight">Forgot your password?</h1>
|
|
58
|
+
<p className="text-sm text-muted-foreground">
|
|
59
|
+
Enter your email and we'll send you a link to reset it
|
|
60
|
+
</p>
|
|
61
|
+
</div>
|
|
62
|
+
|
|
63
|
+
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
|
64
|
+
<div className="space-y-2">
|
|
65
|
+
<Label htmlFor="email">Email</Label>
|
|
66
|
+
<Input
|
|
67
|
+
id="email"
|
|
68
|
+
type="email"
|
|
69
|
+
placeholder="you@example.com"
|
|
70
|
+
autoComplete="email"
|
|
71
|
+
aria-invalid={!!errors.email}
|
|
72
|
+
aria-describedby={errors.email ? 'email-error' : undefined}
|
|
73
|
+
{...register('email')}
|
|
74
|
+
className={cn(errors.email && 'border-destructive')}
|
|
75
|
+
/>
|
|
76
|
+
{errors.email && (
|
|
77
|
+
<p id="email-error" className="text-sm text-destructive">{errors.email.message}</p>
|
|
78
|
+
)}
|
|
79
|
+
</div>
|
|
80
|
+
|
|
81
|
+
{/* Rate limit or email cap, with the wait time (no toast for these). */}
|
|
82
|
+
<LimitNotice error={error} />
|
|
83
|
+
|
|
84
|
+
<Button type="submit" className="w-full" disabled={isPending}>
|
|
85
|
+
{isPending ? (
|
|
86
|
+
<>
|
|
87
|
+
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
|
88
|
+
Sending...
|
|
89
|
+
</>
|
|
90
|
+
) : (
|
|
91
|
+
'Send reset link'
|
|
92
|
+
)}
|
|
93
|
+
</Button>
|
|
94
|
+
</form>
|
|
95
|
+
|
|
96
|
+
<p className="text-center text-sm text-muted-foreground">
|
|
97
|
+
Remembered it?{' '}
|
|
98
|
+
<AppLink
|
|
99
|
+
href={ROUTES.LOGIN}
|
|
100
|
+
className="font-medium text-primary transition-colors duration-150 active:opacity-70 md:hover:text-primary/80"
|
|
101
|
+
>
|
|
102
|
+
Sign in
|
|
103
|
+
</AppLink>
|
|
104
|
+
</p>
|
|
105
|
+
</div>
|
|
106
|
+
);
|
|
107
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import type React from 'react';
|
|
4
|
+
|
|
5
|
+
import { getLimitInfo } from '@/lib/utils/error';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Inline "slow down" message for the auth forms: a rate limit, a login lock or
|
|
9
|
+
* the per-address email cap, with the wait time from the server. Renders
|
|
10
|
+
* nothing for any other error (those keep their toast). The form's request is
|
|
11
|
+
* sent with `skipLimitToast`, so this is the only place the message appears.
|
|
12
|
+
*
|
|
13
|
+
* Building your own login, register or forgot-password screen on useAuth /
|
|
14
|
+
* useForgotPassword? Render this with their error (loginError, registerError,
|
|
15
|
+
* error): for those calls nothing else tells the user to wait.
|
|
16
|
+
*/
|
|
17
|
+
export const LimitNotice = ({ error }: { error: unknown }): React.ReactElement | null => {
|
|
18
|
+
const limit = getLimitInfo(error);
|
|
19
|
+
if (!limit) return null;
|
|
20
|
+
return (
|
|
21
|
+
<p
|
|
22
|
+
role="alert"
|
|
23
|
+
className="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive"
|
|
24
|
+
>
|
|
25
|
+
{limit.message}
|
|
26
|
+
</p>
|
|
27
|
+
);
|
|
28
|
+
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
3
|
import type React from 'react';
|
|
4
|
-
import { Suspense } from 'react';
|
|
4
|
+
import { Suspense, useEffect } from 'react';
|
|
5
5
|
|
|
6
6
|
import { useSearchParams } from 'next/navigation';
|
|
7
7
|
import { useForm } from 'react-hook-form';
|
|
@@ -14,8 +14,10 @@ import { Input } from '@/components/ui/input';
|
|
|
14
14
|
import { Label } from '@/components/ui/label';
|
|
15
15
|
import { AppLink } from '@/components/common/AppLink';
|
|
16
16
|
import { useAuth } from '../hooks/useAuth';
|
|
17
|
+
import { LimitNotice } from './LimitNotice';
|
|
17
18
|
import { ROUTES } from '@/lib/constants/routes';
|
|
18
19
|
import { cn } from '@/lib/utils';
|
|
20
|
+
import { applyFieldErrors } from '@/lib/utils/form';
|
|
19
21
|
import { getSafeRedirectPath } from '@/lib/utils/security';
|
|
20
22
|
|
|
21
23
|
const loginSchema = z.object({
|
|
@@ -26,7 +28,7 @@ const loginSchema = z.object({
|
|
|
26
28
|
type LoginFormData = z.infer<typeof loginSchema>;
|
|
27
29
|
|
|
28
30
|
const LoginFormInner = (): React.ReactElement => {
|
|
29
|
-
const { login, isLoggingIn } = useAuth();
|
|
31
|
+
const { login, isLoggingIn, loginError } = useAuth();
|
|
30
32
|
const searchParams = useSearchParams();
|
|
31
33
|
// `from` is attacker-controllable (anyone can send a /login?from=… link), so
|
|
32
34
|
// only a same-site path is accepted — see getSafeRedirectPath for why a
|
|
@@ -36,11 +38,17 @@ const LoginFormInner = (): React.ReactElement => {
|
|
|
36
38
|
const {
|
|
37
39
|
register,
|
|
38
40
|
handleSubmit,
|
|
41
|
+
setError,
|
|
39
42
|
formState: { errors },
|
|
40
43
|
} = useForm<LoginFormData>({
|
|
41
44
|
resolver: zodResolver(loginSchema),
|
|
42
45
|
});
|
|
43
46
|
|
|
47
|
+
// The server's 422 verdict lands under its field (lib/utils/form.ts).
|
|
48
|
+
useEffect(() => {
|
|
49
|
+
applyFieldErrors(loginError, setError, ['email', 'password']);
|
|
50
|
+
}, [loginError, setError]);
|
|
51
|
+
|
|
44
52
|
const onSubmit = (data: LoginFormData): void => {
|
|
45
53
|
login(data, redirectTo);
|
|
46
54
|
};
|
|
@@ -89,6 +97,9 @@ const LoginFormInner = (): React.ReactElement => {
|
|
|
89
97
|
)}
|
|
90
98
|
</div>
|
|
91
99
|
|
|
100
|
+
{/* Rate limit or login lock, with the wait time (no toast for these). */}
|
|
101
|
+
<LimitNotice error={loginError} />
|
|
102
|
+
|
|
92
103
|
<Button type="submit" className="w-full" disabled={isLoggingIn}>
|
|
93
104
|
{isLoggingIn ? (
|
|
94
105
|
<>
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
3
|
import type React from 'react';
|
|
4
|
+
import { useEffect } from 'react';
|
|
4
5
|
|
|
5
6
|
import { useForm } from 'react-hook-form';
|
|
6
7
|
import { zodResolver } from '@hookform/resolvers/zod';
|
|
@@ -12,20 +13,26 @@ import { Input } from '@/components/ui/input';
|
|
|
12
13
|
import { Label } from '@/components/ui/label';
|
|
13
14
|
import { AppLink } from '@/components/common/AppLink';
|
|
14
15
|
import { useAuth } from '../hooks/useAuth';
|
|
16
|
+
import { LimitNotice } from './LimitNotice';
|
|
15
17
|
import { ROUTES } from '@/lib/constants/routes';
|
|
16
18
|
import { cn } from '@/lib/utils';
|
|
19
|
+
import { applyFieldErrors } from '@/lib/utils/form';
|
|
17
20
|
|
|
21
|
+
// Mirrors the server's registerSchema (server src/modules/auth/auth.schemas.ts),
|
|
22
|
+
// limits and messages alike: change both together. Whatever the server still
|
|
23
|
+
// refuses comes back as a 422 and lands under its field (applyFieldErrors).
|
|
18
24
|
const registerSchema = z
|
|
19
25
|
.object({
|
|
20
|
-
firstName: z.string().min(
|
|
21
|
-
lastName: z.string().min(
|
|
26
|
+
firstName: z.string().trim().min(2, 'First name must be at least 2 characters').max(100, 'First name must be at most 100 characters'),
|
|
27
|
+
lastName: z.string().trim().min(2, 'Last name must be at least 2 characters').max(100, 'Last name must be at most 100 characters'),
|
|
22
28
|
email: z.string().min(1, 'Email is required').email('Invalid email address'),
|
|
23
29
|
password: z
|
|
24
30
|
.string()
|
|
25
|
-
.min(8, '
|
|
26
|
-
.
|
|
27
|
-
.regex(/[
|
|
28
|
-
.regex(/[
|
|
31
|
+
.min(8, 'Password must be at least 8 characters')
|
|
32
|
+
.max(128, 'Password must be at most 128 characters')
|
|
33
|
+
.regex(/[A-Z]/, 'Password must contain at least one uppercase letter')
|
|
34
|
+
.regex(/[a-z]/, 'Password must contain at least one lowercase letter')
|
|
35
|
+
.regex(/[0-9]/, 'Password must contain at least one number'),
|
|
29
36
|
confirmPassword: z.string().min(1, 'Please confirm your password'),
|
|
30
37
|
})
|
|
31
38
|
.refine((data) => data.password === data.confirmPassword, {
|
|
@@ -36,16 +43,22 @@ const registerSchema = z
|
|
|
36
43
|
type RegisterFormData = z.infer<typeof registerSchema>;
|
|
37
44
|
|
|
38
45
|
export const RegisterForm = (): React.ReactElement => {
|
|
39
|
-
const { register: registerUser, isRegistering } = useAuth();
|
|
46
|
+
const { register: registerUser, isRegistering, registerError } = useAuth();
|
|
40
47
|
|
|
41
48
|
const {
|
|
42
49
|
register,
|
|
43
50
|
handleSubmit,
|
|
51
|
+
setError,
|
|
44
52
|
formState: { errors },
|
|
45
53
|
} = useForm<RegisterFormData>({
|
|
46
54
|
resolver: zodResolver(registerSchema),
|
|
47
55
|
});
|
|
48
56
|
|
|
57
|
+
// The server's 422 verdict lands under its field (lib/utils/form.ts).
|
|
58
|
+
useEffect(() => {
|
|
59
|
+
applyFieldErrors(registerError, setError, ['firstName', 'lastName', 'email', 'password']);
|
|
60
|
+
}, [registerError, setError]);
|
|
61
|
+
|
|
49
62
|
const onSubmit = (data: RegisterFormData): void => {
|
|
50
63
|
registerUser({
|
|
51
64
|
firstName: data.firstName,
|
|
@@ -152,6 +165,9 @@ export const RegisterForm = (): React.ReactElement => {
|
|
|
152
165
|
)}
|
|
153
166
|
</div>
|
|
154
167
|
|
|
168
|
+
{/* Rate limit or email cap, with the wait time (no toast for these). */}
|
|
169
|
+
<LimitNotice error={registerError} />
|
|
170
|
+
|
|
155
171
|
<Button type="submit" className="w-full" disabled={isRegistering}>
|
|
156
172
|
{isRegistering ? (
|
|
157
173
|
<>
|
|
@@ -7,7 +7,7 @@ import { toast } from 'sonner';
|
|
|
7
7
|
|
|
8
8
|
import { useAppDispatch, useAppSelector } from '@/store/hooks';
|
|
9
9
|
import { useAppRouter } from '@/hooks/useAppRouter';
|
|
10
|
-
import { getErrorMessage, isErrorCode, ERROR_CODES } from '@/lib/utils/error';
|
|
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';
|
|
@@ -25,6 +25,10 @@ interface UseAuthReturn {
|
|
|
25
25
|
isLoggingIn: boolean;
|
|
26
26
|
isRegistering: boolean;
|
|
27
27
|
isLoggingOut: boolean;
|
|
28
|
+
/** Last login error; the form shows rate-limit and lock answers inline from it. */
|
|
29
|
+
loginError: unknown;
|
|
30
|
+
/** Last register error; the form shows rate-limit answers inline from it. */
|
|
31
|
+
registerError: unknown;
|
|
28
32
|
}
|
|
29
33
|
|
|
30
34
|
export const useAuth = (): UseAuthReturn => {
|
|
@@ -43,6 +47,8 @@ export const useAuth = (): UseAuthReturn => {
|
|
|
43
47
|
router.push(pendingRedirectRef.current);
|
|
44
48
|
},
|
|
45
49
|
onError: (error) => {
|
|
50
|
+
// Rate limit / login lock: LoginForm shows it inline (with the wait), no toast.
|
|
51
|
+
if (isLimitError(error)) return;
|
|
46
52
|
if (isErrorCode(error, ERROR_CODES.ACCOUNT_DEACTIVATED)) {
|
|
47
53
|
toast.error('This account has been deactivated. Contact support if you think this is a mistake.');
|
|
48
54
|
return;
|
|
@@ -71,6 +77,8 @@ export const useAuth = (): UseAuthReturn => {
|
|
|
71
77
|
router.push(ROUTES.DASHBOARD);
|
|
72
78
|
},
|
|
73
79
|
onError: (error) => {
|
|
80
|
+
// Rate limit / email cap: RegisterForm shows it inline (with the wait), no toast.
|
|
81
|
+
if (isLimitError(error)) return;
|
|
74
82
|
toast.error(getErrorMessage(error));
|
|
75
83
|
},
|
|
76
84
|
});
|
|
@@ -106,5 +114,7 @@ export const useAuth = (): UseAuthReturn => {
|
|
|
106
114
|
isLoggingIn: loginMutation.isPending,
|
|
107
115
|
isRegistering: registerMutation.isPending,
|
|
108
116
|
isLoggingOut,
|
|
117
|
+
loginError: loginMutation.error,
|
|
118
|
+
registerError: registerMutation.error,
|
|
109
119
|
};
|
|
110
120
|
};
|
|
@@ -5,12 +5,14 @@ import { toast } from 'sonner';
|
|
|
5
5
|
|
|
6
6
|
import { useAppRouter } from '@/hooks/useAppRouter';
|
|
7
7
|
import { ROUTES } from '@/lib/constants/routes';
|
|
8
|
-
import { getErrorMessage } from '@/lib/utils/error';
|
|
8
|
+
import { getErrorMessage, isLimitError } from '@/lib/utils/error';
|
|
9
9
|
import { authService } from '../services/auth.service';
|
|
10
10
|
|
|
11
11
|
interface UseForgotPasswordReturn {
|
|
12
12
|
forgotPassword: (email: string) => void;
|
|
13
13
|
isPending: boolean;
|
|
14
|
+
/** Last error; ForgotPasswordForm shows rate-limit answers inline from it. */
|
|
15
|
+
error: unknown;
|
|
14
16
|
}
|
|
15
17
|
|
|
16
18
|
export const useForgotPassword = (): UseForgotPasswordReturn => {
|
|
@@ -20,6 +22,8 @@ export const useForgotPassword = (): UseForgotPasswordReturn => {
|
|
|
20
22
|
toast.success('Check your email for reset instructions');
|
|
21
23
|
},
|
|
22
24
|
onError: (error: unknown) => {
|
|
25
|
+
// Rate limit / email cap: shown inline by ForgotPasswordForm, no toast.
|
|
26
|
+
if (isLimitError(error)) return;
|
|
23
27
|
toast.error(getErrorMessage(error));
|
|
24
28
|
},
|
|
25
29
|
});
|
|
@@ -27,6 +31,7 @@ export const useForgotPassword = (): UseForgotPasswordReturn => {
|
|
|
27
31
|
return {
|
|
28
32
|
forgotPassword: mutation.mutate,
|
|
29
33
|
isPending: mutation.isPending,
|
|
34
|
+
error: mutation.error,
|
|
30
35
|
};
|
|
31
36
|
};
|
|
32
37
|
|
|
@@ -46,6 +51,7 @@ export const useResetPassword = (): UseResetPasswordReturn => {
|
|
|
46
51
|
router.push(ROUTES.LOGIN);
|
|
47
52
|
},
|
|
48
53
|
onError: (error: unknown) => {
|
|
54
|
+
if (isLimitError(error)) return; // the global toast already says how long to wait
|
|
49
55
|
toast.error(getErrorMessage(error));
|
|
50
56
|
},
|
|
51
57
|
});
|
|
@@ -10,17 +10,21 @@ interface AuthResponse {
|
|
|
10
10
|
|
|
11
11
|
class AuthService {
|
|
12
12
|
async register(data: IRegisterRequest): Promise<AuthResponse> {
|
|
13
|
+
// skipLimitToast: RegisterForm shows a rate-limit answer inline instead.
|
|
13
14
|
const response = await apiClient.post<ApiResponse<AuthResponse>>(
|
|
14
15
|
API_ENDPOINTS.AUTH.REGISTER,
|
|
15
|
-
data
|
|
16
|
+
data,
|
|
17
|
+
{ skipLimitToast: true }
|
|
16
18
|
);
|
|
17
19
|
return response.data.data;
|
|
18
20
|
}
|
|
19
21
|
|
|
20
22
|
async login(data: ILoginRequest): Promise<AuthResponse> {
|
|
23
|
+
// skipLimitToast: LoginForm shows a rate-limit or lock answer inline instead.
|
|
21
24
|
const response = await apiClient.post<ApiResponse<AuthResponse>>(
|
|
22
25
|
API_ENDPOINTS.AUTH.LOGIN,
|
|
23
|
-
data
|
|
26
|
+
data,
|
|
27
|
+
{ skipLimitToast: true }
|
|
24
28
|
);
|
|
25
29
|
return response.data.data;
|
|
26
30
|
}
|
|
@@ -37,7 +41,8 @@ class AuthService {
|
|
|
37
41
|
}
|
|
38
42
|
|
|
39
43
|
async forgotPassword(email: string): Promise<void> {
|
|
40
|
-
|
|
44
|
+
// skipLimitToast: ForgotPasswordForm shows a rate-limit answer inline instead.
|
|
45
|
+
await apiClient.post(API_ENDPOINTS.AUTH.FORGOT_PASSWORD, { email }, { skipLimitToast: true });
|
|
41
46
|
}
|
|
42
47
|
|
|
43
48
|
async resetPassword(token: string, newPassword: string): Promise<void> {
|
|
@@ -3,7 +3,12 @@ import { createSlice } from '@reduxjs/toolkit';
|
|
|
3
3
|
import type { PayloadAction } from '@reduxjs/toolkit';
|
|
4
4
|
import type { IAuthState, IUser } from '../types/auth.types';
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
/**
|
|
7
|
+
* The state before anything is known. `isInitializing` is true until the
|
|
8
|
+
* start-up "who am I" check answers; makeStore (store/index.ts) starts it as
|
|
9
|
+
* false when the visitor holds no session marker, since then nothing is asked.
|
|
10
|
+
*/
|
|
11
|
+
export const initialAuthState: IAuthState = {
|
|
7
12
|
user: null,
|
|
8
13
|
isAuthenticated: false,
|
|
9
14
|
isInitializing: true,
|
|
@@ -12,7 +17,7 @@ const initialState: IAuthState = {
|
|
|
12
17
|
|
|
13
18
|
const authSlice = createSlice({
|
|
14
19
|
name: 'auth',
|
|
15
|
-
initialState,
|
|
20
|
+
initialState: initialAuthState,
|
|
16
21
|
reducers: {
|
|
17
22
|
setUser: (state, action: PayloadAction<IUser>) => {
|
|
18
23
|
state.user = action.payload;
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
/**
|
|
3
|
+
* The API client's session rules, against a fake transport (an axios adapter):
|
|
4
|
+
* one refresh for parallel 401s, a lost refresh race between tabs, a dead
|
|
5
|
+
* session, a network failure, limits, the start-up probe and a ban mid-session.
|
|
6
|
+
* Each test loads a fresh copy of the module, because the refresh state and the
|
|
7
|
+
* circuit breaker live at module level.
|
|
8
|
+
*/
|
|
9
|
+
import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios';
|
|
10
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
11
|
+
|
|
12
|
+
vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
|
|
13
|
+
vi.mock('@/lib/api/hard-redirect', () => ({ hardRedirect: vi.fn() }));
|
|
14
|
+
|
|
15
|
+
type Handler = (config: InternalAxiosRequestConfig) => { status: number; body?: unknown } | 'network';
|
|
16
|
+
|
|
17
|
+
/** The server's answer for one request: 2xx resolves, anything else rejects like axios' own adapters. */
|
|
18
|
+
function respond(config: InternalAxiosRequestConfig, status: number, body?: unknown): Promise<AxiosResponse> {
|
|
19
|
+
const response: AxiosResponse = { data: body, status, statusText: '', headers: {}, config };
|
|
20
|
+
if (status >= 200 && status < 300) return Promise.resolve(response);
|
|
21
|
+
return Promise.reject(new AxiosError(`Request failed with status code ${status}`, 'ERR_BAD_REQUEST', config, undefined, response));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const fail = (code: string, extra: Record<string, unknown> = {}): unknown => ({ success: false, error: { code, message: code, ...extra } });
|
|
25
|
+
|
|
26
|
+
async function load(handler: Handler) {
|
|
27
|
+
vi.resetModules();
|
|
28
|
+
const { apiClient } = await import('../axios.config');
|
|
29
|
+
const events = await import('../session-events');
|
|
30
|
+
const { hardRedirect } = await import('@/lib/api/hard-redirect');
|
|
31
|
+
const { toast } = await import('sonner');
|
|
32
|
+
const calls: string[] = [];
|
|
33
|
+
const adapter: AxiosAdapter = async (config) => {
|
|
34
|
+
calls.push(`${config.method?.toUpperCase()} ${config.url}`);
|
|
35
|
+
await new Promise((r) => setTimeout(r, 5)); // let parallel requests overlap
|
|
36
|
+
const answer = handler(config);
|
|
37
|
+
if (answer === 'network') throw new AxiosError('Network Error', 'ERR_NETWORK', config);
|
|
38
|
+
return respond(config, answer.status, answer.body);
|
|
39
|
+
};
|
|
40
|
+
apiClient.defaults.adapter = adapter;
|
|
41
|
+
const ended: string[] = [];
|
|
42
|
+
events.onSessionEnded((reason) => ended.push(reason));
|
|
43
|
+
return { apiClient, calls, ended, hardRedirect: vi.mocked(hardRedirect), toastError: vi.mocked(toast.error) };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const count = (calls: string[], call: string): number => calls.filter((c) => c === call).length;
|
|
47
|
+
|
|
48
|
+
beforeEach(() => {
|
|
49
|
+
// Module mocks survive vi.resetModules(): forget the previous test's calls.
|
|
50
|
+
vi.clearAllMocks();
|
|
51
|
+
document.cookie = 'auth_session=1; path=/';
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
describe('expired access token', () => {
|
|
55
|
+
it('parallel 401s share ONE refresh, then every request is replayed', async () => {
|
|
56
|
+
let refreshed = false;
|
|
57
|
+
const t = await load((c) => {
|
|
58
|
+
if (c.url === '/auth/refresh') { refreshed = true; return { status: 200 }; }
|
|
59
|
+
return refreshed ? { status: 200, body: { ok: c.url } } : { status: 401, body: fail('UNAUTHORIZED') };
|
|
60
|
+
});
|
|
61
|
+
const [a, b] = await Promise.all([t.apiClient.get('/a'), t.apiClient.get('/b')]);
|
|
62
|
+
expect([a.data, b.data]).toEqual([{ ok: '/a' }, { ok: '/b' }]);
|
|
63
|
+
expect(count(t.calls, 'POST /auth/refresh')).toBe(1);
|
|
64
|
+
expect(t.ended).toEqual([]);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('a lost refresh race (another tab won) replays the request and keeps the session', async () => {
|
|
68
|
+
let refreshAttempted = false;
|
|
69
|
+
const t = await load((c) => {
|
|
70
|
+
if (c.url === '/auth/refresh') { refreshAttempted = true; return { status: 401, body: fail('REFRESH_TOKEN_ROTATED') }; }
|
|
71
|
+
// The winner's fresh cookies are already in the browser: the replay works.
|
|
72
|
+
return refreshAttempted ? { status: 200, body: 'fresh' } : { status: 401, body: fail('UNAUTHORIZED') };
|
|
73
|
+
});
|
|
74
|
+
const r = await t.apiClient.get('/sessions');
|
|
75
|
+
expect(r.data).toBe('fresh');
|
|
76
|
+
expect(t.ended).toEqual([]);
|
|
77
|
+
expect(t.hardRedirect).not.toHaveBeenCalled();
|
|
78
|
+
expect(document.cookie).toContain('auth_session=1');
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('a lost race also releases the requests queued behind it', async () => {
|
|
82
|
+
let refreshAttempted = false;
|
|
83
|
+
const t = await load((c) => {
|
|
84
|
+
if (c.url === '/auth/refresh') { refreshAttempted = true; return { status: 401, body: fail('REFRESH_TOKEN_ROTATED') }; }
|
|
85
|
+
return refreshAttempted ? { status: 200, body: c.url } : { status: 401, body: fail('UNAUTHORIZED') };
|
|
86
|
+
});
|
|
87
|
+
const results = await Promise.all([t.apiClient.get('/a'), t.apiClient.get('/b')]);
|
|
88
|
+
expect(results.map((r) => r.data)).toEqual(['/a', '/b']);
|
|
89
|
+
expect(count(t.calls, 'POST /auth/refresh')).toBe(1);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('a replay that still gets 401 after a lost race is rejected, not looped', async () => {
|
|
93
|
+
const t = await load((c) =>
|
|
94
|
+
c.url === '/auth/refresh' ? { status: 401, body: fail('REFRESH_TOKEN_ROTATED') } : { status: 401, body: fail('UNAUTHORIZED') },
|
|
95
|
+
);
|
|
96
|
+
await expect(t.apiClient.get('/a')).rejects.toMatchObject({ response: { status: 401 } });
|
|
97
|
+
expect(count(t.calls, 'POST /auth/refresh')).toBe(1);
|
|
98
|
+
expect(count(t.calls, 'GET /a')).toBe(2);
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
describe('a dead session', () => {
|
|
103
|
+
it('a refused refresh signs out, clears the marker and goes to sign-in', async () => {
|
|
104
|
+
const t = await load((c) =>
|
|
105
|
+
c.url === '/auth/refresh' ? { status: 401, body: fail('INVALID_REFRESH_TOKEN') } : { status: 401, body: fail('UNAUTHORIZED') },
|
|
106
|
+
);
|
|
107
|
+
await expect(t.apiClient.get('/sessions')).rejects.toBeTruthy();
|
|
108
|
+
expect(t.ended).toEqual(['expired']);
|
|
109
|
+
expect(t.hardRedirect).toHaveBeenCalledWith('/login');
|
|
110
|
+
expect(document.cookie).not.toContain('auth_session=1');
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('after that, further 401s are rejected without another refresh (circuit breaker)', async () => {
|
|
114
|
+
const t = await load((c) =>
|
|
115
|
+
c.url === '/auth/refresh' ? { status: 401, body: fail('INVALID_REFRESH_TOKEN') } : { status: 401, body: fail('UNAUTHORIZED') },
|
|
116
|
+
);
|
|
117
|
+
await expect(t.apiClient.get('/a')).rejects.toBeTruthy();
|
|
118
|
+
await expect(t.apiClient.get('/b')).rejects.toBeTruthy();
|
|
119
|
+
expect(count(t.calls, 'POST /auth/refresh')).toBe(1);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it('a refresh that never reached the server keeps the session', async () => {
|
|
123
|
+
const t = await load((c) => (c.url === '/auth/refresh' ? 'network' : { status: 401, body: fail('UNAUTHORIZED') }));
|
|
124
|
+
await expect(t.apiClient.get('/a')).rejects.toMatchObject({ code: 'ERR_NETWORK' });
|
|
125
|
+
expect(t.ended).toEqual([]);
|
|
126
|
+
expect(t.hardRedirect).not.toHaveBeenCalled();
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it('the start-up probe finding no session signs out quietly, without leaving the page', async () => {
|
|
130
|
+
const t = await load((c) =>
|
|
131
|
+
c.url === '/auth/refresh' ? { status: 401, body: fail('MISSING_REFRESH_TOKEN') } : { status: 401, body: fail('UNAUTHORIZED') },
|
|
132
|
+
);
|
|
133
|
+
await expect(t.apiClient.get('/auth/me')).rejects.toBeTruthy();
|
|
134
|
+
expect(t.ended).toEqual(['signed-out']);
|
|
135
|
+
expect(t.hardRedirect).not.toHaveBeenCalled();
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
describe('slow down answers', () => {
|
|
140
|
+
it('a 429 shows one toast with the wait and never starts a refresh', async () => {
|
|
141
|
+
const t = await load(() => ({ status: 429, body: fail('RATE_LIMIT_EXCEEDED', { retryAfterSeconds: 60 }) }));
|
|
142
|
+
await expect(t.apiClient.get('/a')).rejects.toBeTruthy();
|
|
143
|
+
expect(t.toastError).toHaveBeenCalledWith('Too many requests. Try again in 1 minute.', { id: 'rate-limit' });
|
|
144
|
+
expect(count(t.calls, 'POST /auth/refresh')).toBe(0);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('skipLimitToast leaves the message to the caller', async () => {
|
|
148
|
+
const t = await load(() => ({ status: 429, body: fail('LOGIN_LOCKED', { retryAfterSeconds: 60 }) }));
|
|
149
|
+
await expect(t.apiClient.post('/auth/login', {}, { skipLimitToast: true })).rejects.toBeTruthy();
|
|
150
|
+
expect(t.toastError).not.toHaveBeenCalled();
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
describe('banned while signed in (403 ACCOUNT_DEACTIVATED)', () => {
|
|
155
|
+
it('ends the session through the logout route ONCE for a burst of calls, then reports it', async () => {
|
|
156
|
+
const t = await load((c) => (c.url === '/auth/logout' ? { status: 200 } : { status: 403, body: fail('ACCOUNT_DEACTIVATED') }));
|
|
157
|
+
const results = await Promise.allSettled([t.apiClient.get('/a'), t.apiClient.get('/b')]);
|
|
158
|
+
expect(results.map((r) => r.status)).toEqual(['rejected', 'rejected']);
|
|
159
|
+
expect(count(t.calls, 'POST /auth/logout')).toBe(1);
|
|
160
|
+
expect(t.ended).toEqual(['deactivated']);
|
|
161
|
+
expect(t.hardRedirect).not.toHaveBeenCalled();
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it('still signs out locally when the logout call itself fails', async () => {
|
|
165
|
+
const t = await load((c) => (c.url === '/auth/logout' ? 'network' : { status: 403, body: fail('ACCOUNT_DEACTIVATED') }));
|
|
166
|
+
await expect(t.apiClient.get('/a')).rejects.toBeTruthy();
|
|
167
|
+
expect(t.ended).toEqual(['deactivated']);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it('a banned account trying to sign in is left to the form (no logout call, no event)', async () => {
|
|
171
|
+
const t = await load(() => ({ status: 403, body: fail('ACCOUNT_DEACTIVATED') }));
|
|
172
|
+
await expect(t.apiClient.post('/auth/login', {})).rejects.toBeTruthy();
|
|
173
|
+
expect(count(t.calls, 'POST /auth/logout')).toBe(0);
|
|
174
|
+
expect(t.ended).toEqual([]);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it('another 403 (a missing role) does not end the session', async () => {
|
|
178
|
+
const t = await load(() => ({ status: 403, body: fail('FORBIDDEN') }));
|
|
179
|
+
await expect(t.apiClient.get('/admin/stats')).rejects.toBeTruthy();
|
|
180
|
+
expect(t.ended).toEqual([]);
|
|
181
|
+
expect(count(t.calls, 'POST /auth/logout')).toBe(0);
|
|
182
|
+
});
|
|
183
|
+
});
|
|
@@ -20,11 +20,25 @@ export interface PaginatedApiResponse<T> {
|
|
|
20
20
|
};
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
/** One wrong input field in a 422 VALIDATION_FAILED answer (never the submitted value). */
|
|
24
|
+
export interface ApiFieldError {
|
|
25
|
+
/** Dot path inside the request part ("email", "address.city"), or the part itself ("body"). */
|
|
26
|
+
field: string;
|
|
27
|
+
message: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
23
30
|
export interface ApiError {
|
|
24
31
|
success: false;
|
|
25
32
|
error: {
|
|
26
33
|
code: string;
|
|
27
34
|
message: string;
|
|
35
|
+
/**
|
|
36
|
+
* Whole seconds until a retry can work. Sent on rate limits (429) and an
|
|
37
|
+
* automatic IP block (403 IP_BLOCKED); see getLimitInfo in lib/utils/error.ts.
|
|
38
|
+
*/
|
|
39
|
+
retryAfterSeconds?: number;
|
|
40
|
+
/** Sent on 422 VALIDATION_FAILED: every wrong field and why; see getFieldErrors. */
|
|
41
|
+
fields?: ApiFieldError[];
|
|
28
42
|
};
|
|
29
43
|
}
|
|
30
44
|
|