fixed show phone number

This commit is contained in:
SlimusMinus
2026-10-27 22:52:10 +03:00
parent 113355c0ef
commit 4b7db41a97
13 changed files with 425 additions and 32 deletions

30
src/api/phoneApi.js Normal file
View File

@@ -0,0 +1,30 @@
// src/api/phoneApi.js
import { API_URL } from "../config/authConstants";
import { apiFetch } from "./apiClient";
import { ensureOk } from "./apiErrors";
import { solveChallenge } from "../utils/proofOfWork";
/**
* Номер автора объявления. В ленте номера нет: бэкенд отдаёт его только в
* обмен на решённую proof-of-work задачу (защита от массового сбора).
* Работает и без входа; с токеном лимиты считаются и на аккаунт.
*
* Бросает ApiError: 404 — номер скрыт или объявление закрыто,
* 429 — лимит (Retry-After), 400 — решение не принято.
*/
export async function revealPhone(postId, { signal } = {}) {
const base = `${API_URL}/api/v1/posts/${encodeURIComponent(postId)}/phone`;
const challengeRes = await ensureOk(await apiFetch(`${base}/challenge`, { signal }));
const task = await challengeRes.json();
const number = await solveChallenge(task, { signal });
const res = await ensureOk(await apiFetch(base, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ salt: task.salt, number, signature: task.signature }),
signal,
}));
const { phone } = await res.json();
return phone;
}

View File

@@ -37,6 +37,8 @@ export const EMPTY_FORM = {
category: "", category: "",
location: "", location: "",
phone: "", phone: "",
// Согласие на показ номера (152-ФЗ). По умолчанию — «только чат»
phoneVisible: false,
date: "", date: "",
address: "", address: "",
rulesAccepted: false, rulesAccepted: false,

View File

@@ -0,0 +1,42 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { revealPhone } from "../api/phoneApi";
import { describeApiError } from "../api/apiErrors";
/**
* useRevealPhone — кнопка «Показать номер» в карточке объявления.
* Браузер решает proof-of-work задачу (доли секунды) и получает номер.
*
* @param {number|string} postId
* @returns {{ phone: string, loading: boolean, error: string, reveal: function, clearError: function }}
*/
export function useRevealPhone(postId) {
const { t } = useTranslation();
const [phone, setPhone] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const abortRef = useRef(null);
// Карточка ушла из ленты — перебор и запросы больше не нужны
useEffect(() => () => abortRef.current?.abort(), []);
const reveal = useCallback(async () => {
if (loading || phone) return;
const controller = new AbortController();
abortRef.current = controller;
setLoading(true);
setError("");
try {
setPhone(await revealPhone(postId, { signal: controller.signal }));
} catch (err) {
if (err?.name === "AbortError") return;
setError(describeApiError(err, t("postCard.phoneError")));
} finally {
if (!controller.signal.aborted) setLoading(false);
}
}, [loading, phone, postId, t]);
const clearError = useCallback(() => setError(""), []);
return { phone, loading, error, reveal, clearError };
}

View File

@@ -145,7 +145,10 @@
"unknownError": "Unknown error", "unknownError": "Unknown error",
"nextStep": "Next", "nextStep": "Next",
"backStep": "Back", "backStep": "Back",
"mapNoCoords": "This listing has no coordinates, so there is no location to show on the map." "mapNoCoords": "This listing has no coordinates, so there is no location to show on the map.",
"phoneConsentCheckbox": "Show my phone number to users who open the listing",
"phoneConsentHint": "Only people who tap “Show number” will see it. You can withdraw consent at any time: untick the box when editing and the number is removed from the listing.",
"chatOnlyHint": "People will contact you via chat — your phone number is not published."
}, },
"feed": { "feed": {
"loading": "Loading ads...", "loading": "Loading ads...",
@@ -196,7 +199,11 @@
"contactError": "Unable to open the chat. Please try again", "contactError": "Unable to open the chat. Please try again",
"reward": "Reward", "reward": "Reward",
"statusModeration": "Under review", "statusModeration": "Under review",
"statusRejected": "Rejected" "statusRejected": "Rejected",
"showPhone": "Show number",
"phoneChecking": "Checking…",
"phoneError": "Could not get the number. Message the author in chat",
"ownAd": "Your listing"
}, },
"chat": { "chat": {
"title": "Chat", "title": "Chat",

View File

@@ -145,7 +145,10 @@
"unknownError": "Неизвестная ошибка", "unknownError": "Неизвестная ошибка",
"nextStep": "Далее", "nextStep": "Далее",
"backStep": "Назад", "backStep": "Назад",
"mapNoCoords": "У объявления не указаны координаты — показывать место на карте нечего." "mapNoCoords": "У объявления не указаны координаты — показывать место на карте нечего.",
"phoneConsentCheckbox": "Показывать мой номер телефона пользователям, открывшим объявление",
"phoneConsentHint": "Номер увидят только те, кто нажмёт «Показать номер». Согласие можно отозвать в любой момент — снимите галочку при редактировании, и номер будет удалён из объявления.",
"chatOnlyHint": "С вами свяжутся через чат — номер телефона не публикуется."
}, },
"feed": { "feed": {
"loading": "Загружаем объявления...", "loading": "Загружаем объявления...",
@@ -196,7 +199,11 @@
"contactError": "Не удалось открыть чат. Попробуйте ещё раз", "contactError": "Не удалось открыть чат. Попробуйте ещё раз",
"reward": "Вознаграждение", "reward": "Вознаграждение",
"statusModeration": "На модерации", "statusModeration": "На модерации",
"statusRejected": "Отклонено" "statusRejected": "Отклонено",
"showPhone": "Показать номер",
"phoneChecking": "Проверка…",
"phoneError": "Не удалось получить номер. Напишите автору в чат",
"ownAd": "Ваше объявление"
}, },
"chat": { "chat": {
"title": "Чат", "title": "Чат",

View File

@@ -46,6 +46,7 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
category: initialData.category || "", category: initialData.category || "",
date: initialData.date || "", date: initialData.date || "",
phone: initialData.phone || profilePhone, phone: initialData.phone || profilePhone,
phoneVisible: !!initialData.phoneVisible,
address: initialData.address || initialData.city || "", address: initialData.address || initialData.city || "",
rulesAccepted: true, rulesAccepted: true,
reward: initialData.reward ?? false, reward: initialData.reward ?? false,
@@ -127,7 +128,11 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
data.append("title", form.title.trim()); data.append("title", form.title.trim());
data.append("description", form.description.trim()); data.append("description", form.description.trim());
data.append("category", form.category); data.append("category", form.category);
data.append("phone", form.phone.trim()); // Без согласия номер не отправляем: бэкенд его и не сохранит.
// Админ согласие не меняет — правит только номер, если автор его показывает
const phoneVisible = adminMode ? !!initialData?.phoneVisible : form.phoneVisible;
if (!adminMode) data.append("phoneVisible", phoneVisible ? "true" : "false");
if (phoneVisible) data.append("phone", form.phone.trim());
// У находки вознаграждения нет: галочка, оставшаяся от типа «Потеря», не уходит // У находки вознаграждения нет: галочка, оставшаяся от типа «Потеря», не уходит
const reward = form.reward && form.type !== "found"; const reward = form.reward && form.type !== "found";
data.append("reward", reward ? "true" : "false"); data.append("reward", reward ? "true" : "false");
@@ -354,7 +359,26 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
{errors.map && <p className="f-err-msg">{errors.map}</p>} {errors.map && <p className="f-err-msg">{errors.map}</p>}
</div> </div>
{/* Телефон */} {/* Телефон: по умолчанию связь только через чат. Номер — персональные
данные (152-ФЗ), показываем его только с явного согласия автора */}
{!adminMode && (
<div className="f-m-group">
<label className="f-reward-checkbox">
<input
type="checkbox"
checked={form.phoneVisible}
onChange={e => set("phoneVisible", e.target.checked)}
/>
<span className="f-reward-checkmark"/>
<span className="f-reward-text">{t('post.phoneConsentCheckbox')}</span>
</label>
<p className="f-hint">
{form.phoneVisible ? t('post.phoneConsentHint') : t('post.chatOnlyHint')}
</p>
</div>
)}
{(adminMode ? !!initialData?.phoneVisible : form.phoneVisible) && (
<div className="f-m-group"> <div className="f-m-group">
<label className="f-m-label">{t('post.phoneLabel')}</label> <label className="f-m-label">{t('post.phoneLabel')}</label>
<ClearableField onClear={() => set("phone", "")} visible={!!form.phone}> <ClearableField onClear={() => set("phone", "")} visible={!!form.phone}>
@@ -368,6 +392,7 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
</ClearableField> </ClearableField>
{errors.phone && <p className="f-err-msg">{errors.phone}</p>} {errors.phone && <p className="f-err-msg">{errors.phone}</p>}
</div> </div>
)}
{/* Вознаграждение — только для потери */} {/* Вознаграждение — только для потери */}
{form.type !== "found" && ( {form.type !== "found" && (

View File

@@ -2,7 +2,8 @@
* На десктопе форма объявления закрывается только крестиком: клик по фону * На десктопе форма объявления закрывается только крестиком: клик по фону
* не должен терять заполненные поля. На мобильном клик по фону закрывает. * не должен терять заполненные поля. На мобильном клик по фону закрывает.
* Там же на десктопе фото можно перетащить в форму (drag & drop). * Там же на десктопе фото можно перетащить в форму (drag & drop).
* Телефон подставляется из профиля, если в объявлении его нет. * Номер — только с согласием на показ (по умолчанию «только чат»);
* после согласия он подставляется из профиля, если в объявлении его нет.
*/ */
import { render, screen, fireEvent } from "@testing-library/react"; import { render, screen, fireEvent } from "@testing-library/react";
import CreateUpdatePost from "./CreateUpdatePost"; import CreateUpdatePost from "./CreateUpdatePost";
@@ -122,8 +123,10 @@ test("на мобильном перетаскивание фото выключ
}); });
const PROFILE_PHONE = "+7 (999) 111-22-33"; const PROFILE_PHONE = "+7 (999) 111-22-33";
const PHONE_PLACEHOLDER = "+7 (___) ___-__-__";
const CONSENT = /Показывать мой номер|Show my phone number/;
/** Рендерит форму и переходит на второй шаг, где находится поле «Телефон». */ /** Рендерит форму и переходит на второй шаг, где находятся согласие и «Телефон». */
function openPhoneStep(props = {}) { function openPhoneStep(props = {}) {
useIsDesktop.mockReturnValue(true); useIsDesktop.mockReturnValue(true);
render(<CreateUpdatePost onClose={jest.fn()} {...props} />); render(<CreateUpdatePost onClose={jest.fn()} {...props} />);
@@ -132,41 +135,69 @@ function openPhoneStep(props = {}) {
fireEvent.change(screen.getByPlaceholderText(/опишите|describe/i), { target: { value: "Связка ключей" } }); fireEvent.change(screen.getByPlaceholderText(/опишите|describe/i), { target: { value: "Связка ключей" } });
} }
fireEvent.click(screen.getByText(/^(Далее|Next)/)); fireEvent.click(screen.getByText(/^(Далее|Next)/));
return screen.getByPlaceholderText("+7 (___) ___-__-__");
} }
test("новое объявление: телефон подставляется из профиля", () => { const phoneField = () => screen.queryByPlaceholderText(PHONE_PLACEHOLDER);
useAuthContext.mockReturnValue({ user: { phone: "79991112233" } });
expect(openPhoneStep().value).toBe(PROFILE_PHONE); test("новое объявление: по умолчанию «только чат» — номер не запрашивается", () => {
useAuthContext.mockReturnValue({ user: { phone: "79991112233" } });
openPhoneStep();
expect(screen.getByLabelText(CONSENT).checked).toBe(false);
expect(phoneField()).toBeNull();
expect(screen.getByText(/номер телефона не публикуется|phone number is not published/)).toBeTruthy();
}); });
test("новое объявление без телефона в профиле: поле пустое", () => { test("новое объявление: после согласия телефон подставляется из профиля", () => {
useAuthContext.mockReturnValue({ user: { phone: "" } }); useAuthContext.mockReturnValue({ user: { phone: "79991112233" } });
openPhoneStep();
expect(openPhoneStep().value).toBe(""); fireEvent.click(screen.getByLabelText(CONSENT));
expect(phoneField().value).toBe(PROFILE_PHONE);
});
test("согласие без номера не даёт опубликовать", () => {
useAuthContext.mockReturnValue({ user: { phone: "" } });
openPhoneStep();
fireEvent.click(screen.getByLabelText(CONSENT));
fireEvent.click(screen.getByText(/Разместить объявление|Publish/));
expect(phoneField().value).toBe("");
expect(screen.getByText(/Введите номер телефона|Enter a phone number/)).toBeTruthy();
}); });
const POST = { id: 1, type: "LOSS", title: "Ключи", description: "Связка ключей", category: "KEYS" }; const POST = { id: 1, type: "LOSS", title: "Ключи", description: "Связка ключей", category: "KEYS" };
test("редактирование: телефон объявления не заменяется телефоном профиля", () => { test("редактирование: телефон объявления не заменяется телефоном профиля", () => {
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } }); useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
openPhoneStep({ initialData: { ...POST, phoneVisible: true, phone: "+7 (900) 000-00-00" } });
const phone = openPhoneStep({ initialData: { ...POST, phone: "+7 (900) 000-00-00" } }); expect(screen.getByLabelText(CONSENT).checked).toBe(true);
expect(phoneField().value).toBe("+7 (900) 000-00-00");
expect(phone.value).toBe("+7 (900) 000-00-00");
}); });
test("редактирование объявления без телефона: подставляется телефон профиля", () => { test("редактирование объявления «только чат»: согласие не включается само", () => {
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } }); useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
openPhoneStep({ initialData: { ...POST, phoneVisible: false, phone: null } });
expect(openPhoneStep({ initialData: { ...POST, phone: "" } }).value).toBe(PROFILE_PHONE); expect(screen.getByLabelText(CONSENT).checked).toBe(false);
expect(phoneField()).toBeNull();
}); });
test("админ правит чужое объявление: свой телефон не подставляется", () => { test("админ не может включить показ номера за автора", () => {
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } }); useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
openPhoneStep({ initialData: { ...POST, phoneVisible: false, phone: null }, adminMode: true });
const phone = openPhoneStep({ initialData: { ...POST, phone: "" }, adminMode: true }); expect(screen.queryByLabelText(CONSENT)).toBeNull();
expect(phoneField()).toBeNull();
expect(phone.value).toBe(""); });
test("админ правит номер объявления с согласием: свой телефон не подставляется", () => {
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
openPhoneStep({ initialData: { ...POST, phoneVisible: true, phone: "" }, adminMode: true });
expect(screen.queryByLabelText(CONSENT)).toBeNull();
expect(phoneField().value).toBe("");
}); });

View File

@@ -5,6 +5,7 @@ import PhoneIcon from "../components/icons/PhoneIcon";
import TrashIcon from "../components/icons/TrashIcon"; import TrashIcon from "../components/icons/TrashIcon";
import CheckIcon from "../components/icons/CheckIcon"; import CheckIcon from "../components/icons/CheckIcon";
import {useContactSeller} from "../hooks/useContactSeller"; import {useContactSeller} from "../hooks/useContactSeller";
import {useRevealPhone} from "../hooks/useRevealPhone";
import {useAuthContext} from "../context/AuthContext"; import {useAuthContext} from "../context/AuthContext";
import {getImageUrl} from "../config/authConstants"; import {getImageUrl} from "../config/authConstants";
import {CATEGORY_PET} from "../config/feedConstants"; import {CATEGORY_PET} from "../config/feedConstants";
@@ -31,6 +32,7 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
// isOwner тут не подходит — в общей ленте он false и для своих объявлений. // isOwner тут не подходит — в общей ленте он false и для своих объявлений.
const isOwnAd = user?.id != null && ad.userId != null && String(ad.userId) === String(user.id); const isOwnAd = user?.id != null && ad.userId != null && String(ad.userId) === String(user.id);
const { contactSeller, error: contactError, clearError } = useContactSeller(ad); const { contactSeller, error: contactError, clearError } = useContactSeller(ad);
const phoneReveal = useRevealPhone(ad.id);
useEffect(() => { useEffect(() => {
const check = () => { const check = () => {
@@ -108,6 +110,13 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
? t('postCard.foundStatusWithDate', {status: foundText, date: foundDate}) ? t('postCard.foundStatusWithDate', {status: foundText, date: foundDate})
: foundText; : foundText;
// Номер в ленту не приходит: в «Моих объявлениях» и в админке он есть в ad.phone,
// в общей ленте его открывают кнопкой (proof-of-work на бэкенде) — и автор
// своего объявления тоже, чтобы видеть то же, что покупатель.
// У закрытого объявления номер не показывается: вещь уже вернулась.
const shownPhone = ad.phone || phoneReveal.phone;
const canRevealPhone = !shownPhone && ad.phoneVisible && !isClosed;
const headAccentClass = ad.type === "found" ? " f-head-found" : " f-head-loss"; const headAccentClass = ad.type === "found" ? " f-head-found" : " f-head-loss";
const typeBadge = ( const typeBadge = (
@@ -317,15 +326,27 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
<div className="f-card-foot"> <div className="f-card-foot">
<div className="f-card-foot-left"> <div className="f-card-foot-left">
{ad.phone && ( {shownPhone ? (
<a className="f-card-phone" href={`tel:${ad.phone}`} <a className="f-card-phone" href={`tel:${shownPhone}`}
onClick={e => e.stopPropagation()}> onClick={e => e.stopPropagation()}>
<PhoneIcon/> {ad.phone} <PhoneIcon/> {shownPhone}
</a> </a>
) : canRevealPhone && (
<button type="button" className="f-card-phone f-card-phone-reveal"
disabled={phoneReveal.loading}
aria-busy={phoneReveal.loading}
onClick={e => {
e.stopPropagation();
phoneReveal.reveal();
}}>
<PhoneIcon/> {phoneReveal.loading ? t('postCard.phoneChecking') : t('postCard.showPhone')}
</button>
)} )}
</div> </div>
<div className="f-card-foot-right"> <div className="f-card-foot-right">
{!isOwnAd && ( {isOwnAd ? (
<span className="f-card-own-label">{t('postCard.ownAd')}</span>
) : (
<button type="button" className="f-card-contact" <button type="button" className="f-card-contact"
onClick={handleContact}> onClick={handleContact}>
{t('postCard.write')} {t('postCard.write')}
@@ -369,6 +390,14 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
</div> </div>
)} )}
{phoneReveal.error && (
<Toast
message={phoneReveal.error}
type="error"
onDismiss={phoneReveal.clearError}
/>
)}
{contactError && ( {contactError && (
<Toast <Toast
message={contactError} message={contactError}

View File

@@ -0,0 +1,71 @@
/**
* Номер в карточке: в ленту он не приходит, открывается кнопкой
* «Показать номер» (proof-of-work на бэкенде). Автор и админ видят номер сразу.
*/
import { render, screen, fireEvent } from "@testing-library/react";
import PostOnFeed from "./PostOnFeed";
import { useAuthContext } from "../context/AuthContext";
import { revealPhone } from "../api/phoneApi";
import "../i18n";
jest.mock("../context/AuthContext", () => ({ useAuthContext: jest.fn() }));
jest.mock("../hooks/useContactSeller", () => ({
useContactSeller: () => ({ contactSeller: jest.fn(), error: "", clearError: jest.fn() }),
}));
jest.mock("../api/phoneApi", () => ({ revealPhone: jest.fn() }));
const AD = { id: 7, userId: 2, title: "Ключи", type: "loss", status: "ACTIVE", images: [] };
const SHOW = /Показать номер|Show number/;
beforeEach(() => {
useAuthContext.mockReturnValue({ isAuthenticated: false, user: null });
});
test("номер открывается по кнопке", async () => {
revealPhone.mockResolvedValue("+7 (999) 111-22-33");
render(<PostOnFeed ad={{ ...AD, phoneVisible: true }} />);
fireEvent.click(screen.getByText(SHOW));
expect(await screen.findByText("+7 (999) 111-22-33")).toBeTruthy();
expect(revealPhone).toHaveBeenCalledWith(7, expect.anything());
});
test("без согласия автора кнопки нет — только чат", () => {
render(<PostOnFeed ad={{ ...AD, phoneVisible: false }} />);
expect(screen.queryByText(SHOW)).toBeNull();
});
test("у закрытого объявления номер не предлагается", () => {
render(<PostOnFeed ad={{ ...AD, phoneVisible: true, status: "CLOSED" }} />);
expect(screen.queryByText(SHOW)).toBeNull();
});
test("номер, пришедший с объявлением (автор, админ), показывается сразу", () => {
render(<PostOnFeed ad={{ ...AD, phoneVisible: true, phone: "+7 (900) 000-00-00" }} />);
expect(screen.getByText("+7 (900) 000-00-00")).toBeTruthy();
expect(revealPhone).not.toHaveBeenCalled();
});
test("ошибка показа номера — сообщение", async () => {
revealPhone.mockRejectedValue(new TypeError("Failed to fetch"));
render(<PostOnFeed ad={{ ...AD, phoneVisible: true }} />);
fireEvent.click(screen.getByText(SHOW));
expect(await screen.findByText(/связ|connection|network/i)).toBeTruthy();
});
test("своё объявление в ленте: номер открывается кнопкой, вместо «Написать» — подпись", async () => {
useAuthContext.mockReturnValue({ isAuthenticated: true, user: { id: 2 } });
revealPhone.mockResolvedValue("+7 (999) 111-22-33");
render(<PostOnFeed ad={{ ...AD, phoneVisible: true }} />);
expect(screen.queryByText(/^(Написать|Write)$/)).toBeNull();
expect(screen.getByText(/Ваше объявление|Your listing/)).toBeTruthy();
fireEvent.click(screen.getByText(SHOW));
expect(await screen.findByText("+7 (999) 111-22-33")).toBeTruthy();
});

View File

@@ -385,6 +385,12 @@ button.f-card-reward-btn.f-card-reward-on-img:hover {
text-decoration: none; display: flex; align-items: center; gap: 4px; text-decoration: none; display: flex; align-items: center; gap: 4px;
white-space: nowrap; white-space: nowrap;
} }
.f-card-phone-reveal {
background: none; border: none; padding: 0;
cursor: pointer; font-family: var(--font);
}
.f-card-own-label { color: var(--muted2); font-size: .8rem; font-weight: 600; }
.f-card-phone-reveal:disabled { opacity: .6; cursor: progress; }
.f-card-date { color: var(--muted2); font-size: .75rem; } .f-card-date { color: var(--muted2); font-size: .75rem; }
.f-card-contact { .f-card-contact {

109
src/utils/proofOfWork.js Normal file
View File

@@ -0,0 +1,109 @@
// src/utils/proofOfWork.js
/**
* Решатель proof-of-work задачи для показа номера (схема ALTCHA, бэкенд —
* ProofOfWorkService). Сервер присылает challenge = SHA-256(salt + n) и
* maxNumber; ищем n перебором от 0 до maxNumber. В среднем это maxNumber/2
* хешей — доли секунды для человека, часы CPU для сборщика тысяч номеров.
*
* SHA-256 написан на JS, а не через crypto.subtle: subtle есть только в
* защищённом контексте (HTTPS/localhost) и на коротких строках медленнее
* из-за промиса на каждый хеш. Перебор идёт порциями с уступкой потоку,
* чтобы интерфейс не зависал.
*/
const K = new Uint32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
]);
const W = new Uint32Array(64);
/**
* SHA-256 строки из ASCII-символов (salt — hex, цифры и точки) в виде 8 слов
* со знаком (|0), чтобы сравнивать без перевода в hex.
*/
export function sha256Words(str) {
const len = str.length;
const blocks = ((len + 8) >> 6) + 1;
const m = new Uint32Array(blocks * 16);
for (let i = 0; i < len; i++) {
m[i >> 2] |= (str.charCodeAt(i) & 0xff) << (24 - (i & 3) * 8);
}
m[len >> 2] |= 0x80 << (24 - (len & 3) * 8);
m[blocks * 16 - 1] = len * 8;
let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a;
let h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
for (let b = 0; b < blocks; b++) {
for (let t = 0; t < 16; t++) W[t] = m[b * 16 + t];
for (let t = 16; t < 64; t++) {
const x = W[t - 15];
const y = W[t - 2];
const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10);
W[t] = (W[t - 16] + s0 + W[t - 7] + s1) | 0;
}
let a = h0, bb = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7;
for (let t = 0; t < 64; t++) {
const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
const ch = (e & f) ^ (~e & g);
const t1 = (h + S1 + ch + K[t] + W[t]) | 0;
const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
const maj = (a & bb) ^ (a & c) ^ (bb & c);
const t2 = (S0 + maj) | 0;
h = g; g = f; f = e; e = (d + t1) | 0;
d = c; c = bb; bb = a; a = (t1 + t2) | 0;
}
h0 = (h0 + a) | 0; h1 = (h1 + bb) | 0; h2 = (h2 + c) | 0; h3 = (h3 + d) | 0;
h4 = (h4 + e) | 0; h5 = (h5 + f) | 0; h6 = (h6 + g) | 0; h7 = (h7 + h) | 0;
}
return [h0, h1, h2, h3, h4, h5, h6, h7];
}
export function sha256Hex(str) {
return sha256Words(str).map(w => (w >>> 0).toString(16).padStart(8, "0")).join("");
}
function hexToWords(hex) {
const words = [];
for (let i = 0; i < 8; i++) words.push(parseInt(hex.slice(i * 8, i * 8 + 8), 16) | 0);
return words;
}
const yieldToBrowser = () => new Promise(resolve => setTimeout(resolve, 0));
/**
* Находит n, для которого SHA-256(salt + n) === challenge.
*
* @param {{algorithm: string, challenge: string, salt: string, maxNumber: number}} task
* @param {{signal?: AbortSignal, chunk?: number}} [options]
* @returns {Promise<number>}
*/
export async function solveChallenge(task, { signal, chunk = 20000 } = {}) {
if (task.algorithm !== "SHA-256" || !/^[0-9a-f]{64}$/.test(task.challenge || "")) {
throw new Error("Unsupported proof-of-work challenge");
}
const target = hexToWords(task.challenge);
const { salt, maxNumber } = task;
for (let n = 0; n <= maxNumber; n++) {
const h = sha256Words(salt + n);
if (h[0] === target[0] && h[1] === target[1] && h[2] === target[2] && h[3] === target[3]
&& h[4] === target[4] && h[5] === target[5] && h[6] === target[6] && h[7] === target[7]) {
return n;
}
if (n % chunk === chunk - 1) {
await yieldToBrowser();
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
}
}
throw new Error("Proof-of-work solution not found");
}

View File

@@ -0,0 +1,34 @@
import { createHash } from "crypto";
import { sha256Hex, solveChallenge } from "./proofOfWork";
const nodeSha256 = (s) => createHash("sha256").update(s).digest("hex");
test("SHA-256 совпадает с эталоном", () => {
expect(sha256Hex("abc")).toBe("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
expect(sha256Hex("")).toBe(nodeSha256(""));
// строка длиннее одного блока (64 байта)
const long = "a1b2c3d4e5f6a7b8c9d0e1f2.123456.1793102400".repeat(3);
expect(sha256Hex(long)).toBe(nodeSha256(long));
});
test("решает задачу в формате бэкенда (salt + n)", async () => {
const salt = "0a1b2c3d4e5f60718293a4b5.42.1793102400";
const secret = 31337;
const task = { algorithm: "SHA-256", challenge: nodeSha256(salt + secret), salt, maxNumber: 50000 };
await expect(solveChallenge(task, { chunk: 5000 })).resolves.toBe(secret);
});
test("неизвестный алгоритм не решается", async () => {
await expect(solveChallenge({ algorithm: "MD5", challenge: "x", salt: "s", maxNumber: 1 }))
.rejects.toThrow();
});
test("перебор прерывается по AbortSignal", async () => {
const controller = new AbortController();
controller.abort();
const task = { algorithm: "SHA-256", challenge: "0".repeat(64), salt: "s", maxNumber: 100000 };
await expect(solveChallenge(task, { signal: controller.signal, chunk: 100 }))
.rejects.toMatchObject({ name: "AbortError" });
});

View File

@@ -12,10 +12,10 @@ export function validatePostForm(form) {
if (!description) errors.description = i18n.t('validation.descriptionRequired'); if (!description) errors.description = i18n.t('validation.descriptionRequired');
if (!form.category) errors.category = i18n.t('validation.categoryRequired'); if (!form.category) errors.category = i18n.t('validation.categoryRequired');
// Телефон обязателен для объявления (в отличие от профиля) — проверяем // Телефон нужен, только если автор согласился его показывать (иначе
// количество цифр, а не просто пустоту, т.к. form.phone форматируется // связь через чат). Проверяем количество цифр, а не пустоту: form.phone
// через formatPhone и всегда содержит минимум "+7". // форматируется через formatPhone и всегда содержит минимум "+7".
if ((form.phone ?? "").replace(/\D/g, "").length < 11) { if (form.phoneVisible && (form.phone ?? "").replace(/\D/g, "").length < 11) {
errors.phone = i18n.t('validation.phoneRequired'); errors.phone = i18n.t('validation.phoneRequired');
} }