🌊 Волна 15: frontend #5 — security + юзабилити (16 багов)
Security (XSS): - feed_modal_javascript_url_xss: safeUrl валидация (FeedModal.tsx) - feed_modal_telegram_url_xss: safeUrl валидация (FeedModal.tsx) Данные: - feed_composer_duplicate_post_on_upload_fail: isPublished флаг (FeedPostComposer.tsx) - STRICTMODE_DOUBLE_REGISTER_RETRY: двойная защита + cleanup (App.tsx) - RETRY_TIMEOUT_NOT_CLEANED: clearTimeout в cleanup (App.tsx) Производительность: - CONTENT_TYPE_ON_GET_TRIGGERS_PREFLIGHT: Content-Type только при body (api.ts) - DUPLICATED_FETCH_LOGIC: fetchWithTimeout helper (api.ts) - UNENCODED_PATH_PARAMS: encodeURIComponent для path (api.ts) Юзабилити: - content_editor_no_escape: Escape (ContentEditorMenu.tsx) - lessons_editor_no_backdrop_close: Escape + backdrop (LessonsEditor.tsx) - support_delete_ticket_no_confirm: модалка подтверждения (SupportChatModal.tsx) Качество: - GET_INIT_DATA_CONSOLE_SPAM: логируем один раз (telegram.ts) - words_editor_dead_button: удалена мёртвая кнопка (WordsEditor.tsx) - highlights_carousel_setstate_on_unmount: убран setState в cleanup (HighlightsCarousel.tsx) - image_lightbox_timers_accumulate: очистка таймеров (ImageLightbox.tsx) - typing_modal_timeout_not_cleared: clearTimeout (TypingModal.tsx) Пропущено осознанно: - INIT_DATA_IN_URL_DELETE_FEED (fallback для deleteFeedPost, Cloudflare preflight) Аудит v3: Issue #4, frontend 17/18 задач
This commit is contained in:
+72
-53
@@ -177,6 +177,24 @@ export interface SentryErrorsError {
|
||||
export type SentryErrorsResponse = SentryErrorsSuccess | SentryErrorsError;
|
||||
|
||||
// ============ FETCH WRAPPER ============
|
||||
|
||||
// 🔧 ФИКС (24.09.2026): DUPLICATED_FETCH_LOGIC —
|
||||
// общий helper для fetch с таймаутом. Используется в fetchAPI, getTTS,
|
||||
// uploadFeedImage, deleteFeedPost.
|
||||
const fetchWithTimeout = async (
|
||||
url: string,
|
||||
options: RequestInit = {},
|
||||
timeoutMs: number = FETCH_TIMEOUT_MS,
|
||||
): Promise<Response> => {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
return await fetch(url, { ...options, signal: controller.signal });
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchAPI = async (endpoint: string, options: RequestInit = {}) => {
|
||||
const initData = getInitData();
|
||||
|
||||
@@ -186,31 +204,36 @@ const fetchAPI = async (endpoint: string, options: RequestInit = {}) => {
|
||||
// Формат "tma <initData>" — стандарт Telegram Mini Apps.
|
||||
const url = `${API_BASE}${endpoint}`;
|
||||
|
||||
// 🔧 ФИКС (23.09.2026): FETCH_NO_TIMEOUT — AbortController с таймаутом.
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||
// 🔧 ФИКС (24.09.2026): CONTENT_TYPE_ON_GET_TRIGGERS_PREFLIGHT —
|
||||
// Content-Type ставим ТОЛЬКО когда есть body (POST/PUT/PATCH).
|
||||
// Для GET — не задаём, чтобы не триггерить CORS preflight.
|
||||
const method = (options.method || 'GET').toUpperCase();
|
||||
const hasBody = options.body !== undefined && options.body !== null;
|
||||
// Content-Type нужен только для методов с телом (POST/PUT/PATCH/DELETE с body).
|
||||
// Для GET/HEAD — никогда, даже если по ошибке передали body.
|
||||
const needsContentType = hasBody && method !== 'GET' && method !== 'HEAD';
|
||||
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
...options,
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `tma ${initData}`,
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
throw new Error(`API Error: ${res.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
return data;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
const headers: Record<string, string> = {
|
||||
'Authorization': `tma ${initData}`,
|
||||
...(options.headers as Record<string, string> || {}),
|
||||
};
|
||||
if (needsContentType && !headers['Content-Type']) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
|
||||
// 🔧 ФИКС (24.09.2026): DUPLICATED_FETCH_LOGIC — используем helper.
|
||||
const res = await fetchWithTimeout(url, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
throw new Error(`API Error: ${res.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
return data;
|
||||
};
|
||||
|
||||
// ============ Пользователь ============
|
||||
@@ -342,32 +365,26 @@ export const getNextPronunciationWord = () =>
|
||||
fetchAPI('/pronunciation/next');
|
||||
|
||||
// ============ TTS (Edge TTS) ============
|
||||
export const getTTS = (text: string, voice: string = 'female'): Promise<Blob> => {
|
||||
export const getTTS = async (text: string, voice: string = 'female'): Promise<Blob> => {
|
||||
const initData = getInitData();
|
||||
|
||||
// 🔧 ФИКС (23.09.2026): INIT_DATA_IN_URL — initData в заголовке.
|
||||
// Заодно: voice теперь кодируется через encodeURIComponent (TTS_VOICE_NOT_ENCODED).
|
||||
const url = `${API_BASE}/tts?text=${encodeURIComponent(text)}&voice=${encodeURIComponent(voice)}`;
|
||||
|
||||
// 🔧 ФИКС (23.09.2026): FETCH_NO_TIMEOUT — таймаут на TTS.
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||
|
||||
return fetch(url, {
|
||||
// 🔧 ФИКС (24.09.2026): DUPLICATED_FETCH_LOGIC — используем helper.
|
||||
const res = await fetchWithTimeout(url, {
|
||||
method: 'GET',
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
'Authorization': `tma ${initData}`,
|
||||
},
|
||||
}).then(async (res) => {
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
throw new Error(`API Error: ${res.status} - ${errorText}`);
|
||||
}
|
||||
return res.blob();
|
||||
}).finally(() => {
|
||||
clearTimeout(timeoutId);
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
throw new Error(`API Error: ${res.status} - ${errorText}`);
|
||||
}
|
||||
return res.blob();
|
||||
};
|
||||
|
||||
// ============ AI Assistant ============
|
||||
@@ -403,16 +420,16 @@ export const getLearningLevels = (): Promise<LearningLevelsResponse> =>
|
||||
fetchAPI('/learning/levels');
|
||||
|
||||
export const getLearningTopics = (level: string) =>
|
||||
fetchAPI(`/learning/topics?level=${level}`);
|
||||
fetchAPI(`/learning/topics?level=${encodeURIComponent(level)}`);
|
||||
|
||||
export const getLearningTopic = (topicId: string) =>
|
||||
fetchAPI(`/learning/topics/${topicId}`);
|
||||
fetchAPI(`/learning/topics/${encodeURIComponent(topicId)}`);
|
||||
|
||||
export const getLearningLesson = (lessonId: string) =>
|
||||
fetchAPI(`/learning/lessons/${lessonId}`);
|
||||
fetchAPI(`/learning/lessons/${encodeURIComponent(lessonId)}`);
|
||||
|
||||
export const getTopicTest = (topicId: string) =>
|
||||
fetchAPI(`/learning/test/${topicId}`);
|
||||
fetchAPI(`/learning/test/${encodeURIComponent(topicId)}`);
|
||||
|
||||
export const startLearningSession = (levelCode: string, topicId: string, sessionType: string = 'lesson') =>
|
||||
fetchAPI('/learning/session/start', {
|
||||
@@ -839,7 +856,8 @@ export const deleteFeedPost = async (postId: number): Promise<{ status: string }
|
||||
const initData = getInitData();
|
||||
const url = `${API_BASE}/admin/feed/post/${postId}/delete?initData=${encodeURIComponent(initData)}`;
|
||||
|
||||
const res = await fetch(url, { method: 'POST' });
|
||||
// 🔧 ФИКС (24.09.2026): DUPLICATED_FETCH_LOGIC — используем helper.
|
||||
const res = await fetchWithTimeout(url, { method: 'POST' });
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
@@ -914,7 +932,8 @@ export const uploadFeedImage = async (
|
||||
formData.append('post_id', String(postId));
|
||||
formData.append('file', blob, cleanName);
|
||||
|
||||
const res = await fetch(url, {
|
||||
// 🔧 ФИКС (24.09.2026): DUPLICATED_FETCH_LOGIC — используем helper.
|
||||
const res = await fetchWithTimeout(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `tma ${initData}`,
|
||||
@@ -1005,7 +1024,7 @@ export const getLevelWords = (level: string, q?: string): Promise<ContentWordsLi
|
||||
const params = new URLSearchParams();
|
||||
if (q) params.set('q', q);
|
||||
const qs = params.toString();
|
||||
return fetchAPI(`/admin/content/words/level/${level}${qs ? '?' + qs : ''}`);
|
||||
return fetchAPI(`/admin/content/words/level/${encodeURIComponent(level)}${qs ? '?' + qs : ''}`);
|
||||
};
|
||||
|
||||
export const getWord = (wordId: number): Promise<ContentWord & { level: string }> =>
|
||||
@@ -1028,7 +1047,7 @@ export const createWord = (level: string, payload: {
|
||||
translation_uk: string;
|
||||
translation_en: string;
|
||||
}): Promise<{ status: string; word_id: number }> =>
|
||||
fetchAPI(`/admin/content/words/level/${level}`, {
|
||||
fetchAPI(`/admin/content/words/level/${encodeURIComponent(level)}`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
@@ -1041,7 +1060,7 @@ export const getLevelTexts = (level: string, q?: string): Promise<ContentTextsLi
|
||||
const params = new URLSearchParams();
|
||||
if (q) params.set('q', q);
|
||||
const qs = params.toString();
|
||||
return fetchAPI(`/admin/content/texts/level/${level}${qs ? '?' + qs : ''}`);
|
||||
return fetchAPI(`/admin/content/texts/level/${encodeURIComponent(level)}${qs ? '?' + qs : ''}`);
|
||||
};
|
||||
|
||||
export const getText = (textId: number): Promise<ContentText & { level: string }> =>
|
||||
@@ -1064,12 +1083,12 @@ export const createText = (level: string, payload: {
|
||||
translation_uk: string;
|
||||
translation_en: string;
|
||||
}): Promise<{ status: string; text_id: number; sentence_number: number }> =>
|
||||
fetchAPI(`/admin/content/texts/level/${level}`, {
|
||||
fetchAPI(`/admin/content/texts/level/${encodeURIComponent(level)}`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
// ============ ADMIN CONTENT: LESSONS ============
|
||||
// ============ ADMIN CONTENT: LESSONS ============
|
||||
|
||||
export interface ContentLessonLevel {
|
||||
code: string;
|
||||
@@ -1125,11 +1144,11 @@ export const getLessonLevels = (): Promise<{ levels: ContentLessonLevel[] }> =>
|
||||
|
||||
// Темы уровня
|
||||
export const getLessonTopics = (level: string): Promise<{ level: string; topics: ContentLessonTopic[] }> =>
|
||||
fetchAPI(`/admin/content/lessons/level/${level}/topics`);
|
||||
fetchAPI(`/admin/content/lessons/level/${encodeURIComponent(level)}/topics`);
|
||||
|
||||
// Тема целиком (с уроками)
|
||||
export const getLessonTopic = (topicId: string): Promise<ContentTopicDetail> =>
|
||||
fetchAPI(`/admin/content/lessons/topic/${topicId}`);
|
||||
fetchAPI(`/admin/content/lessons/topic/${encodeURIComponent(topicId)}`);
|
||||
|
||||
// Урок целиком (для WYSIWYG)
|
||||
export const getLessonFull = (lessonId: string): Promise<{
|
||||
@@ -1137,7 +1156,7 @@ export const getLessonFull = (lessonId: string): Promise<{
|
||||
examples: any[];
|
||||
questions: any[];
|
||||
}> =>
|
||||
fetchAPI(`/admin/content/lessons/lesson/${lessonId}`);
|
||||
fetchAPI(`/admin/content/lessons/lesson/${encodeURIComponent(lessonId)}`);
|
||||
|
||||
// Сохранить урок
|
||||
export const updateLessonFull = (
|
||||
@@ -1160,7 +1179,7 @@ export const updateLessonFull = (
|
||||
}>;
|
||||
}
|
||||
): Promise<{ status: string; lesson_id: string; examples_count: number; questions_count: number }> =>
|
||||
fetchAPI(`/admin/content/lessons/lesson/${lessonId}`, {
|
||||
fetchAPI(`/admin/content/lessons/lesson/${encodeURIComponent(lessonId)}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user