Phase 5: Upload — multer, UUID filenames, MIME whitelist, /uploads static
This commit is contained in:
+5
-2
@@ -8,6 +8,7 @@ import { notFoundHandler } from './middleware/notFound.middleware.js';
|
||||
import authRouter from './routes/auth.routes.js';
|
||||
import healthRouter from './routes/health.routes.js';
|
||||
import newsRouter from './routes/news.routes.js';
|
||||
import uploadRouter from './routes/upload.routes.js';
|
||||
|
||||
/**
|
||||
* Создаёт и настраивает Express-приложение.
|
||||
@@ -33,13 +34,15 @@ export function createApp(extraMiddleware?: express.RequestHandler): express.Exp
|
||||
app.use(json());
|
||||
app.use(urlencoded({ extended: true }));
|
||||
|
||||
// Статические загруженные файлы (Phase 5)
|
||||
// app.use('/uploads', express.static(env.uploadDir));
|
||||
// Статические загруженные файлы
|
||||
// eslint-disable-next-line import-x/no-named-as-default-member -- express.static стандартный API
|
||||
app.use('/uploads', express.static(env.uploadDir));
|
||||
|
||||
// API-маршруты
|
||||
app.use('/api', healthRouter);
|
||||
app.use('/api/auth', authRouter);
|
||||
app.use('/api/news', newsRouter);
|
||||
app.use('/api/uploads', uploadRouter);
|
||||
|
||||
// Дополнительные middleware (тестовые маршруты, заглушки)
|
||||
if (extraMiddleware) {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import multer, { type FileFilterCallback } from 'multer';
|
||||
|
||||
import { env } from '../config/env.js';
|
||||
|
||||
/**
|
||||
* Разрешённые MIME-типы для загрузки.
|
||||
*/
|
||||
const ALLOWED_MIME_TYPES = new Set([
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/gif',
|
||||
'image/webp',
|
||||
'application/pdf',
|
||||
'application/msword',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Расширения файлов для генерации safe filename.
|
||||
* Ключ — MIME-тип, значение — расширение.
|
||||
*/
|
||||
const MIME_EXTENSIONS: Record<string, string> = {
|
||||
'image/jpeg': 'jpg',
|
||||
'image/png': 'png',
|
||||
'image/gif': 'gif',
|
||||
'image/webp': 'webp',
|
||||
'application/pdf': 'pdf',
|
||||
'application/msword': 'doc',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
|
||||
};
|
||||
|
||||
/**
|
||||
* Проверка MIME-типа загружаемого файла.
|
||||
*
|
||||
* @param _req — запрос Express
|
||||
* @param file — файл из multer
|
||||
* @param cb — callback multer
|
||||
*/
|
||||
function checkMimeType(_req: unknown, file: { mimetype: string }, cb: FileFilterCallback): void {
|
||||
if (ALLOWED_MIME_TYPES.has(file.mimetype)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
const err = new Error(
|
||||
`Недопустимый тип файла: ${file.mimetype}. Разрешены: изображения (jpg, png, gif, webp), PDF, Word (doc, docx)`,
|
||||
);
|
||||
cb(err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Настройка multer:
|
||||
* - diskStorage в env.uploadDir
|
||||
* - UUID-based filenames (без пользовательского имени)
|
||||
* - MIME whitelist
|
||||
* - 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);
|
||||
},
|
||||
filename: (_req, file, cb) => {
|
||||
// Генерируем безопасное имя: UUID + расширение по MIME
|
||||
const ext = MIME_EXTENSIONS[file.mimetype] ?? 'bin';
|
||||
cb(null, `${randomUUID()}.${ext}`);
|
||||
},
|
||||
}),
|
||||
limits: {
|
||||
fileSize: env.maxUploadSize,
|
||||
files: 1,
|
||||
},
|
||||
fileFilter: checkMimeType,
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Router, type Request, type Response } from 'express';
|
||||
|
||||
import { requireAuth, type AuthenticatedRequest } from '../middleware/auth.middleware.js';
|
||||
import { upload } from '../middleware/upload.middleware.js';
|
||||
import { ApiError } from '../utils/ApiError.js';
|
||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||
|
||||
const uploadRouter = Router();
|
||||
|
||||
/**
|
||||
* Обёртка для multer: конвертирует multer errors в ApiError (400/413).
|
||||
*/
|
||||
function multerHandler(fileFilter: 'file') {
|
||||
return (req: Request, res: Response, next: (err?: unknown) => void): void => {
|
||||
upload.single(fileFilter)(req, res, (err: unknown) => {
|
||||
if (err instanceof ApiError) {
|
||||
next(err);
|
||||
return;
|
||||
}
|
||||
if (err !== null && err !== undefined) {
|
||||
// MulterError или ошибка fileFilter
|
||||
const message = err instanceof Error ? err.message : 'Ошибка загрузки';
|
||||
const isFileSize = message.includes('File too large');
|
||||
next(new ApiError(isFileSize ? 413 : 400, 'UPLOAD_ERROR', message));
|
||||
return;
|
||||
}
|
||||
next();
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/uploads
|
||||
* Загрузка одного файла. Требует авторизацию.
|
||||
*
|
||||
* @returns 201 { file: { name, url } }
|
||||
* - name: имя файла на диске (UUID.ext)
|
||||
* - url: путь для доступа /uploads/<name>
|
||||
*/
|
||||
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', 'Требуется авторизация');
|
||||
}
|
||||
|
||||
// Multer устанавливает req.file при успешной загрузке
|
||||
if (!req.file) {
|
||||
throw new ApiError(400, 'NO_FILE', 'Файл не был загружен');
|
||||
}
|
||||
|
||||
const fileName = req.file.filename;
|
||||
|
||||
res.status(201).json({
|
||||
file: {
|
||||
name: fileName,
|
||||
url: `/uploads/${fileName}`,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
export default uploadRouter;
|
||||
@@ -0,0 +1,130 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import request from 'supertest';
|
||||
import { describe, expect, it, beforeAll, afterAll } from 'vitest';
|
||||
|
||||
import { createApp } from '../src/app.js';
|
||||
import { env } from '../src/config/env.js';
|
||||
import { User, hashPassword } from '../src/models/user.model.js';
|
||||
import { signUserToken } from '../src/utils/jwt.js';
|
||||
|
||||
const app = createApp();
|
||||
const TEST_EMAIL = 'upload-test@example.com';
|
||||
|
||||
let authToken = '';
|
||||
const uploadedFiles: string[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
// Убеждаемся что uploadDir существует
|
||||
if (!fs.existsSync(env.uploadDir)) {
|
||||
fs.mkdirSync(env.uploadDir, { recursive: true });
|
||||
}
|
||||
|
||||
const user = await User.create({
|
||||
email: TEST_EMAIL,
|
||||
passwordHash: await hashPassword('Upload-Pass-123'),
|
||||
});
|
||||
authToken = signUserToken(user.id);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
// Удаляем загруженные тестовые файлы
|
||||
for (const file of uploadedFiles) {
|
||||
const filePath = path.join(env.uploadDir, file);
|
||||
if (fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/** Запоминает файл для последующей очистки. */
|
||||
function trackFile(name: string): void {
|
||||
uploadedFiles.push(name);
|
||||
}
|
||||
|
||||
/** Создаёт маленький PNG-файл (1x1 пиксель). */
|
||||
function createTestPng(): Buffer {
|
||||
return Buffer.from(
|
||||
'89504e470d0a1a0a0000000d4948445200000001000000010802000000907753' +
|
||||
'de0000000c4944415408d763f8cfc0f0000000050001b5f73564000000004945' +
|
||||
'4e44ae426082',
|
||||
'hex',
|
||||
);
|
||||
}
|
||||
|
||||
describe('Загрузка файлов', () => {
|
||||
it('POST /api/uploads без токена — 401', async () => {
|
||||
const png = createTestPng();
|
||||
const res = await request(app)
|
||||
.post('/api/uploads')
|
||||
.attach('file', png, 'test.png');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('успешная загрузка PNG', async () => {
|
||||
const png = createTestPng();
|
||||
const res = await request(app)
|
||||
.post('/api/uploads')
|
||||
.set('Authorization', `Bearer ${authToken}`)
|
||||
.attach('file', png, 'test.png');
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.file.name).toBeDefined();
|
||||
expect(res.body.file.url).toBe(`/uploads/${res.body.file.name}`);
|
||||
expect(res.body.file.name).toMatch(/^[0-9a-f-]{36}\.png$/);
|
||||
|
||||
trackFile(res.body.file.name);
|
||||
|
||||
// Файл существует на диске
|
||||
const filePath = path.join(env.uploadDir, res.body.file.name);
|
||||
expect(fs.existsSync(filePath)).toBe(true);
|
||||
});
|
||||
|
||||
it('загрузка PDF', async () => {
|
||||
const pdf = Buffer.from('%PDF-1.4 test');
|
||||
const res = await request(app)
|
||||
.post('/api/uploads')
|
||||
.set('Authorization', `Bearer ${authToken}`)
|
||||
.attach('file', pdf, 'test.pdf');
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.file.name).toMatch(/\.pdf$/);
|
||||
trackFile(res.body.file.name);
|
||||
});
|
||||
|
||||
it('запрещённый MIME — 400', async () => {
|
||||
const exe = Buffer.from('MZ executable content');
|
||||
const res = await request(app)
|
||||
.post('/api/uploads')
|
||||
.set('Authorization', `Bearer ${authToken}`)
|
||||
.attach('file', exe, 'malware.exe');
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.code).toBe('UPLOAD_ERROR');
|
||||
});
|
||||
|
||||
it('без файла — 400', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/uploads')
|
||||
.set('Authorization', `Bearer ${authToken}`);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.code).toBe('NO_FILE');
|
||||
});
|
||||
|
||||
it('GET /uploads/<name> отдаёт файл', async () => {
|
||||
const png = createTestPng();
|
||||
const uploadRes = await request(app)
|
||||
.post('/api/uploads')
|
||||
.set('Authorization', `Bearer ${authToken}`)
|
||||
.attach('file', png, 'static-test.png');
|
||||
|
||||
const fileName = uploadRes.body.file.name;
|
||||
trackFile(fileName);
|
||||
|
||||
const res = await request(app).get(`/uploads/${fileName}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-type']).toContain('image/png');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user