Merge branch 'final'

This commit is contained in:
Kirill
2026-05-24 15:49:25 +05:00
32 changed files with 412 additions and 45 deletions
+4
View File
@@ -0,0 +1,4 @@
User-agent: *
Allow: /
Sitemap: https://любимыйкреатив.рф/sitemap.xml
+28
View File
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://любимыйкреатив.рф/</loc>
<priority>1.0</priority>
<changefreq>daily</changefreq>
</url>
<url>
<loc>https://любимыйкреатив.рф/info</loc>
<priority>0.8</priority>
<changefreq>monthly</changefreq>
</url>
<url>
<loc>https://любимыйкреатив.рф/about</loc>
<priority>0.7</priority>
<changefreq>monthly</changefreq>
</url>
<url>
<loc>https://любимыйкреатив.рф/privacy</loc>
<priority>0.5</priority>
<changefreq>yearly</changefreq>
</url>
<url>
<loc>https://любимыйкреатив.рф/terms</loc>
<priority>0.5</priority>
<changefreq>yearly</changefreq>
</url>
</urlset>
+3
View File
@@ -11,12 +11,15 @@ import { NotFoundPage } from '@/pages/not-found'
import { PrivacyPolicyPage } from '@/pages/privacy-policy'
import { ProductPage } from '@/pages/product'
import { TermsPage } from '@/pages/terms'
import { usePageTitleReset } from '@/shared/lib/use-page-title'
import { SkeletonPage } from '@/shared/ui/SkeletonPage'
const AdminLayoutPage = lazy(() => import('@/pages/admin-layout').then((m) => ({ default: m.AdminLayoutPage })))
const MeLayoutPage = lazy(() => import('@/pages/me').then((m) => ({ default: m.MeLayoutPage })))
export function AppRoutes() {
usePageTitleReset()
return (
<MainLayout>
<Routes>
+12 -8
View File
@@ -1,13 +1,14 @@
import type { ReactNode } from 'react'
import { useCallback, useMemo, useRef } from 'react'
import { useMediaQuery } from '@mui/material'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import CardMedia from '@mui/material/CardMedia'
import Chip from '@mui/material/Chip'
import Stack from '@mui/material/Stack'
import Typography from '@mui/material/Typography'
import { useNavigate } from 'react-router-dom'
import { Autoplay } from 'swiper/modules'
import { Swiper, SwiperSlide } from 'swiper/react'
import 'swiper/css'
import type { Product } from '@/entities/product/model/types'
@@ -19,6 +20,7 @@ type Props = { product: Product; mediaHeight?: number; actions?: ReactNode }
export function ProductCard({ product, mediaHeight = 200, actions }: Props) {
const navigate = useNavigate()
const isMobile = useMediaQuery('(max-width:600px)')
const swiperRef = useRef<SwiperType | null>(null)
const imageUrls = useMemo(() => {
const fromImages = (product.images ?? [])
@@ -76,12 +78,14 @@ export function ProductCard({ product, mediaHeight = 200, actions }: Props) {
>
<Box sx={{ position: 'relative' }}>
{imageUrls.length ? (
<Box onMouseMove={onMouseMove} sx={{ height: mediaHeight, overflow: 'hidden' }}>
<Box onMouseMove={!isMobile ? onMouseMove : undefined} sx={{ height: mediaHeight, overflow: 'hidden' }}>
<Swiper
onSwiper={(s) => {
swiperRef.current = s
}}
allowTouchMove={false}
modules={isMobile ? [Autoplay] : undefined}
autoplay={isMobile ? { delay: 3000, disableOnInteraction: false, pauseOnMouseEnter: true } : undefined}
allowTouchMove={!isMobile}
style={{ width: '100%', height: mediaHeight }}
>
{imageUrls.map((url) => (
@@ -150,8 +154,8 @@ export function ProductCard({ product, mediaHeight = 200, actions }: Props) {
)}
</Box>
<CardContent sx={{ flexGrow: 1, p: 2, '&:last-child': { pb: 2 } }}>
<Stack spacing={1.25}>
<Box sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column', p: 2, pb: 2 }}>
<Stack spacing={1.25} sx={{ flexGrow: 1 }}>
{product.category && (
<Chip
label={product.category.name}
@@ -231,15 +235,15 @@ export function ProductCard({ product, mediaHeight = 200, actions }: Props) {
>
{product.shortDescription ?? 'Описание появится позже.'}
</Typography>
</Stack>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mt: 'auto', pt: 0.5 }}>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', pt: 1.5 }}>
<Typography variant="h6" color="primary" sx={{ fontWeight: 700, fontSize: '1.1rem' }}>
{formatPriceRub(product.priceCents)}
</Typography>
{actions}
</Box>
</Stack>
</CardContent>
</Box>
</Card>
)
}
+2
View File
@@ -7,6 +7,7 @@ import * as maplibregl from 'maplibre-gl'
import Map, { Marker } from 'react-map-gl/maplibre'
import { STORE_EMAIL, STORE_PHONE, VK_URL } from '@/shared/config'
import { PICKUP_ADDRESS_FULL, PICKUP_COORDINATES } from '@/shared/constants/pickup-point'
import { usePageTitle } from '@/shared/lib/use-page-title'
const rasterStyle = {
version: 8 as const,
@@ -22,6 +23,7 @@ const rasterStyle = {
}
export function AboutPage() {
usePageTitle('О нас')
const { lat, lng } = PICKUP_COORDINATES
return (
<Box>
+2
View File
@@ -12,9 +12,11 @@ import { Minus, Plus, Trash2 } from 'lucide-react'
import { Link as RouterLink } from 'react-router-dom'
import { fetchMyCart, removeCartItem, setCartQty } from '@/entities/cart/api/cart-api'
import { formatPriceRub } from '@/shared/lib/format-price'
import { usePageTitle } from '@/shared/lib/use-page-title'
import { $user } from '@/shared/model/auth'
export function CartPage() {
usePageTitle('Корзина')
const user = useUnit($user)
const qc = useQueryClient()
+2
View File
@@ -3,6 +3,7 @@ import Container from '@mui/material/Container'
import Divider from '@mui/material/Divider'
import Stack from '@mui/material/Stack'
import Typography from '@mui/material/Typography'
import { usePageTitle } from '@/shared/lib/use-page-title'
import { DeliverySection } from './sections/DeliverySection'
import { HowToOrderSection } from './sections/HowToOrderSection'
import { OrderStatusesSection } from './sections/OrderStatusesSection'
@@ -10,6 +11,7 @@ import { PaymentSection } from './sections/PaymentSection'
import { ReturnsSection } from './sections/ReturnsSection'
export function InfoPage() {
usePageTitle('Информация для покупателей')
return (
<Container maxWidth="lg" sx={{ py: { xs: 4 } }}>
{/* Hero */}
@@ -7,7 +7,8 @@ const methods = [
{
icon: <CreditCard size={18} />,
primary: 'Онлайн-оплата через ЮKassa',
secondary: 'Карты, СБП. Оплата после подтверждения заказа админом. Перенаправление на защищённую платёжную страницу.',
secondary:
'Карты, СБП. Оплата после подтверждения заказа админом. Перенаправление на защищённую платёжную страницу.',
},
{
icon: <Banknote size={18} />,
@@ -39,7 +40,8 @@ export function PaymentSection() {
maxWidth: '56ch',
}}
>
Оплата происходит после подтверждения заказа админом. Вы получите уведомление, когда заказ будет подтверждён и готов к оплате.
Оплата происходит после подтверждения заказа админом. Вы получите уведомление, когда заказ будет подтверждён и
готов к оплате.
</Typography>
<Stack spacing={2}>
@@ -36,7 +36,9 @@ export function ReturnsSection() {
lineHeight: 1.65,
}}
>
Если товар не соответствует описанию или имеет производственный дефект, свяжитесь с нами в течение 7 дней после получения. Мы заменим изделие на аналогичное или вернём деньги. Возврат товара надлежащего качества возможен в течение 14 дней, если изделие не было в употреблении и сохранён его товарный вид.
Если товар не соответствует описанию или имеет производственный дефект, свяжитесь с нами в течение 7 дней
после получения. Мы заменим изделие на аналогичное или вернём деньги. Возврат товара надлежащего качества
возможен в течение 14 дней, если изделие не было в употреблении и сохранён его товарный вид.
</Typography>
</Box>
@@ -58,7 +60,9 @@ export function ReturnsSection() {
lineHeight: 1.65,
}}
>
Мы отвечаем за качество каждого изделия ручной работы. Все дефекты, возникшие не по вине покупателя, устраняются или компенсируются заменой изделия. Если у вас возникли вопросы по качеству напишите нам, и мы решим проблему в кратчайшие сроки.
Мы отвечаем за качество каждого изделия ручной работы. Все дефекты, возникшие не по вине покупателя,
устраняются или компенсируются заменой изделия. Если у вас возникли вопросы по качеству напишите нам, и мы
решим проблему в кратчайшие сроки.
</Typography>
</Box>
</Stack>
@@ -16,6 +16,7 @@ import {
} from '@/entities/user/api/address-api'
import type { ShippingAddress } from '@/entities/user/model/types'
import { AddressFormDialog, type AddressFormValues } from '@/features/address-form'
import { usePageTitle } from '@/shared/lib/use-page-title'
const defaultAddressForm = (isDefault: boolean): AddressFormValues => ({
label: '',
@@ -29,6 +30,7 @@ const defaultAddressForm = (isDefault: boolean): AddressFormValues => ({
})
export function AddressesPage() {
usePageTitle('Адреса доставки')
const queryClient = useQueryClient()
const [open, setOpen] = useState(false)
const [editing, setEditing] = useState<ShippingAddress | null>(null)
@@ -16,6 +16,7 @@ import { fetchMyOrder, postOrderMessage } from '@/entities/order/api/order-api'
import { fetchMyConversations, markOrderMessagesRead } from '@/entities/user/api/messages-api'
import { fetchAdminAvatar } from '@/entities/user/api/user-api'
import { orderStatusLabelRu } from '@/shared/lib/order-status-labels'
import { usePageTitle } from '@/shared/lib/use-page-title'
import { $user } from '@/shared/model/auth'
import { ChatMessageBubble } from '@/shared/ui/ChatMessageBubble'
import { OrderMessageBody } from '@/shared/ui/OrderMessageBody'
@@ -24,6 +25,7 @@ import { RichTextMessageEditor } from '@/shared/ui/RichTextMessageEditor'
import { UserAvatar } from '@/shared/ui/UserAvatar'
export function MessagesPage() {
usePageTitle('Сообщения')
const qc = useQueryClient()
const [selectedId, setSelectedId] = useState<string | null>(null)
const [text, setText] = useState('')
@@ -13,6 +13,7 @@ import {
} from '@/entities/notification/api/notifications-api'
import type { UserNotificationSettings } from '@/entities/notification/api/notifications-api'
import { isSyntheticEmail } from '@/shared/lib/is-synthetic-email'
import { usePageTitle } from '@/shared/lib/use-page-title'
import { $user } from '@/shared/model/auth'
function isOrderStatusChangesOn(s: UserNotificationSettings): boolean {
@@ -27,6 +28,7 @@ const orderStatusChangesPayload = (on: boolean) => ({
})
export function NotificationsPage() {
usePageTitle('Уведомления')
const queryClient = useQueryClient()
const [error, setError] = useState<string | null>(null)
const user = useUnit($user)
@@ -12,8 +12,10 @@ import { ORDER_STATUSES } from '@/shared/constants/order'
import { formatPriceRub } from '@/shared/lib/format-price'
import { groupOrdersByStatus } from '@/shared/lib/group-orders-by-status'
import { orderStatusLabelRu } from '@/shared/lib/order-status-labels'
import { usePageTitle } from '@/shared/lib/use-page-title'
export function OrdersPage() {
usePageTitle('Заказы')
const ordersQuery = useQuery({
queryKey: ['me', 'orders'],
queryFn: fetchMyOrders,
@@ -4,6 +4,7 @@ import Divider from '@mui/material/Divider'
import Stack from '@mui/material/Stack'
import Typography from '@mui/material/Typography'
import { useUnit } from 'effector-react'
import { usePageTitle } from '@/shared/lib/use-page-title'
import { $user } from '@/shared/model/auth'
import { AuthMethodsSection } from './AuthMethodsSection'
import { AvatarSection } from './AvatarSection'
@@ -11,6 +12,7 @@ import { DeleteAccountSection } from './DeleteAccountSection'
import { ProfileSection } from './ProfileSection'
export function SettingsPage() {
usePageTitle('Настройки')
const user = useUnit($user)
if (!user) {
@@ -9,6 +9,7 @@ import {
STORE_OP_ADDR,
STORE_PUBLIC_SITE_URL,
} from '@/shared/config'
import { usePageTitle } from '@/shared/lib/use-page-title'
const SITE_URL = STORE_PUBLIC_SITE_URL || (typeof window !== 'undefined' ? window.location.origin : '')
@@ -90,6 +91,7 @@ const sections = [
]
export function PrivacyPolicyPage() {
usePageTitle('Политика конфиденциальности')
return (
<Box sx={{ maxWidth: 800, mx: 'auto', py: { xs: 3, md: 5 }, px: { xs: 2, md: 0 } }}>
<Typography
@@ -23,6 +23,7 @@ import { ProductReviewsList } from '@/features/product-review'
import { formatPriceRub } from '@/shared/lib/format-price'
import { getOriginalWebpUrl } from '@/shared/lib/get-original-webp-url'
import { reviewsCountRu } from '@/shared/lib/reviews-count-ru'
import { usePageTitle } from '@/shared/lib/use-page-title'
import { $user } from '@/shared/model/auth'
import { OptimizedImage } from '@/shared/ui/OptimizedImage'
@@ -39,6 +40,8 @@ export function ProductPage() {
enabled: Boolean(id),
})
usePageTitle(productQuery.data?.title ?? null)
const imageUrls = useMemo(() => {
const p = productQuery.data
if (!p) return []
+2
View File
@@ -10,6 +10,7 @@ import {
STORE_OP_INN,
STORE_OP_ADDR,
} from '@/shared/config'
import { usePageTitle } from '@/shared/lib/use-page-title'
const SITE_URL = STORE_PUBLIC_SITE_URL || (typeof window !== 'undefined' ? window.location.origin : '')
@@ -147,6 +148,7 @@ const sections = [
]
export function TermsPage() {
usePageTitle('Пользовательское соглашение')
return (
<Box sx={{ maxWidth: 800, mx: 'auto', py: { xs: 3, md: 5 }, px: { xs: 2, md: 0 } }}>
<Typography
+10 -2
View File
@@ -1,5 +1,12 @@
export type StatusColor = 'warning' | 'success' | 'info' | 'error'
export type StatusIconName = 'banknote' | 'check-circle' | 'package-search' | 'package' | 'package-check' | 'store' | 'x-circle'
export type StatusIconName =
| 'banknote'
| 'check-circle'
| 'package-search'
| 'package'
| 'package-check'
| 'store'
| 'x-circle'
export interface OrderStatusData {
code: string
@@ -37,7 +44,8 @@ export const ORDER_STATUS_DATA: ReadonlyArray<OrderStatusData> = [
label: 'Отправлен',
iconName: 'package',
color: 'info',
description: 'Заказ передан в службу доставки. Трек-номер для отслеживания(при наличии) будет указан в сообщении админа.',
description:
'Заказ передан в службу доставки. Трек-номер для отслеживания(при наличии) будет указан в сообщении админа.',
},
{
code: 'READY_FOR_PICKUP',
+22
View File
@@ -0,0 +1,22 @@
import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'
const BASE_TITLE = 'Любимый Креатив — Изделия ручной работы'
let currentTitle: string = BASE_TITLE
export function usePageTitle(title: string | null) {
useEffect(() => {
currentTitle = title ? `${title} — Любимый Креатив` : BASE_TITLE
document.title = currentTitle
}, [title])
}
export function usePageTitleReset() {
const location = useLocation()
useEffect(() => {
document.title = BASE_TITLE
currentTitle = BASE_TITLE
}, [location.pathname])
}
+70 -7
View File
@@ -6,20 +6,47 @@ import { getOrderStatusData, type StatusIconName } from '@/shared/lib/order-stat
const iconMap: Record<StatusIconName, ReactNode> = {
banknote: (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<rect x="2" y="6" width="20" height="12" rx="2" />
<circle cx="12" cy="12" r="3" />
<path d="M6 12h.01M18 12h.01" />
</svg>
),
'check-circle': (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
<polyline points="22 4 12 14.01 9 11.01" />
</svg>
),
'package-search': (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M16 16a4 4 0 1 0 0-8 4 4 0 0 0 0 8z" />
<path d="M19 19l-3-3" />
<path d="M21 10V7a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 7v3" />
@@ -27,14 +54,32 @@ const iconMap: Record<StatusIconName, ReactNode> = {
</svg>
),
package: (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M16.5 9.4l-9-5.19M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
<polyline points="3.27 6.96 12 12.01 20.73 6.96" />
<line x1="12" y1="22.08" x2="12" y2="12" />
</svg>
),
'package-check': (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M16.5 9.4l-9-5.19M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
<polyline points="3.27 6.96 12 12.01 20.73 6.96" />
<line x1="12" y1="22.08" x2="12" y2="12" />
@@ -42,13 +87,31 @@ const iconMap: Record<StatusIconName, ReactNode> = {
</svg>
),
store: (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
<polyline points="9 22 9 12 15 12 15 22" />
</svg>
),
'x-circle': (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="10" />
<path d="M15 9l-6 6M9 9l6 6" />
</svg>
+25
View File
@@ -169,3 +169,28 @@ curl http://127.0.0.1:3333/health
```bash
curl https://craftshop.твой-домен/api/health
```
## 9. Бэкапы БД (systemd timer)
Установить таймер для автоматического бэкапа каждые 6 часов:
```bash
# Установить sqlite3 для безопасного копирования
apt-get install -y sqlite3
# Скопировать unit-файлы
cp /opt/craftshop/scripts/craftshop-backup.service /etc/systemd/system/
cp /opt/craftshop/scripts/craftshop-backup.timer /etc/systemd/system/
systemctl daemon-reload
systemctl enable --now craftshop-backup.timer
# Проверить статус
systemctl list-timers craftshop-backup.timer
# Ручной запуск для проверки
systemctl start craftshop-backup.service
ls /opt/craftshop/server/backups/
```
Бэкапы хранятся 30 дней (настраивается в `scripts/backup-db.sh`).
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env bash
# Backup SQLite database — копирует .db файл с timestamp в директорию бэкапов.
# Вызывается из systemd timer или cron.
#
# Использование: ./scripts/backup-db.sh [path-to-db] [backup-dir] [retention-days]
# По умолчанию: db=server/prisma/prod.db, backup=server/backups, retention=30
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
DB_PATH="${1:-$ROOT/server/prisma/prod.db}"
BACKUP_DIR="${2:-$ROOT/server/backups}"
RETENTION_DAYS="${3:-30}"
if [[ ! -f "$DB_PATH" ]]; then
echo "[$(date -Iseconds)] DB not found: $DB_PATH" >&2
exit 1
fi
mkdir -p "$BACKUP_DIR"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/craftshop_${TIMESTAMP}.db"
# SQLite-safe copy: use .backup to avoid copying a file mid-write
if command -v sqlite3 &>/dev/null; then
sqlite3 "$DB_PATH" ".backup '$BACKUP_FILE'"
else
# Fallback: plain copy (risk of inconsistent state if DB is being written)
cp "$DB_PATH" "$BACKUP_FILE"
fi
# Compress
gzip -f "$BACKUP_FILE"
# Remove old backups
find "$BACKUP_DIR" -name 'craftshop_*.db.gz' -mtime +"$RETENTION_DAYS" -delete
echo "[$(date -Iseconds)] Backup created: ${BACKUP_FILE}.gz"
+7
View File
@@ -0,0 +1,7 @@
[Unit]
Description=Craftshop SQLite Database Backup
After=network.target
[Service]
Type=oneshot
ExecStart=/opt/craftshop/scripts/backup-db.sh /opt/craftshop/server/prisma/prod.db /opt/craftshop/server/backups 30
+9
View File
@@ -0,0 +1,9 @@
[Unit]
Description=Craftshop Database Backup Timer
[Timer]
OnCalendar=*-*-* 00/6:00:00
Persistent=true
[Install]
WantedBy=timers.target
Binary file not shown.
+40 -1
View File
@@ -19,13 +19,14 @@ import { prisma } from './lib/prisma.js'
import { getMaxUploadBodyBytes, getProductImageMaxFileBytes } from './lib/upload-limits.js'
import { registerAuth } from './plugins/auth.js'
import { registerIpGate } from './plugins/ip-gate.js'
import { registerSecurityHeaders } from './plugins/security-headers.js'
import { registerApiRoutes } from './routes/api.js'
import { registerOAuthSocialRoutes } from './routes/oauth-social.js'
import { registerSseRoutes } from './routes/sse.js'
import { registerUploadsResized } from './routes/uploads-resized.js'
import { registerUserNotificationRoutes } from './routes/user/notifications.js'
import { registerUserAddressRoutes } from './routes/user-addresses.js'
import { registerUserCartRoutes } from './routes/user-cart.js'
import { registerSseRoutes } from './routes/sse.js'
import { registerUserMessageRoutes } from './routes/user-messages.js'
import { registerUserOrderRoutes } from './routes/user-orders.js'
import { registerUserPaymentRoutes } from './routes/user-payments.js'
@@ -48,6 +49,44 @@ await fastify.register(cors, {
credentials: true,
})
await registerSecurityHeaders(fastify)
fastify.get('/health', async () => {
try {
await prisma.$queryRaw`SELECT 1`
return { status: 'ok', database: 'connected', uptime: process.uptime() }
} catch {
return { status: 'degraded', database: 'disconnected', uptime: process.uptime() }
}
})
fastify.setErrorHandler(function errorHandler(error, request, reply) {
const isProd = process.env.NODE_ENV === 'production'
if (error.validation) {
return reply.code(400).send({
error: 'Ошибка валидации',
details: isProd ? undefined : error.validation,
})
}
if (error.code === 'FST_ERR_VALIDATION') {
return reply.code(400).send({ error: 'Неверный формат запроса' })
}
if (error.statusCode) {
return reply.code(error.statusCode).send({
error: error.message || 'Произошла ошибка',
})
}
request.log.error(error)
return reply.code(500).send({
error: isProd ? 'Внутренняя ошибка сервера' : error.message,
})
})
await fastify.register(jwt, {
secret: process.env.JWT_SECRET || 'dev-jwt-secret-change-me',
})
+1 -1
View File
@@ -1,5 +1,5 @@
import { createAvatar } from '@dicebear/core'
import { avataaars } from '@dicebear/collection'
import { createAvatar } from '@dicebear/core'
const DEFAULT_STYLE = avataaars
+34 -9
View File
@@ -1,26 +1,51 @@
const windows = new Map()
const MAX_ATTEMPTS = 5
const WINDOW_MS = 60_000
const DEFAULT_MAX_ATTEMPTS = 5
const DEFAULT_WINDOW_MS = 60_000
// Per-endpoint rate limits
const LIMITS = {
login: { maxAttempts: 5, windowMs: 60_000 },
codeRequest: { maxAttempts: 3, windowMs: 60_000 },
codeVerify: { maxAttempts: 5, windowMs: 60_000 },
}
setInterval(() => {
const now = Date.now()
for (const [ip, entry] of windows) {
if (now - entry.start > WINDOW_MS) windows.delete(ip)
if (now - entry.start > DEFAULT_WINDOW_MS) windows.delete(ip)
}
}, 5 * 60_000).unref()
export function checkLoginRateLimit(ip) {
function getKey(ip, scope) {
return `${scope}:${ip}`
}
function checkRateLimit(ip, scope) {
const limit = LIMITS[scope] || { maxAttempts: DEFAULT_MAX_ATTEMPTS, windowMs: DEFAULT_WINDOW_MS }
const key = getKey(ip, scope)
const now = Date.now()
const entry = windows.get(ip)
if (!entry || now - entry.start > WINDOW_MS) {
windows.set(ip, { start: now, count: 1 })
const entry = windows.get(key)
if (!entry || now - entry.start > limit.windowMs) {
windows.set(key, { start: now, count: 1 })
return { allowed: true }
}
entry.count += 1
if (entry.count > MAX_ATTEMPTS) {
const retryAfter = Math.ceil((entry.start + WINDOW_MS - now) / 1000)
if (entry.count > limit.maxAttempts) {
const retryAfter = Math.ceil((entry.start + limit.windowMs - now) / 1000)
return { allowed: false, retryAfter }
}
return { allowed: true }
}
export function checkLoginRateLimit(ip) {
return checkRateLimit(ip, 'login')
}
export function checkCodeRequestRateLimit(ip) {
return checkRateLimit(ip, 'codeRequest')
}
export function checkCodeVerifyRateLimit(ip) {
return checkRateLimit(ip, 'codeVerify')
}
+24
View File
@@ -0,0 +1,24 @@
export async function registerSecurityHeaders(fastify) {
fastify.addHook('onSend', async (request, reply) => {
reply.header('X-Content-Type-Options', 'nosniff')
reply.header('X-Frame-Options', 'DENY')
reply.header('X-XSS-Protection', '0')
reply.header('Referrer-Policy', 'strict-origin-when-cross-origin')
reply.header('Permissions-Policy', 'camera=(), microphone=(), geolocation=()')
const cspDirectives = [
"default-src 'self'",
"script-src 'self' https://*.yookassa.ru https://*.vk.com https://oauth.yandex.ru",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
"img-src 'self' data: blob: https://tile.openstreetmap.org https://*.yookassa.ru https://*.vk.com https://oauth.yandex.ru",
"font-src 'self' https://fonts.gstatic.com",
"connect-src 'self' https://*.yookassa.ru https://*.vk.com https://oauth.yandex.ru",
'frame-src https://*.yookassa.ru',
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
].join('; ')
reply.header('Content-Security-Policy', cspDirectives)
})
}
@@ -1,7 +1,20 @@
import { describe, it, expect } from 'vitest'
import { describe, it, expect, afterEach } from 'vitest'
import { prisma } from '../../lib/prisma.js'
describe('OAuth — User model fields', () => {
const createdIds = []
afterEach(async () => {
for (const id of createdIds) {
try {
await prisma.user.delete({ where: { id } })
} catch {
// Already deleted by another test or cleanup — ignore
}
}
createdIds.length = 0
})
it('stores displayName and avatar fields on User model', async () => {
const user = await prisma.user.create({
data: {
@@ -11,10 +24,10 @@ describe('OAuth — User model fields', () => {
},
})
createdIds.push(user.id)
expect(user.displayName).toBe('Test User')
expect(user.avatar).toBe('https://example.com/avatar.jpg')
await prisma.user.delete({ where: { id: user.id } })
})
it('allows nullable fields', async () => {
@@ -24,9 +37,9 @@ describe('OAuth — User model fields', () => {
},
})
createdIds.push(user.id)
expect(user.displayName).toBeNull()
expect(user.avatar).toBeNull()
await prisma.user.delete({ where: { id: user.id } })
})
})
+7 -2
View File
@@ -1,5 +1,5 @@
import Fastify from 'fastify'
import { EventEmitter } from 'node:events'
import Fastify from 'fastify'
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { buildSseListeners, formatHeartbit, formatSSE, isAdminUser, registerSseRoutes } from '../sse.js'
@@ -84,7 +84,12 @@ describe('buildSseListeners', () => {
it('forwards order:statusChanged to matching userId', () => {
const cleanup = buildSseListeners('user-1', false, eventBus, write)
eventBus.emit('order:statusChanged', { orderId: 'o1', userId: 'user-1', oldStatus: 'PENDING_PAYMENT', newStatus: 'PAID' })
eventBus.emit('order:statusChanged', {
orderId: 'o1',
userId: 'user-1',
oldStatus: 'PENDING_PAYMENT',
newStatus: 'PAID',
})
expect(write).toHaveBeenCalledTimes(1)
expect(write.mock.calls[0][0]).toContain('event: order:statusChanged')
expect(write.mock.calls[0][0]).toContain('"newStatus":"PAID"')
+19 -1
View File
@@ -10,7 +10,7 @@ import {
} from '../lib/auth.js'
import { generateAvatar } from '../lib/generate-avatar.js'
import { prisma } from '../lib/prisma.js'
import { checkLoginRateLimit } from '../lib/rate-limit.js'
import { checkCodeRequestRateLimit, checkCodeVerifyRateLimit, checkLoginRateLimit } from '../lib/rate-limit.js'
export function mapUserForClient(user) {
const adminEmail = normalizeEmail(process.env.ADMIN_EMAIL)
@@ -30,6 +30,15 @@ export async function registerAuthRoutes(fastify) {
const email = normalizeEmail(request.body?.email)
if (!email || !email.includes('@')) return reply.code(400).send({ error: 'Некорректная почта' })
const ip = request.ip
const rate = checkCodeRequestRateLimit(ip)
if (!rate.allowed) {
return reply
.code(429)
.header('Retry-After', String(rate.retryAfter))
.send({ error: `Слишком много запросов. Попробуйте через ${rate.retryAfter} сек.` })
}
const code = await issueEmailCode({ email, purpose: 'login' })
const adminEmail = process.env.ADMIN_EMAIL?.trim().toLowerCase()
@@ -50,6 +59,15 @@ export async function registerAuthRoutes(fastify) {
if (!email || !email.includes('@')) return reply.code(400).send({ error: 'Некорректная почта' })
if (!code || code.length !== 6) return reply.code(400).send({ error: 'Код должен быть из 6 цифр' })
const ip = request.ip
const rate = checkCodeVerifyRateLimit(ip)
if (!rate.allowed) {
return reply
.code(429)
.header('Retry-After', String(rate.retryAfter))
.send({ error: `Слишком много попыток. Попробуйте через ${rate.retryAfter} сек.` })
}
const ok = await verifyEmailCode({ email, purpose: 'login', code })
if (!ok) return reply.code(401).send({ error: 'Неверный или истёкший код' })