Tests for auth refresh, ad viewability and URL safety; nginx, Dockerfile, README
- Jest: single-flight refresh, session expiry vs transient errors, token save on login change, logout revoke, IAB viewability, safe URLs, HTML escaping, password policy, ad session id - test:ci with explicit testMatch (dot-directories in worktree paths hid all tests) - nginx: gzip, nosniff/Referrer-Policy/X-Frame-Options, no-cache for index.html - Dockerfile: npm ci, REACT_APP_WS_ERROR_QUEUE build arg - README: new backend contracts, flags, compatibility notes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,8 +5,21 @@ import i18n from "../i18n";
|
||||
export const PASSWORD_MIN_LENGTH = 8;
|
||||
export const PASSWORD_MAX_BYTES = 72;
|
||||
|
||||
/**
|
||||
* Длина строки в байтах UTF-8 — как password.getBytes(UTF_8) в Java
|
||||
* (одиночный суррогат Java заменяет на "?", 1 байт).
|
||||
*/
|
||||
export function passwordByteLength(password) {
|
||||
return new TextEncoder().encode(password).length;
|
||||
let bytes = 0;
|
||||
for (const ch of password) {
|
||||
const code = ch.codePointAt(0);
|
||||
if (code < 0x80) bytes += 1;
|
||||
else if (code < 0x800) bytes += 2;
|
||||
else if (code >= 0xd800 && code <= 0xdfff) bytes += 1;
|
||||
else if (code < 0x10000) bytes += 3;
|
||||
else bytes += 4;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/** Текст ошибки или "" — если пароль подходит. */
|
||||
|
||||
87
src/utils/security.test.js
Normal file
87
src/utils/security.test.js
Normal file
@@ -0,0 +1,87 @@
|
||||
import { toSafeHttpUrl, isSafeHttpUrl } from "./safeUrl";
|
||||
import { escapeHtml, escapeCssUrl } from "./escapeHtml";
|
||||
import { validatePassword } from "./passwordPolicy";
|
||||
import { getAdSessionId, isValidAdSessionId } from "./adSession";
|
||||
import { parseRetryAfter, describeApiError, ApiError } from "../api/apiErrors";
|
||||
|
||||
describe("toSafeHttpUrl", () => {
|
||||
it("пропускает только абсолютные http(s)", () => {
|
||||
expect(toSafeHttpUrl("https://example.com/promo")).toBe("https://example.com/promo");
|
||||
expect(toSafeHttpUrl(" http://example.com ")).toBe("http://example.com/");
|
||||
});
|
||||
|
||||
it.each([
|
||||
// eslint-disable-next-line no-script-url
|
||||
"javascript:alert(1)",
|
||||
// eslint-disable-next-line no-script-url
|
||||
"JAVASCRIPT:alert(1)",
|
||||
"data:text/html,<script>alert(1)</script>",
|
||||
"//evil.example",
|
||||
"/relative/path",
|
||||
"ftp://example.com",
|
||||
"",
|
||||
null,
|
||||
])("отклоняет %p", (value) => {
|
||||
expect(isSafeHttpUrl(value)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("escapeHtml", () => {
|
||||
it("экранирует разметку из пользовательского текста", () => {
|
||||
expect(escapeHtml(`<img src=x onerror="alert(1)">'&`))
|
||||
.toBe("<img src=x onerror="alert(1)">'&");
|
||||
});
|
||||
|
||||
it("URL не выходит за пределы url('...')", () => {
|
||||
expect(escapeCssUrl("a.jpg');background:url('x")).not.toMatch(/['()]/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validatePassword", () => {
|
||||
it("минимум 8 символов, как на бэкенде", () => {
|
||||
expect(validatePassword("1234567")).not.toBe("");
|
||||
expect(validatePassword("12345678")).toBe("");
|
||||
});
|
||||
|
||||
it("не длиннее 72 байт в UTF-8 (кириллица — 2 байта на букву)", () => {
|
||||
expect(validatePassword("я".repeat(36))).toBe("");
|
||||
expect(validatePassword("я".repeat(37))).not.toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAdSessionId", () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
it("стабилен между вызовами и подходит под формат бэкенда", () => {
|
||||
const id = getAdSessionId();
|
||||
expect(isValidAdSessionId(id)).toBe(true);
|
||||
expect(getAdSessionId()).toBe(id);
|
||||
});
|
||||
|
||||
it("заменяет сохранённый id с недопустимыми символами", () => {
|
||||
localStorage.setItem("ad_session_id", "bad id|with spaces");
|
||||
const id = getAdSessionId();
|
||||
expect(id).not.toBe("bad id|with spaces");
|
||||
expect(isValidAdSessionId(id)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ошибки API", () => {
|
||||
it("Retry-After — секунды или HTTP-дата", () => {
|
||||
expect(parseRetryAfter("120")).toBe(120);
|
||||
const now = Date.parse("2026-10-20T12:00:00Z");
|
||||
expect(parseRetryAfter("Tue, 20 Oct 2026 12:05:00 GMT", now)).toBe(300);
|
||||
expect(parseRetryAfter(null)).toBeNull();
|
||||
});
|
||||
|
||||
it("429 с Retry-After — сообщение с минутами, без Retry-After — текст сервера", () => {
|
||||
expect(describeApiError(new ApiError(429, { retryAfterSeconds: 900 }))).toMatch(/15/);
|
||||
expect(describeApiError(new ApiError(429, { message: "Слишком много неудачных попыток входа" })))
|
||||
.toBe("Слишком много неудачных попыток входа");
|
||||
});
|
||||
|
||||
it("400 — текст сервера, 5xx — fallback", () => {
|
||||
expect(describeApiError(new ApiError(400, { message: "Неверный логин" }), "fb")).toBe("Неверный логин");
|
||||
expect(describeApiError(new ApiError(500, { message: "Internal server error" }), "fb")).toBe("fb");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user