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

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 (!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');
}