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:
147
src/api/apiClient.test.js
Normal file
147
src/api/apiClient.test.js
Normal file
@@ -0,0 +1,147 @@
|
||||
import {
|
||||
apiFetch,
|
||||
getTokenExpiry,
|
||||
isTokenExpiring,
|
||||
refreshAccessToken,
|
||||
SessionExpiredError,
|
||||
setOnSessionExpired,
|
||||
} from "./apiClient";
|
||||
|
||||
/** JWT без подписи — клиенту нужен только payload.exp. */
|
||||
function jwt(expSecondsFromNow) {
|
||||
const payload = { sub: "user", exp: Math.floor(Date.now() / 1000) + expSecondsFromNow };
|
||||
const encode = (obj) => btoa(JSON.stringify(obj)).replace(/=+$/, "");
|
||||
return `${encode({ alg: "HS256" })}.${encode(payload)}.sig`;
|
||||
}
|
||||
|
||||
function response(status, body) {
|
||||
return {
|
||||
status,
|
||||
ok: status >= 200 && status < 300,
|
||||
headers: { get: () => null },
|
||||
json: async () => body,
|
||||
};
|
||||
}
|
||||
|
||||
const FRESH = jwt(15 * 60);
|
||||
const REFRESH = `uuid.${jwt(7 * 24 * 3600)}`;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
global.fetch = jest.fn();
|
||||
setOnSessionExpired(null);
|
||||
});
|
||||
|
||||
describe("getTokenExpiry", () => {
|
||||
it("читает exp у access-токена и у refresh-токена вида {uuid}.{jwt}", () => {
|
||||
expect(getTokenExpiry(FRESH)).toBeGreaterThan(Date.now());
|
||||
expect(getTokenExpiry(REFRESH)).toBeGreaterThan(Date.now() + 6 * 24 * 3600 * 1000);
|
||||
});
|
||||
|
||||
it("не JWT — null, а не исключение", () => {
|
||||
expect(getTokenExpiry("garbage")).toBeNull();
|
||||
expect(getTokenExpiry(null)).toBeNull();
|
||||
});
|
||||
|
||||
it("истекающий токен считается истекающим заранее", () => {
|
||||
expect(isTokenExpiring(jwt(10))).toBe(true);
|
||||
expect(isTokenExpiring(FRESH)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("refreshAccessToken", () => {
|
||||
it("параллельные вызовы делают один POST /auth/refresh (refresh-токен одноразовый)", async () => {
|
||||
localStorage.setItem("token", jwt(-10));
|
||||
localStorage.setItem("refreshToken", REFRESH);
|
||||
const newAccess = jwt(900);
|
||||
global.fetch.mockResolvedValue(response(200, { token: newAccess, refreshToken: `uuid2.${jwt(3600)}` }));
|
||||
|
||||
const [a, b, c] = await Promise.all([refreshAccessToken(), refreshAccessToken(), refreshAccessToken()]);
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
expect([a, b, c]).toEqual([newAccess, newAccess, newAccess]);
|
||||
expect(localStorage.getItem("token")).toBe(newAccess);
|
||||
});
|
||||
|
||||
it("401 на refresh — SessionExpiredError", async () => {
|
||||
localStorage.setItem("token", jwt(-10));
|
||||
localStorage.setItem("refreshToken", REFRESH);
|
||||
global.fetch.mockResolvedValue(response(401, { message: "Unauthorized" }));
|
||||
|
||||
await expect(refreshAccessToken()).rejects.toBeInstanceOf(SessionExpiredError);
|
||||
});
|
||||
|
||||
it("истёкший refresh-токен не отправляется на сервер", async () => {
|
||||
localStorage.setItem("token", jwt(-10));
|
||||
localStorage.setItem("refreshToken", `uuid.${jwt(-60)}`);
|
||||
|
||||
await expect(refreshAccessToken()).rejects.toBeInstanceOf(SessionExpiredError);
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("apiFetch", () => {
|
||||
it("на 401 обновляет токен один раз для всех параллельных запросов и повторяет их", async () => {
|
||||
const stale = jwt(600);
|
||||
const fresh = jwt(900);
|
||||
localStorage.setItem("token", stale);
|
||||
localStorage.setItem("refreshToken", REFRESH);
|
||||
|
||||
global.fetch.mockImplementation(async (url, init) => {
|
||||
if (url.endsWith("/api/v1/auth/refresh")) {
|
||||
return response(200, { token: fresh, refreshToken: `uuid2.${jwt(3600)}` });
|
||||
}
|
||||
const auth = init?.headers?.Authorization;
|
||||
return auth === `Bearer ${fresh}` ? response(200, { ok: true }) : response(401, {});
|
||||
});
|
||||
|
||||
const results = await Promise.all([apiFetch("http://api/a"), apiFetch("http://api/b")]);
|
||||
|
||||
expect(results.map((r) => r.status)).toEqual([200, 200]);
|
||||
const refreshCalls = global.fetch.mock.calls.filter(([url]) => url.endsWith("/auth/refresh"));
|
||||
expect(refreshCalls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("refresh отклонён — сессия очищается и вызывается onSessionExpired", async () => {
|
||||
localStorage.setItem("token", FRESH);
|
||||
localStorage.setItem("refreshToken", REFRESH);
|
||||
localStorage.setItem("user", "{}");
|
||||
const onExpired = jest.fn();
|
||||
setOnSessionExpired(onExpired);
|
||||
global.fetch.mockImplementation(async (url) =>
|
||||
url.endsWith("/auth/refresh") ? response(401, {}) : response(401, {}));
|
||||
|
||||
await expect(apiFetch("http://api/a")).rejects.toBeInstanceOf(SessionExpiredError);
|
||||
expect(onExpired).toHaveBeenCalledTimes(1);
|
||||
expect(localStorage.getItem("token")).toBeNull();
|
||||
expect(localStorage.getItem("user")).toBeNull();
|
||||
});
|
||||
|
||||
it("сбой сети или 5xx на refresh не разлогинивает: возвращается исходный 401", async () => {
|
||||
localStorage.setItem("token", FRESH);
|
||||
localStorage.setItem("refreshToken", REFRESH);
|
||||
global.fetch.mockImplementation(async (url) =>
|
||||
url.endsWith("/auth/refresh") ? response(503, {}) : response(401, {}));
|
||||
|
||||
const res = await apiFetch("http://api/a");
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(localStorage.getItem("token")).toBe(FRESH);
|
||||
expect(localStorage.getItem("refreshToken")).toBe(REFRESH);
|
||||
});
|
||||
|
||||
it("истекающий токен обновляется до запроса (публичные GET не отвечают 401)", async () => {
|
||||
const fresh = jwt(900);
|
||||
localStorage.setItem("token", jwt(5));
|
||||
localStorage.setItem("refreshToken", REFRESH);
|
||||
global.fetch.mockImplementation(async (url) =>
|
||||
url.endsWith("/auth/refresh")
|
||||
? response(200, { token: fresh, refreshToken: `uuid2.${jwt(3600)}` })
|
||||
: response(200, []));
|
||||
|
||||
await apiFetch("http://api/posts");
|
||||
|
||||
const [, init] = global.fetch.mock.calls.find(([url]) => url === "http://api/posts");
|
||||
expect(init.headers.Authorization).toBe(`Bearer ${fresh}`);
|
||||
});
|
||||
});
|
||||
60
src/context/AuthContext.test.jsx
Normal file
60
src/context/AuthContext.test.jsx
Normal file
@@ -0,0 +1,60 @@
|
||||
import { render, act } from "@testing-library/react";
|
||||
import { AuthProvider, useAuthContext } from "./AuthContext";
|
||||
|
||||
let ctx;
|
||||
function Probe() {
|
||||
ctx = useAuthContext();
|
||||
return null;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
global.fetch = jest.fn().mockResolvedValue({ ok: true, status: 204 });
|
||||
});
|
||||
|
||||
describe("AuthContext.updateUser", () => {
|
||||
it("сохраняет новую пару токенов из ответа PUT /users/{id} и не кладёт её в user", () => {
|
||||
localStorage.setItem("token", "old-access");
|
||||
localStorage.setItem("refreshToken", "old-refresh");
|
||||
render(<AuthProvider><Probe /></AuthProvider>);
|
||||
|
||||
act(() => {
|
||||
ctx.updateUser({ id: 1, login: "new-login", token: "new-access", refreshToken: "new-refresh" });
|
||||
});
|
||||
|
||||
expect(localStorage.getItem("token")).toBe("new-access");
|
||||
expect(localStorage.getItem("refreshToken")).toBe("new-refresh");
|
||||
expect(JSON.parse(localStorage.getItem("user"))).toEqual({ id: 1, login: "new-login" });
|
||||
expect(ctx.user).toEqual({ id: 1, login: "new-login" });
|
||||
expect(ctx.token).toBe("new-access");
|
||||
});
|
||||
|
||||
it("без новых токенов (логин не менялся) оставляет прежние", () => {
|
||||
localStorage.setItem("token", "access");
|
||||
localStorage.setItem("refreshToken", "refresh");
|
||||
render(<AuthProvider><Probe /></AuthProvider>);
|
||||
|
||||
act(() => {
|
||||
ctx.updateUser({ id: 1, login: "same", email: null, phone: null });
|
||||
});
|
||||
|
||||
expect(localStorage.getItem("token")).toBe("access");
|
||||
expect(localStorage.getItem("refreshToken")).toBe("refresh");
|
||||
});
|
||||
});
|
||||
|
||||
describe("AuthContext.logout", () => {
|
||||
it("отзывает refresh-токен на сервере и чистит сессию", () => {
|
||||
localStorage.setItem("token", "access");
|
||||
localStorage.setItem("refreshToken", "refresh");
|
||||
render(<AuthProvider><Probe /></AuthProvider>);
|
||||
|
||||
act(() => { ctx.logout(); });
|
||||
|
||||
const [url, init] = global.fetch.mock.calls[0];
|
||||
expect(url).toMatch(/\/api\/v1\/auth\/logout$/);
|
||||
expect(JSON.parse(init.body)).toEqual({ refreshToken: "refresh" });
|
||||
expect(localStorage.getItem("token")).toBeNull();
|
||||
expect(ctx.isAuthenticated).toBe(false);
|
||||
});
|
||||
});
|
||||
70
src/hooks/useAdViewability.test.jsx
Normal file
70
src/hooks/useAdViewability.test.jsx
Normal file
@@ -0,0 +1,70 @@
|
||||
import { render, act } from "@testing-library/react";
|
||||
import { useRef } from "react";
|
||||
import { useAdViewability, VIEWABLE_MS } from "./useAdViewability";
|
||||
|
||||
let observerCallback;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
observerCallback = null;
|
||||
global.IntersectionObserver = jest.fn(function IntersectionObserver(cb) {
|
||||
observerCallback = cb;
|
||||
this.observe = jest.fn();
|
||||
this.disconnect = jest.fn();
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
function Banner({ onViewable }) {
|
||||
const ref = useRef(null);
|
||||
useAdViewability(ref, onViewable);
|
||||
return <div ref={ref} />;
|
||||
}
|
||||
|
||||
const intersect = (ratio) => act(() => {
|
||||
observerCallback([{ isIntersecting: ratio > 0, intersectionRatio: ratio }]);
|
||||
});
|
||||
|
||||
describe("useAdViewability", () => {
|
||||
it("засчитывает показ, когда ≥ 50% видно ≥ 1 секунды", () => {
|
||||
const onViewable = jest.fn();
|
||||
render(<Banner onViewable={onViewable} />);
|
||||
|
||||
intersect(0.6);
|
||||
act(() => { jest.advanceTimersByTime(VIEWABLE_MS - 1); });
|
||||
expect(onViewable).not.toHaveBeenCalled();
|
||||
|
||||
act(() => { jest.advanceTimersByTime(1); });
|
||||
expect(onViewable).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("меньше 50% или ушёл с экрана раньше секунды — не показ", () => {
|
||||
const onViewable = jest.fn();
|
||||
render(<Banner onViewable={onViewable} />);
|
||||
|
||||
intersect(0.3);
|
||||
act(() => { jest.advanceTimersByTime(5000); });
|
||||
intersect(0.8);
|
||||
act(() => { jest.advanceTimersByTime(500); });
|
||||
intersect(0);
|
||||
act(() => { jest.advanceTimersByTime(5000); });
|
||||
|
||||
expect(onViewable).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("показ засчитывается один раз", () => {
|
||||
const onViewable = jest.fn();
|
||||
render(<Banner onViewable={onViewable} />);
|
||||
|
||||
intersect(1);
|
||||
act(() => { jest.advanceTimersByTime(VIEWABLE_MS); });
|
||||
intersect(0);
|
||||
intersect(1);
|
||||
act(() => { jest.advanceTimersByTime(VIEWABLE_MS * 3); });
|
||||
|
||||
expect(onViewable).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -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