Support new backend contracts: single-flight refresh, ad impression tokens, error handling

- apiFetch: proactive refresh, cross-tab single-flight via Web Locks, no logout on transient errors
- AuthContext: save tokens returned on own login change, revoke refresh on logout, sync tabs
- Ads: X-Session-Id, impressionToken in impression/click, IAB viewability, safe http(s) targetUrl
- STOMP: refresh before CONNECT, stop reconnect loop on dead session, /user/queue/errors behind flag
- Auth form: password 8 chars / 72 bytes; 429/413 messages via describeApiError
- My posts with auth + moderation badges; post form step validation and field limits
- Map: escape user text in Yandex hint/template

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-20 02:03:42 +03:00
parent 67de963d6d
commit db37befb8d
34 changed files with 1005 additions and 260 deletions

View File

@@ -1,15 +1,23 @@
import { useState, useEffect, useRef } from 'react';
import { trackAdClick } from '../hooks/useAdClickTracking';
import { useAdImpressionTracking } from '../hooks/useAdImpressionTracking';
import { useState, useEffect, useRef, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { trackAdClick, trackAdImpression } from '../api/adsApi';
import { useAdViewability } from '../hooks/useAdViewability';
import { toSafeHttpUrl } from '../utils/safeUrl';
const SKIP_DELAY_SECONDS = 5;
export default function AdCard({ ad, onClose }) {
const { t } = useTranslation();
const [remaining, setRemaining] = useState(SKIP_DELAY_SECONDS);
const cardRef = useRef(null);
const videoRef = useRef(null);
// targetUrl приходит из данных: открываем только абсолютный http(s),
// "javascript:"/"data:" и относительные ссылки отбрасываем.
const targetUrl = toSafeHttpUrl(ad.targetUrl);
useAdImpressionTracking(cardRef, ad.advertisingId);
// Показ засчитывается, когда ≥ 50% баннера видно ≥ 1 с (а не при выдаче).
const handleViewable = useCallback(() => trackAdImpression(ad), [ad]);
useAdViewability(cardRef, handleViewable);
useEffect(() => {
if (remaining <= 0) return;
@@ -43,43 +51,56 @@ export default function AdCard({ ad, onClose }) {
return () => observer.disconnect();
}, []);
const handleClick = () => {
trackAdClick(ad.advertisingId);
window.open(ad.targetUrl, '_blank', 'noopener,noreferrer');
};
// Переход делает сам <a target="_blank" rel="noopener noreferrer"> — клик
// только учитываем. Так ссылка работает с клавиатуры и средней кнопкой мыши.
const handleClick = () => trackAdClick(ad);
const media = ad.type === 'VIDEO' ? (
<video
ref={videoRef}
src={ad.mediaUrl}
className="ad-card__media"
muted
autoPlay
playsInline
loop
preload="metadata"
aria-label={t('ads.label')}
/>
) : (
<img
src={ad.mediaUrl}
alt={t('ads.label')}
className="ad-card__media"
decoding="async"
/>
);
return (
<div ref={cardRef} className="ad-card">
<span className="ad-card__label">Реклама</span>
<span className="ad-card__label">{t('ads.label')}</span>
{ad.type === 'VIDEO' ? (
<video
ref={videoRef}
src={ad.mediaUrl}
className="ad-card__media"
muted
autoPlay
playsInline
loop
preload="auto"
{targetUrl ? (
<a
href={targetUrl}
target="_blank"
rel="noopener noreferrer sponsored"
className="ad-card__link"
onClick={handleClick}
/>
) : (
<img
src={ad.mediaUrl}
alt="Реклама"
className="ad-card__media"
onClick={handleClick}
/>
)}
onAuxClick={handleClick}
aria-label={t('ads.openLink')}
>
{media}
</a>
) : media}
{remaining > 0 ? (
<span className="ad-card__skip-timer">Закрыть через {remaining}с</span>
<span className="ad-card__skip-timer">{t('ads.closeIn', { seconds: remaining })}</span>
) : (
<button className="ad-card__close" onClick={onClose} aria-label="Закрыть рекламу">
<button type="button" className="ad-card__close" onClick={onClose} aria-label={t('ads.close')}>
✕
</button>
)}
</div>
);
}
}

View File

@@ -1,7 +1,5 @@
import { useEffect, useRef, useState } from 'react';
import { API_URL } from '../config/authConstants';
import { getAccessToken } from '../api/apiClient';
import { normalizeMediaUrl } from '../api/adsApi';
import { getNextAd } from '../api/adsApi';
import AdCard from './AdCard';
export default function AdSlot() {
@@ -17,29 +15,20 @@ export default function AdSlot() {
if (!node) return;
let cancelled = false;
const controller = new AbortController();
const observer = new IntersectionObserver(
([entry]) => {
if (!entry.isIntersecting) return;
observer.disconnect();
const token = getAccessToken();
fetch(`${API_URL}/api/ads/next`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
})
.then((res) => {
// 204 No Content — свободных объявлений нет
if (res.status === 204) return null;
if (!res.ok) throw new Error(`Error ${res.status}`);
return res.json();
})
// Выдача — ещё не показ: показ засчитывается в AdCard, когда
// баннер реально виден (useAdViewability).
getNextAd(controller.signal)
.then((data) => {
if (cancelled) return;
if (!data) {
setEmpty(true);
return;
}
if (data.mediaUrl) data.mediaUrl = normalizeMediaUrl(data.mediaUrl);
setAd(data);
// null — 204 (нет кандидатов, лимит, пауза между показами) или 429
if (!data) setEmpty(true);
else setAd(data);
})
.catch(() => {
if (!cancelled) setEmpty(true);
@@ -51,6 +40,7 @@ export default function AdSlot() {
observer.observe(node);
return () => {
cancelled = true;
controller.abort();
observer.disconnect();
};
}, [closed]);

View File

@@ -4,6 +4,8 @@ import { useTranslation } from 'react-i18next';
import CloseIcon from "./icons/CloseIcon";
import { useAuthContext } from "../context/AuthContext";
import { login as apiLogin, register as apiRegister } from "../api/apiClient";
import { describeApiError } from "../api/apiErrors";
import { validatePassword } from "../utils/passwordPolicy";
/**
* AuthModal — модальное окно входа и регистрации прямо на странице ленты.
@@ -63,13 +65,13 @@ function LoginFormInline({ saveAuth, onClose, onSwitch }) {
setLoading(true); setError("");
try {
const { token, refreshToken, user } = await apiLogin(
login, password, t('auth.invalidCredentials')
);
const { token, refreshToken, user } = await apiLogin(login, password);
saveAuth(user, token, refreshToken);
onClose();
} catch (err) {
setError(err.message);
// 400 — неверные данные (текст с сервера), 429 — лимит попыток или
// блокировка аккаунта на 15 минут после 10 неудачных входов
setError(describeApiError(err, t('auth.invalidCredentials')));
} finally {
setLoading(false);
}
@@ -85,7 +87,8 @@ function LoginFormInline({ saveAuth, onClose, onSwitch }) {
placeholder={t('auth.yourLogin')}
value={login}
onChange={e => { setLogin(e.target.value); setError(""); }}
autoComplete="off"
autoComplete="username"
autoCapitalize="none"
/>
</div>
@@ -95,6 +98,7 @@ function LoginFormInline({ saveAuth, onClose, onSwitch }) {
className="f-m-field"
type="password"
placeholder={t('auth.yourPassword')}
autoComplete="current-password"
value={password}
onChange={e => { setPassword(e.target.value); setError(""); }}
/>
@@ -136,7 +140,8 @@ function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
if (!form.name.trim()) e.name = t('auth.validateNameRequired');
if (!form.login.trim()) e.login = t('auth.validateLoginRequired');
else if (form.login.length < 3) e.login = t('auth.loginMinChars');
if (form.password.length < 6) e.password = t('auth.validatePasswordMin');
const passwordError = validatePassword(form.password);
if (passwordError) e.password = passwordError;
if (form.password !== form.password2) e.password2 = t('auth.validatePasswordMatch');
setErrors(e);
return !Object.keys(e).length;
@@ -147,21 +152,24 @@ function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
if (!validate()) return;
setLoading(true); setError("");
let registered = false;
try {
await apiRegister(form.name, form.login, form.password, t('auth.registrationError'));
let session;
try {
session = await apiLogin(form.login, form.password, t('auth.autoLoginFailed'));
} catch {
throw new Error(t('auth.accountCreatedLoginManually'));
// Регистрация сразу возвращает {token, refreshToken, user}. Отдельный
// вход нужен только если бэкенд их не прислал — лишний запрос к
// /auth/login тратил бы лимит попыток входа.
let session = await apiRegister(form.name, form.login, form.password);
registered = true;
if (!session?.token) {
session = await apiLogin(form.login, form.password);
}
const { token, refreshToken, user } = session;
saveAuth(user, token, refreshToken);
onClose();
} catch (err) {
setError(err.message);
setError(registered
? t('auth.accountCreatedLoginManually')
: describeApiError(err, t('auth.registrationError')));
} finally {
setLoading(false);
}
@@ -187,6 +195,8 @@ function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
className={`f-m-field${errors.login ? " err" : ""}`}
type="text"
placeholder={t('auth.loginPlaceholder')}
autoComplete="username"
autoCapitalize="none"
value={form.login}
onChange={e => setField("login", e.target.value)}
/>
@@ -200,6 +210,7 @@ function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
className={`f-m-field${errors.password ? " err" : ""}`}
type="password"
placeholder={t('auth.passwordMinShort')}
autoComplete="new-password"
value={form.password}
onChange={e => setField("password", e.target.value)}
/>
@@ -211,6 +222,7 @@ function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
className={`f-m-field${errors.password2 ? " err" : ""}`}
type="password"
placeholder={t('auth.repeatPlaceholder')}
autoComplete="new-password"
value={form.password2}
onChange={e => setField("password2", e.target.value)}
/>

View File

@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { openExternalUrl } from "../utils/safeUrl";
const SKIP_DELAY_SECONDS = 5;
@@ -18,6 +19,26 @@ export default function FullscreenAdOverlay({ ad, onClose }) {
const [remaining, setRemaining] = useState(SKIP_DELAY_SECONDS);
const [soundOn, setSoundOn] = useState(false);
const videoRef = useRef(null);
const closeRef = useRef(null);
const canClose = remaining <= 0;
// Фон под оверлеем не скроллится (на iOS иначе «уезжает» лента)
useEffect(() => {
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => { document.body.style.overflow = prev; };
}, []);
// Esc закрывает, как только появилась кнопка закрытия; фокус — на неё
useEffect(() => {
if (!canClose) return;
closeRef.current?.focus();
const onKey = (e) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [canClose, onClose]);
useEffect(() => {
if (remaining <= 0) return;
@@ -54,9 +75,8 @@ export default function FullscreenAdOverlay({ ad, onClose }) {
const handleVideoClick = () => {
videoRef.current?.play().catch(() => {});
if (ad.targetUrl) {
window.open(ad.targetUrl, "_blank", "noopener,noreferrer");
}
// Только абсолютный http(s): targetUrl — данные с сервера
openExternalUrl(ad.targetUrl);
};
const handleToggleSound = (e) => {
@@ -70,7 +90,7 @@ export default function FullscreenAdOverlay({ ad, onClose }) {
};
return (
<div className="fs-ad-overlay">
<div className="fs-ad-overlay" role="dialog" aria-modal="true" aria-label={t('fullscreenAd.label')}>
<span className="fs-ad-label">{t('fullscreenAd.label')}</span>
<video
ref={(node) => {
@@ -95,12 +115,13 @@ export default function FullscreenAdOverlay({ ad, onClose }) {
>
{soundOn ? "🔊" : "🔇"}
</button>
{remaining > 0 ? (
{!canClose ? (
<span className="fs-ad-skip-timer">
{t('fullscreenAd.closeIn', { seconds: remaining })}
</span>
) : (
<button
ref={closeRef}
type="button"
className="fs-ad-close"
onClick={onClose}

View File

@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
import { API_URL, getImageUrl } from "../config/authConstants";
import { useGeolocation, GEO_STATUS } from "../hooks/useGeolocation";
import { whenYmapsReady } from "../utils/ymapsApi";
import { escapeCssUrl, escapeHtml } from "../utils/escapeHtml";
const MARKER_COLORS = {
LOST: "#ff3b30",
@@ -12,7 +13,7 @@ const MARKER_COLORS = {
function createMarkerLayout(color, imageUrl) {
const bgStyle = imageUrl
? `background-image:url('${imageUrl}');background-size:cover;background-position:center;`
? `background-image:url('${escapeCssUrl(imageUrl)}');background-size:cover;background-position:center;`
: "";
return window.ymaps.templateLayoutFactory.createClass(
@@ -89,7 +90,9 @@ function createPostPlacemark(m) {
return new window.ymaps.Placemark(
[m.latitude, m.longitude],
{},
// hintContent — свойство метки (не опция) и рендерится как HTML:
// заголовок объявления — пользовательский текст, экранируем.
{ hintContent: escapeHtml(m.title || typeLabel) },
{
iconLayout,
iconImageSize: [40, 40],
@@ -104,7 +107,6 @@ function createPostPlacemark(m) {
},
hasBalloon: false,
hasHint: true,
hintContent: m.title || typeLabel,
}
);
}

View File

@@ -3,6 +3,7 @@ import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useTranslation } from "react-i18next";
import { isSafeHttpUrl } from "../../utils/safeUrl";
import CloseIcon from "../icons/CloseIcon";
import {
createAdvertising,
@@ -55,7 +56,9 @@ export default function AdvertisingCreateModal({ campaignId, onClose, onCreated
const schema = useMemo(
() => z.object({
type: z.enum(["IMAGE", "VIDEO"]),
targetUrl: z.string().trim().url(t("adminPanel.urlInvalid")),
// Бэкенд принимает только абсолютный http(s) (иначе 400): z.url()
// пропустил бы и "javascript:", и "ftp:"
targetUrl: z.string().trim().refine(isSafeHttpUrl, t("adminPanel.urlInvalid")),
weight: z.coerce.number().int(t("adminPanel.weightInvalid")).positive(t("adminPanel.weightInvalid")),
}),
[t]

View File

@@ -3,6 +3,7 @@ import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useTranslation } from "react-i18next";
import { isSafeHttpUrl } from "../../utils/safeUrl";
import CloseIcon from "../icons/CloseIcon";
import { updateAdvertising } from "../../api/adminAdsApi";
@@ -18,7 +19,9 @@ export default function AdvertisingEditModal({ ad, onClose, onUpdated }) {
const schema = useMemo(
() => z.object({
targetUrl: z.string().trim().url(t("adminPanel.urlInvalid")),
// Бэкенд принимает только абсолютный http(s) (иначе 400): z.url()
// пропустил бы и "javascript:", и "ftp:"
targetUrl: z.string().trim().refine(isSafeHttpUrl, t("adminPanel.urlInvalid")),
weight: z.coerce.number().int(t("adminPanel.weightInvalid")).positive(t("adminPanel.weightInvalid")),
}),
[t]