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
+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;
}