Implement rate limiting and enhance authentication flow
- Added rate limiting configuration for authentication endpoints, allowing customizable request limits via environment variables. - Updated authentication flow to utilize HttpRequest for cookie management, ensuring secure handling of refresh tokens. - Introduced a new endpoint to retrieve user subscription details. - Enhanced the handling of Telegram bot token validation to prevent errors with empty tokens. - Updated the application to serialize enums as strings for better documentation and compatibility with TypeScript. - Improved test coverage for new features and adjustments in command handlers.
This commit is contained in:
@@ -0,0 +1,146 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { QRCodeSVG } from 'qrcode.react'
|
||||
import { Copy, QrCode, RefreshCw, Trash2 } from 'lucide-react'
|
||||
import { toast } from '@/shared/ui/toast-store'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/shared/ui/card'
|
||||
import { Badge } from '@/shared/ui/badge'
|
||||
import { Button } from '@/shared/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/shared/ui/dialog'
|
||||
import { HttpError } from '@/shared/api/client'
|
||||
import { formatBytes } from '@/shared/lib/format'
|
||||
import type { ConfigStatus, VpnConfigDto } from '@/shared/api/types'
|
||||
import { getConfigLink, revokeConfig, rotateConfig } from './api'
|
||||
|
||||
const STATUS_VARIANT: Record<ConfigStatus, 'success' | 'warning' | 'destructive'> = {
|
||||
Active: 'success',
|
||||
Disabled: 'warning',
|
||||
Expired: 'destructive',
|
||||
LimitReached: 'destructive',
|
||||
Revoked: 'destructive',
|
||||
}
|
||||
|
||||
export function ConfigCard({ config }: { config: VpnConfigDto }) {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const [detailsOpen, setDetailsOpen] = useState(false)
|
||||
|
||||
const linkQuery = useQuery({
|
||||
queryKey: ['config-link', config.id],
|
||||
queryFn: () => getConfigLink(config.id),
|
||||
enabled: detailsOpen,
|
||||
})
|
||||
|
||||
const rotateMutation = useMutation({
|
||||
mutationFn: () => rotateConfig(config.id),
|
||||
onSuccess: async () => {
|
||||
toast.success(t('configs.rotated'))
|
||||
await queryClient.invalidateQueries({ queryKey: ['my-configs'] })
|
||||
await queryClient.invalidateQueries({ queryKey: ['config-link', config.id] })
|
||||
},
|
||||
onError: () => toast.error(t('auth.genericError')),
|
||||
})
|
||||
|
||||
const revokeMutation = useMutation({
|
||||
mutationFn: () => revokeConfig(config.id),
|
||||
onSuccess: async () => {
|
||||
toast.success(t('configs.revoked'))
|
||||
setDetailsOpen(false)
|
||||
await queryClient.invalidateQueries({ queryKey: ['my-configs'] })
|
||||
},
|
||||
onError: () => toast.error(t('auth.genericError')),
|
||||
})
|
||||
|
||||
const copy = async (value: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value)
|
||||
toast.success(t('configs.copied'))
|
||||
} catch {
|
||||
toast.error(t('auth.genericError'))
|
||||
}
|
||||
}
|
||||
|
||||
const isActive = config.status === 'Active'
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
<CardHeader className="flex-row items-start justify-between gap-2 space-y-0">
|
||||
<div>
|
||||
<CardTitle className="text-base">{config.label ?? config.location}</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">{config.location}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline">{config.protocol}</Badge>
|
||||
<Badge variant={STATUS_VARIANT[config.status]}>{t(`configs.status.${config.status}`)}</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<div className="flex justify-between text-sm text-muted-foreground">
|
||||
<span>
|
||||
↑ {formatBytes(config.usedUpBytes)} ↓ {formatBytes(config.usedDownBytes)}
|
||||
</span>
|
||||
<span>{config.deviceLimit > 0 ? t('configs.deviceLimit', { count: config.deviceLimit }) : t('configs.deviceLimitUnlimited')}</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" variant="outline" onClick={() => setDetailsOpen(true)}>
|
||||
<QrCode className="h-4 w-4" />
|
||||
{t('configs.showLink')}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" disabled={!isActive || rotateMutation.isPending} onClick={() => rotateMutation.mutate()}>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
{t('configs.rotate')}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={config.status === 'Revoked' || revokeMutation.isPending}
|
||||
onClick={() => {
|
||||
if (confirm(t('configs.confirmRevoke'))) revokeMutation.mutate()
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={detailsOpen} onOpenChange={setDetailsOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{config.label ?? config.location}</DialogTitle>
|
||||
</DialogHeader>
|
||||
{linkQuery.isLoading && <p className="text-sm text-muted-foreground">{t('configs.loadingLink')}</p>}
|
||||
{linkQuery.isError && (
|
||||
<p className="text-sm text-red-500">
|
||||
{linkQuery.error instanceof HttpError ? linkQuery.error.detail : t('auth.genericError')}
|
||||
</p>
|
||||
)}
|
||||
{linkQuery.data && (
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<QRCodeSVG value={linkQuery.data.connectionString} size={200} />
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<code className="flex-1 truncate rounded-md bg-muted px-2 py-1.5 text-xs">
|
||||
{linkQuery.data.connectionString}
|
||||
</code>
|
||||
<Button size="icon" variant="outline" onClick={() => void copy(linkQuery.data!.connectionString)}>
|
||||
<Copy className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t('configs.subscriptionLink')}</p>
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<code className="flex-1 truncate rounded-md bg-muted px-2 py-1.5 text-xs">
|
||||
{linkQuery.data.subscriptionUrl}
|
||||
</code>
|
||||
<Button size="icon" variant="outline" onClick={() => void copy(linkQuery.data!.subscriptionUrl)}>
|
||||
<Copy className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Plus } from 'lucide-react'
|
||||
import { toast } from '@/shared/ui/toast-store'
|
||||
import { Button } from '@/shared/ui/button'
|
||||
import { Input } from '@/shared/ui/input'
|
||||
import { Label } from '@/shared/ui/label'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/shared/ui/dialog'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'
|
||||
import { HttpError } from '@/shared/api/client'
|
||||
import { createConfig, listAvailableInbounds } from './api'
|
||||
|
||||
export function CreateConfigDialog() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [inboundId, setInboundId] = useState('')
|
||||
const [label, setLabel] = useState('')
|
||||
const [deviceLimit, setDeviceLimit] = useState('')
|
||||
|
||||
const inboundsQuery = useQuery({ queryKey: ['available-inbounds'], queryFn: listAvailableInbounds, enabled: open })
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: () => createConfig(inboundId, label.trim() || undefined, deviceLimit ? Number(deviceLimit) : undefined),
|
||||
onSuccess: async () => {
|
||||
toast.success(t('configs.created'))
|
||||
await queryClient.invalidateQueries({ queryKey: ['my-configs'] })
|
||||
setOpen(false)
|
||||
setInboundId('')
|
||||
setLabel('')
|
||||
setDeviceLimit('')
|
||||
},
|
||||
onError: (error) => {
|
||||
const message =
|
||||
error instanceof HttpError && error.status === 409 ? t('configs.quotaExceeded') : t('auth.genericError')
|
||||
toast.error(message)
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="h-4 w-4" />
|
||||
{t('configs.create')}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('configs.create')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
if (inboundId) createMutation.mutate()
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>{t('configs.location')}</Label>
|
||||
<Select value={inboundId} onValueChange={setInboundId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('configs.selectLocation')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{inboundsQuery.data?.map((inbound) => (
|
||||
<SelectItem key={inbound.inboundId} value={inbound.inboundId}>
|
||||
{inbound.displayName} ({inbound.protocol})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{inboundsQuery.data?.length === 0 && (
|
||||
<p className="text-xs text-muted-foreground">{t('configs.noInboundsAvailable')}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="label">{t('configs.label')}</Label>
|
||||
<Input id="label" value={label} onChange={(e) => setLabel(e.target.value)} />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="deviceLimit">{t('configs.deviceLimitLabel')}</Label>
|
||||
<Input
|
||||
id="deviceLimit"
|
||||
type="number"
|
||||
min={0}
|
||||
placeholder={t('configs.deviceLimitPlaceholder')}
|
||||
value={deviceLimit}
|
||||
onChange={(e) => setDeviceLimit(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" disabled={!inboundId || createMutation.isPending}>
|
||||
{t('configs.create')}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { QRCodeSVG } from 'qrcode.react'
|
||||
import { Copy } from 'lucide-react'
|
||||
import { toast } from '@/shared/ui/toast-store'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/shared/ui/card'
|
||||
import { Button } from '@/shared/ui/button'
|
||||
import { getMySubscription } from './api'
|
||||
|
||||
export function SubscriptionCard() {
|
||||
const { t } = useTranslation()
|
||||
const { data, isLoading } = useQuery({ queryKey: ['my-subscription'], queryFn: getMySubscription })
|
||||
|
||||
const copy = async () => {
|
||||
if (!data) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(data.subscriptionUrl)
|
||||
toast.success(t('configs.copied'))
|
||||
} catch {
|
||||
toast.error(t('auth.genericError'))
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading || !data) return null
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">{t('configs.aggregatedSubscription')}</CardTitle>
|
||||
<CardDescription>{t('configs.aggregatedSubscriptionHint')}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex items-center gap-4">
|
||||
<QRCodeSVG value={data.subscriptionUrl} size={96} />
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<code className="truncate rounded-md bg-muted px-2 py-1.5 text-xs">{data.subscriptionUrl}</code>
|
||||
<Button size="sm" variant="outline" className="self-start" onClick={() => void copy()}>
|
||||
<Copy className="h-4 w-4" />
|
||||
{t('configs.copyLink')}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { apiRequest } from '@/shared/api/client'
|
||||
import type {
|
||||
AvailableInboundDto,
|
||||
ConfigLinkDto,
|
||||
GetMyConfigsResult,
|
||||
MySubscriptionDto,
|
||||
VpnConfigDto,
|
||||
} from '@/shared/api/types'
|
||||
|
||||
export function listAvailableInbounds() {
|
||||
return apiRequest<AvailableInboundDto[]>('/inbounds/available')
|
||||
}
|
||||
|
||||
export function getMyConfigs() {
|
||||
return apiRequest<GetMyConfigsResult>('/configs')
|
||||
}
|
||||
|
||||
export function createConfig(inboundId: string, label: string | undefined, deviceLimit: number | undefined) {
|
||||
return apiRequest<VpnConfigDto>('/configs', {
|
||||
method: 'POST',
|
||||
body: { inboundId, label: label ?? null, deviceLimit: deviceLimit ?? null },
|
||||
})
|
||||
}
|
||||
|
||||
export function editConfig(id: string, label: string | undefined, deviceLimit: number | undefined) {
|
||||
return apiRequest<VpnConfigDto>(`/configs/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: { label: label ?? null, deviceLimit: deviceLimit ?? null },
|
||||
})
|
||||
}
|
||||
|
||||
export function rotateConfig(id: string) {
|
||||
return apiRequest<VpnConfigDto>(`/configs/${id}/rotate`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export function revokeConfig(id: string) {
|
||||
return apiRequest<void>(`/configs/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export function getConfigLink(id: string) {
|
||||
return apiRequest<ConfigLinkDto>(`/configs/${id}/link`)
|
||||
}
|
||||
|
||||
export function getMySubscription() {
|
||||
return apiRequest<MySubscriptionDto>('/subscription')
|
||||
}
|
||||
Reference in New Issue
Block a user