Phase 10: запрет inline eslint-disable, file-level overrides, IUser-тип

This commit is contained in:
Suslov-MD
2026-08-16 17:06:45 +00:00
parent 65c44f570c
commit dad4642197
22 changed files with 144 additions and 67 deletions
+42 -7
View File
@@ -18,6 +18,8 @@ const CONFIG_ROOT = import.meta.dirname;
const TEST_FILES = ['**/*.{test,spec}.{ts,tsx}'];
const CONFIG_AND_SCRIPT_FILES = ['**/*.config.{ts,mts,cts}', '**/vite.config.*'];
/* eslint-disable no-unused-vars -- eslint.config.js lintится самим собой */
/* Забираем правила из пресетов плагинов */
const reactRecommendedRules =
react.configs.flat?.recommended?.rules ??
@@ -50,8 +52,11 @@ export default defineConfig(
{
name: 'client/linter-policy',
linterOptions: {
noInlineConfig: false,
// Inline-директивы (eslint-disable и т.п.) в коде запрещены.
// Единственный способ отключить правило — file-level override в этом конфиге.
noInlineConfig: true,
reportUnusedDisableDirectives: 'error',
reportUnusedInlineConfigs: 'error',
},
},
@@ -274,12 +279,6 @@ export default defineConfig(
'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',
},
},
/* ── Файловые исключения (единственный способ отключить правило) ── */
{
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',
},
},
);
-1
View File
@@ -80,7 +80,6 @@ async function handleResponse<T>(res: Response): Promise<T> {
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;
if (!res.ok) {
-8
View File
@@ -17,10 +17,8 @@ function useLoadNews(newsId: string | undefined, isNew: boolean) {
if (isNew) {
return;
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- async IIFE в useEffect
void (async () => {
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}`);
setTitle(data.news.title);
setContent(data.news.content);
@@ -45,7 +43,6 @@ function useLoadNews(newsId: string | undefined, isNew: boolean) {
* @param newsId — id новости или undefined для создания
* @returns состояние и обработчики для NewsEditorPage
*/
/* eslint-disable max-lines-per-function -- хук-оркестратор */
export function useNewsEditor(newsId: string | undefined) {
const isNew = newsId === undefined;
const { title, setTitle, content, setContent, newsStatus, loading } = useLoadNews(newsId, isNew);
@@ -149,7 +146,6 @@ export function useNewsEditor(newsId: string | undefined) {
if (newsId === undefined) {
return;
}
// eslint-disable-next-line no-alert -- подтверждение удаления
if (!window.confirm('Удалить новость?')) {
return;
}
@@ -157,7 +153,6 @@ export function useNewsEditor(newsId: string | undefined) {
setError('');
try {
await apiFetch(`/news/${newsId}`, { method: 'DELETE' });
// eslint-disable-next-line require-atomic-updates -- navigation after await
window.location.href = '/news';
} catch (err) {
setError(err instanceof Error ? err.message : 'Ошибка удаления');
@@ -214,7 +209,6 @@ export function useNewsEditor(newsId: string | undefined) {
if (file !== undefined) {
handleFileUpload(file, true).catch((err: unknown) => { console.error(err); });
}
// eslint-disable-next-line no-param-reassign -- сброс file input
e.target.value = '';
}, [handleFileUpload]);
@@ -224,7 +218,6 @@ export function useNewsEditor(newsId: string | undefined) {
if (file !== undefined) {
handleFileUpload(file, false).catch((err: unknown) => { console.error(err); });
}
// eslint-disable-next-line no-param-reassign -- сброс file input
e.target.value = '';
}, [handleFileUpload]);
@@ -239,4 +232,3 @@ export function useNewsEditor(newsId: string | undefined) {
onSave, onPublish, onDelete, onSchedule,
};
}
/* eslint-enable max-lines-per-function */
-2
View File
@@ -16,7 +16,6 @@ export function LoginPage() {
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
/* eslint-disable @typescript-eslint/no-floating-promises -- Promise обработан через .catch() */
const handleSubmit = (e: FormEvent): void => {
e.preventDefault();
setError('');
@@ -28,7 +27,6 @@ export function LoginPage() {
})
.finally(() => { setLoading(false); });
};
/* eslint-enable @typescript-eslint/no-floating-promises */
return (
<div className={styles.page}>
-1
View File
@@ -17,7 +17,6 @@ export function NewsListPage() {
const [error, setError] = useState('');
useEffect(() => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- async IIFE в useEffect
void (async () => {
try {
const data = await apiFetch<{ news: NewsItem[] }>('/news');
-2
View File
@@ -17,7 +17,6 @@ export function RegisterPage() {
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
/* eslint-disable @typescript-eslint/no-floating-promises -- Promise обработан через .catch() */
const handleSubmit = (e: FormEvent): void => {
e.preventDefault();
if (password !== confirmPassword) {
@@ -33,7 +32,6 @@ export function RegisterPage() {
})
.finally(() => { setLoading(false); });
};
/* eslint-enable @typescript-eslint/no-floating-promises */
return (
<div className={styles.page}>
+87 -8
View File
@@ -13,7 +13,7 @@ import tseslint from 'typescript-eslint';
const CONFIG_ROOT = import.meta.dirname;
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(
/* ── Глобальные игноры ─────────────────────────────────────── */
@@ -30,8 +30,11 @@ export default defineConfig(
{
name: 'server/linter-policy',
linterOptions: {
noInlineConfig: false,
// Inline-директивы (eslint-disable и т.п.) в коде запрещены.
// Единственный способ отключить правило — file-level override в этом конфиге.
noInlineConfig: true,
reportUnusedDisableDirectives: 'error',
reportUnusedInlineConfigs: 'error',
},
},
@@ -227,12 +230,6 @@ export default defineConfig(
'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-argument': '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',
},
},
);
-1
View File
@@ -51,7 +51,6 @@ export function createApp(options?: CreateAppOptions): express.Express {
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));
// API-маршруты
-1
View File
@@ -40,7 +40,6 @@ export function requireAuth(req: Request, _res: Response, next: NextFunction): v
try {
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 };
next();
} catch {
@@ -23,7 +23,6 @@ function errorMessageOf(err: unknown): string {
* `{ error: { code, message } }`, а непредвиденные ошибки — в 500.
* В production stack trace клиенту не возвращается.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- сигнатура Express требует 4 аргумента
export const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
// Если ответ уже отправлен (Socket.IO) — не дублируем
if (res.headersSent) {
@@ -57,7 +57,6 @@ function checkMimeType(_req: unknown, file: { mimetype: string }, cb: FileFilter
* - Size limit из env
*/
export const upload = multer({
// eslint-disable-next-line import-x/no-named-as-default-member -- multer.diskStorage стандартный API
storage: multer.diskStorage({
destination: (_req, _file, cb) => {
cb(null, env.uploadDir);
+15 -8
View File
@@ -1,7 +1,17 @@
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 createdAt / updatedAt — автоматические timestamps
*/
export const userSchema = new mongoose.Schema(
const userSchema = new mongoose.Schema<IUser>(
{
email: {
type: String,
@@ -18,7 +28,6 @@ export const userSchema = new mongoose.Schema(
unique: true,
lowercase: true,
trim: true,
index: true,
},
passwordHash: {
type: String,
@@ -36,7 +45,7 @@ export const userSchema = new mongoose.Schema(
* Хранит email и bcrypt-хеш пароля. Пароль никогда не возвращается
* в ответах API — только через select('-passwordHash') или omit.
*/
export const User = mongoose.model('User', userSchema);
export const User = mongoose.model<IUser>('User', userSchema);
/**
* Хешит пароль с bcrypt (cost 12).
@@ -59,8 +68,6 @@ export async function comparePassword(password: string, hashValue: string): Prom
return compare(password, hashValue);
}
// Реэкспорт JWT-утилит для удобства импорта
export { signUserToken, verifyUserToken };
export type { JwtPayload } from '../utils/jwt.js';
-8
View File
@@ -20,7 +20,6 @@ function extractCredentials(rawBody: unknown): { email: string; password: string
if (typeof rawBody !== 'object' || rawBody === null) {
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 email = record.email;
const password = record.password;
@@ -30,7 +29,6 @@ function extractCredentials(rawBody: unknown): { email: string; password: string
if (emailStr.length === 0) {
throw new ApiError(400, 'VALIDATION_ERROR', 'Email не указан');
}
// eslint-disable-next-line sonarjs/slow-regex -- email regex, ограниченный input
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(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 user = await User.create({ email, passwordHash });
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- user.id из mongoose
const token = signUserToken(user.id);
res.status(201).json({
token,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- mongoose документ
user: { id: user.id, email: user.email },
});
}));
@@ -105,11 +101,9 @@ authRouter.post('/login', asyncHandler(async (req: Request, res: Response) => {
return;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- user.id из mongoose
const token = signUserToken(user.id);
res.json({
token,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- mongoose документ
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) => {
// req.user установлен requireAuth middleware
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
const authedReq = req as AuthenticatedRequest;
if (authedReq.user === undefined) {
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: 'Пользователь не найден' } });
return;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- mongoose документ
res.json({ id: user.id, email: user.email });
}));
-4
View File
@@ -13,7 +13,6 @@ const NOT_FOUND_MSG = 'Новость не найдена';
/** Возвращает id авторизованного пользователя. */
function getUserId(req: Request): string {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
const authedReq = req as AuthenticatedRequest;
if (!authedReq.user) {
throw new ApiError(401, 'UNAUTHORIZED', AUTH_MSG);
@@ -23,7 +22,6 @@ function getUserId(req: Request): string {
/** Безопасно извлекает поле из req.body. */
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>;
return raw[key];
}
@@ -48,7 +46,6 @@ function serializeNews(n: InstanceType<typeof News>) {
* @param io — Socket.IO server для отправки real-time событий
* @returns настроенный Router
*/
/* eslint-disable max-lines-per-function -- factory-функция с 6 inline handlers (стандартный Express-паттерн) */
export function createNewsRouter(io?: SocketIOServer): Router {
const router = Router();
router.use(requireAuth);
@@ -194,7 +191,6 @@ export function createNewsRouter(io?: SocketIOServer): Router {
return router;
}
/* eslint-enable max-lines-per-function */
/** Дефолтный экспорт (без Socket.IO). */
const newsRouter = createNewsRouter();
-1
View File
@@ -17,7 +17,6 @@ notificationRouter.use(requireAuth);
* @returns id пользователя
*/
function getUserId(req: Request): string {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
const authedReq = req as AuthenticatedRequest;
if (!authedReq.user) {
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
-2
View File
@@ -41,9 +41,7 @@ uploadRouter.post(
'/',
requireAuth,
multerHandler('file'),
// eslint-disable-next-line @typescript-eslint/require-await -- asyncHandler требует async
asyncHandler(async (req: Request, res: Response) => {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
const authedReq = req as AuthenticatedRequest;
if (!authedReq.user) {
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
@@ -34,7 +34,6 @@ export function startPublicationScheduler(intervalMs = 20_000): void {
);
if (result.modifiedCount > 0) {
// eslint-disable-next-line no-console -- логирование публикации
console.log(`[scheduler] Опубликовано новостей: ${String(result.modifiedCount)}`);
}
} catch (err) {
-2
View File
@@ -28,7 +28,6 @@ export function createSocketServer(httpServer: HttpServer): IOServer {
}
try {
const payload = verifyUserToken(token);
// eslint-disable-next-line no-param-reassign -- socket.userId — стандартный паттерн Socket.IO
socket.userId = payload.id;
next();
} catch {
@@ -38,7 +37,6 @@ export function createSocketServer(httpServer: HttpServer): IOServer {
// При подключении — добавляем socket в room пользователя
io.on('connection', (socket) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- socket.join fire-and-forget
void socket.join(`user:${socket.userId}`);
});
-2
View File
@@ -24,7 +24,6 @@ export interface JwtPayload {
export function signUserToken(userId: string): string {
const payload: Omit<JwtPayload, 'iat' | 'exp'> = { id: userId, sub: userId };
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);
return typeof token === 'string' ? token : '';
}
@@ -36,7 +35,6 @@ export function signUserToken(userId: string): string {
* @returns payload токена
*/
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);
if (typeof decoded === 'string') {
throw new Error('Неожиданный формат JWT payload');
-3
View File
@@ -22,7 +22,6 @@ function fieldOf(obj: unknown, key: string): string | undefined {
if (typeof obj !== 'object' || obj === null) {
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 value = record[key];
return typeof value === 'string' ? value : undefined;
@@ -48,7 +47,6 @@ function userEmailOf(body: unknown): string | undefined {
if (typeof body !== 'object' || body === null) {
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>;
// /me возвращает { id, email } на верхнем уровне, register/login — { user: { id, email } }
if (record.email !== undefined) {
@@ -67,7 +65,6 @@ function userIdOf(body: unknown): string | undefined {
if (typeof body !== 'object' || body === null) {
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;
return fieldOf(user, 'id');
}
-2
View File
@@ -16,12 +16,10 @@ function errorCodeOf(body: unknown): string | undefined {
if (typeof body !== 'object' || body === null) {
return undefined;
}
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- извлечение полей из unknown
const error = (body as { error?: unknown }).error;
if (typeof error !== 'object' || error === null) {
return undefined;
}
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- извлечение полей из unknown
const code = (error as { code?: unknown }).code;
return typeof code === 'string' ? code : undefined;
}
-1
View File
@@ -27,7 +27,6 @@ function authed(req: request.Test): request.Test {
/** Создаёт тестовую новость и возвращает её id. */
async function createTestNews(title: string): Promise<string> {
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;
}