fixed show phone number

This commit is contained in:
SlimusMinus
2026-10-27 22:49:16 +03:00
parent aa7c9f25f0
commit 1cd72fbec4
27 changed files with 1054 additions and 15 deletions

View File

@@ -6,6 +6,7 @@ import com.krylov.refound.config.MinioProperties;
import com.krylov.refound.ratelimit.RateLimitProperties;
import com.krylov.refound.search.SearchProperties;
import com.krylov.refound.service.advertising.AdsProperties;
import com.krylov.refound.service.phone.PhoneRevealProperties;
import io.awspring.cloud.autoconfigure.s3.S3AutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -19,7 +20,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class }
)@EnableScheduling
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class,
SearchProperties.class, RateLimitProperties.class, AdsProperties.class})
SearchProperties.class, RateLimitProperties.class, AdsProperties.class, PhoneRevealProperties.class})
@EnableRetry
public class ReFoundApplication {

View File

@@ -0,0 +1,61 @@
package com.krylov.refound.controller;
import com.krylov.refound.dto.PhoneRevealRequest;
import com.krylov.refound.dto.PhoneRevealResponse;
import com.krylov.refound.entity.User;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.service.UserService;
import com.krylov.refound.service.phone.PhoneRevealService;
import com.krylov.refound.service.phone.ProofOfWorkService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Показ номера автора: сначала задача proof-of-work, затем номер в обмен на
* решение. Оба эндпоинта публичные — позвонить можно без регистрации.
* IP — {@code request.getRemoteAddr()}, за прокси восстанавливается из
* X-Forwarded-For (server.forward-headers-strategy).
*/
@RestController
@RequestMapping("/api/v1/posts/{id:\\d+}/phone")
@RequiredArgsConstructor
public class PhoneRevealController {
private final PhoneRevealService phoneRevealService;
private final UserService userService;
@GetMapping("/challenge")
public ResponseEntity<ProofOfWorkService.Challenge> challenge(@PathVariable Long id, HttpServletRequest request) {
return ResponseEntity.ok()
.cacheControl(CacheControl.noStore())
.body(phoneRevealService.challenge(id, request.getRemoteAddr()));
}
@PostMapping
public ResponseEntity<PhoneRevealResponse> reveal(@PathVariable Long id, @RequestBody PhoneRevealRequest body,
HttpServletRequest request) {
String phone = phoneRevealService.reveal(id, body.salt(), body.number(), body.signature(),
request.getRemoteAddr(), currentUserId());
return ResponseEntity.ok()
.cacheControl(CacheControl.noStore())
.body(new PhoneRevealResponse(phone));
}
/** id пользователя с токеном или null для анонимного запроса. */
private Long currentUserId() {
try {
User user = userService.getCurrentUser();
return user == null ? null : user.getId();
} catch (ApiException e) {
return null;
}
}
}

View File

@@ -90,11 +90,13 @@ public class PostController {
@PutMapping(value = "/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public PostResponse update(@PathVariable Long id, @RequestParam String type, @RequestParam String title, @RequestParam(required = false) String address,
@RequestParam(required = false) Double latitude, @RequestParam(required = false) Double longitude, @RequestParam(required = false) String description,
@RequestParam(required = false) String category, @RequestParam(required = false) String phone, @RequestParam(required = false) Boolean reward,
@RequestParam(required = false) String category, @RequestParam(required = false) String phone,
@RequestParam(required = false) Boolean phoneVisible, @RequestParam(required = false) Boolean reward,
@RequestParam(required = false) String rewardText,
@RequestParam(value = "images", required = false) List<MultipartFile> images, @RequestParam(value = "existingImages", required = false) String existingImagesJson) {
log.info("update post {}", id);
return service.update(id, type, title, address, latitude, longitude, description, category, phone, reward, rewardText, images, existingImagesJson);
return service.update(id, type, title, address, latitude, longitude, description, category, phone, phoneVisible, reward, rewardText, images,
existingImagesJson);
}
@DeleteMapping("/{id}")

View File

@@ -0,0 +1,5 @@
package com.krylov.refound.dto;
/** Решение proof-of-work задачи из GET /api/v1/posts/{id}/phone/challenge. */
public record PhoneRevealRequest(String salt, Long number, String signature) {
}

View File

@@ -0,0 +1,5 @@
package com.krylov.refound.dto;
/** Номер автора объявления (POST /api/v1/posts/{id}/phone). */
public record PhoneRevealResponse(String phone) {
}

View File

@@ -14,6 +14,8 @@ public class PostRequest {
private String description;
private String category;
private String phone;
/** Явное согласие на показ номера другим пользователям; без него номер не сохраняется. */
private Boolean phoneVisible;
private String imageUrl;
private Double latitude;
private Double longitude;

View File

@@ -29,7 +29,14 @@ public class PostResponse {
private LocalDateTime closedAt;
/** Логин автора. */
private String userLogin;
/**
* Номер автора — только в ответах самому автору (свои объявления, правка).
* Остальные получают номер через POST /api/v1/posts/{id}/phone с решённой
* proof-of-work задачей, чтобы его нельзя было собрать из ленты.
*/
private String phone;
/** Автор разрешил показ номера: фронт показывает кнопку «Показать номер». */
private boolean phoneVisible;
private List<String> images;
private Long userId;
private Role userRole;

View File

@@ -31,6 +31,8 @@ public class AdminPostResponse {
private Double latitude;
private Double longitude;
private String phone;
/** Автор согласился на показ номера; без согласия phone = null. */
private boolean phoneVisible;
private Boolean reward;
private String rewardText;
private LocalDateTime createdAt;

View File

@@ -44,7 +44,15 @@ public class Post {
private Double latitude;
private Double longitude;
private LocalDateTime createdAt;
// Хранится только при согласии на показ (phoneVisible); без него — null
private String phone;
// Согласие автора на показ номера другим пользователям (152-ФЗ).
// false — режим «только чат», по умолчанию. Ведётся в PostService.applyPhone
@Column(name = "phone_visible", nullable = false)
private boolean phoneVisible = false;
// Когда дано согласие на показ номера; сбрасывается при отзыве
@Column(name = "phone_consent_at")
private LocalDateTime phoneConsentAt;
// В БД колонка boolean NOT NULL (changelog 013). Строка была рассинхронизирована
// со схемой и ломала ddl-auto: validate.
@Column(name = "rules_accepted", nullable = false)

View File

@@ -9,10 +9,17 @@ public class ApiException extends RuntimeException {
private final ErrorCode errorCode;
private final HttpStatus status;
/** Для 429: через сколько секунд повторить (заголовок Retry-After); null — не указывать. */
private final Long retryAfterSeconds;
public ApiException(ErrorCode errorCode, String message, HttpStatus status) {
this(errorCode, message, status, null);
}
public ApiException(ErrorCode errorCode, String message, HttpStatus status, Long retryAfterSeconds) {
super(message);
this.errorCode = errorCode;
this.status = status;
this.retryAfterSeconds = retryAfterSeconds;
}
}

View File

@@ -9,6 +9,7 @@ import java.time.LocalDateTime;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
@@ -37,7 +38,13 @@ public class GlobalExceptionHandler {
@ExceptionHandler(ApiException.class)
public ResponseEntity<ErrorResponse> handleApiException(ApiException ex, HttpServletRequest request) {
return buildResponse(ex.getStatus(), ex.getErrorCode(), ex.getMessage(), request);
ResponseEntity<ErrorResponse> response = buildResponse(ex.getStatus(), ex.getErrorCode(), ex.getMessage(), request);
if (ex.getRetryAfterSeconds() == null) {
return response;
}
return ResponseEntity.status(response.getStatusCode())
.header(HttpHeaders.RETRY_AFTER, Long.toString(ex.getRetryAfterSeconds()))
.body(response.getBody());
}
@ExceptionHandler(MethodArgumentNotValidException.class)

View File

@@ -16,6 +16,10 @@ public interface PostMapper {
@Mapping(source = "category", target = "category", qualifiedByName = "stringToPostCategory")
@Mapping(source = "rewardText", target = "reward")
@Mapping(source = "rulesAccepted", target = "rulesAccepted", qualifiedByName = "stringToBoolean")
// Номер и согласие на его показ ставит PostService.applyPhone
@Mapping(target = "phone", ignore = true)
@Mapping(target = "phoneVisible", ignore = true)
@Mapping(target = "phoneConsentAt", ignore = true)
Post toEntity(PostRequest request);
@Mapping(source = "user.id", target = "userId")
@@ -26,6 +30,9 @@ public interface PostMapper {
@Mapping(source = "isReward", target = "reward")
@Mapping(source = "reward", target = "rewardText")
@Mapping(source = "rulesAccepted", target = "rulesAccepted", qualifiedByName = "booleanToString")
// Номер в публичном ответе (лента, кэш ленты, избранное) не отдаётся:
// владельцу его добавляет PostService.toOwnerResponse
@Mapping(target = "phone", ignore = true)
PostResponse toResponse(Post post);
/** Фронт присылает правила как строку ("true"), в БД колонка boolean. */

View File

@@ -64,6 +64,8 @@ public class SecurityConfig {
.requestMatchers(HttpMethod.POST, "/api/v1/reviews/**").authenticated()
.requestMatchers(HttpMethod.PUT, "/api/v1/reviews/**").authenticated()
.requestMatchers(HttpMethod.DELETE, "/api/v1/reviews/**").authenticated()
// показ номера — без регистрации, защищён proof-of-work и лимитами (PhoneRevealService)
.requestMatchers(HttpMethod.POST, "/api/v1/posts/*/phone").permitAll()
.requestMatchers(HttpMethod.POST, "/api/v1/posts/**").authenticated()
.requestMatchers(HttpMethod.PUT, "/api/v1/posts/**").authenticated()
.requestMatchers(HttpMethod.DELETE, "/api/v1/posts/**").authenticated()

View File

@@ -82,6 +82,10 @@ public class PostService {
public PostResponse create(PostRequest request, List<MultipartFile> images) {
User currentUser = userService.getCurrentUser();
PostFieldLimits.validate(request.getTitle(), request.getAddress(), request.getPhone(), request.getRewardText());
boolean phoneVisible = Boolean.TRUE.equals(request.getPhoneVisible());
if (phoneVisible) {
PostFieldLimits.requirePhone(request.getPhone());
}
AddressInfo location = geocode(request.getLatitude(), request.getLongitude());
List<String> imageKeys = uploadImages(images);
@@ -94,6 +98,7 @@ public class PostService {
post.setStatus(PostStatus.MODERATION);
post.setUser(currentUser);
post.setIsReward(request.getReward());
applyPhone(post, request.getPhone(), phoneVisible);
// Адрес из формы сохраняем как есть; геокодер заполняет только city/district
post.setAddress(normalizeAddress(request.getAddress()));
applyLocation(post, location, request.getAddress());
@@ -106,7 +111,7 @@ public class PostService {
statisticsService.incrementCreated();
postCacheService.invalidatePosts();
// Ответ собираем в транзакции: картинки и автор — ленивые связи
return toResponse(post, true);
return toOwnerResponse(post, true);
});
} catch (RuntimeException e) {
postDeletionService.deleteFilesAfterCommit(imageKeys);
@@ -196,10 +201,11 @@ public class PostService {
*/
@Transactional(readOnly = true)
public Page<PostResponse> getPostsByUser(Long userId, Pageable pageable) {
Page<Post> posts = isCurrentUser(userId)
boolean owner = isCurrentUser(userId);
Page<Post> posts = owner
? postRepository.findByUserId(userId, pageable)
: postRepository.findByUserIdAndStatusIn(userId, FEED_VISIBLE_STATUSES, pageable);
return posts.map(post -> toResponse(post, false));
return posts.map(post -> owner ? toOwnerResponse(post, false) : toResponse(post, false));
}
/**
@@ -207,8 +213,8 @@ public class PostService {
* Как и при создании, геокодер и загрузка фото выполняются до транзакции.
*/
public PostResponse update(Long id, String type, String title, String address, Double latitude,
Double longitude, String description, String category, String phone, Boolean reward,
String rewardText, List<MultipartFile> images, String existingImagesJson) {
Double longitude, String description, String category, String phone, Boolean phoneVisible,
Boolean reward, String rewardText, List<MultipartFile> images, String existingImagesJson) {
PostRequest request = new PostRequest();
request.setType(PostType.from(type));
@@ -216,12 +222,16 @@ public class PostService {
request.setDescription(description);
request.setCategory(category);
request.setPhone(phone);
request.setPhoneVisible(phoneVisible);
request.setLatitude(latitude);
request.setLongitude(longitude);
request.setAddress(address);
request.setReward(reward);
request.setRewardText(rewardText);
PostFieldLimits.validate(title, address, phone, rewardText);
if (Boolean.TRUE.equals(phoneVisible)) {
PostFieldLimits.requirePhone(phone);
}
List<String> existingUrls = parseExistingImages(existingImagesJson);
@@ -248,7 +258,9 @@ public class PostService {
if (request.getCategory() != null) {
post.setCategory(PostCategory.fromDisplayName(request.getCategory()));
}
post.setPhone(request.getPhone());
// Старый клиент не присылает phoneVisible — тогда согласие не меняется
boolean phoneVisible = request.getPhoneVisible() != null ? request.getPhoneVisible() : post.isPhoneVisible();
applyPhone(post, request.getPhone(), phoneVisible);
post.setType(request.getType());
post.setIsReward(request.getReward());
post.setReward(request.getRewardText());
@@ -273,7 +285,7 @@ public class PostService {
Post updated = postRepository.save(post);
log.info("Обновлён пост id={}: удалено изображений={}, добавлено={}, статус={}", id, toRemove.size(), uploaded, updated.getStatus());
postCacheService.invalidatePosts();
return mapper.toResponse(updated);
return withOwnerPhone(mapper.toResponse(updated), updated);
}
@Transactional
@@ -306,7 +318,7 @@ public class PostService {
Post updated = postRepository.save(post);
log.info("Статус поста id={} изменён: {} -> {}", id, previousStatus, newStatus);
postCacheService.invalidatePosts();
return mapper.toResponse(updated);
return withOwnerPhone(mapper.toResponse(updated), updated);
}
public List<String> getCities() {
@@ -422,6 +434,7 @@ public class PostService {
post.setCity(PostFieldLimits.cityFromAddress(address));
}
/** Публичное представление: без номера телефона (см. PostResponse.phone). */
public PostResponse toResponse(Post post, boolean includeUserRole) {
PostResponse response = mapper.toResponse(post);
response.setReward(post.getIsReward());
@@ -431,6 +444,37 @@ public class PostService {
return response;
}
/** Представление для автора: с номером, чтобы форма правки его показала. */
private PostResponse toOwnerResponse(Post post, boolean includeUserRole) {
return withOwnerPhone(toResponse(post, includeUserRole), post);
}
private static PostResponse withOwnerPhone(PostResponse response, Post post) {
if (response != null) {
response.setPhone(post.getPhone());
}
return response;
}
/**
* Номер хранится, только пока автор согласен на его показ: при отзыве
* согласия номер стирается (152-ФЗ — не храним данные без цели).
* Время согласия ставится при включении и не сдвигается при правках.
*/
public static void applyPhone(Post post, String phone, boolean phoneVisible) {
if (!phoneVisible || !StringUtils.hasText(phone)) {
post.setPhoneVisible(false);
post.setPhone(null);
post.setPhoneConsentAt(null);
return;
}
if (!post.isPhoneVisible() || post.getPhoneConsentAt() == null) {
post.setPhoneConsentAt(TimeZoneContext.now());
}
post.setPhoneVisible(true);
post.setPhone(phone.trim());
}
private List<String> parseExistingImages(String existingImagesJson) {
if (existingImagesJson == null) {
return List.of();
@@ -450,11 +494,12 @@ public class PostService {
// Неопубликованный пост (MODERATION, REJECTED) виден только владельцу.
// Остальным отвечаем 404, чтобы не раскрывать, что такой id существует
if (!FEED_VISIBLE_STATUSES.contains(post.getStatus()) && !isCurrentUser(post.getUser().getId())) {
boolean owner = isCurrentUser(post.getUser().getId());
if (!FEED_VISIBLE_STATUSES.contains(post.getStatus()) && !owner) {
throw new ApiException(ErrorCode.NOT_FOUND, "Post not found", HttpStatus.NOT_FOUND);
}
return toResponse(post, true);
return owner ? toOwnerResponse(post, true) : toResponse(post, true);
}
private static String normalizeAddress(String address) {

View File

@@ -17,6 +17,7 @@ import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.service.FileStorageService;
import com.krylov.refound.service.GeocodingService;
import com.krylov.refound.service.PostDeletionService;
import com.krylov.refound.service.PostService;
import com.krylov.refound.service.StatisticsService;
import com.krylov.refound.service.redis.PostCacheService;
import com.krylov.refound.util.PostFieldLimits;
@@ -130,7 +131,11 @@ public class AdminPostService {
post.setType(parseTypeOrThrow(type));
post.setTitle(title);
post.setDescription(description);
post.setPhone(phone);
// Согласие на показ номера даёт только автор: админ может поправить или
// убрать номер, но не включить показ там, где автор выбрал «только чат»
if (post.isPhoneVisible()) {
PostService.applyPhone(post, phone, true);
}
post.setIsReward(Boolean.TRUE.equals(reward));
post.setReward(rewardText);
@@ -288,6 +293,7 @@ public class AdminPostService {
.latitude(post.getLatitude())
.longitude(post.getLongitude())
.phone(post.getPhone())
.phoneVisible(post.isPhoneVisible())
.reward(Boolean.TRUE.equals(post.getIsReward()))
.rewardText(post.getReward())
.createdAt(post.getCreatedAt())

View File

@@ -0,0 +1,59 @@
package com.krylov.refound.service.phone;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Защита номеров от массового сбора ({@code phone-reveal.*} в application.yaml).
* Номер отдаётся только с решённой proof-of-work задачей; сложность растёт с
* числом открытых с одного IP номеров. Счётчики и баны — в Redis.
*/
@Getter
@Setter
@ConfigurationProperties(prefix = "phone-reveal")
public class PhoneRevealProperties {
/** HMAC-ключ подписи задач; пусто — используется jwt.secret. */
private String secret;
/** Сколько живёт выданная задача. */
private Duration challengeTtl = Duration.ofMinutes(2);
/**
* Верхняя граница перебора для первых открытий: браузер решает в среднем
* за maxNumber/2 хешей SHA-256 (100 000 — доли секунды на телефоне).
*/
private long baseMaxNumber = 100_000;
/** Каждые столько номеров за час с IP сложность умножается на escalationFactor. */
private int escalationStep = 5;
private int escalationFactor = 4;
/** Предел сложности (~десяток секунд на слабом телефоне). */
private long maxMaxNumber = 5_000_000;
/** Сколько номеров можно открыть с одного IP за час и за сутки. */
private int ipHourlyLimit = 30;
private int ipDailyLimit = 100;
/** Сколько номеров может открыть один аккаунт за сутки. */
private int userDailyLimit = 50;
/**
* Подозрительные запросы (номер объявления, где его нет или которого нет,
* неверное решение задачи) — интерфейс таких не делает. После strikeLimit
* за час IP банится на banDuration.
*/
private int strikeLimit = 5;
private Duration strikeWindow = Duration.ofHours(1);
private Duration banDuration = Duration.ofHours(24);
/**
* Объявления-ловушки: id, которых нет в интерфейсе. Запрос номера по ним —
* сразу бан. Подходят id удалённых объявлений или id далеко за текущим
* максимумом — на них натыкается только перебор.
*/
private List<Long> trapPostIds = new ArrayList<>();
}

View File

@@ -0,0 +1,151 @@
package com.krylov.refound.service.phone;
import com.krylov.refound.entity.Post;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.enums.PostStatus;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.ratelimit.RedisRateLimiter;
import com.krylov.refound.repository.PostRepository;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
/**
* Показ номера автора объявления. Цель — сделать массовый сбор номеров дорогим,
* а разовый звонок оставить бесплатным и без регистрации:
* <ul>
* <li>номер отдаётся только с решённой proof-of-work задачей (ProofOfWorkService),
* сложность растёт с числом открытых с IP номеров;</li>
* <li>лимиты на IP (час, сутки) и на аккаунт (сутки);</li>
* <li>ловушки: запросы, которые интерфейс не делает (номер объявления без
* номера или несуществующего, неверное решение, id-ловушки), — это
* перебор; после нескольких таких IP банится на сутки.</li>
* </ul>
* Номер показывается только у активных объявлений с согласием автора.
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class PhoneRevealService {
static final String RULE_HOUR = "phone-reveal-hour";
static final String RULE_DAY = "phone-reveal-day";
static final String RULE_USER_DAY = "phone-reveal-user-day";
static final String RULE_STRIKE = "phone-strike";
private static final String BAN_KEY_PREFIX = "phone-ban:";
private static final Duration HOUR = Duration.ofHours(1);
private static final Duration DAY = Duration.ofDays(1);
private final PostRepository postRepository;
private final ProofOfWorkService proofOfWork;
private final RedisRateLimiter rateLimiter;
private final StringRedisTemplate redisTemplate;
private final PhoneRevealProperties properties;
/** Задача для открытия номера; сложность зависит от того, сколько номеров IP уже открыл за час. */
@Transactional(readOnly = true)
public ProofOfWorkService.Challenge challenge(long postId, String ip) {
checkNotBanned(ip);
requireRevealablePost(postId, ip);
long revealsThisHour = rateLimiter.current(RULE_HOUR, ip, HOUR);
return proofOfWork.create(postId, proofOfWork.maxNumberFor(revealsThisHour));
}
/** Номер автора, если решение задачи верно и лимиты не исчерпаны. */
@Transactional(readOnly = true)
public String reveal(long postId, String salt, Long number, String signature, String ip, Long userId) {
checkNotBanned(ip);
Optional<Long> solvedFor = proofOfWork.verify(salt, number, signature);
if (solvedFor.isEmpty() || solvedFor.get() != postId) {
strike(ip, "неверное решение задачи для поста " + postId);
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Проверка не пройдена, попробуйте ещё раз",
HttpStatus.BAD_REQUEST);
}
Post post = requireRevealablePost(postId, ip);
if (userId != null && post.getUser() != null && userId.equals(post.getUser().getId())) {
// Автор смотрит свой номер в ленте — это не сбор, лимиты не тратим
return post.getPhone();
}
// Лимиты считаем после проверки решения: каждая попытка сборщика стоит ему CPU
checkLimit(RULE_HOUR, ip, properties.getIpHourlyLimit(), HOUR);
checkLimit(RULE_DAY, ip, properties.getIpDailyLimit(), DAY);
if (userId != null) {
checkLimit(RULE_USER_DAY, "u" + userId, properties.getUserDailyLimit(), DAY);
}
log.info("Показан номер: postId={}, ip={}, userId={}", postId, ip, userId);
return post.getPhone();
}
private Post requireRevealablePost(long postId, String ip) {
if (properties.getTrapPostIds().contains(postId)) {
ban(ip, "запрос номера объявления-ловушки " + postId);
throw notFound();
}
Post post = postRepository.findById(postId).orElse(null);
if (post == null || post.getStatus() != PostStatus.ACTIVE || !post.isPhoneVisible()
|| !StringUtils.hasText(post.getPhone())) {
strike(ip, "запрос номера поста без номера " + postId);
throw notFound();
}
return post;
}
private void checkLimit(String rule, String subject, int limit, Duration window) {
RedisRateLimiter.Decision decision = rateLimiter.hit(rule, subject, limit, window);
if (!decision.allowed()) {
log.warn("Лимит показа номеров '{}' превышен: {}", rule, subject);
throw tooManyRequests(decision.retryAfterSeconds());
}
}
private void strike(String ip, String reason) {
RedisRateLimiter.Decision decision = rateLimiter.hit(RULE_STRIKE, ip, properties.getStrikeLimit(),
properties.getStrikeWindow());
log.warn("Подозрительный запрос номера ({}): ip={}, {}/{}", reason, ip, decision.count(),
properties.getStrikeLimit());
if (decision.count() >= properties.getStrikeLimit()) {
ban(ip, "превышен порог подозрительных запросов");
}
}
private void ban(String ip, String reason) {
try {
redisTemplate.opsForValue().set(BAN_KEY_PREFIX + ip, "1", properties.getBanDuration());
log.warn("IP {} заблокирован для показа номеров на {}: {}", ip, properties.getBanDuration(), reason);
} catch (RuntimeException e) {
log.warn("Бан IP {} не записан, Redis недоступен: {}", ip, e.getMessage());
}
}
/** Забаненному отвечаем тем же 429, что и при лимите: причину бана сборщику не раскрываем. */
private void checkNotBanned(String ip) {
Long ttl;
try {
ttl = redisTemplate.getExpire(BAN_KEY_PREFIX + ip, TimeUnit.SECONDS);
} catch (RuntimeException e) {
return;
}
if (ttl != null && ttl > 0) {
throw tooManyRequests(ttl);
}
}
private static ApiException tooManyRequests(long retryAfterSeconds) {
return new ApiException(ErrorCode.TOO_MANY_REQUESTS,
"Слишком много запросов номера, повторите позже или напишите в чат", HttpStatus.TOO_MANY_REQUESTS,
retryAfterSeconds);
}
private static ApiException notFound() {
return new ApiException(ErrorCode.NOT_FOUND, "Номер недоступен", HttpStatus.NOT_FOUND);
}
}

View File

@@ -0,0 +1,148 @@
package com.krylov.refound.service.phone;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.util.HexFormat;
import java.util.Optional;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
/**
* Proof-of-work по схеме ALTCHA, без внешних сервисов. Сервер берёт случайное
* число {@code n ≤ maxNumber} и отдаёт {@code challenge = SHA-256(salt + n)};
* браузер перебирает n, пока хеш не совпадёт. Человек тратит доли секунды,
* сборщику на 10 000 номеров нужны часы CPU.
*
* <p>Задача не хранится на сервере: {@code signature = HMAC(challenge)}, а id
* объявления и срок годности лежат в salt ({@code <random>.<postId>.<expiresAt>}),
* поэтому решение нельзя перенести на другое объявление или использовать
* после срока. Повторное использование решения отсекается ключом в Redis.
*/
@Slf4j
@Service
public class ProofOfWorkService {
public static final String ALGORITHM = "SHA-256";
private static final String USED_KEY_PREFIX = "pow:used:";
private static final HexFormat HEX = HexFormat.of();
private final byte[] secret;
private final PhoneRevealProperties properties;
private final StringRedisTemplate redisTemplate;
private final Clock clock;
private final SecureRandom random = new SecureRandom();
/** Задача для клиента; поля совпадают с форматом ALTCHA. */
public record Challenge(String algorithm, String challenge, String salt, long maxNumber, String signature) {
}
@Autowired
public ProofOfWorkService(PhoneRevealProperties properties, StringRedisTemplate redisTemplate,
@Value("${jwt.secret}") String jwtSecret) {
this(properties, redisTemplate, jwtSecret, Clock.systemUTC());
}
ProofOfWorkService(PhoneRevealProperties properties, StringRedisTemplate redisTemplate, String jwtSecret,
Clock clock) {
String configured = properties.getSecret();
this.secret = (configured == null || configured.isBlank() ? jwtSecret : configured)
.getBytes(StandardCharsets.UTF_8);
this.properties = properties;
this.redisTemplate = redisTemplate;
this.clock = clock;
}
public Challenge create(long postId, long maxNumber) {
byte[] nonce = new byte[12];
random.nextBytes(nonce);
long expiresAt = clock.instant().plus(properties.getChallengeTtl()).getEpochSecond();
String salt = HEX.formatHex(nonce) + "." + postId + "." + expiresAt;
long number = random.nextLong(maxNumber + 1);
String challenge = sha256Hex(salt + number);
return new Challenge(ALGORITHM, challenge, salt, maxNumber, HEX.formatHex(hmac(challenge)));
}
/**
* Проверяет решение и «гасит» его. Возвращает id объявления, для которого
* выдана задача, или пусто, если решение неверно, просрочено или уже использовано.
*/
public Optional<Long> verify(String salt, Long number, String signature) {
if (salt == null || number == null || number < 0 || signature == null) {
return Optional.empty();
}
String[] parts = salt.split("\\.", -1);
if (parts.length != 3) {
return Optional.empty();
}
long postId;
long expiresAt;
byte[] actual;
try {
postId = Long.parseLong(parts[1]);
expiresAt = Long.parseLong(parts[2]);
actual = HEX.parseHex(signature);
} catch (IllegalArgumentException e) {
return Optional.empty();
}
long now = clock.instant().getEpochSecond();
if (now > expiresAt) {
return Optional.empty();
}
String challenge = sha256Hex(salt + number);
if (!MessageDigest.isEqual(hmac(challenge), actual)) {
return Optional.empty();
}
if (!markUsed(challenge, Duration.ofSeconds(expiresAt - now + 1))) {
return Optional.empty();
}
return Optional.of(postId);
}
/** Сложность по числу уже открытых с IP номеров за час. */
public long maxNumberFor(long revealsThisHour) {
long maxNumber = properties.getBaseMaxNumber();
long steps = properties.getEscalationStep() <= 0 ? 0 : revealsThisHour / properties.getEscalationStep();
for (long i = 0; i < steps && maxNumber < properties.getMaxMaxNumber(); i++) {
maxNumber *= properties.getEscalationFactor();
}
return Math.min(maxNumber, properties.getMaxMaxNumber());
}
/** false — решение уже использовано. При недоступном Redis пропускаем: подпись и срок проверены. */
private boolean markUsed(String challenge, Duration ttl) {
try {
Boolean fresh = redisTemplate.opsForValue().setIfAbsent(USED_KEY_PREFIX + challenge, "1", ttl);
return !Boolean.FALSE.equals(fresh);
} catch (RuntimeException e) {
log.warn("PoW: повторное использование не проверено, Redis недоступен: {}", e.getMessage());
return true;
}
}
static String sha256Hex(String value) {
try {
return HEX.formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (GeneralSecurityException e) {
throw new IllegalStateException("SHA-256 недоступен", e);
}
}
private byte[] hmac(String value) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret, "HmacSHA256"));
return mac.doFinal(value.getBytes(StandardCharsets.UTF_8));
} catch (GeneralSecurityException e) {
throw new IllegalStateException("HmacSHA256 недоступен", e);
}
}
}

View File

@@ -16,6 +16,8 @@ public final class PostFieldLimits {
public static final int REWARD_TEXT = 255;
public static final int ADDRESS = 500;
public static final int CITY = 100;
private static final int MIN_PHONE_DIGITS = 10;
private static final int MAX_PHONE_DIGITS = 15;
private PostFieldLimits() {
}
@@ -31,6 +33,18 @@ public final class PostFieldLimits {
checkLength("Текст вознаграждения", rewardText, REWARD_TEXT);
}
/**
* Номер для показа другим пользователям: 10–15 цифр (E.164), остальное —
* форматирование. 400 VALIDATION_ERROR, если номера нет или он некорректен.
*/
public static void requirePhone(String phone) {
int digits = phone == null ? 0 : (int) phone.chars().filter(Character::isDigit).count();
if (digits < MIN_PHONE_DIGITS || digits > MAX_PHONE_DIGITS) {
throw new ApiException(ErrorCode.VALIDATION_ERROR,
"Укажите корректный номер телефона или отключите его показ", HttpStatus.BAD_REQUEST);
}
}
/**
* Город, когда геокодер его не дал: берётся адрес из формы, обрезанный под
* колонку city (адрес допускает 500 символов, город — 100).

View File

@@ -181,6 +181,18 @@ rate-limit:
paths: [/api/v1/chats/with/**]
limit: 30
window: PT1M
# Первый рубеж против сборщиков номеров — короткие всплески; часовые и
# суточные лимиты, PoW и баны — в PhoneRevealService (phone-reveal.*)
- name: phone-challenge
method: GET
paths: [/api/v1/posts/*/phone/challenge]
limit: 20
window: PT1M
- name: phone-reveal
method: POST
paths: [/api/v1/posts/*/phone]
limit: 10
window: PT1M
- name: ads-next
method: GET
paths: [/api/ads/next, /api/fullscreen-ad]
@@ -192,6 +204,24 @@ rate-limit:
limit: 120
window: PT1M
# Защита номеров от сбора (PhoneRevealService, docs/phone-protection.md)
phone-reveal:
# HMAC-ключ задач proof-of-work; пусто — используется jwt.secret
secret: ${PHONE_REVEAL_SECRET:}
challenge-ttl: PT2M
base-max-number: 100000 # ~0,1–0,5 с на телефоне
escalation-step: 5 # каждые 5 номеров за час с IP —
escalation-factor: 4 # задача в 4 раза тяжелее
max-max-number: 5000000
ip-hourly-limit: 30
ip-daily-limit: 100
user-daily-limit: 50
strike-limit: 5 # подозрительных запросов за strike-window до бана
strike-window: PT1H
ban-duration: PT24H
# id объявлений-ловушек через запятую (см. docs/phone-protection.md)
trap-post-ids: ${PHONE_TRAP_POST_IDS:}
# Реклама (docs/advertising.md)
ads:
# Пояс дат кампаний и календарных суток дневного лимита

View File

@@ -0,0 +1,25 @@
databaseChangeLog:
- changeSet:
id: 023-add-phone-visible-posts
author: krylov
comment: >
Согласие автора на показ номера (152-ФЗ). phone_visible = false — режим
«только чат»: номер не хранится и не показывается. phone_consent_at —
когда дано согласие. У старых объявлений явного согласия не было,
поэтому их номера скрываются до правки объявления автором.
preConditions:
onFail: MARK_RAN
not:
columnExists:
tableName: posts
columnName: phone_visible
changes:
- addColumn:
tableName: posts
columns:
- column:
name: phone_visible
type: BOOLEAN
defaultValueBoolean: false
constraints: { nullable: false }
- column: { name: phone_consent_at, type: TIMESTAMP }

View File

@@ -35,3 +35,4 @@ databaseChangeLog:
- include: { file: db/changelog/search/020-search-words.yaml }
- include: { file: db/changelog/add/021-ad-stats-indexes.yaml }
- include: { file: db/changelog/add/022-add-closed-at-posts.yaml }
- include: { file: db/changelog/add/023-add-phone-visible-posts.yaml }