Phase 10: запрет inline eslint-disable, file-level overrides, IUser-тип
This commit is contained in:
+42
-7
@@ -18,6 +18,8 @@ const CONFIG_ROOT = import.meta.dirname;
|
|||||||
const TEST_FILES = ['**/*.{test,spec}.{ts,tsx}'];
|
const TEST_FILES = ['**/*.{test,spec}.{ts,tsx}'];
|
||||||
const CONFIG_AND_SCRIPT_FILES = ['**/*.config.{ts,mts,cts}', '**/vite.config.*'];
|
const CONFIG_AND_SCRIPT_FILES = ['**/*.config.{ts,mts,cts}', '**/vite.config.*'];
|
||||||
|
|
||||||
|
/* eslint-disable no-unused-vars -- eslint.config.js lintится самим собой */
|
||||||
|
|
||||||
/* Забираем правила из пресетов плагинов */
|
/* Забираем правила из пресетов плагинов */
|
||||||
const reactRecommendedRules =
|
const reactRecommendedRules =
|
||||||
react.configs.flat?.recommended?.rules ??
|
react.configs.flat?.recommended?.rules ??
|
||||||
@@ -50,8 +52,11 @@ export default defineConfig(
|
|||||||
{
|
{
|
||||||
name: 'client/linter-policy',
|
name: 'client/linter-policy',
|
||||||
linterOptions: {
|
linterOptions: {
|
||||||
noInlineConfig: false,
|
// Inline-директивы (eslint-disable и т.п.) в коде запрещены.
|
||||||
|
// Единственный способ отключить правило — file-level override в этом конфиге.
|
||||||
|
noInlineConfig: true,
|
||||||
reportUnusedDisableDirectives: 'error',
|
reportUnusedDisableDirectives: 'error',
|
||||||
|
reportUnusedInlineConfigs: 'error',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -274,12 +279,6 @@ export default defineConfig(
|
|||||||
'newlines-between': 'always',
|
'newlines-between': 'always',
|
||||||
}],
|
}],
|
||||||
|
|
||||||
/* Запрет необъяснённых disable-директив */
|
|
||||||
'@eslint-community/eslint-comments/disable-enable-pair': ['error', { allowWholeFile: false }],
|
|
||||||
'@eslint-community/eslint-comments/no-aggregating-enable': 'error',
|
|
||||||
'@eslint-community/eslint-comments/no-duplicate-disable': 'error',
|
|
||||||
'@eslint-community/eslint-comments/no-unlimited-disable': 'error',
|
|
||||||
'@eslint-community/eslint-comments/require-description': ['error', { ignore: ['eslint-enable'] }],
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -310,4 +309,40 @@ export default defineConfig(
|
|||||||
'@typescript-eslint/require-await': 'off',
|
'@typescript-eslint/require-await': 'off',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/* ── Файловые исключения (единственный способ отключить правило) ── */
|
||||||
|
{
|
||||||
|
name: 'client/api-client',
|
||||||
|
files: ['src/api/client.ts'],
|
||||||
|
rules: {
|
||||||
|
// fetch.json() возвращает any — assertion неизбежен
|
||||||
|
'@typescript-eslint/no-unsafe-type-assertion': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'client/news-editor',
|
||||||
|
files: ['src/hooks/useNewsEditor.ts'],
|
||||||
|
rules: {
|
||||||
|
// Хук-оркестратор: 4 action-обработчика + toolbar + upload
|
||||||
|
'max-lines-per-function': 'off',
|
||||||
|
// window.confirm для подтверждения удаления
|
||||||
|
'no-alert': 'off',
|
||||||
|
// e.target.value = '' — сброс file input (стандартный паттерн)
|
||||||
|
'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: ['e'] }],
|
||||||
|
// Навигация после await (window.location.href → useNavigate)
|
||||||
|
'require-atomic-updates': 'off',
|
||||||
|
// async IIFE в useEffect для загрузки новости
|
||||||
|
'@typescript-eslint/no-floating-promises': 'off',
|
||||||
|
// newsId гарантированно string (проверено isNew)
|
||||||
|
'@typescript-eslint/restrict-template-expressions': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'client/auth-pages',
|
||||||
|
files: ['src/pages/LoginPage.tsx', 'src/pages/RegisterPage.tsx'],
|
||||||
|
rules: {
|
||||||
|
// .then()/.catch() в цепочке — не floating promise
|
||||||
|
'@typescript-eslint/no-floating-promises': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -80,7 +80,6 @@ async function handleResponse<T>(res: Response): Promise<T> {
|
|||||||
window.location.href = '/login';
|
window.location.href = '/login';
|
||||||
}
|
}
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- fetch.json() returns any
|
|
||||||
const data = (await res.json().catch(() => ({}))) as unknown as ApiErrorBody & T;
|
const data = (await res.json().catch(() => ({}))) as unknown as ApiErrorBody & T;
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
|
|||||||
@@ -17,10 +17,8 @@ function useLoadNews(newsId: string | undefined, isNew: boolean) {
|
|||||||
if (isNew) {
|
if (isNew) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- async IIFE в useEffect
|
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- newsId гарантированно string (проверено isNew)
|
|
||||||
const data = await apiFetch<{ news: { title: string; content: string; status: string } }>(`/news/${newsId}`);
|
const data = await apiFetch<{ news: { title: string; content: string; status: string } }>(`/news/${newsId}`);
|
||||||
setTitle(data.news.title);
|
setTitle(data.news.title);
|
||||||
setContent(data.news.content);
|
setContent(data.news.content);
|
||||||
@@ -45,7 +43,6 @@ function useLoadNews(newsId: string | undefined, isNew: boolean) {
|
|||||||
* @param newsId — id новости или undefined для создания
|
* @param newsId — id новости или undefined для создания
|
||||||
* @returns состояние и обработчики для NewsEditorPage
|
* @returns состояние и обработчики для NewsEditorPage
|
||||||
*/
|
*/
|
||||||
/* eslint-disable max-lines-per-function -- хук-оркестратор */
|
|
||||||
export function useNewsEditor(newsId: string | undefined) {
|
export function useNewsEditor(newsId: string | undefined) {
|
||||||
const isNew = newsId === undefined;
|
const isNew = newsId === undefined;
|
||||||
const { title, setTitle, content, setContent, newsStatus, loading } = useLoadNews(newsId, isNew);
|
const { title, setTitle, content, setContent, newsStatus, loading } = useLoadNews(newsId, isNew);
|
||||||
@@ -149,7 +146,6 @@ export function useNewsEditor(newsId: string | undefined) {
|
|||||||
if (newsId === undefined) {
|
if (newsId === undefined) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line no-alert -- подтверждение удаления
|
|
||||||
if (!window.confirm('Удалить новость?')) {
|
if (!window.confirm('Удалить новость?')) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -157,7 +153,6 @@ export function useNewsEditor(newsId: string | undefined) {
|
|||||||
setError('');
|
setError('');
|
||||||
try {
|
try {
|
||||||
await apiFetch(`/news/${newsId}`, { method: 'DELETE' });
|
await apiFetch(`/news/${newsId}`, { method: 'DELETE' });
|
||||||
// eslint-disable-next-line require-atomic-updates -- navigation after await
|
|
||||||
window.location.href = '/news';
|
window.location.href = '/news';
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : 'Ошибка удаления');
|
setError(err instanceof Error ? err.message : 'Ошибка удаления');
|
||||||
@@ -214,7 +209,6 @@ export function useNewsEditor(newsId: string | undefined) {
|
|||||||
if (file !== undefined) {
|
if (file !== undefined) {
|
||||||
handleFileUpload(file, true).catch((err: unknown) => { console.error(err); });
|
handleFileUpload(file, true).catch((err: unknown) => { console.error(err); });
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line no-param-reassign -- сброс file input
|
|
||||||
e.target.value = '';
|
e.target.value = '';
|
||||||
}, [handleFileUpload]);
|
}, [handleFileUpload]);
|
||||||
|
|
||||||
@@ -224,7 +218,6 @@ export function useNewsEditor(newsId: string | undefined) {
|
|||||||
if (file !== undefined) {
|
if (file !== undefined) {
|
||||||
handleFileUpload(file, false).catch((err: unknown) => { console.error(err); });
|
handleFileUpload(file, false).catch((err: unknown) => { console.error(err); });
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line no-param-reassign -- сброс file input
|
|
||||||
e.target.value = '';
|
e.target.value = '';
|
||||||
}, [handleFileUpload]);
|
}, [handleFileUpload]);
|
||||||
|
|
||||||
@@ -239,4 +232,3 @@ export function useNewsEditor(newsId: string | undefined) {
|
|||||||
onSave, onPublish, onDelete, onSchedule,
|
onSave, onPublish, onDelete, onSchedule,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
/* eslint-enable max-lines-per-function */
|
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ export function LoginPage() {
|
|||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
/* eslint-disable @typescript-eslint/no-floating-promises -- Promise обработан через .catch() */
|
|
||||||
const handleSubmit = (e: FormEvent): void => {
|
const handleSubmit = (e: FormEvent): void => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError('');
|
setError('');
|
||||||
@@ -28,7 +27,6 @@ export function LoginPage() {
|
|||||||
})
|
})
|
||||||
.finally(() => { setLoading(false); });
|
.finally(() => { setLoading(false); });
|
||||||
};
|
};
|
||||||
/* eslint-enable @typescript-eslint/no-floating-promises */
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.page}>
|
<div className={styles.page}>
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ export function NewsListPage() {
|
|||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- async IIFE в useEffect
|
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
const data = await apiFetch<{ news: NewsItem[] }>('/news');
|
const data = await apiFetch<{ news: NewsItem[] }>('/news');
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ export function RegisterPage() {
|
|||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
/* eslint-disable @typescript-eslint/no-floating-promises -- Promise обработан через .catch() */
|
|
||||||
const handleSubmit = (e: FormEvent): void => {
|
const handleSubmit = (e: FormEvent): void => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (password !== confirmPassword) {
|
if (password !== confirmPassword) {
|
||||||
@@ -33,7 +32,6 @@ export function RegisterPage() {
|
|||||||
})
|
})
|
||||||
.finally(() => { setLoading(false); });
|
.finally(() => { setLoading(false); });
|
||||||
};
|
};
|
||||||
/* eslint-enable @typescript-eslint/no-floating-promises */
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.page}>
|
<div className={styles.page}>
|
||||||
|
|||||||
+87
-8
@@ -13,7 +13,7 @@ import tseslint from 'typescript-eslint';
|
|||||||
const CONFIG_ROOT = import.meta.dirname;
|
const CONFIG_ROOT = import.meta.dirname;
|
||||||
|
|
||||||
const TEST_FILES = ['**/*.{test,spec}.ts', 'tests/**/*.{ts,mts,cts}'];
|
const TEST_FILES = ['**/*.{test,spec}.ts', 'tests/**/*.{ts,mts,cts}'];
|
||||||
const CONFIG_AND_SCRIPT_FILES = ['**/*.config.{ts,mts,cts}', '**/eslint.config.*'];
|
const CONFIG_AND_SCRIPT_FILES = ['**/*.config.{ts,mts,cts}', '**/eslint.config.*', '**/vite.config.*'];
|
||||||
|
|
||||||
export default defineConfig(
|
export default defineConfig(
|
||||||
/* ── Глобальные игноры ─────────────────────────────────────── */
|
/* ── Глобальные игноры ─────────────────────────────────────── */
|
||||||
@@ -30,8 +30,11 @@ export default defineConfig(
|
|||||||
{
|
{
|
||||||
name: 'server/linter-policy',
|
name: 'server/linter-policy',
|
||||||
linterOptions: {
|
linterOptions: {
|
||||||
noInlineConfig: false,
|
// Inline-директивы (eslint-disable и т.п.) в коде запрещены.
|
||||||
|
// Единственный способ отключить правило — file-level override в этом конфиге.
|
||||||
|
noInlineConfig: true,
|
||||||
reportUnusedDisableDirectives: 'error',
|
reportUnusedDisableDirectives: 'error',
|
||||||
|
reportUnusedInlineConfigs: 'error',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -227,12 +230,6 @@ export default defineConfig(
|
|||||||
'newlines-between': 'always',
|
'newlines-between': 'always',
|
||||||
}],
|
}],
|
||||||
|
|
||||||
/* Запрет необъяснённых disable-директив */
|
|
||||||
'@eslint-community/eslint-comments/disable-enable-pair': ['error', { allowWholeFile: false }],
|
|
||||||
'@eslint-community/eslint-comments/no-aggregating-enable': 'error',
|
|
||||||
'@eslint-community/eslint-comments/no-duplicate-disable': 'error',
|
|
||||||
'@eslint-community/eslint-comments/no-unlimited-disable': 'error',
|
|
||||||
'@eslint-community/eslint-comments/require-description': ['error', { ignore: ['eslint-enable'] }],
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -264,6 +261,88 @@ export default defineConfig(
|
|||||||
'@typescript-eslint/no-unsafe-member-access': 'off',
|
'@typescript-eslint/no-unsafe-member-access': 'off',
|
||||||
'@typescript-eslint/no-unsafe-argument': 'off',
|
'@typescript-eslint/no-unsafe-argument': 'off',
|
||||||
'@typescript-eslint/restrict-template-expressions': 'off',
|
'@typescript-eslint/restrict-template-expressions': 'off',
|
||||||
|
// Тесты извлекают поля из unknown-ответов (supertest body)
|
||||||
|
'@typescript-eslint/consistent-type-assertions': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-type-assertion': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-return': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
/* ── Файловые исключения (единственный способ отключить правило) ── */
|
||||||
|
{
|
||||||
|
name: 'server/express-assertions',
|
||||||
|
files: [
|
||||||
|
'src/routes/news.routes.ts',
|
||||||
|
'src/routes/auth.routes.ts',
|
||||||
|
'src/routes/upload.routes.ts',
|
||||||
|
'src/routes/notification.routes.ts',
|
||||||
|
'src/middleware/auth.middleware.ts',
|
||||||
|
],
|
||||||
|
rules: {
|
||||||
|
// Express req расширяется middleware — assertion неизбежен
|
||||||
|
'@typescript-eslint/consistent-type-assertions': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-type-assertion': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'server/auth-middleware',
|
||||||
|
files: ['src/middleware/auth.middleware.ts'],
|
||||||
|
rules: {
|
||||||
|
// req.user устанавливается auth middleware (стандартный паттерн Express)
|
||||||
|
'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: ['req'] }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'server/error-middleware',
|
||||||
|
files: ['src/middleware/error.middleware.ts'],
|
||||||
|
rules: {
|
||||||
|
// Сигнатура ErrorRequestHandler требует 4 аргумента
|
||||||
|
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'server/import-default-exports',
|
||||||
|
files: ['src/app.ts', 'src/utils/jwt.ts', 'src/middleware/upload.middleware.ts'],
|
||||||
|
rules: {
|
||||||
|
// express.static, jwt.sign/verify, multer.diskStorage — default export API
|
||||||
|
'import-x/no-named-as-default-member': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'server/auth-mongoose',
|
||||||
|
files: ['src/routes/auth.routes.ts'],
|
||||||
|
rules: {
|
||||||
|
// Mongoose документ (без IUser-интерфейса) — no-unsafe срабатывает
|
||||||
|
'@typescript-eslint/no-unsafe-argument': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-assignment': 'off',
|
||||||
|
// Email-regex на ограниченном input (после trim)
|
||||||
|
'sonarjs/slow-regex': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'server/upload-routes',
|
||||||
|
files: ['src/routes/upload.routes.ts'],
|
||||||
|
rules: {
|
||||||
|
// asyncHandler требует async-обёртку
|
||||||
|
'@typescript-eslint/require-await': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'server/scheduler',
|
||||||
|
files: ['src/services/publicationScheduler.service.ts'],
|
||||||
|
rules: {
|
||||||
|
// Логирование факта публикации в production
|
||||||
|
'no-console': ['error', { allow: ['error', 'warn', 'log'] }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'server/socket',
|
||||||
|
files: ['src/socket/socketServer.ts'],
|
||||||
|
rules: {
|
||||||
|
// socket.userId — стандартный паттерн Socket.IO (socket.data)
|
||||||
|
'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: ['socket'] }],
|
||||||
|
// socket.join — fire-and-forget (void)
|
||||||
|
'@typescript-eslint/no-floating-promises': 'off',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -51,7 +51,6 @@ export function createApp(options?: CreateAppOptions): express.Express {
|
|||||||
app.use(urlencoded({ extended: true }));
|
app.use(urlencoded({ extended: true }));
|
||||||
|
|
||||||
// Статические загруженные файлы
|
// Статические загруженные файлы
|
||||||
// eslint-disable-next-line import-x/no-named-as-default-member -- express.static стандартный API
|
|
||||||
app.use('/uploads', express.static(env.uploadDir));
|
app.use('/uploads', express.static(env.uploadDir));
|
||||||
|
|
||||||
// API-маршруты
|
// API-маршруты
|
||||||
|
|||||||
@@ -40,7 +40,6 @@ export function requireAuth(req: Request, _res: Response, next: NextFunction): v
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const payload = verifyUserToken(token);
|
const payload = verifyUserToken(token);
|
||||||
// eslint-disable-next-line no-param-reassign, @typescript-eslint/consistent-type-assertions -- установка req.user
|
|
||||||
(req as AuthenticatedRequest).user = { id: payload.id };
|
(req as AuthenticatedRequest).user = { id: payload.id };
|
||||||
next();
|
next();
|
||||||
} catch {
|
} catch {
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ function errorMessageOf(err: unknown): string {
|
|||||||
* `{ error: { code, message } }`, а непредвиденные ошибки — в 500.
|
* `{ error: { code, message } }`, а непредвиденные ошибки — в 500.
|
||||||
* В production stack trace клиенту не возвращается.
|
* В production stack trace клиенту не возвращается.
|
||||||
*/
|
*/
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- сигнатура Express требует 4 аргумента
|
|
||||||
export const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
|
export const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
|
||||||
// Если ответ уже отправлен (Socket.IO) — не дублируем
|
// Если ответ уже отправлен (Socket.IO) — не дублируем
|
||||||
if (res.headersSent) {
|
if (res.headersSent) {
|
||||||
|
|||||||
@@ -57,7 +57,6 @@ function checkMimeType(_req: unknown, file: { mimetype: string }, cb: FileFilter
|
|||||||
* - Size limit из env
|
* - Size limit из env
|
||||||
*/
|
*/
|
||||||
export const upload = multer({
|
export const upload = multer({
|
||||||
// eslint-disable-next-line import-x/no-named-as-default-member -- multer.diskStorage стандартный API
|
|
||||||
storage: multer.diskStorage({
|
storage: multer.diskStorage({
|
||||||
destination: (_req, _file, cb) => {
|
destination: (_req, _file, cb) => {
|
||||||
cb(null, env.uploadDir);
|
cb(null, env.uploadDir);
|
||||||
|
|||||||
@@ -1,7 +1,17 @@
|
|||||||
import { compare, hash } from 'bcrypt';
|
import { compare, hash } from 'bcrypt';
|
||||||
import mongoose from 'mongoose';
|
import mongoose, { type HydratedDocument } from 'mongoose';
|
||||||
|
|
||||||
import { signUserToken, verifyUserToken } from '../utils/jwt.js';
|
/**
|
||||||
|
* Интерфейс документа пользователя.
|
||||||
|
*/
|
||||||
|
export interface IUser {
|
||||||
|
email: string;
|
||||||
|
passwordHash: string;
|
||||||
|
createdAt: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UserDocument = HydratedDocument<IUser>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Схема пользователя.
|
* Схема пользователя.
|
||||||
@@ -10,7 +20,7 @@ import { signUserToken, verifyUserToken } from '../utils/jwt.js';
|
|||||||
* @property passwordHash — хеш пароля (bcrypt, cost 12)
|
* @property passwordHash — хеш пароля (bcrypt, cost 12)
|
||||||
* @property createdAt / updatedAt — автоматические timestamps
|
* @property createdAt / updatedAt — автоматические timestamps
|
||||||
*/
|
*/
|
||||||
export const userSchema = new mongoose.Schema(
|
const userSchema = new mongoose.Schema<IUser>(
|
||||||
{
|
{
|
||||||
email: {
|
email: {
|
||||||
type: String,
|
type: String,
|
||||||
@@ -18,7 +28,6 @@ export const userSchema = new mongoose.Schema(
|
|||||||
unique: true,
|
unique: true,
|
||||||
lowercase: true,
|
lowercase: true,
|
||||||
trim: true,
|
trim: true,
|
||||||
index: true,
|
|
||||||
},
|
},
|
||||||
passwordHash: {
|
passwordHash: {
|
||||||
type: String,
|
type: String,
|
||||||
@@ -36,7 +45,7 @@ export const userSchema = new mongoose.Schema(
|
|||||||
* Хранит email и bcrypt-хеш пароля. Пароль никогда не возвращается
|
* Хранит email и bcrypt-хеш пароля. Пароль никогда не возвращается
|
||||||
* в ответах API — только через select('-passwordHash') или omit.
|
* в ответах API — только через select('-passwordHash') или omit.
|
||||||
*/
|
*/
|
||||||
export const User = mongoose.model('User', userSchema);
|
export const User = mongoose.model<IUser>('User', userSchema);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Хешит пароль с bcrypt (cost 12).
|
* Хешит пароль с bcrypt (cost 12).
|
||||||
@@ -59,8 +68,6 @@ export async function comparePassword(password: string, hashValue: string): Prom
|
|||||||
return compare(password, hashValue);
|
return compare(password, hashValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Реэкспорт JWT-утилит для удобства импорта
|
|
||||||
export { signUserToken, verifyUserToken };
|
|
||||||
export type { JwtPayload } from '../utils/jwt.js';
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ function extractCredentials(rawBody: unknown): { email: string; password: string
|
|||||||
if (typeof rawBody !== 'object' || rawBody === null) {
|
if (typeof rawBody !== 'object' || rawBody === null) {
|
||||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Тело запроса некорректно');
|
throw new ApiError(400, 'VALIDATION_ERROR', 'Тело запроса некорректно');
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- извлечение полей из unknown
|
|
||||||
const record = rawBody as Record<string, unknown>;
|
const record = rawBody as Record<string, unknown>;
|
||||||
const email = record.email;
|
const email = record.email;
|
||||||
const password = record.password;
|
const password = record.password;
|
||||||
@@ -30,7 +29,6 @@ function extractCredentials(rawBody: unknown): { email: string; password: string
|
|||||||
if (emailStr.length === 0) {
|
if (emailStr.length === 0) {
|
||||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Email не указан');
|
throw new ApiError(400, 'VALIDATION_ERROR', 'Email не указан');
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line sonarjs/slow-regex -- email regex, ограниченный input
|
|
||||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailStr)) {
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailStr)) {
|
||||||
throw new ApiError(400, 'VALIDATION_ERROR', `Некорректный формат email: ${emailStr}`);
|
throw new ApiError(400, 'VALIDATION_ERROR', `Некорректный формат email: ${emailStr}`);
|
||||||
}
|
}
|
||||||
@@ -73,12 +71,10 @@ authRouter.post('/register', asyncHandler(async (req: Request, res: Response) =>
|
|||||||
|
|
||||||
const passwordHash = await hashPassword(password);
|
const passwordHash = await hashPassword(password);
|
||||||
const user = await User.create({ email, passwordHash });
|
const user = await User.create({ email, passwordHash });
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- user.id из mongoose
|
|
||||||
const token = signUserToken(user.id);
|
const token = signUserToken(user.id);
|
||||||
|
|
||||||
res.status(201).json({
|
res.status(201).json({
|
||||||
token,
|
token,
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- mongoose документ
|
|
||||||
user: { id: user.id, email: user.email },
|
user: { id: user.id, email: user.email },
|
||||||
});
|
});
|
||||||
}));
|
}));
|
||||||
@@ -105,11 +101,9 @@ authRouter.post('/login', asyncHandler(async (req: Request, res: Response) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- user.id из mongoose
|
|
||||||
const token = signUserToken(user.id);
|
const token = signUserToken(user.id);
|
||||||
res.json({
|
res.json({
|
||||||
token,
|
token,
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- mongoose документ
|
|
||||||
user: { id: user.id, email: user.email },
|
user: { id: user.id, email: user.email },
|
||||||
});
|
});
|
||||||
}));
|
}));
|
||||||
@@ -124,7 +118,6 @@ authRouter.post('/login', asyncHandler(async (req: Request, res: Response) => {
|
|||||||
*/
|
*/
|
||||||
authRouter.get('/me', requireAuth, asyncHandler(async (req: Request, res: Response) => {
|
authRouter.get('/me', requireAuth, asyncHandler(async (req: Request, res: Response) => {
|
||||||
// req.user установлен requireAuth middleware
|
// req.user установлен requireAuth middleware
|
||||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
|
|
||||||
const authedReq = req as AuthenticatedRequest;
|
const authedReq = req as AuthenticatedRequest;
|
||||||
if (authedReq.user === undefined) {
|
if (authedReq.user === undefined) {
|
||||||
res.status(401).json({ error: { code: 'UNAUTHORIZED', message: 'Требуется авторизация' } });
|
res.status(401).json({ error: { code: 'UNAUTHORIZED', message: 'Требуется авторизация' } });
|
||||||
@@ -135,7 +128,6 @@ authRouter.get('/me', requireAuth, asyncHandler(async (req: Request, res: Respon
|
|||||||
res.status(404).json({ error: { code: 'USER_NOT_FOUND', message: 'Пользователь не найден' } });
|
res.status(404).json({ error: { code: 'USER_NOT_FOUND', message: 'Пользователь не найден' } });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- mongoose документ
|
|
||||||
res.json({ id: user.id, email: user.email });
|
res.json({ id: user.id, email: user.email });
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ const NOT_FOUND_MSG = 'Новость не найдена';
|
|||||||
|
|
||||||
/** Возвращает id авторизованного пользователя. */
|
/** Возвращает id авторизованного пользователя. */
|
||||||
function getUserId(req: Request): string {
|
function getUserId(req: Request): string {
|
||||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
|
|
||||||
const authedReq = req as AuthenticatedRequest;
|
const authedReq = req as AuthenticatedRequest;
|
||||||
if (!authedReq.user) {
|
if (!authedReq.user) {
|
||||||
throw new ApiError(401, 'UNAUTHORIZED', AUTH_MSG);
|
throw new ApiError(401, 'UNAUTHORIZED', AUTH_MSG);
|
||||||
@@ -23,7 +22,6 @@ function getUserId(req: Request): string {
|
|||||||
|
|
||||||
/** Безопасно извлекает поле из req.body. */
|
/** Безопасно извлекает поле из req.body. */
|
||||||
function bodyField(req: Request, key: string): unknown {
|
function bodyField(req: Request, key: string): unknown {
|
||||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- req.body из express typed as any
|
|
||||||
const raw = (req.body ?? {}) as Record<string, unknown>;
|
const raw = (req.body ?? {}) as Record<string, unknown>;
|
||||||
return raw[key];
|
return raw[key];
|
||||||
}
|
}
|
||||||
@@ -48,7 +46,6 @@ function serializeNews(n: InstanceType<typeof News>) {
|
|||||||
* @param io — Socket.IO server для отправки real-time событий
|
* @param io — Socket.IO server для отправки real-time событий
|
||||||
* @returns настроенный Router
|
* @returns настроенный Router
|
||||||
*/
|
*/
|
||||||
/* eslint-disable max-lines-per-function -- factory-функция с 6 inline handlers (стандартный Express-паттерн) */
|
|
||||||
export function createNewsRouter(io?: SocketIOServer): Router {
|
export function createNewsRouter(io?: SocketIOServer): Router {
|
||||||
const router = Router();
|
const router = Router();
|
||||||
router.use(requireAuth);
|
router.use(requireAuth);
|
||||||
@@ -194,7 +191,6 @@ export function createNewsRouter(io?: SocketIOServer): Router {
|
|||||||
|
|
||||||
return router;
|
return router;
|
||||||
}
|
}
|
||||||
/* eslint-enable max-lines-per-function */
|
|
||||||
|
|
||||||
/** Дефолтный экспорт (без Socket.IO). */
|
/** Дефолтный экспорт (без Socket.IO). */
|
||||||
const newsRouter = createNewsRouter();
|
const newsRouter = createNewsRouter();
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ notificationRouter.use(requireAuth);
|
|||||||
* @returns id пользователя
|
* @returns id пользователя
|
||||||
*/
|
*/
|
||||||
function getUserId(req: Request): string {
|
function getUserId(req: Request): string {
|
||||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
|
|
||||||
const authedReq = req as AuthenticatedRequest;
|
const authedReq = req as AuthenticatedRequest;
|
||||||
if (!authedReq.user) {
|
if (!authedReq.user) {
|
||||||
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
|
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
|
||||||
|
|||||||
@@ -41,9 +41,7 @@ uploadRouter.post(
|
|||||||
'/',
|
'/',
|
||||||
requireAuth,
|
requireAuth,
|
||||||
multerHandler('file'),
|
multerHandler('file'),
|
||||||
// eslint-disable-next-line @typescript-eslint/require-await -- asyncHandler требует async
|
|
||||||
asyncHandler(async (req: Request, res: Response) => {
|
asyncHandler(async (req: Request, res: Response) => {
|
||||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
|
|
||||||
const authedReq = req as AuthenticatedRequest;
|
const authedReq = req as AuthenticatedRequest;
|
||||||
if (!authedReq.user) {
|
if (!authedReq.user) {
|
||||||
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
|
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
|
||||||
|
|||||||
@@ -34,7 +34,6 @@ export function startPublicationScheduler(intervalMs = 20_000): void {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (result.modifiedCount > 0) {
|
if (result.modifiedCount > 0) {
|
||||||
// eslint-disable-next-line no-console -- логирование публикации
|
|
||||||
console.log(`[scheduler] Опубликовано новостей: ${String(result.modifiedCount)}`);
|
console.log(`[scheduler] Опубликовано новостей: ${String(result.modifiedCount)}`);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -28,7 +28,6 @@ export function createSocketServer(httpServer: HttpServer): IOServer {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const payload = verifyUserToken(token);
|
const payload = verifyUserToken(token);
|
||||||
// eslint-disable-next-line no-param-reassign -- socket.userId — стандартный паттерн Socket.IO
|
|
||||||
socket.userId = payload.id;
|
socket.userId = payload.id;
|
||||||
next();
|
next();
|
||||||
} catch {
|
} catch {
|
||||||
@@ -38,7 +37,6 @@ export function createSocketServer(httpServer: HttpServer): IOServer {
|
|||||||
|
|
||||||
// При подключении — добавляем socket в room пользователя
|
// При подключении — добавляем socket в room пользователя
|
||||||
io.on('connection', (socket) => {
|
io.on('connection', (socket) => {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- socket.join fire-and-forget
|
|
||||||
void socket.join(`user:${socket.userId}`);
|
void socket.join(`user:${socket.userId}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ export interface JwtPayload {
|
|||||||
export function signUserToken(userId: string): string {
|
export function signUserToken(userId: string): string {
|
||||||
const payload: Omit<JwtPayload, 'iat' | 'exp'> = { id: userId, sub: userId };
|
const payload: Omit<JwtPayload, 'iat' | 'exp'> = { id: userId, sub: userId };
|
||||||
const options: SignOptions = { expiresIn: 7 * 24 * 60 * 60 };
|
const options: SignOptions = { expiresIn: 7 * 24 * 60 * 60 };
|
||||||
// eslint-disable-next-line import-x/no-named-as-default-member -- jsonwebtoken использует default export
|
|
||||||
const token = jwt.sign(payload, env.jwtSecret, options);
|
const token = jwt.sign(payload, env.jwtSecret, options);
|
||||||
return typeof token === 'string' ? token : '';
|
return typeof token === 'string' ? token : '';
|
||||||
}
|
}
|
||||||
@@ -36,7 +35,6 @@ export function signUserToken(userId: string): string {
|
|||||||
* @returns payload токена
|
* @returns payload токена
|
||||||
*/
|
*/
|
||||||
export function verifyUserToken(token: string): JwtPayload {
|
export function verifyUserToken(token: string): JwtPayload {
|
||||||
// eslint-disable-next-line import-x/no-named-as-default-member -- jsonwebtoken использует default export
|
|
||||||
const decoded = jwt.verify(token, env.jwtSecret);
|
const decoded = jwt.verify(token, env.jwtSecret);
|
||||||
if (typeof decoded === 'string') {
|
if (typeof decoded === 'string') {
|
||||||
throw new Error('Неожиданный формат JWT payload');
|
throw new Error('Неожиданный формат JWT payload');
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ function fieldOf(obj: unknown, key: string): string | undefined {
|
|||||||
if (typeof obj !== 'object' || obj === null) {
|
if (typeof obj !== 'object' || obj === null) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- извлечение полей из unknown
|
|
||||||
const record = obj as Record<string, unknown>;
|
const record = obj as Record<string, unknown>;
|
||||||
const value = record[key];
|
const value = record[key];
|
||||||
return typeof value === 'string' ? value : undefined;
|
return typeof value === 'string' ? value : undefined;
|
||||||
@@ -48,7 +47,6 @@ function userEmailOf(body: unknown): string | undefined {
|
|||||||
if (typeof body !== 'object' || body === null) {
|
if (typeof body !== 'object' || body === null) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- извлечение полей из unknown
|
|
||||||
const record = body as Record<string, unknown>;
|
const record = body as Record<string, unknown>;
|
||||||
// /me возвращает { id, email } на верхнем уровне, register/login — { user: { id, email } }
|
// /me возвращает { id, email } на верхнем уровне, register/login — { user: { id, email } }
|
||||||
if (record.email !== undefined) {
|
if (record.email !== undefined) {
|
||||||
@@ -67,7 +65,6 @@ function userIdOf(body: unknown): string | undefined {
|
|||||||
if (typeof body !== 'object' || body === null) {
|
if (typeof body !== 'object' || body === null) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- извлечение полей из unknown
|
|
||||||
const user = (body as Record<string, unknown>).user;
|
const user = (body as Record<string, unknown>).user;
|
||||||
return fieldOf(user, 'id');
|
return fieldOf(user, 'id');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,12 +16,10 @@ function errorCodeOf(body: unknown): string | undefined {
|
|||||||
if (typeof body !== 'object' || body === null) {
|
if (typeof body !== 'object' || body === null) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- извлечение полей из unknown
|
|
||||||
const error = (body as { error?: unknown }).error;
|
const error = (body as { error?: unknown }).error;
|
||||||
if (typeof error !== 'object' || error === null) {
|
if (typeof error !== 'object' || error === null) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- извлечение полей из unknown
|
|
||||||
const code = (error as { code?: unknown }).code;
|
const code = (error as { code?: unknown }).code;
|
||||||
return typeof code === 'string' ? code : undefined;
|
return typeof code === 'string' ? code : undefined;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ function authed(req: request.Test): request.Test {
|
|||||||
/** Создаёт тестовую новость и возвращает её id. */
|
/** Создаёт тестовую новость и возвращает её id. */
|
||||||
async function createTestNews(title: string): Promise<string> {
|
async function createTestNews(title: string): Promise<string> {
|
||||||
const res = await authed(request(app).post('/api/news').send({ title, content: 'Тест' }));
|
const res = await authed(request(app).post('/api/news').send({ title, content: 'Тест' }));
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return -- supertest body
|
|
||||||
return res.body.news.id;
|
return res.body.news.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user