From 4b7db41a9708ed043279e13407457c6f9656d058 Mon Sep 17 00:00:00 2001 From: SlimusMinus Date: Tue, 27 Oct 2026 22:52:10 +0300 Subject: [PATCH] fixed show phone number --- src/api/phoneApi.js | 30 ++++++++ src/config/feedConstants.js | 2 + src/hooks/useRevealPhone.js | 42 +++++++++++ src/locales/en.json | 11 ++- src/locales/ru.json | 11 ++- src/pages/CreateUpdatePost.jsx | 29 +++++++- src/pages/CreateUpdatePost.test.jsx | 67 ++++++++++++----- src/pages/PostOnFeed.jsx | 37 +++++++++- src/pages/PostOnFeed.phone.test.jsx | 71 ++++++++++++++++++ src/styles/card.css | 6 ++ src/utils/proofOfWork.js | 109 ++++++++++++++++++++++++++++ src/utils/proofOfWork.test.js | 34 +++++++++ src/utils/validatePostForm.js | 8 +- 13 files changed, 425 insertions(+), 32 deletions(-) create mode 100644 src/api/phoneApi.js create mode 100644 src/hooks/useRevealPhone.js create mode 100644 src/pages/PostOnFeed.phone.test.jsx create mode 100644 src/utils/proofOfWork.js create mode 100644 src/utils/proofOfWork.test.js diff --git a/src/api/phoneApi.js b/src/api/phoneApi.js new file mode 100644 index 0000000..e9aad57 --- /dev/null +++ b/src/api/phoneApi.js @@ -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; +} diff --git a/src/config/feedConstants.js b/src/config/feedConstants.js index f328e1d..65e6b0f 100644 --- a/src/config/feedConstants.js +++ b/src/config/feedConstants.js @@ -37,6 +37,8 @@ export const EMPTY_FORM = { category: "", location: "", phone: "", + // Согласие на показ номера (152-ФЗ). По умолчанию — «только чат» + phoneVisible: false, date: "", address: "", rulesAccepted: false, diff --git a/src/hooks/useRevealPhone.js b/src/hooks/useRevealPhone.js new file mode 100644 index 0000000..31a24fd --- /dev/null +++ b/src/hooks/useRevealPhone.js @@ -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 }; +} diff --git a/src/locales/en.json b/src/locales/en.json index bf65f68..df3bb9a 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -145,7 +145,10 @@ "unknownError": "Unknown error", "nextStep": "Next", "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": { "loading": "Loading ads...", @@ -196,7 +199,11 @@ "contactError": "Unable to open the chat. Please try again", "reward": "Reward", "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": { "title": "Chat", diff --git a/src/locales/ru.json b/src/locales/ru.json index 301a9af..3964036 100644 --- a/src/locales/ru.json +++ b/src/locales/ru.json @@ -145,7 +145,10 @@ "unknownError": "Неизвестная ошибка", "nextStep": "Далее", "backStep": "Назад", - "mapNoCoords": "У объявления не указаны координаты — показывать место на карте нечего." + "mapNoCoords": "У объявления не указаны координаты — показывать место на карте нечего.", + "phoneConsentCheckbox": "Показывать мой номер телефона пользователям, открывшим объявление", + "phoneConsentHint": "Номер увидят только те, кто нажмёт «Показать номер». Согласие можно отозвать в любой момент — снимите галочку при редактировании, и номер будет удалён из объявления.", + "chatOnlyHint": "С вами свяжутся через чат — номер телефона не публикуется." }, "feed": { "loading": "Загружаем объявления...", @@ -196,7 +199,11 @@ "contactError": "Не удалось открыть чат. Попробуйте ещё раз", "reward": "Вознаграждение", "statusModeration": "На модерации", - "statusRejected": "Отклонено" + "statusRejected": "Отклонено", + "showPhone": "Показать номер", + "phoneChecking": "Проверка…", + "phoneError": "Не удалось получить номер. Напишите автору в чат", + "ownAd": "Ваше объявление" }, "chat": { "title": "Чат", diff --git a/src/pages/CreateUpdatePost.jsx b/src/pages/CreateUpdatePost.jsx index 03094a0..a7623af 100644 --- a/src/pages/CreateUpdatePost.jsx +++ b/src/pages/CreateUpdatePost.jsx @@ -46,6 +46,7 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi category: initialData.category || "", date: initialData.date || "", phone: initialData.phone || profilePhone, + phoneVisible: !!initialData.phoneVisible, address: initialData.address || initialData.city || "", rulesAccepted: true, reward: initialData.reward ?? false, @@ -127,7 +128,11 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi data.append("title", form.title.trim()); data.append("description", form.description.trim()); 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"; data.append("reward", reward ? "true" : "false"); @@ -354,7 +359,26 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi {errors.map &&

{errors.map}

} - {/* Телефон */} + {/* Телефон: по умолчанию связь только через чат. Номер — персональные + данные (152-ФЗ), показываем его только с явного согласия автора */} + {!adminMode && ( +
+ +

+ {form.phoneVisible ? t('post.phoneConsentHint') : t('post.chatOnlyHint')} +

+
+ )} + + {(adminMode ? !!initialData?.phoneVisible : form.phoneVisible) && (
set("phone", "")} visible={!!form.phone}> @@ -368,6 +392,7 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi {errors.phone &&

{errors.phone}

}
+ )} {/* Вознаграждение — только для потери */} {form.type !== "found" && ( diff --git a/src/pages/CreateUpdatePost.test.jsx b/src/pages/CreateUpdatePost.test.jsx index e66c370..6ee3c72 100644 --- a/src/pages/CreateUpdatePost.test.jsx +++ b/src/pages/CreateUpdatePost.test.jsx @@ -2,7 +2,8 @@ * На десктопе форма объявления закрывается только крестиком: клик по фону * не должен терять заполненные поля. На мобильном клик по фону закрывает. * Там же на десктопе фото можно перетащить в форму (drag & drop). - * Телефон подставляется из профиля, если в объявлении его нет. + * Номер — только с согласием на показ (по умолчанию «только чат»); + * после согласия он подставляется из профиля, если в объявлении его нет. */ import { render, screen, fireEvent } from "@testing-library/react"; import CreateUpdatePost from "./CreateUpdatePost"; @@ -122,8 +123,10 @@ test("на мобильном перетаскивание фото выключ }); const PROFILE_PHONE = "+7 (999) 111-22-33"; +const PHONE_PLACEHOLDER = "+7 (___) ___-__-__"; +const CONSENT = /Показывать мой номер|Show my phone number/; -/** Рендерит форму и переходит на второй шаг, где находится поле «Телефон». */ +/** Рендерит форму и переходит на второй шаг, где находятся согласие и «Телефон». */ function openPhoneStep(props = {}) { useIsDesktop.mockReturnValue(true); render(); @@ -132,41 +135,69 @@ function openPhoneStep(props = {}) { fireEvent.change(screen.getByPlaceholderText(/опишите|describe/i), { target: { value: "Связка ключей" } }); } fireEvent.click(screen.getByText(/^(Далее|Next)/)); - return screen.getByPlaceholderText("+7 (___) ___-__-__"); } -test("новое объявление: телефон подставляется из профиля", () => { - useAuthContext.mockReturnValue({ user: { phone: "79991112233" } }); +const phoneField = () => screen.queryByPlaceholderText(PHONE_PLACEHOLDER); - 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("новое объявление без телефона в профиле: поле пустое", () => { - useAuthContext.mockReturnValue({ user: { phone: "" } }); +test("новое объявление: после согласия телефон подставляется из профиля", () => { + 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" }; test("редактирование: телефон объявления не заменяется телефоном профиля", () => { 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(phone.value).toBe("+7 (900) 000-00-00"); + expect(screen.getByLabelText(CONSENT).checked).toBe(true); + expect(phoneField().value).toBe("+7 (900) 000-00-00"); }); -test("редактирование объявления без телефона: подставляется телефон профиля", () => { +test("редактирование объявления «только чат»: согласие не включается само", () => { 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 } }); + openPhoneStep({ initialData: { ...POST, phoneVisible: false, phone: null }, adminMode: true }); - const phone = openPhoneStep({ initialData: { ...POST, phone: "" }, adminMode: true }); - - expect(phone.value).toBe(""); + expect(screen.queryByLabelText(CONSENT)).toBeNull(); + expect(phoneField()).toBeNull(); +}); + +test("админ правит номер объявления с согласием: свой телефон не подставляется", () => { + useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } }); + openPhoneStep({ initialData: { ...POST, phoneVisible: true, phone: "" }, adminMode: true }); + + expect(screen.queryByLabelText(CONSENT)).toBeNull(); + expect(phoneField().value).toBe(""); }); diff --git a/src/pages/PostOnFeed.jsx b/src/pages/PostOnFeed.jsx index d71623e..7002e2e 100644 --- a/src/pages/PostOnFeed.jsx +++ b/src/pages/PostOnFeed.jsx @@ -5,6 +5,7 @@ import PhoneIcon from "../components/icons/PhoneIcon"; import TrashIcon from "../components/icons/TrashIcon"; import CheckIcon from "../components/icons/CheckIcon"; import {useContactSeller} from "../hooks/useContactSeller"; +import {useRevealPhone} from "../hooks/useRevealPhone"; import {useAuthContext} from "../context/AuthContext"; import {getImageUrl} from "../config/authConstants"; import {CATEGORY_PET} from "../config/feedConstants"; @@ -31,6 +32,7 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen // isOwner тут не подходит — в общей ленте он false и для своих объявлений. const isOwnAd = user?.id != null && ad.userId != null && String(ad.userId) === String(user.id); const { contactSeller, error: contactError, clearError } = useContactSeller(ad); + const phoneReveal = useRevealPhone(ad.id); useEffect(() => { const check = () => { @@ -108,6 +110,13 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen ? t('postCard.foundStatusWithDate', {status: foundText, date: foundDate}) : 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 typeBadge = ( @@ -317,15 +326,27 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
- {ad.phone && ( - e.stopPropagation()}> - {ad.phone} + {shownPhone} + ) : canRevealPhone && ( + )}
- {!isOwnAd && ( + {isOwnAd ? ( + {t('postCard.ownAd')} + ) : (
)} + {phoneReveal.error && ( + + )} + {contactError && ( ({ 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(); + + fireEvent.click(screen.getByText(SHOW)); + + expect(await screen.findByText("+7 (999) 111-22-33")).toBeTruthy(); + expect(revealPhone).toHaveBeenCalledWith(7, expect.anything()); +}); + +test("без согласия автора кнопки нет — только чат", () => { + render(); + + expect(screen.queryByText(SHOW)).toBeNull(); +}); + +test("у закрытого объявления номер не предлагается", () => { + render(); + + expect(screen.queryByText(SHOW)).toBeNull(); +}); + +test("номер, пришедший с объявлением (автор, админ), показывается сразу", () => { + render(); + + expect(screen.getByText("+7 (900) 000-00-00")).toBeTruthy(); + expect(revealPhone).not.toHaveBeenCalled(); +}); + +test("ошибка показа номера — сообщение", async () => { + revealPhone.mockRejectedValue(new TypeError("Failed to fetch")); + render(); + + 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(); + + 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(); +}); diff --git a/src/styles/card.css b/src/styles/card.css index cd34c66..75defe0 100644 --- a/src/styles/card.css +++ b/src/styles/card.css @@ -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; 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-contact { diff --git a/src/utils/proofOfWork.js b/src/utils/proofOfWork.js new file mode 100644 index 0000000..103691f --- /dev/null +++ b/src/utils/proofOfWork.js @@ -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} + */ +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"); +} diff --git a/src/utils/proofOfWork.test.js b/src/utils/proofOfWork.test.js new file mode 100644 index 0000000..c25c480 --- /dev/null +++ b/src/utils/proofOfWork.test.js @@ -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" }); +}); diff --git a/src/utils/validatePostForm.js b/src/utils/validatePostForm.js index 3329c78..1c86dec 100644 --- a/src/utils/validatePostForm.js +++ b/src/utils/validatePostForm.js @@ -12,10 +12,10 @@ export function validatePostForm(form) { if (!description) errors.description = i18n.t('validation.descriptionRequired'); if (!form.category) errors.category = i18n.t('validation.categoryRequired'); - // Телефон обязателен для объявления (в отличие от профиля) — проверяем - // количество цифр, а не просто пустоту, т.к. form.phone форматируется - // через formatPhone и всегда содержит минимум "+7". - if ((form.phone ?? "").replace(/\D/g, "").length < 11) { + // Телефон нужен, только если автор согласился его показывать (иначе + // связь через чат). Проверяем количество цифр, а не пустоту: form.phone + // форматируется через formatPhone и всегда содержит минимум "+7". + if (form.phoneVisible && (form.phone ?? "").replace(/\D/g, "").length < 11) { errors.phone = i18n.t('validation.phoneRequired'); }