Add anti-fraud verification questions and scam warnings
- posts can carry up to 3 verification questions (post_verification_questions,
changelog 026); to contact the author one answers them first
- POST /api/v1/posts/{id}/claim creates a PENDING chat with the answers as a
CLAIM message; the claimant cannot write or see the phone until the author
approves via POST /api/v1/chats/{chatId}/verification
- plain first message to such a post and phone reveal return 403
VERIFICATION_REQUIRED; GET /api/v1/chats/{chatId} exposes the status
- FraudSignals flags prepayment, card data (Luhn) and SMS-code requests in
messages (MessageDto.fraudSignal); ChatDto.otherUserCreatedAt for new accounts
- claim limits: 5 per day per account, 2 per post per 30 days, 10/h per IP
- docs/anti-fraud.md, tests
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,10 +1,12 @@
|
||||
package com.krylov.refound.service.phone;
|
||||
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.enums.ChatVerificationStatus;
|
||||
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.ChatRepository;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
@@ -28,7 +30,8 @@ import org.springframework.util.StringUtils;
|
||||
* номера или несуществующего, неверное решение, id-ловушки), — это
|
||||
* перебор; после нескольких таких IP банится на сутки.</li>
|
||||
* </ul>
|
||||
* Номер показывается только у активных объявлений с согласием автора.
|
||||
* Номер показывается только у активных объявлений с согласием автора. У объявления
|
||||
* с контрольными вопросами — только автору и заявителю, чьи ответы автор подтвердил.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -48,12 +51,14 @@ public class PhoneRevealService {
|
||||
private final RedisRateLimiter rateLimiter;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
private final PhoneRevealProperties properties;
|
||||
private final ChatRepository chatRepository;
|
||||
|
||||
/** Задача для открытия номера; сложность зависит от того, сколько номеров IP уже открыл за час. */
|
||||
@Transactional(readOnly = true)
|
||||
public ProofOfWorkService.Challenge challenge(long postId, String ip) {
|
||||
public ProofOfWorkService.Challenge challenge(long postId, String ip, Long userId) {
|
||||
checkNotBanned(ip);
|
||||
requireRevealablePost(postId, ip);
|
||||
// Задачу не выдаём, если номер всё равно не откроется: не тратим CPU клиента
|
||||
checkVerified(requireRevealablePost(postId, ip), userId);
|
||||
long revealsThisHour = rateLimiter.current(RULE_HOUR, ip, HOUR);
|
||||
return proofOfWork.create(postId, proofOfWork.maxNumberFor(revealsThisHour));
|
||||
}
|
||||
@@ -69,10 +74,11 @@ public class PhoneRevealService {
|
||||
HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
Post post = requireRevealablePost(postId, ip);
|
||||
if (userId != null && post.getUser() != null && userId.equals(post.getUser().getId())) {
|
||||
if (isOwner(post, userId)) {
|
||||
// Автор смотрит свой номер в ленте — это не сбор, лимиты не тратим
|
||||
return post.getPhone();
|
||||
}
|
||||
checkVerified(post, userId);
|
||||
|
||||
// Лимиты считаем после проверки решения: каждая попытка сборщика стоит ему CPU
|
||||
checkLimit(RULE_HOUR, ip, properties.getIpHourlyLimit(), HOUR);
|
||||
@@ -99,6 +105,25 @@ public class PhoneRevealService {
|
||||
return post;
|
||||
}
|
||||
|
||||
/**
|
||||
* Объявление с контрольными вопросами: номер — только заявителю с подтверждёнными
|
||||
* ответами. Это не перебор (кнопку видят все), поэтому без штрафа IP.
|
||||
*/
|
||||
private void checkVerified(Post post, Long userId) {
|
||||
if (!post.requiresVerification() || isOwner(post, userId)) {
|
||||
return;
|
||||
}
|
||||
if (userId == null || !chatRepository.existsByClaimantIdAndPostIdAndVerificationStatus(userId, post.getId(),
|
||||
ChatVerificationStatus.APPROVED)) {
|
||||
throw new ApiException(ErrorCode.VERIFICATION_REQUIRED,
|
||||
"Номер откроется, когда автор объявления подтвердит ваши ответы на его вопросы", HttpStatus.FORBIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isOwner(Post post, Long userId) {
|
||||
return userId != null && post.getUser() != null && userId.equals(post.getUser().getId());
|
||||
}
|
||||
|
||||
private void checkLimit(String rule, String subject, int limit, Duration window) {
|
||||
RedisRateLimiter.Decision decision = rateLimiter.hit(rule, subject, limit, window);
|
||||
if (!decision.allowed()) {
|
||||
|
||||
Reference in New Issue
Block a user