fix: правки

This commit is contained in:
2026-10-10 02:13:35 +03:00
parent 1bef3845bc
commit ff47290919
30 changed files with 902 additions and 183 deletions
+1 -5
View File
@@ -1,8 +1,4 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { BadRequestException, Injectable } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { DatabaseClient } from '../database/database.client.js';
import type { Cursor } from '../common/http/cursor.js';
+2 -1
View File
@@ -4,6 +4,7 @@ import {
NotFoundException,
} from '@nestjs/common';
import { encodeCursor, decodeCursor } from '../common/http/cursor.js';
import type { Page } from '../common/http/page.js';
import type { User } from '../users/user.js';
import type { CreateChatDto } from './dto/create-chat.dto.js';
import type { Chat } from './chat.js';
@@ -34,7 +35,7 @@ export class ChatsService {
currentUser: User,
limit: number,
cursorValue?: string,
): Promise<{ items: Chat[]; next_cursor: string | null }> {
): Promise<Page<Chat>> {
const scope = `chats:${currentUser.id}`;
const cursor = cursorValue
? decodeCursor(cursorValue, scope)
+2 -2
View File
@@ -5,13 +5,13 @@ import {
IsArray,
IsString,
IsUUID,
Length,
Matches,
} from 'class-validator';
import { CodePointLength } from '../../common/validation/code-point-length.js';
export class CreateChatDto {
@IsString()
@Length(1, 100)
@CodePointLength(1, 100)
@Matches(/\S/, {
message: 'title must contain a non-whitespace character',
})
+7
View File
@@ -0,0 +1,7 @@
export type ApiErrorBody = {
error: {
code: string;
message: string;
request_id: string;
};
};
+57 -27
View File
@@ -4,35 +4,56 @@ import {
ExceptionFilter,
HttpException,
HttpStatus,
Logger,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { randomUUID } from 'node:crypto';
import type { ApiErrorBody } from './api-error.js';
type RequestWithId = { requestId?: string; method?: string; url?: string };
type ExceptionBody = { message?: unknown; challenge?: unknown };
// Connection/session loss codes reported by node-postgres and the network layer.
const UNAVAILABLE_ERROR_CODES = new Set([
'ECONNREFUSED',
'ECONNRESET',
'ENOTFOUND',
'ETIMEDOUT',
'EPIPE',
'08000',
'08001',
'08003',
'08004',
'08006',
'57P01',
'57P02',
'57P03',
'53300',
]);
const UNAVAILABLE_ERROR_CODES: Record<string, true> = {
ECONNREFUSED: true,
ECONNRESET: true,
ENOTFOUND: true,
ETIMEDOUT: true,
EPIPE: true,
'08000': true,
'08001': true,
'08003': true,
'08004': true,
'08006': true,
'57P01': true,
'57P02': true,
'57P03': true,
'53300': true,
};
// Some driver failures carry no `code` at all: node-postgres raises plain errors
// when a connection dies or its pool attempt times out, and node-redis reports a
// closed socket the same way. Without these patterns a stopped database would
// surface as an internal fault instead of a bounded outage.
const UNAVAILABLE_ERROR_MESSAGES = [
'Connection terminated unexpectedly',
'Connection terminated due to connection timeout',
'timeout exceeded when trying to connect',
'Client has encountered a connection error and is not queryable',
'Socket closed unexpectedly',
'Connection is closed',
];
function isDependencyOutage(exception: unknown): boolean {
if (typeof exception !== 'object' || exception === null) return false;
const code = (exception as { code?: unknown }).code;
return typeof code === 'string' && UNAVAILABLE_ERROR_CODES.has(code);
if (typeof code === 'string' && UNAVAILABLE_ERROR_CODES[code] === true)
return true;
const message = (exception as { message?: unknown }).message;
return (
typeof message === 'string' &&
UNAVAILABLE_ERROR_MESSAGES.some((pattern) => message.includes(pattern))
);
}
function errorCodeForStatus(status: number): string {
@@ -51,6 +72,8 @@ function errorCodeForStatus(status: number): string {
@Catch()
export class ApiExceptionFilter implements ExceptionFilter {
private readonly logger = new Logger(ApiExceptionFilter.name);
constructor(private readonly adapterHost: HttpAdapterHost) {}
catch(exception: unknown, host: ArgumentsHost): void {
@@ -92,6 +115,16 @@ export class ApiExceptionFilter implements ExceptionFilter {
// A dropped dependency is a bounded outage, not an internal fault.
status = HttpStatus.SERVICE_UNAVAILABLE;
message = 'Service unavailable';
this.logger.warn(
`Dependency outage on ${request.method ?? ''} ${request.url ?? ''}: ${exception instanceof Error ? exception.message : 'unknown error'}`,
);
} else {
this.logger.error(
`Unhandled exception on ${request.method ?? ''} ${request.url ?? ''}`,
exception instanceof Error
? exception.stack
: String(exception),
);
}
if (status === HttpStatus.UNAUTHORIZED) {
const authChallenge =
@@ -103,16 +136,13 @@ export class ApiExceptionFilter implements ExceptionFilter {
adapter.setHeader(response, 'WWW-Authenticate', authChallenge);
}
adapter.setHeader(response, 'X-Request-Id', requestId);
adapter.reply(
response,
{
error: {
code: errorCodeForStatus(status),
message,
request_id: requestId,
},
const payload: ApiErrorBody = {
error: {
code: errorCodeForStatus(status),
message,
request_id: requestId,
},
status,
);
};
adapter.reply(response, payload, status);
}
}
+85
View File
@@ -0,0 +1,85 @@
import { BadRequestException } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { describe, expect, it } from 'vitest';
import { decodeCursor, encodeCursor } from './cursor.js';
const scope = 'messages:6f1c2a3e-1111-4222-8333-444455556666';
function encode(createdAt: string, cursorScope = scope): string {
return encodeCursor({
scope: cursorScope,
created_at: createdAt,
id: randomUUID(),
});
}
describe('decodeCursor', () => {
it('accepts valid instants and normalizes them to canonical milliseconds', () => {
const accepted: Array<[string, string]> = [
['2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'],
['2026-01-01T00:00:00Z', '2026-01-01T00:00:00.000Z'],
['2026-01-01T00:00:00.999999Z', '2026-01-01T00:00:00.999Z'],
['2024-02-29T23:59:59.000Z', '2024-02-29T23:59:59.000Z'],
['2026-12-31T23:59:59.999Z', '2026-12-31T23:59:59.999Z'],
];
for (const [createdAt, expected] of accepted) {
const decoded = decodeCursor(encode(createdAt), scope);
expect(decoded.created_at).toBe(expected);
expect(decoded.scope).toBe(scope);
}
});
it('rejects calendar dates that the platform parser rolls over', () => {
// 2026-02-31 would silently become 2026-03-03 and then fail inside SQL.
for (const createdAt of [
'2026-02-31T00:00:00.000Z',
'2025-02-29T00:00:00.000Z',
'2026-04-31T00:00:00.000Z',
'2026-06-31T12:00:00.000Z',
]) {
expect(() => decodeCursor(encode(createdAt), scope)).toThrow(
BadRequestException,
);
}
});
it('rejects out-of-range and malformed timestamps', () => {
for (const createdAt of [
'2026-01-01T24:00:00.000Z',
'2026-01-01T00:00:60.000Z',
'2026-13-01T00:00:00.000Z',
'2026-00-01T00:00:00.000Z',
'2026-01-01T00:00:00',
'2026-01-01T00:00:00+02:00',
'2026-1-1T00:00:00.000Z',
'2026-01-01',
'not-a-timestamp',
]) {
expect(() => decodeCursor(encode(createdAt), scope)).toThrow(
BadRequestException,
);
}
});
it('rejects a cursor from another scope, a malformed id, and non-cursor input', () => {
expect(() =>
decodeCursor(
encode('2026-01-01T00:00:00.000Z', 'messages:other'),
scope,
),
).toThrow(BadRequestException);
expect(() =>
decodeCursor(
encodeCursor({
scope,
created_at: '2026-01-01T00:00:00.000Z',
id: 'not-a-uuid',
}),
scope,
),
).toThrow(BadRequestException);
expect(() => decodeCursor('not-a-cursor', scope)).toThrow(
BadRequestException,
);
});
});
+14 -17
View File
@@ -1,4 +1,5 @@
import { BadRequestException } from '@nestjs/common';
import { isValid, parseISO } from 'date-fns';
export type Cursor = {
scope: string;
@@ -6,6 +7,14 @@ export type Cursor = {
id: string;
};
// Format check for the canonical API shape: `Date.prototype.toISOString()` with
// optional fractional seconds. Explicit ranges reject values such as 24:00:00.
// Calendar validity (2026-02-31, 2025-02-29, 2026-04-31) is checked by
// date-fns `parseISO`, which refuses impossible dates that the platform parser
// would silently roll over into another day.
const CURSOR_TIMESTAMP =
/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?Z$/u;
export function encodeCursor(cursor: Cursor): string {
return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');
}
@@ -28,30 +37,18 @@ export function decodeCursor(value: string, expectedScope: string): Cursor {
!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(
parsed.id,
) ||
!/^(?:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)$/u.test(
parsed.created_at,
)
!CURSOR_TIMESTAMP.test(parsed.created_at)
)
throw new Error('invalid cursor');
const timestamp = Date.parse(parsed.created_at);
if (!Number.isFinite(timestamp)) throw new Error('invalid cursor');
const instant = parseISO(parsed.created_at);
if (!isValid(instant)) throw new Error('invalid cursor');
return {
scope: parsed.scope,
created_at: parsed.created_at,
created_at: instant.toISOString(),
id: parsed.id,
};
} catch {
throw new BadRequestException('Invalid cursor');
}
}
export function isAfter(
createdAt: string,
id: string,
cursor: Cursor,
): boolean {
return (
createdAt > cursor.created_at ||
(createdAt === cursor.created_at && id > cursor.id)
);
}
+4
View File
@@ -0,0 +1,4 @@
export type Page<T> = {
items: T[];
next_cursor: string | null;
};
@@ -0,0 +1,43 @@
import { validate } from 'class-validator';
import { describe, expect, it } from 'vitest';
import { CodePointLength } from './code-point-length.js';
class Sample {
@CodePointLength(3, 5)
value!: string;
}
async function fails(value: unknown): Promise<boolean> {
const sample = new Sample();
(sample as { value: unknown }).value = value;
const errors = await validate(sample);
return errors.length > 0;
}
describe('CodePointLength', () => {
it('counts Unicode code points instead of UTF-16 units', async () => {
// '🔐' is one code point but two UTF-16 units.
expect(await fails('🔐🔐')).toBe(true);
expect(await fails('🔐🔐🔐')).toBe(false);
expect(await fails('🔐🔐🔐🔐🔐')).toBe(false);
expect(await fails('🔐🔐🔐🔐🔐🔐')).toBe(true);
// Combining marks are separate code points, not grapheme clusters:
// three 'é' sequences are six code points and exceed the maximum.
expect(await fails('e\u0301e\u0301')).toBe(false);
expect(await fails('e\u0301e\u0301e\u0301')).toBe(true);
});
it('applies to BMP text boundaries', async () => {
expect(await fails('ab')).toBe(true);
expect(await fails('abc')).toBe(false);
expect(await fails('abcde')).toBe(false);
expect(await fails('abcdef')).toBe(true);
});
it('rejects empty and non-string values', async () => {
expect(await fails('')).toBe(true);
expect(await fails(undefined)).toBe(true);
expect(await fails(12345)).toBe(true);
expect(await fails(['a', 'b', 'c'])).toBe(true);
});
});
@@ -0,0 +1,38 @@
import {
registerDecorator,
ValidatorConstraint,
type ValidationArguments,
type ValidatorConstraintInterface,
} from 'class-validator';
// JSON Schema (and the course contract) measure string lengths in Unicode code
// points, while String.prototype.length counts UTF-16 units: one emoji outside
// the BMP is two units. `@Length` therefore accepted an 11-emoji password
// (22 units) and rejected 4000 emoji (8000 units), so these fields use an
// explicit code-point validator instead.
@ValidatorConstraint({ name: 'codePointLength', async: false })
class CodePointLengthConstraint implements ValidatorConstraintInterface {
validate(value: unknown, args: ValidationArguments): boolean {
const [min, max] = args.constraints as [number, number];
if (typeof value !== 'string') return false;
const length = [...value].length;
return length >= min && length <= max;
}
defaultMessage(args: ValidationArguments): string {
const [min, max] = args.constraints as [number, number];
return `${args.property} must be between ${min} and ${max} code points`;
}
}
export function CodePointLength(min: number, max: number): PropertyDecorator {
return (target, propertyKey) => {
registerDecorator({
name: 'codePointLength',
target: target.constructor,
propertyName: String(propertyKey),
constraints: [min, max],
validator: CodePointLengthConstraint,
});
};
}
+2 -4
View File
@@ -3,15 +3,13 @@ import { ConfigService } from '@nestjs/config';
import { setTimeout as delay } from 'node:timers/promises';
import type { AppConfig } from '../../config/app-config.schema.js';
import { RedisClient } from '../../redis/redis.client.js';
import type { Page } from '../../common/http/page.js';
import { MetricsService } from '../../metrics/metrics.service.js';
const LOCK_RETRY_COUNT = 4;
const LOCK_RETRY_DELAY_MS = 25;
export type CachePage = {
items: unknown[];
next_cursor: string | null;
};
export type CachePage = Page<unknown>;
@Injectable()
export class MessagesCacheService {
+3 -2
View File
@@ -1,7 +1,8 @@
import { IsString, Length } from 'class-validator';
import { IsString } from 'class-validator';
import { CodePointLength } from '../../common/validation/code-point-length.js';
export class CreateMessageDto {
@IsString()
@Length(1, 4000)
@CodePointLength(1, 4000)
text!: string;
}
-2
View File
@@ -1,12 +1,10 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { DatabaseClient } from '../database/database.client.js';
import type { Cursor } from '../common/http/cursor.js';
import type { User } from '../users/user.js';
import type { Message } from './message.js';
type MessageRow = {
+3 -2
View File
@@ -1,5 +1,6 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { decodeCursor, encodeCursor } from '../common/http/cursor.js';
import type { Page } from '../common/http/page.js';
import type { User } from '../users/user.js';
import { ChatsService } from '../chats/chats.service.js';
import type { CreateMessageDto } from './dto/create-message.dto.js';
@@ -35,7 +36,7 @@ export class MessagesService {
currentUser: User,
limit: number,
cursorValue?: string,
): Promise<{ items: Message[]; next_cursor: string | null }> {
): Promise<Page<Message>> {
await this.chatsService.getForUser(chatId, currentUser);
const scope = `messages:${chatId}`;
const cursor = cursorValue
@@ -70,6 +71,6 @@ export class MessagesService {
};
},
);
return page as { items: Message[]; next_cursor: string | null };
return page as Page<Message>;
}
}
+7 -3
View File
@@ -1,4 +1,5 @@
import { IsString, Length, Matches } from 'class-validator';
import { IsString, Matches } from 'class-validator';
import { CodePointLength } from '../../common/validation/code-point-length.js';
export class CreateUserDTO {
@IsString()
@@ -6,13 +7,16 @@ export class CreateUserDTO {
username!: string;
@IsString()
@Length(1, 100)
@CodePointLength(1, 100)
@Matches(/\S/u, {
message: 'display_name must contain a non-whitespace character',
})
display_name!: string;
@IsString()
@Length(12, 128)
@CodePointLength(12, 128)
@Matches(/\S/u, {
message: 'password must contain a non-whitespace character',
})
password!: string;
}
+1 -8
View File
@@ -1,4 +1,4 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import argon2 from 'argon2';
import { randomUUID } from 'node:crypto';
import { CreateUserDTO } from './dto/create-user.dto.js';
@@ -10,13 +10,6 @@ export class UsersService {
constructor(private readonly usersRepository: UsersRepository) {}
async create(input: CreateUserDTO): Promise<User> {
if (
[...input.display_name].length < 1 ||
[...input.display_name].length > 100 ||
input.display_name.trim().length === 0
) {
throw new BadRequestException('Invalid display name');
}
const passwordHash = await argon2.hash(input.password, {
type: argon2.argon2id,
});