From 4ee52845c4a5e72f1329070e10e12c37c7f871e9 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Fri, 3 Apr 2026 17:23:12 +0000 Subject: [PATCH] refactor(backend): optimize snippets for deterministic Agent parsing Refactored pattern snippets across Express.js, NestJS, Node.js, and MongoDB documentation to strictly adhere to the mandatory 4-step lifecycle (Bad Practice -> Problem -> Best Practice -> Solution). Removed out-of-order warning blocks and systematically inserted them into the correct position. Co-authored-by: beginwebdev2002 <102213457+beginwebdev2002@users.noreply.github.com> --- backend/expressjs/readme.md | 151 ++++++++++++++---------------------- backend/mongodb/readme.md | 4 +- backend/nestjs/readme.md | 63 ++++++++++++++- backend/nodejs/readme.md | 52 +++++-------- 4 files changed, 144 insertions(+), 126 deletions(-) diff --git a/backend/expressjs/readme.md b/backend/expressjs/readme.md index a93e5d9..47e7364 100644 --- a/backend/expressjs/readme.md +++ b/backend/expressjs/readme.md @@ -64,6 +64,8 @@ app.post('/api/users', async (req, res) => { /* бизнес-логика здесь */ }); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript router.post('/api/users', UserController.create); @@ -75,14 +77,13 @@ class UserController { ### 🚀 Solution Роутер только описывает эндпоинты, Контроллер извлекает данные запроса и отдает ответ. Логика — в Сервисах. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 2. Async/Await Error Wrapping (Express 4) ### ❌ Bad Practice ```javascript router.get('/', async (req, res) => { throw new Error('Crash'); }); // Express 4 не ловит rejection ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const asyncHandler = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); @@ -91,14 +92,13 @@ router.get('/', asyncHandler(UserController.get)); ### 🚀 Solution В Express 4 всегда оборачивайте async-маршруты в `asyncHandler`, чтобы пробрасывать ошибки в глобальный Error Handler. (В Express 5 это встроено). - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 3. Global Error Handler Middleware ### ❌ Bad Practice ```javascript app.use((req, res) => res.status(404).send('Not Found')); // Нет ловца ошибок 500 ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.use((err, req, res, next) => { @@ -109,14 +109,13 @@ app.use((err, req, res, next) => { ### 🚀 Solution Определите единую middleware с 4 аргументами `(err, req, res, next)` в самом конце пайплайна для перехвата всех сбоев. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 4. Request Payload Validation (Joi / Zod) ### ❌ Bad Practice ```javascript if (!req.body.email || req.body.age < 18) return res.status(400); // Ручная проверка ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const validate = schema => (req, res, next) => { @@ -129,14 +128,13 @@ router.post('/', validate(userSchema), UserController.create); ### 🚀 Solution Проверяйте тело и параметры запросов на уровне Middleware с помощью надежных библиотек валидации (Joi, Zod), не пуская мусор в контроллеры. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 5. Environment Variables separation ### ❌ Bad Practice ```javascript mongoose.connect('mongodb://admin:pass@host/db'); // Хардкод секретов ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript require('dotenv').config(); @@ -145,12 +143,11 @@ mongoose.connect(process.env.DB_URI); ### 🚀 Solution Используйте `dotenv` и конфигурационные файлы для разных окружений. Секреты хранятся только в `.env` (который добавлен в `.gitignore`). - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 6. HTTP Security Headers (Helmet) ### ❌ Bad Practice // Приложение светит 'X-Powered-By: Express' +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const helmet = require('helmet'); @@ -159,14 +156,13 @@ app.use(helmet()); ### 🚀 Solution Используйте `helmet` для автоматической защиты от XSS, clickjacking и скрытия заголовков фреймворка из коробки. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 7. Cross-Origin Resource Sharing (CORS) ### ❌ Bad Practice ```javascript app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); next(); }); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const cors = require('cors'); @@ -175,12 +171,11 @@ app.use(cors({ origin: 'https://myapp.com', credentials: true })); ### 🚀 Solution Используйте официальный модуль `cors`. Разрешайте доступ только доверенным доменам, а не всем подряд (`*`). - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 8. Rate Limiting (Защита от DDoS) ### ❌ Bad Practice // API открыт для миллиона запросов в секунду +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const rateLimit = require('express-rate-limit'); @@ -189,14 +184,13 @@ app.use('/api/', rateLimit({ windowMs: 15 * 60 * 1000, max: 100 })); ### 🚀 Solution Защищайте все эндпоинты (а особенно авторизацию) встроенным лимитером запросов. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 9. Body Parsing & Payload Limits ### ❌ Bad Practice ```javascript app.use(express.json()); // Злоумышленник может отправить 500Мб JSON ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.use(express.json({ limit: '10kb' })); @@ -205,14 +199,13 @@ app.use(express.urlencoded({ extended: true, limit: '10kb' })); ### 🚀 Solution Строго ограничивайте размер принимаемого JSON через опцию `limit`, чтобы предотвратить исчерпание RAM. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 10. Centralized Logging (Morgan + Winston) ### ❌ Bad Practice ```javascript console.log('User signed in'); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.use(morgan('combined', { stream: winstonLogger.stream })); @@ -221,14 +214,13 @@ winstonLogger.info('User signed in'); ### 🚀 Solution Заменяйте `console.log` на логгеры вроде Winston (с уровнями log/warn/error) и Morgan (для фиксации HTTP-запросов). - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 11. Database Connection Management ### ❌ Bad Practice ```javascript // Коннект к базе делается перед каждым запросом ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript mongoose.connect(process.env.DB_URI).then(() => { @@ -238,14 +230,13 @@ mongoose.connect(process.env.DB_URI).then(() => { ### 🚀 Solution Открывайте единый пул подключений к БД (Connection Pool) при запуске приложения и используйте его во всех контроллерах. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 12. JWT Authentication Middleware ### ❌ Bad Practice ```javascript // Проверка токена встроена в контроллер профиля ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const authGuard = (req, res, next) => { @@ -258,14 +249,13 @@ const authGuard = (req, res, next) => { ### 🚀 Solution Аутентификация должна представлять собой изолированную Middleware, которая вешается на защищенные маршруты и прикрепляет объект `req.user`. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 13. Role-Based Access Control (RBAC) Middleware ### ❌ Bad Practice ```javascript if (req.user.role !== 'admin') return res.status(403); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const requireRole = (...roles) => (req, res, next) => { @@ -277,14 +267,13 @@ router.delete('/:id', requireRole('admin', 'manager'), Controller.del); ### 🚀 Solution Доступ к маршрутам по ролям должен задаваться декларативно через Middleware. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 14. Standard API Response Wrapper ### ❌ Bad Practice ```javascript res.json({ foo: 'bar' }); // Каждый метод возвращает случайную структуру ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript class ApiResponse { @@ -295,14 +284,13 @@ class ApiResponse { ### 🚀 Solution Используйте единый класс-утилиту для отправки ответов, чтобы клиент всегда ожидал `success` и `data`/`error` поля. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 15. Pagination details in API ### ❌ Bad Practice ```javascript res.json(users); // Выбросить миллион записей ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const page = parseInt(req.query.page) || 1; @@ -312,12 +300,11 @@ res.json({ data: users, meta: { total, page, limit, pages: Math.ceil(total/limit ### 🚀 Solution Любой список сущностей обязан иметь пагинацию (Offset или Cursor) и секцию `meta` в ответе. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 16. Graceful Shutdown ### ❌ Bad Practice // При получении SIGTERM сервер моментально обрывает процессы +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript process.on('SIGTERM', () => { @@ -329,12 +316,11 @@ process.on('SIGTERM', () => { ### 🚀 Solution Корректно закрывайте активные HTTP-сессии и пулы подключений к БД перед остановкой контейнера. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 17. 404 Route Handler ### ❌ Bad Practice // Если роут не найден, возвращается пустая белая страница +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.use('*', (req, res) => { @@ -344,15 +330,14 @@ app.use('*', (req, res) => { ### 🚀 Solution Поместите этот обработчик ПОСЛЕ всех ваших маршрутов (но ДО глобального обработчика ошибок). - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 18. Application Structure (Folder organization) ### ❌ Bad Practice ``` /routes.js /app.js // Монолит на 5000 строк ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ``` src/ @@ -365,12 +350,11 @@ src/ ### 🚀 Solution Строго разделяйте проект на логические папки. Имплементируйте многослойную архитектуру. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 19. Health Check Endpoint ### ❌ Bad Practice // Нет проверки жизнеспособности подов Kubernetes +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.get('/health', (req, res) => { @@ -380,14 +364,13 @@ app.get('/health', (req, res) => { ### 🚀 Solution Всегда имейте эндпоинт `/health` для систем мониторинга, балансировщиков и Health Probes. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 20. Data Sanitization (XSS / NoSQL Injection) ### ❌ Bad Practice ```javascript User.find({ username: req.body.username }); // body.username = { "$gt": "" } ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const mongoSanitize = require('express-mongo-sanitize'); @@ -398,12 +381,11 @@ app.use(xss()); ### 🚀 Solution Защищайте БД от NoSQL-инъекций и XSS скриптов, очищая `req.body` и `req.query`. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 21. Swagger / OpenAPI documentation ### ❌ Bad Practice // Документация в стороннем Word-файле +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const swaggerUi = require('swagger-ui-express'); @@ -413,14 +395,13 @@ app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); ### 🚀 Solution Генерируйте или обслуживайте API-документацию прямо в приложении (Swagger, OpenAPI). - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 22. Manual Dependency Injection ### ❌ Bad Practice ```javascript const UserService = require('./UserService'); // Прямой импорт, невозможно тестировать ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript class UserController { @@ -431,12 +412,11 @@ const controller = new UserController(new UserService(db)); ### 🚀 Solution Если не используете IoC (Awilix), инжектируйте зависимости вручную для облегчения Unit-тестирования. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 23. File Uploads (Multer) ### ❌ Bad Practice // Парсинг бинарников руками +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const multer = require('multer'); @@ -446,15 +426,14 @@ router.post('/avatar', upload.single('file'), Controller.upload); ### 🚀 Solution Используйте `multer` с обязательным ограничением размера файла (`limits`), чтобы обезопасить сервер от переполнения диска. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 24. Event Emitters (Фоновые задачи) ### ❌ Bad Practice ```javascript await emailService.send(); // Блокировка респонса res.send('Welcome'); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const EventEmitter = require('events'); @@ -467,12 +446,11 @@ res.send('Welcome'); ### 🚀 Solution Снимайте длительные задачи с основного потока ответа с помощью нативных Events NodeJS. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 25. Caching (Redis Middleware) ### ❌ Bad Practice // БД обрабатывает сложные расчеты на каждый хит +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const cacheMiddleware = (req, res, next) => { @@ -485,14 +463,13 @@ const cacheMiddleware = (req, res, next) => { ### 🚀 Solution Используйте кэширование (Redis) для GET-запросов, результат которых меняется редко. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 26. Custom Error Classes ### ❌ Bad Practice ```javascript throw new Error('Not found'); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript class AppError extends Error { @@ -507,14 +484,13 @@ throw new AppError('User not found', 404); ### 🚀 Solution Создавайте кастомные классы ошибок, чтобы глобальный логгер мог отличать операционные ошибки (Operational) от фатальных крашей кода. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 27. Proxy Trust in Production ### ❌ Bad Practice ```javascript req.ip // Дает '127.0.0.1' через Nginx ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.set('trust proxy', 1); // Доверяем первому прокси @@ -522,15 +498,14 @@ app.set('trust proxy', 1); // Доверяем первому прокси ### 🚀 Solution Если Express стоит за Nginx / AWS ELB, включите `trust proxy`, чтобы получать реальные IP пользователей. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 28. Separating Server from App ### ❌ Bad Practice ```javascript // app.js app.listen(3000); // Мешает интеграционным тестам ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript // app.js @@ -543,12 +518,11 @@ app.listen(3000); ### 🚀 Solution Экспортируйте Express App отдельно от `listen`, чтобы `supertest` мог легко запускать тесты на случайных портах. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 29. UUID Request Correlation ### ❌ Bad Practice // Ошибки в логах невозможно связать с конкретным пользователем +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const { v4: uuidv4 } = require('uuid'); @@ -561,12 +535,11 @@ app.use((req, res, next) => { ### 🚀 Solution Устанавливайте уникальный ID каждому запросу для отслеживания его пути по всем логам и микросервисам. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 30. Secure Session Management ### ❌ Bad Practice // Сессия хранится в памяти (MemoryStore) с открытыми куками +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.use(session({ @@ -584,7 +557,3 @@ app.use(session({