[+] Completed lab 4

This commit is contained in:
Антон Архипов
2026-11-16 16:23:32 +03:00
parent ec540a1a72
commit 06f0a9f31e
60 changed files with 7160 additions and 53 deletions
+47
View File
@@ -0,0 +1,47 @@
import express, { type Express } from 'express';
import swaggerUi from 'swagger-ui-express';
import { join } from 'node:path';
import { readFileSync } from 'node:fs';
import { RegisterRoutes } from './generated/routes';
import { requireAuthenticatedUser } from './middleware/auth';
import { requireJsonContentType } from './middleware/content-type';
import { errorHandler } from './middleware/error-handler';
import { notFoundHandler } from './middleware/not-found';
import { requestContext } from './middleware/request-context';
import { requestLogger } from './middleware/request-logger';
const contractPath = join(__dirname, '..', 'contracts', 'openapi.json');
const swaggerDocument = JSON.parse(readFileSync(contractPath, 'utf8'));
const parseJson = express.json({ limit: '64kb', strict: true });
export function createApp(): Express {
const app = express();
app.disable('x-powered-by');
app.set('query parser', 'simple');
app.use(requestContext);
app.use(requestLogger);
app.use('/api/v1/users/me', requireAuthenticatedUser);
app.use('/api/v1/chats', requireAuthenticatedUser);
app.use('/api/v1/attachments', requireAuthenticatedUser);
app.use('/api/v1/auth/sessions/current', requireAuthenticatedUser);
app.use(requireJsonContentType);
app.use((req, res, next) => {
if (/^\/api\/v1\/auth\/sessions\/?$/i.test(req.path) ||
/^\/api\/v1\/chats\/[^/]+\/attachments\/?$/i.test(req.path)) {
next();
return;
}
parseJson(req, res, next);
});
app.get('/docs/openapi.json', (_req, res) => res.json(swaggerDocument));
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
RegisterRoutes(app);
app.use(notFoundHandler);
app.use(errorHandler);
return app;
}
+27
View File
@@ -0,0 +1,27 @@
import { setTimeout as sleep } from 'node:timers/promises';
import { checkBucket, createBucket, s3Status } from './repositories/s3';
async function bootstrap(): Promise<void> {
const deadline = Date.now() + 38_000;
do {
try {
try {
await checkBucket();
} catch (error) {
if (s3Status(error) !== 404) throw error;
await createBucket();
await checkBucket();
}
console.log('Private S3 bucket is ready');
return;
} catch {
await sleep(500);
}
} while (Date.now() < deadline);
throw new Error('S3 bucket bootstrap timed out');
}
void bootstrap().catch(() => {
console.error('S3 bucket bootstrap failed. Check service status, endpoint and credentials.');
process.exitCode = 1;
});
+26
View File
@@ -0,0 +1,26 @@
import { z } from 'zod';
const envSchema = z.object({
APP_HOST: z.string().min(1).default('0.0.0.0'),
APP_PORT: z.coerce.number().int().min(1).max(65535).default(8080),
APP_ENV: z.string().min(1).default('lab'),
DB_HOST: z.string().min(1).default('127.0.0.1'),
DB_PORT: z.coerce.number().int().min(1).max(65535).default(5432),
POSTGRES_USER: z.string().min(1).default('messenger'),
POSTGRES_DB: z.string().min(1).default('messenger'),
POSTGRES_PASSWORD: z.string().min(1),
SESSION_TTL_SECONDS: z.coerce.number().int().min(1).max(31_536_000).default(3600),
INSTANCE_ID: z.string().regex(/^[A-Za-z0-9._-]{1,96}$/).optional(),
S3_ENDPOINT: z.string().url().default('http://s3:9000'),
S3_REGION: z.literal('us-east-1').default('us-east-1'),
S3_BUCKET: z.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/).default('messenger-attachments'),
S3_ACCESS_KEY_ID: z.string().min(3),
S3_SECRET_ACCESS_KEY: z.string().min(8),
MAX_UPLOAD_BYTES: z.coerce.number().int().min(1).max(10_485_760).default(10_485_760),
MAX_IMAGE_PIXELS: z.coerce.number().int().min(1).max(40_000_000).default(40_000_000),
LOG_LEVEL: z
.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent'])
.default('info'),
});
export const env = envSchema.parse(process.env);
+8
View File
@@ -0,0 +1,8 @@
import pino from 'pino';
import { env } from './env';
export const logger = pino({
level: env.LOG_LEVEL,
base: undefined,
timestamp: pino.stdTimeFunctions.isoTime,
});
+44
View File
@@ -0,0 +1,44 @@
import { pipeline } from 'node:stream/promises';
import { Controller, Get, Middlewares, Path, Post, Request, Route, SuccessResponse, Tags } from 'tsoa';
import type { Attachment } from '../domain/models';
import { invalidRequest, unsupportedMediaType } from '../errors/api-error';
import { prepareUpload, readUpload, type UploadRequest } from '../middleware/attachment-upload';
import type { SessionRequest } from '../middleware/auth';
import { attachmentMetadata, downloadAttachment, saveAttachment } from '../services/attachment.service';
@Route('api/v1')
@Tags('Attachments')
export class AttachmentsController extends Controller {
@Post('chats/{chat_id}/attachments')
@SuccessResponse(201, 'Created')
@Middlewares(prepareUpload, readUpload)
public async upload(@Path() chat_id: string, @Request() req: UploadRequest): Promise<Attachment> {
if (!Buffer.isBuffer(req.body)) throw unsupportedMediaType();
this.setStatus(201);
return saveAttachment(req.session.user, req.upload, req.body);
}
@Get('attachments/{attachment_id}')
public async metadata(@Path() attachment_id: string, @Request() req: SessionRequest): Promise<Attachment> {
return attachmentMetadata(req.session.user, attachment_id);
}
@Get('attachments/{attachment_id}/content')
public async content(@Path() attachment_id: string, @Request() req: SessionRequest): Promise<void> {
const variant = req.query.variant ?? 'original';
if (typeof variant !== 'string' || !['original', 'thumbnail', 'crop', 'optimized'].includes(variant)) {
throw invalidRequest('Некорректный вариант вложения');
}
const res = req.res;
if (!res) throw new Error('Response unavailable');
const { content, contentType, size } = await downloadAttachment(req.session.user, attachment_id, variant);
res.status(200).set({
'Content-Type': contentType,
'Content-Length': String(size),
'Cache-Control': 'private, no-store',
'X-Content-Type-Options': 'nosniff',
});
await pipeline(content, res);
}
}
+26
View File
@@ -0,0 +1,26 @@
import type { Request as ExpressRequest } from 'express';
import { Controller, Delete, Post, Request, Route, SuccessResponse, Tags } from 'tsoa';
import type { Session } from '../domain/models';
import { invalidRequest } from '../errors/api-error';
import type { SessionRequest } from '../middleware/auth';
import { createSession, revokeSession } from '../services/auth.service';
@Route('api/v1/auth/sessions')
@Tags('Auth')
export class AuthController extends Controller {
@Post()
@SuccessResponse(201, 'Created')
public async login(@Request() req: ExpressRequest): Promise<Session> {
if (req.get('Transfer-Encoding') || Number(req.get('Content-Length') ?? '0') !== 0) {
throw invalidRequest('Вход принимает только заголовок Authorization');
}
this.setStatus(201);
return createSession(req.get('Authorization'));
}
@Delete('current')
@SuccessResponse(204, 'No content')
public async logout(@Request() req: SessionRequest): Promise<void> {
await revokeSession(req.session);
}
}
+25
View File
@@ -0,0 +1,25 @@
import { Controller, Get, Path, Post, Request, Route, SuccessResponse, Tags } from 'tsoa';
import type { Chat, Page } from '../domain/models';
import type { SessionRequest } from '../middleware/auth';
import { createChat, listChats, requireAccessibleChat } from '../services/chat.service';
@Route('api/v1/chats')
@Tags('Chats')
export class ChatsController extends Controller {
@Post()
@SuccessResponse(201, 'Created')
public async createChat(@Request() req: SessionRequest): Promise<Chat> {
this.setStatus(201);
return createChat(req.session.user, req.body);
}
@Get()
public async listChats(@Request() req: SessionRequest): Promise<Page<Chat>> {
return listChats(req.session.user, req.query.limit, req.query.cursor);
}
@Get('{chat_id}')
public async getChat(@Path() chat_id: string, @Request() req: SessionRequest): Promise<Chat> {
return requireAccessibleChat(req.session.user, chat_id);
}
}
+28
View File
@@ -0,0 +1,28 @@
import { Controller, Get, Route, Tags } from 'tsoa';
import type { Health } from '../domain/models';
import { unavailable } from '../errors/api-error';
import { db } from '../repositories/postgres';
import { checkBucket } from '../repositories/s3';
@Route('health')
@Tags('Health')
export class HealthController extends Controller {
@Get('live')
public liveness(): Health {
return { status: 'ok' };
}
@Get('ready')
public async readiness(): Promise<Health> {
try {
const [{ rows }] = await Promise.all([
db.query("SELECT 1 FROM schema_migrations WHERE version = '003_attachments.sql'"),
checkBucket(),
]);
if (!rows.length) throw unavailable();
return { status: 'ok' };
} catch {
throw unavailable();
}
}
}
+20
View File
@@ -0,0 +1,20 @@
import { Controller, Get, Path, Post, Request, Route, SuccessResponse, Tags } from 'tsoa';
import type { Message, Page } from '../domain/models';
import type { SessionRequest } from '../middleware/auth';
import { createMessage, listMessages } from '../services/message.service';
@Route('api/v1/chats/{chat_id}/messages')
@Tags('Messages')
export class MessagesController extends Controller {
@Post()
@SuccessResponse(201, 'Created')
public async createMessage(@Path() chat_id: string, @Request() req: SessionRequest): Promise<Message> {
this.setStatus(201);
return createMessage(req.session.user, chat_id, req.body, req.get('Idempotency-Key'));
}
@Get()
public async listMessages(@Path() chat_id: string, @Request() req: SessionRequest): Promise<Page<Message>> {
return listMessages(req.session.user, chat_id, req.query.limit, req.query.cursor);
}
}
+21
View File
@@ -0,0 +1,21 @@
import type { Request as ExpressRequest } from 'express';
import { Controller, Get, Post, Request, Route, SuccessResponse, Tags } from 'tsoa';
import type { User } from '../domain/models';
import type { SessionRequest } from '../middleware/auth';
import { createUser } from '../services/user.service';
@Route('api/v1/users')
@Tags('Users')
export class UsersController extends Controller {
@Post()
@SuccessResponse(201, 'Created')
public async registerUser(@Request() req: ExpressRequest): Promise<User> {
this.setStatus(201);
return createUser(req.body);
}
@Get('me')
public currentUser(@Request() req: SessionRequest): User {
return req.session.user;
}
}
+90
View File
@@ -0,0 +1,90 @@
export interface User {
id: string;
username: string;
display_name: string;
created_at: string;
}
export interface CreateUserBody {
password: string;
username: string;
display_name: string;
}
export interface Session {
token: string;
token_type: 'Bearer';
expires_at: string;
user: User;
}
export interface Chat {
id: string;
title: string;
member_ids: string[];
created_at: string;
}
export interface CreateChatBody {
title: string;
member_ids: string[];
}
export interface Message {
id: string;
chat_id: string;
sender_id: string;
text: string;
created_at: string;
attachment_ids: string[];
}
export interface CreateMessageBody {
text: string;
attachment_ids?: string[];
}
export type ImageType = 'image/png' | 'image/jpeg';
export interface Attachment {
id: string;
chat_id: string;
owner_id: string;
filename: string;
content_type: ImageType;
size_bytes: number;
sha256: string;
status: 'ready';
variants: unknown[];
error_code: null;
created_at: string;
updated_at: string;
}
export interface Page<T> {
items: T[];
next_cursor: string | null;
}
export interface Health {
status: 'ok';
}
export type ErrorCode =
| 'invalid_request'
| 'unauthorized'
| 'not_found'
| 'conflict'
| 'payload_too_large'
| 'unsupported_media_type'
| 'rate_limited'
| 'unavailable'
| 'internal_error';
export interface ErrorResponse {
error: {
code: ErrorCode;
message: string;
request_id: string;
};
}
+39
View File
@@ -0,0 +1,39 @@
import type { ErrorCode } from '../domain/models';
export class ApiError extends Error {
public constructor(
public readonly status: number,
public readonly code: ErrorCode,
message: string,
public readonly challenge?: string,
) {
super(message);
this.name = 'ApiError';
}
}
export const invalidRequest = (message = 'Некорректный запрос') =>
new ApiError(400, 'invalid_request', message);
export const unauthorized = (scheme: 'Basic' | 'Bearer') =>
new ApiError(401, 'unauthorized', 'Требуются действительные учётные данные',
scheme === 'Basic' ? 'Basic realm="messenger", charset="UTF-8"' : 'Bearer realm="messenger"');
export const notFound = () =>
new ApiError(404, 'not_found', 'Объект не найден');
export const conflict = (message = 'Конфликт') =>
new ApiError(409, 'conflict', message);
export const unsupportedMediaType = () =>
new ApiError(
415,
'unsupported_media_type',
'Неподдерживаемый Content-Type или кодировка',
);
export const unavailable = (message = 'Сервис временно недоступен') =>
new ApiError(503, 'unavailable', message);
export const payloadTooLarge = (message = 'Тело запроса слишком большое') =>
new ApiError(413, 'payload_too_large', message);
+35
View File
@@ -0,0 +1,35 @@
import express, { type RequestHandler } from 'express';
import { z } from 'zod';
import { env } from '../config/env';
import type { ImageType } from '../domain/models';
import { unsupportedMediaType } from '../errors/api-error';
import { requireAccessibleChat } from '../services/chat.service';
import { parseWith } from '../validation/parse';
import type { SessionRequest } from './auth';
const filenameSchema = z.string().refine(
(name) => name.trim().length > 0 && Array.from(name).length <= 255 && !/[\/\\\p{Cc}\uD800-\uDFFF]/u.test(name),
'Некорректное имя файла',
);
export type UploadRequest = SessionRequest & {
upload: { chatId: string; filename: string; contentType: ImageType };
};
async function authorizeUpload(req: UploadRequest): Promise<void> {
const chat = await requireAccessibleChat(req.session.user, req.params.chat_id ?? '');
const filename = parseWith(filenameSchema, req.query.filename);
const contentType = req.get('Content-Type')?.split(';')[0]?.trim().toLowerCase();
if (contentType !== 'image/png' && contentType !== 'image/jpeg') throw unsupportedMediaType();
req.upload = { chatId: chat.id, filename, contentType };
}
export const prepareUpload: RequestHandler = (req, _res, next) => {
void authorizeUpload(req as UploadRequest).then(() => next(), next);
};
export const readUpload = express.raw({
limit: env.MAX_UPLOAD_BYTES,
type: () => true,
inflate: false,
});
+11
View File
@@ -0,0 +1,11 @@
import type { Request, RequestHandler } from 'express';
import { requireSession, type AuthenticatedSession } from '../services/auth.service';
export type SessionRequest = Request & { session: AuthenticatedSession };
export const requireAuthenticatedUser: RequestHandler = (req, _res, next) => {
void requireSession(req.get('Authorization')).then((session) => {
(req as SessionRequest).session = session;
next();
}, next);
};
+25
View File
@@ -0,0 +1,25 @@
import type { RequestHandler } from 'express';
import { unsupportedMediaType } from '../errors/api-error';
const jsonPostRoutes = [
/^\/api\/v1\/users\/?$/,
/^\/api\/v1\/chats\/?$/,
/^\/api\/v1\/chats\/[^/]+\/messages\/?$/,
];
export const requireJsonContentType: RequestHandler = (req, _res, next) => {
if (
req.method !== 'POST' ||
!jsonPostRoutes.some((pattern) => pattern.test(req.path))
) {
next();
return;
}
if (req.get('Content-Type')?.split(';')[0]?.trim().toLowerCase() !== 'application/json') {
next(unsupportedMediaType());
return;
}
next();
};
+79
View File
@@ -0,0 +1,79 @@
import type { ErrorRequestHandler } from 'express';
import { ValidateError } from 'tsoa';
import { logger } from '../config/logger';
import type { ErrorResponse } from '../domain/models';
import {
ApiError,
invalidRequest,
payloadTooLarge,
unsupportedMediaType,
unavailable,
} from '../errors/api-error';
interface BodyParserError extends Error {
status?: number;
type?: string;
code?: string;
}
export const errorHandler: ErrorRequestHandler = (
error: unknown,
_req,
res,
next,
): void => {
if (res.headersSent) {
next(error);
return;
}
const requestId = String(res.locals.requestId ?? 'unknown');
let apiError: ApiError;
if (error instanceof ApiError) {
apiError = error;
} else if (error instanceof ValidateError || error instanceof URIError) {
apiError = invalidRequest('Некорректные параметры запроса');
} else if (
error instanceof SyntaxError &&
((error as BodyParserError).status === 400 ||
(error as BodyParserError).type === 'entity.parse.failed')
) {
apiError = invalidRequest('Некорректный JSON');
} else if ((error as BodyParserError | undefined)?.status === 415) {
apiError = unsupportedMediaType();
} else if (
(error as BodyParserError | undefined)?.type === 'entity.too.large'
) {
apiError = payloadTooLarge();
} else if ((error as BodyParserError | undefined)?.status === 400) {
apiError = invalidRequest();
} else if (/^(08...|57P0[123]|57014|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND)$/.test(
(error as BodyParserError | undefined)?.code ?? '',
) || (error instanceof Error && /^Connection terminated|^timeout exceeded when trying to connect/.test(error.message))) {
apiError = unavailable();
} else {
logger.error(
{
request_id: requestId,
error_name:
error instanceof Error ? error.name : 'UnknownError',
},
'unhandled request error',
);
apiError = new ApiError(
500,
'internal_error',
'Внутренняя ошибка сервера',
);
}
if (apiError.challenge) res.setHeader('WWW-Authenticate', apiError.challenge);
const body: ErrorResponse = {
error: {
code: apiError.code,
message: apiError.message,
request_id: requestId,
},
};
res.status(apiError.status).json(body);
};
+10
View File
@@ -0,0 +1,10 @@
import type { NextFunction, Request, Response } from 'express';
import { notFound } from '../errors/api-error';
export function notFoundHandler(
_req: Request,
_res: Response,
next: NextFunction,
): void {
next(notFound());
}
+17
View File
@@ -0,0 +1,17 @@
import type { NextFunction, Request, Response } from 'express';
import { v4 as uuidv4 } from 'uuid';
import { env } from '../config/env';
const instanceId = env.INSTANCE_ID ?? uuidv4();
export function requestContext(
_req: Request,
res: Response,
next: NextFunction,
): void {
const requestId = uuidv4();
res.locals.requestId = requestId;
res.setHeader('X-Request-Id', requestId);
res.setHeader('X-Instance-Id', instanceId);
next();
}
+24
View File
@@ -0,0 +1,24 @@
import type { NextFunction, Request, Response } from 'express';
import { logger } from '../config/logger';
export function requestLogger(
req: Request,
res: Response,
next: NextFunction,
): void {
const started = process.hrtime.bigint();
res.once('finish', () => {
const elapsedMs = Number(process.hrtime.bigint() - started) / 1_000_000;
logger.info(
{
request_id: res.locals.requestId,
method: req.method,
path: req.path,
status: res.statusCode,
duration_ms: Math.round(elapsedMs * 100) / 100,
},
'request completed',
);
});
next();
}
+43
View File
@@ -0,0 +1,43 @@
import { createHash } from 'node:crypto';
import { readdir, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { db, transaction } from './repositories/postgres';
async function migrate(): Promise<void> {
const directory = join(__dirname, '..', 'migrations');
const files = (await readdir(directory)).filter((name) => /^\d{3}_.+\.sql$/.test(name)).sort();
if (files.length === 0) throw new Error('No migrations found');
await transaction(async (client) => {
await client.query('SELECT pg_advisory_xact_lock(20261116, 1)');
await client.query(`
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
checksum text NOT NULL,
applied_at timestamptz NOT NULL DEFAULT now()
)
`);
for (const version of files) {
const sql = await readFile(join(directory, version), 'utf8');
const checksum = createHash('sha256').update(sql).digest('hex');
const previous = await client.query<{ checksum: string }>(
'SELECT checksum FROM schema_migrations WHERE version = $1', [version],
);
if (previous.rows[0]) {
if (previous.rows[0].checksum !== checksum) throw new Error(`Migration changed: ${version}`);
continue;
}
await client.query(sql);
await client.query(
'INSERT INTO schema_migrations (version, checksum) VALUES ($1, $2)', [version, checksum],
);
console.log(`Applied ${version}`);
}
});
console.log('Migrations up to date');
}
migrate().catch((error: unknown) => {
console.error(error instanceof Error ? error.message : 'Migration failed');
process.exitCode = 1;
}).finally(() => db.end());
+40
View File
@@ -0,0 +1,40 @@
import { Pool, types, type PoolClient } from 'pg';
import { env } from '../config/env';
import { logger } from '../config/logger';
const parseTimestamp = types.getTypeParser(types.builtins.TIMESTAMPTZ);
types.setTypeParser(types.builtins.TIMESTAMPTZ, (value) => parseTimestamp(value).toISOString());
export const db = new Pool({
host: env.DB_HOST,
port: env.DB_PORT,
user: env.POSTGRES_USER,
password: env.POSTGRES_PASSWORD,
database: env.POSTGRES_DB,
max: 8,
connectionTimeoutMillis: 2_000,
statement_timeout: 4_000,
idle_in_transaction_session_timeout: 5_000,
});
db.on('error', () => logger.warn('idle PostgreSQL connection lost'));
export async function transaction<T>(work: (client: PoolClient) => Promise<T>): Promise<T> {
const client = await db.connect();
let discardConnection = false;
try {
await client.query('BEGIN');
const result = await work(client);
await client.query('COMMIT');
return result;
} catch (error) {
try {
await client.query('ROLLBACK');
} catch {
discardConnection = true;
}
throw error;
} finally {
client.release(discardConnection);
}
}
+42
View File
@@ -0,0 +1,42 @@
import {
CreateBucketCommand, DeleteObjectCommand, GetObjectCommand, HeadBucketCommand,
PutObjectCommand, S3Client,
} from '@aws-sdk/client-s3';
import { env } from '../config/env';
const client = new S3Client({
endpoint: env.S3_ENDPOINT,
region: env.S3_REGION,
forcePathStyle: true,
credentials: { accessKeyId: env.S3_ACCESS_KEY_ID, secretAccessKey: env.S3_SECRET_ACCESS_KEY },
maxAttempts: 1,
requestChecksumCalculation: 'WHEN_REQUIRED',
responseChecksumValidation: 'WHEN_REQUIRED',
});
const Bucket = env.S3_BUCKET;
export function s3Status(error: unknown): number | undefined {
return (error as { $metadata?: { httpStatusCode?: number } } | undefined)?.$metadata?.httpStatusCode;
}
export async function checkBucket(): Promise<void> {
await client.send(new HeadBucketCommand({ Bucket }), { abortSignal: AbortSignal.timeout(1_500) });
}
export async function createBucket(): Promise<void> {
await client.send(new CreateBucketCommand({ Bucket }), { abortSignal: AbortSignal.timeout(3_000) });
}
export async function putOriginal(key: string, content: Buffer, mediaType: string): Promise<void> {
await client.send(new PutObjectCommand({
Bucket, Key: key, Body: content, ContentLength: content.length, ContentType: mediaType,
}), { abortSignal: AbortSignal.timeout(8_000) });
}
export async function deleteOriginal(key: string): Promise<void> {
await client.send(new DeleteObjectCommand({ Bucket, Key: key }), { abortSignal: AbortSignal.timeout(2_000) });
}
export async function getOriginal(key: string) {
return client.send(new GetObjectCommand({ Bucket, Key: key }), { abortSignal: AbortSignal.timeout(8_000) });
}
+42
View File
@@ -0,0 +1,42 @@
import type { Server } from 'node:http';
import { createApp } from './app';
import { env } from './config/env';
import { logger } from './config/logger';
import { db } from './repositories/postgres';
const app = createApp();
const server: Server = app.listen(env.APP_PORT, env.APP_HOST, () => {
logger.info(
{ host: env.APP_HOST, port: env.APP_PORT, environment: env.APP_ENV },
'server started',
);
});
let shuttingDown = false;
function shutdown(signal: NodeJS.Signals): void {
if (shuttingDown) return;
shuttingDown = true;
logger.info({ signal }, 'graceful shutdown started');
const forceTimer = setTimeout(() => {
logger.error('graceful shutdown timed out');
server.closeAllConnections();
process.exit(1);
}, 9_000);
forceTimer.unref();
server.close((error) => {
void db.end().finally(() => {
clearTimeout(forceTimer);
if (error) {
logger.error({ error_name: error.name }, 'server close failed');
process.exitCode = 1;
} else {
logger.info('server stopped');
}
}).catch(() => { process.exitCode = 1; });
});
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
+112
View File
@@ -0,0 +1,112 @@
import { createHash, randomUUID } from 'node:crypto';
import { Readable } from 'node:stream';
import sharp from 'sharp';
import { env } from '../config/env';
import type { Attachment, ImageType, User } from '../domain/models';
import { notFound, payloadTooLarge, unavailable, unsupportedMediaType } from '../errors/api-error';
import { logger } from '../config/logger';
import { db } from '../repositories/postgres';
import { deleteOriginal, getOriginal, putOriginal } from '../repositories/s3';
import { parseWith } from '../validation/parse';
import { uuidSchema } from '../validation/schemas';
type AttachmentRow = Pick<Attachment, 'id' | 'chat_id' | 'owner_id' | 'filename' | 'content_type'
| 'size_bytes' | 'sha256' | 'created_at'> & { object_key: string };
interface UploadTarget {
chatId: string;
filename: string;
contentType: ImageType;
}
const attachmentFields = `
a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.created_at, a.object_key
`;
function publicMetadata({ object_key: _key, ...row }: AttachmentRow): Attachment {
return { ...row, status: 'ready', variants: [], error_code: null, updated_at: row.created_at };
}
async function validateImage(data: Buffer, mediaType: ImageType): Promise<void> {
const expected = mediaType === 'image/png' ? 'png' : 'jpeg';
let metadata: sharp.Metadata;
try {
// Reading metadata probes the header without decompressing the pixel array.
metadata = await sharp(data, { limitInputPixels: false, failOn: 'warning' }).metadata();
} catch {
throw unsupportedMediaType();
}
const { format, width, height } = metadata;
if (format !== expected || !width || !height) throw unsupportedMediaType();
if (width > Math.floor(env.MAX_IMAGE_PIXELS / height)) {
throw payloadTooLarge('Размер изображения превышает лимит пикселей');
}
try {
await sharp(data, { limitInputPixels: env.MAX_IMAGE_PIXELS, failOn: 'warning' }).stats();
} catch {
throw unsupportedMediaType();
}
}
export async function saveAttachment(actor: User, target: UploadTarget, bytes: Buffer): Promise<Attachment> {
if (bytes.length === 0) throw unsupportedMediaType();
await validateImage(bytes, target.contentType);
const sha256 = createHash('sha256').update(bytes).digest('hex');
const key = `originals/${randomUUID()}`;
try {
await putOriginal(key, bytes, target.contentType);
} catch {
throw unavailable('Хранилище вложений временно недоступно');
}
try {
const { rows } = await db.query<AttachmentRow>(
`INSERT INTO attachments AS a (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key)
VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING ${attachmentFields}`,
[target.chatId, actor.id, target.filename, target.contentType, bytes.length, sha256, key],
);
if (!rows[0]) throw new Error('Attachment not returned');
return publicMetadata(rows[0]);
} catch (error) {
const sqlState = (error as { code?: string } | undefined)?.code ?? '';
// Keep the object if a lost connection leaves the commit outcome uncertain.
if (/^(22...|23...|57014)$/.test(sqlState)) {
await deleteOriginal(key).catch(() => logger.warn('attachment compensation failed'));
}
throw error;
}
}
async function requireAttachment(actor: User, attachmentId: string): Promise<AttachmentRow> {
const id = parseWith(uuidSchema, attachmentId);
const { rows } = await db.query<AttachmentRow>(
`SELECT ${attachmentFields} FROM attachments a
JOIN chat_members m ON m.chat_id = a.chat_id WHERE a.id = $1 AND m.user_id = $2`,
[id, actor.id],
);
if (!rows[0]) throw notFound();
return rows[0];
}
export async function attachmentMetadata(actor: User, id: string): Promise<Attachment> {
return publicMetadata(await requireAttachment(actor, id));
}
export async function downloadAttachment(actor: User, id: string, variant: string) {
const row = await requireAttachment(actor, id);
if (variant !== 'original') throw notFound();
try {
const { Body, ContentLength } = await getOriginal(row.object_key);
if (!(Body instanceof Readable) || ContentLength !== row.size_bytes) {
if (Body instanceof Readable) Body.destroy();
throw new Error('Original missing or storage length mismatch');
}
return { content: Body, contentType: row.content_type, size: row.size_bytes };
} catch {
throw unavailable('Оригинал вложения временно недоступен');
}
}
+86
View File
@@ -0,0 +1,86 @@
import { createHash, randomBytes } from 'node:crypto';
import type { Session, User } from '../domain/models';
import { unauthorized } from '../errors/api-error';
import { env } from '../config/env';
import { db } from '../repositories/postgres';
import { passwordSchema, usernameSchema } from '../validation/schemas';
import { verifyPassword } from './password.service';
interface Account extends User {
password_hash: string;
}
export interface AuthenticatedSession {
user: User;
tokenHash: string;
}
const hashToken = (token: string): string =>
createHash('sha256').update(token, 'ascii').digest('hex');
function basicCredentials(authorization: string | undefined): { username: string; password: string } {
const encoded = /^Basic +([A-Za-z0-9+/]+={0,2})$/i.exec(authorization ?? '')?.[1];
if (!encoded || encoded.length > 800) throw unauthorized('Basic');
const bytes = Buffer.from(encoded, 'base64');
if (bytes.toString('base64') !== encoded) throw unauthorized('Basic');
let value: string;
try {
value = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
} catch {
throw unauthorized('Basic');
}
const separator = value.indexOf(':');
const username = value.slice(0, separator);
const password = value.slice(separator + 1);
if (separator < 0 || !usernameSchema.safeParse(username).success || !passwordSchema.safeParse(password).success) {
throw unauthorized('Basic');
}
return { username, password };
}
export async function createSession(authorization: string | undefined): Promise<Session> {
const { username, password } = basicCredentials(authorization);
const result = await db.query<Account>(
'SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1',
[username],
);
const account = result.rows[0];
if (!(await verifyPassword(password, account?.password_hash)) || !account) throw unauthorized('Basic');
const token = randomBytes(32).toString('base64url');
const { rows } = await db.query<{ expires_at: string }>(
`INSERT INTO sessions (token_hash, user_id, expires_at)
VALUES ($1, $2, clock_timestamp() + $3::int * interval '1 second') RETURNING expires_at`,
[hashToken(token), account.id, env.SESSION_TTL_SECONDS],
);
const session = rows[0];
if (!session) throw new Error('Session not returned');
const { id, display_name, created_at } = account;
return { token, token_type: 'Bearer', expires_at: session.expires_at,
user: { id, username, display_name, created_at } };
}
export async function requireSession(authorization: string | undefined): Promise<AuthenticatedSession> {
const token = /^Bearer +([A-Za-z0-9_-]{43})$/i.exec(authorization ?? '')?.[1];
if (!token) throw unauthorized('Bearer');
const tokenHash = hashToken(token);
const { rows } = await db.query<User>(
`SELECT u.id, u.username, u.display_name, u.created_at
FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.token_hash = $1 AND s.expires_at > clock_timestamp()`,
[tokenHash],
);
const user = rows[0];
if (!user) throw unauthorized('Bearer');
return { user, tokenHash };
}
export async function revokeSession(session: AuthenticatedSession): Promise<void> {
const result = await db.query(
'DELETE FROM sessions WHERE token_hash = $1 AND expires_at > clock_timestamp()',
[session.tokenHash],
);
if (result.rowCount !== 1) throw unauthorized('Bearer');
}
+59
View File
@@ -0,0 +1,59 @@
import type { Chat, Page, User } from '../domain/models';
import { invalidRequest, notFound } from '../errors/api-error';
import { db, transaction } from '../repositories/postgres';
import { parseWith } from '../validation/parse';
import { createChatSchema, uuidSchema } from '../validation/schemas';
import { makePage, parsePage } from './cursor.service';
const chatFields = `
c.id, c.title, c.created_at,
ARRAY(SELECT user_id FROM chat_members
WHERE chat_id = c.id ORDER BY position) AS member_ids
`;
export async function createChat(actor: User, input: unknown): Promise<Chat> {
const { title, member_ids } = parseWith(createChatSchema, input);
if (!member_ids.includes(actor.id)) {
throw invalidRequest('Текущий пользователь должен входить в member_ids');
}
return transaction(async (client) => {
const ids = await client.query('SELECT id FROM users WHERE id = ANY($1::uuid[])', [member_ids]);
if (ids.rowCount !== member_ids.length) {
throw invalidRequest('member_ids содержит неизвестного пользователя');
}
const { rows } = await client.query<Omit<Chat, 'member_ids'>>(
'INSERT INTO chats (title) VALUES ($1) RETURNING id, title, created_at', [title],
);
const chat = rows[0];
if (!chat) throw new Error('Chat not returned');
await client.query(
`INSERT INTO chat_members (chat_id, user_id, position)
SELECT $1, id, position FROM unnest($2::uuid[]) WITH ORDINALITY AS m(id, position)`,
[chat.id, member_ids],
);
return { ...chat, member_ids };
});
}
export async function requireAccessibleChat(actor: User, chatId: string): Promise<Chat> {
const id = parseWith(uuidSchema, chatId);
const { rows } = await db.query<Chat>(
`SELECT ${chatFields} FROM chats c JOIN chat_members m ON m.chat_id = c.id
WHERE c.id = $1 AND m.user_id = $2`,
[id, actor.id],
);
if (!rows[0]) throw notFound();
return rows[0];
}
export async function listChats(actor: User, limit: unknown, cursor: unknown): Promise<Page<Chat>> {
const scope = { kind: 'chats', resource: actor.id } as const;
const page = parsePage(limit, cursor, scope);
const { rows } = await db.query<Chat>(
`SELECT ${chatFields} FROM chats c JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = $1 AND ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3))
ORDER BY c.created_at, c.id LIMIT $4`,
[actor.id, page.after?.created_at, page.after?.id, page.limit + 1],
);
return makePage(rows, page.limit, scope);
}
+45
View File
@@ -0,0 +1,45 @@
import type { Page } from '../domain/models';
import { invalidRequest } from '../errors/api-error';
import { parseWith } from '../validation/parse';
import { cursorPayloadSchema, paginationSchema, type CursorPayload } from '../validation/schemas';
type CursorScope = Pick<CursorPayload, 'kind' | 'resource'>;
export function encodeCursor(payload: CursorPayload): string {
return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');
}
export function decodeCursor(cursor: string): CursorPayload {
try {
const bytes = Buffer.from(cursor, 'base64url');
if (bytes.toString('base64url') !== cursor) throw new Error('Invalid encoding');
return cursorPayloadSchema.parse(JSON.parse(bytes.toString('utf8')));
} catch {
throw invalidRequest('Некорректный cursor');
}
}
export function parsePage(limit: unknown, cursor: unknown, scope: CursorScope) {
if (limit !== undefined && (typeof limit !== 'string' || !/^[0-9]+$/.test(limit))) {
throw invalidRequest('Некорректный limit');
}
const query = parseWith(paginationSchema, { limit: limit === undefined ? undefined : Number(limit), cursor });
const after = query.cursor === undefined ? null : decodeCursor(query.cursor);
if (after && (after.kind !== scope.kind || after.resource !== scope.resource)) {
throw invalidRequest('Cursor не относится к этому списку');
}
return { limit: query.limit, after };
}
export function makePage<T extends { id: string; created_at: string }>(
rows: T[],
limit: number,
scope: CursorScope,
): Page<T> {
const items = rows.slice(0, limit);
const last = items.at(-1);
const next_cursor = last && rows.length > limit
? encodeCursor({ v: 1, ...scope, id: last.id, created_at: new Date(last.created_at).toISOString() })
: null;
return { items, next_cursor };
}
+52
View File
@@ -0,0 +1,52 @@
import { createHash } from 'node:crypto';
import type { PoolClient } from 'pg';
import { conflict, invalidRequest } from '../errors/api-error';
interface Identity {
userId: string;
chatId: string;
key: string;
}
export function parseIdempotencyKey(value: string | undefined): string {
if (!value || !/^[A-Za-z0-9._:-]{1,128}$/.test(value)) {
throw invalidRequest('Требуется корректный Idempotency-Key');
}
return value;
}
export async function reserveMessageKey(
client: PoolClient, identity: Identity, body: object,
): Promise<string | null> {
const hash = createHash('sha256').update(JSON.stringify(body)).digest('hex');
const values = [identity.userId, identity.chatId, identity.key];
// A conflicting insertion waits for the transaction holding this unique key.
const reserved = await client.query(
`INSERT INTO message_idempotency (user_id, chat_id, idempotency_key, request_hash, expires_at)
VALUES ($1, $2, $3, $4, clock_timestamp() + interval '24 hours')
ON CONFLICT (user_id, chat_id, idempotency_key) DO UPDATE
SET request_hash = EXCLUDED.request_hash, message_id = NULL, expires_at = EXCLUDED.expires_at
WHERE message_idempotency.expires_at <= clock_timestamp()
RETURNING idempotency_key`,
[...values, hash],
);
if (reserved.rowCount === 1) return null;
const { rows } = await client.query<{ request_hash: string; message_id: string | null }>(
`SELECT request_hash, message_id FROM message_idempotency
WHERE user_id = $1 AND chat_id = $2 AND idempotency_key = $3`,
values,
);
const record = rows[0];
if (!record?.message_id) throw new Error('Idempotency record incomplete');
if (record.request_hash !== hash) throw conflict('Ключ уже связан с другим сообщением');
return record.message_id;
}
export async function rememberMessage(client: PoolClient, identity: Identity, messageId: string): Promise<void> {
await client.query(
`UPDATE message_idempotency SET message_id = $4, expires_at = clock_timestamp() + interval '24 hours'
WHERE user_id = $1 AND chat_id = $2 AND idempotency_key = $3`,
[identity.userId, identity.chatId, identity.key, messageId],
);
}
+74
View File
@@ -0,0 +1,74 @@
import type { Message, Page, User } from '../domain/models';
import { notFound } from '../errors/api-error';
import { db, transaction } from '../repositories/postgres';
import { parseWith } from '../validation/parse';
import { createMessageSchema } from '../validation/schemas';
import { requireAccessibleChat } from './chat.service';
import { makePage, parsePage } from './cursor.service';
import { parseIdempotencyKey, rememberMessage, reserveMessageKey } from './idempotency.service';
const messageFields = `
m.id, m.chat_id, m.sender_id, m.text, m.created_at,
ARRAY(SELECT attachment_id FROM message_attachments
WHERE message_id = m.id ORDER BY position) AS attachment_ids
`;
export async function createMessage(
actor: User, chatId: string, input: unknown, keyHeader: string | undefined,
): Promise<Message> {
const chat = await requireAccessibleChat(actor, chatId);
const { text, attachment_ids } = parseWith(createMessageSchema, input);
const identity = { userId: actor.id, chatId: chat.id, key: parseIdempotencyKey(keyHeader) };
return transaction(async (client) => {
if (attachment_ids.length) {
const attachments = await client.query(
'SELECT id FROM attachments WHERE chat_id = $1 AND id = ANY($2::uuid[])',
[chat.id, attachment_ids],
);
if (attachments.rowCount !== attachment_ids.length) throw notFound();
}
// Keep the Lab 3 hash for text-only messages and equate omitted IDs with [].
const hashBody = attachment_ids.length ? { text, attachment_ids } : { text };
const replayId = await reserveMessageKey(client, identity, hashBody);
if (replayId) {
const { rows } = await client.query<Message>(
`SELECT ${messageFields} FROM messages m WHERE m.id = $1`, [replayId],
);
if (!rows[0]) throw new Error('Saved message not found');
return rows[0];
}
const { rows } = await client.query<Omit<Message, 'attachment_ids'>>(
`INSERT INTO messages (chat_id, sender_id, text) VALUES ($1, $2, $3)
RETURNING id, chat_id, sender_id, text, created_at`,
[chat.id, actor.id, text],
);
const message = rows[0];
if (!message) throw new Error('Message not returned');
if (attachment_ids.length) {
await client.query(
`INSERT INTO message_attachments (chat_id, message_id, attachment_id, position)
SELECT $1, $2, id, position FROM unnest($3::uuid[]) WITH ORDINALITY AS a(id, position)`,
[chat.id, message.id, attachment_ids],
);
}
await rememberMessage(client, identity, message.id);
return { ...message, attachment_ids };
});
}
export async function listMessages(actor: User, chatId: string, limit: unknown, cursor: unknown): Promise<Page<Message>> {
const chat = await requireAccessibleChat(actor, chatId);
const scope = { kind: 'messages', resource: chat.id } as const;
const page = parsePage(limit, cursor, scope);
const { rows } = await db.query<Message>(
`SELECT ${messageFields} FROM messages m
WHERE m.chat_id = $1 AND ($2::timestamptz IS NULL OR (m.created_at, m.id) > ($2, $3))
ORDER BY m.created_at, m.id LIMIT $4`,
[chat.id, page.after?.created_at, page.after?.id, page.limit + 1],
);
return makePage(rows, page.limit, scope);
}
+19
View File
@@ -0,0 +1,19 @@
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
import { promisify } from 'node:util';
const derive = promisify(scrypt);
const dummyHash = 'scrypt$00000000000000000000000000000000$' + '0'.repeat(128);
export async function hashPassword(password: string): Promise<string> {
const salt = randomBytes(16);
const key = (await derive(password, salt, 64)) as Buffer;
return `scrypt$${salt.toString('hex')}$${key.toString('hex')}`;
}
export async function verifyPassword(password: string, stored: string | undefined): Promise<boolean> {
const [, salt, hash] = (stored ?? dummyHash).split('$');
if (!salt || !hash) throw new Error('Invalid password hash');
const expected = Buffer.from(hash, 'hex');
const actual = (await derive(password, Buffer.from(salt, 'hex'), expected.length)) as Buffer;
return timingSafeEqual(actual, expected) && stored !== undefined;
}
+19
View File
@@ -0,0 +1,19 @@
import type { User } from '../domain/models';
import { conflict } from '../errors/api-error';
import { db } from '../repositories/postgres';
import { parseWith } from '../validation/parse';
import { createUserSchema } from '../validation/schemas';
import { hashPassword } from './password.service';
export async function createUser(input: unknown): Promise<User> {
const body = parseWith(createUserSchema, input);
const hash = await hashPassword(body.password);
const { rows } = await db.query<User>(
`INSERT INTO users (username, display_name, password_hash) VALUES ($1, $2, $3)
ON CONFLICT (username) DO NOTHING RETURNING id, username, display_name, created_at`,
[body.username, body.display_name, hash],
);
const user = rows[0];
if (!user) throw conflict('Username уже занят');
return user;
}
+1
View File
@@ -0,0 +1 @@
export {};
+16
View File
@@ -0,0 +1,16 @@
import { z } from 'zod';
import { invalidRequest } from '../errors/api-error';
export function parseWith<T extends z.ZodTypeAny>(
schema: T,
value: unknown,
): z.output<T> {
const result = schema.safeParse(value);
if (result.success) {
return result.data;
}
const issue = result.error.issues[0];
throw invalidRequest(issue?.message ?? 'Некорректный запрос');
}
+71
View File
@@ -0,0 +1,71 @@
import { z } from 'zod';
const codePointLength = (value: string): number => Array.from(value).length;
const validUnicode = (value: string): boolean => !/[\u0000\uD800-\uDFFF]/u.test(value);
const nonBlank = (value: string): boolean => value.trim().length > 0;
const boundedUnicodeString = (max: number, label: string) =>
z
.string()
.refine(validUnicode, 'Недопустимый символ')
.refine(nonBlank, `${label} не может состоять только из пробелов`)
.refine(
(value) => codePointLength(value) <= max,
`${label} слишком длинное`,
);
export const uuidSchema = z.string().uuid('Ожидался UUID').transform((id) => id.toLowerCase());
export const usernameSchema = z.string().regex(/^[a-z0-9_]{3,32}$/, 'Некорректный username');
export const passwordSchema = boundedUnicodeString(128, 'password')
.refine((value) => codePointLength(value) >= 12, 'password слишком короткий');
export const createUserSchema = z
.object({
username: usernameSchema,
password: passwordSchema,
display_name: boundedUnicodeString(100, 'display_name'),
})
.strict();
export const createChatSchema = z
.object({
title: boundedUnicodeString(100, 'title'),
member_ids: z
.array(uuidSchema)
.min(1)
.max(100)
.refine(
(ids) => new Set(ids).size === ids.length,
'member_ids содержит дубликаты',
),
})
.strict();
export const createMessageSchema = z
.object({
text: z.string().refine(validUnicode, 'Недопустимый символ')
.refine((value) => codePointLength(value) <= 4000, 'text слишком длинный'),
attachment_ids: z.array(uuidSchema).max(10)
.refine((ids) => new Set(ids).size === ids.length, 'attachment_ids содержит дубликаты')
.default([]),
})
.strict()
.refine((body) => nonBlank(body.text) || body.attachment_ids.length > 0,
'Нужен текст или хотя бы одно вложение');
export const paginationSchema = z.object({
limit: z.number().int().min(1).max(100).default(50),
cursor: z.string().min(1).max(512).optional(),
});
export const cursorPayloadSchema = z
.object({
v: z.literal(1),
kind: z.enum(['chats', 'messages']),
resource: z.string().min(1),
created_at: z.string().datetime({ precision: 3 }),
id: uuidSchema,
})
.strict();
export type CursorPayload = z.infer<typeof cursorPayloadSchema>;