2 Commits
Author SHA1 Message Date
ksv741 ec934a34b5 chore: bump Node to 24.22.1 (WealthLedger/backend#122)
Backend verify / commits (pull_request) Successful in 28s
Backend verify / security (pull_request) Successful in 8s
Backend verify / verify (pull_request) Successful in 4m58s
Fixes the better-sqlite3 GC abort (nodejs/node#63985) in Node
24.19.0-24.21.x. Keeps all repositories on the same Node version.
2026-10-23 08:15:41 +03:00
ksv741 4ae2db225d fix: persist refresh cookie across browser restarts (WealthLedger/backend#123)
The refresh cookie had no Max-Age, so browsers dropped it on close
while the Session stayed valid for 7 days. Set maxAge from
REFRESH_TTL_MS, the same constant behind Session.expiresAt.
2026-10-23 08:15:41 +03:00
9 changed files with 1330 additions and 1180 deletions
-14
View File
@@ -1,19 +1,5 @@
# Changelog # Changelog
## [2.3.0](https://git.personal.ksv741.ru/WealthLedger/backend/compare/v2.2.0...v2.3.0) (2026-10-24)
### Features
* log unhandled errors and pretty dev output (WealthLedger/backend[#120](https://git.personal.ksv741.ru/WealthLedger/backend/issues/120)) ([#126](https://git.personal.ksv741.ru/WealthLedger/backend/issues/126)) ([966a1f7](https://git.personal.ksv741.ru/WealthLedger/backend/commit/966a1f793aa2087cce3e47750e0017f78315bd64))
### Bug Fixes
* persist refresh cookie across browser restarts (WealthLedger/backend[#123](https://git.personal.ksv741.ru/WealthLedger/backend/issues/123)) ([d1f6969](https://git.personal.ksv741.ru/WealthLedger/backend/commit/d1f6969dc7c22ae3cf7396bccdbf0cea2f61db2e))
### Maintenance
* **deps:** update non-major dependencies [#11](https://git.personal.ksv741.ru/WealthLedger/backend/issues/11) ([449cfcd](https://git.personal.ksv741.ru/WealthLedger/backend/commit/449cfcd6c5a91307012bb3a640c8255ba243cbf5))
## [2.2.0](https://git.personal.ksv741.ru/WealthLedger/backend/compare/v2.1.0...v2.2.0) (2026-10-18) ## [2.2.0](https://git.personal.ksv741.ru/WealthLedger/backend/compare/v2.1.0...v2.2.0) (2026-10-18)
### Features ### Features
+1270 -1010
View File
File diff suppressed because it is too large Load Diff
+38 -48
View File
@@ -1,6 +1,6 @@
{ {
"name": "wealth-ledger-backend", "name": "wealth-ledger-backend",
"version": "2.3.0", "version": "2.2.0",
"description": "", "description": "",
"author": "", "author": "",
"private": true, "private": true,
@@ -39,17 +39,17 @@
"test:lint": "node --test test/eslint-config.cjs" "test:lint": "node --test test/eslint-config.cjs"
}, },
"dependencies": { "dependencies": {
"@grpc/grpc-js": "1.14.6", "@grpc/grpc-js": "1.14.5",
"@grpc/proto-loader": "0.8.1", "@grpc/proto-loader": "0.8.1",
"@nestjs/common": "12.2.0", "@nestjs/common": "12.0.1",
"@nestjs/config": "12.0.1", "@nestjs/config": "12.0.0",
"@nestjs/core": "12.2.0", "@nestjs/core": "12.0.1",
"@nestjs/jwt": "12.0.3", "@nestjs/jwt": "12.0.1",
"@nestjs/passport": "12.0.0", "@nestjs/passport": "12.0.0",
"@nestjs/platform-express": "12.2.0", "@nestjs/platform-express": "12.0.1",
"@nestjs/swagger": "12.0.4", "@nestjs/swagger": "12.0.1",
"@prisma/adapter-better-sqlite3": "7.10.1", "@prisma/adapter-better-sqlite3": "7.10.0",
"@prisma/client": "7.10.1", "@prisma/client": "7.10.0",
"bcrypt": "6.0.0", "bcrypt": "6.0.0",
"better-sqlite3": "12.11.1", "better-sqlite3": "12.11.1",
"cheerio": "1.2.0", "cheerio": "1.2.0",
@@ -57,77 +57,67 @@
"class-validator": "0.15.1", "class-validator": "0.15.1",
"cookie-parser": "1.4.7", "cookie-parser": "1.4.7",
"dotenv": "17.4.2", "dotenv": "17.4.2",
"lru-cache": "11.5.3", "lru-cache": "11.5.2",
"nestjs-pino": "5.3.1", "nestjs-pino": "5.1.0",
"passport": "0.7.0", "passport": "0.7.0",
"passport-jwt": "4.0.1", "passport-jwt": "4.0.1",
"pino-http": "11.0.0", "pino-http": "11.0.0",
"prisma": "7.10.1", "prisma": "7.10.0",
"reflect-metadata": "0.2.2", "reflect-metadata": "0.2.2",
"rxjs": "7.8.2" "rxjs": "7.8.2"
}, },
"devDependencies": { "devDependencies": {
"@commitlint/cli": "21.2.4", "@commitlint/cli": "21.2.2",
"@commitlint/config-conventional": "21.2.4", "@commitlint/config-conventional": "21.2.2",
"@darraghor/eslint-plugin-nestjs-typed": "7.5.8", "@darraghor/eslint-plugin-nestjs-typed": "7.5.6",
"@eslint/js": "10.0.1", "@eslint/js": "10.0.1",
"@nestjs/cli": "12.0.10", "@nestjs/cli": "12.0.0",
"@nestjs/schematics": "12.0.10", "@nestjs/schematics": "12.0.1",
"@nestjs/testing": "12.2.0", "@nestjs/testing": "12.0.1",
"@release-it/conventional-changelog": "12.0.2", "@release-it/conventional-changelog": "12.0.0",
"@stylistic/eslint-plugin": "5.10.0", "@stylistic/eslint-plugin": "5.10.0",
"@types/bcrypt": "6.0.0", "@types/bcrypt": "6.0.0",
"@types/cookie-parser": "1.4.10", "@types/cookie-parser": "1.4.10",
"@types/express": "5.0.6", "@types/express": "5.0.6",
"@types/jest": "30.0.0", "@types/jest": "30.0.0",
"@types/node": "24.19.2", "@types/node": "24.13.4",
"@types/passport-jwt": "4.0.1", "@types/passport-jwt": "4.0.1",
"@types/supertest": "7.2.1", "@types/supertest": "7.2.1",
"conventional-changelog-conventionalcommits": "10.4.1", "conventional-changelog-conventionalcommits": "10.4.0",
"eslint": "10.13.0", "eslint": "10.11.0",
"eslint-import-resolver-typescript": "4.4.5", "eslint-import-resolver-typescript": "4.4.5",
"eslint-plugin-import-x": "4.17.1", "eslint-plugin-import-x": "4.17.1",
"eslint-plugin-jest": "29.17.0", "eslint-plugin-jest": "29.16.6",
"eslint-plugin-n": "18.5.0", "eslint-plugin-n": "18.4.0",
"eslint-plugin-perfectionist": "5.13.0", "eslint-plugin-perfectionist": "5.12.1",
"eslint-plugin-regexp": "3.3.1", "eslint-plugin-regexp": "3.3.1",
"eslint-plugin-security": "4.2.0", "eslint-plugin-security": "4.1.0",
"eslint-plugin-sonarjs": "4.2.2", "eslint-plugin-sonarjs": "4.2.1",
"globals": "17.13.0", "globals": "17.12.0",
"jest": "30.5.2", "jest": "30.5.1",
"pino-pretty": "13.2.0", "release-it": "21.0.2",
"release-it": "21.1.1", "supertest": "7.2.2",
"supertest": "7.3.1", "ts-jest": "29.4.12",
"ts-jest": "29.4.15",
"ts-loader": "9.6.2", "ts-loader": "9.6.2",
"ts-node": "10.9.2", "ts-node": "10.9.2",
"tsconfig-paths": "4.2.0", "tsconfig-paths": "4.2.0",
"typescript": "6.0.3", "typescript": "6.0.3",
"typescript-eslint": "8.72.0" "typescript-eslint": "8.70.1"
}, },
"overrides": { "overrides": {
"proxy-addr": "2.0.8", "proxy-addr": "2.0.8",
"express": {
"body-parser": "2.4.0"
},
"@nestjs/platform-express": { "@nestjs/platform-express": {
"multer": "2.5.0" "multer": "2.4.0"
},
"ajv": {
"fast-uri": "3.1.9"
}, },
"@prisma/config@7.10.0": { "@prisma/config@7.10.0": {
"deepmerge-ts": "8.0.2" "deepmerge-ts": "8.0.2"
}, },
"release-it": { "release-it": {
"basic-ftp": "6.2.3", "basic-ftp": "6.2.1",
"undici": "7.30.1" "undici": "7.29.1"
},
"socks": {
"ip-address": "10.7.4"
}, },
"prisma": { "prisma": {
"mysql2": "3.24.6" "mysql2": "3.24.4"
} }
}, },
"jest": { "jest": {
@@ -1,29 +1,24 @@
import { ArgumentsHost, BadRequestException } from '@nestjs/common'; import { ArgumentsHost } from '@nestjs/common';
import { StructuredLogger } from '../logging/structured-logger.service';
import { HttpExceptionFilter } from './http-exception.filter'; import { HttpExceptionFilter } from './http-exception.filter';
describe('HttpExceptionFilter', () => { describe('HttpExceptionFilter', () => {
const setup = () => { it('does not expose internal error details', () => {
const status = jest.fn().mockReturnThis(); const status = jest.fn().mockReturnThis();
const type = jest.fn().mockReturnThis(); const type = jest.fn().mockReturnThis();
const json = jest.fn(); const json = jest.fn();
const locals: Record<string, unknown> = {}; const locals: Record<string, unknown> = {};
const logger = { event: jest.fn() }; const filter = new HttpExceptionFilter();
const filter = new HttpExceptionFilter(logger as unknown as StructuredLogger);
const host = { const host = {
switchToHttp: () => ({ switchToHttp: () => ({
getResponse: () => ({ status, type, json, locals }), getResponse: () => ({ status, type, json, locals }),
}), }),
} as unknown as ArgumentsHost; } as unknown as ArgumentsHost;
return { filter, host, status, type, json, locals, logger };
};
it('logs unhandled errors with name and stack frames but never the message', () => { filter.catch(
const { filter, host, status, type, json, locals, logger } = setup(); new Error('operation failed\npassword: SYNTHETIC_AUDIT_SECRET'),
const error = new Error('operation failed\npassword: SYNTHETIC_AUDIT_SECRET'); host,
);
filter.catch(error, host);
expect(status).toHaveBeenCalledWith(500); expect(status).toHaveBeenCalledWith(500);
expect(type).toHaveBeenCalledWith('application/problem+json'); expect(type).toHaveBeenCalledWith('application/problem+json');
@@ -32,29 +27,6 @@ describe('HttpExceptionFilter', () => {
code: 'INTERNAL_SERVER_ERROR', code: 'INTERNAL_SERVER_ERROR',
}); });
expect(locals.publicErrorCode).toBe('INTERNAL_SERVER_ERROR'); expect(locals.publicErrorCode).toBe('INTERNAL_SERVER_ERROR');
expect(logger.event).toHaveBeenCalledTimes(1); expect(locals.errorStack).toBeUndefined();
const [level, event, fields] = logger.event.mock.calls[0] as [string, string, Record<string, unknown>];
expect(level).toBe('error');
expect(event).toBe('http.request.unhandled');
expect(fields).toMatchObject({ code: 'INTERNAL_SERVER_ERROR', errorName: 'Error' });
expect(JSON.stringify(fields)).not.toContain('SYNTHETIC_AUDIT_SECRET');
expect(String(fields['errorStack']).split('\n').every((line) => line.startsWith(' at '))).toBe(true);
});
it('logs field pointers without values for validation errors', () => {
const { filter, host, status, logger, locals } = setup();
const exception = new BadRequestException({
message: [
{ property: 'amount', constraints: { isPositive: 'amount must be positive' }, value: -42 },
{ property: 'amount', constraints: { min: 'amount too small' }, value: -42 },
],
});
filter.catch(exception, host);
expect(status).toHaveBeenCalledWith(400);
expect(locals.invalidFields).toBe('#/amount');
expect(logger.event).not.toHaveBeenCalled();
expect(JSON.stringify(locals)).not.toContain('-42');
}); });
}); });
@@ -10,12 +10,9 @@ import {
} from '@nestjs/common'; } from '@nestjs/common';
import { HttpErrorCode } from '../error-code'; import { HttpErrorCode } from '../error-code';
import { StructuredLogger } from '../logging/structured-logger.service';
@Catch() @Catch()
export class HttpExceptionFilter implements ExceptionFilter { export class HttpExceptionFilter implements ExceptionFilter {
constructor(private readonly logger: StructuredLogger) {}
catch(exception: unknown, host: ArgumentsHost): void { catch(exception: unknown, host: ArgumentsHost): void {
const context = host.switchToHttp(); const context = host.switchToHttp();
const response = context.getResponse<Response>(); const response = context.getResponse<Response>();
@@ -34,18 +31,6 @@ export class HttpExceptionFilter implements ExceptionFilter {
: this.codeFor(status, payload); : this.codeFor(status, payload);
response.locals ??= {}; response.locals ??= {};
response.locals.publicErrorCode = code; response.locals.publicErrorCode = code;
if (isValidation) {
response.locals.invalidFields = [
...new Set(
this.validationErrors(
(payload as { message: ValidationError[] }).message,
).map((error) => error.pointer),
),
].join(',');
}
if (!(exception instanceof HttpException)) {
this.logUnhandled(exception, code);
}
response response
.status(status) .status(status)
.type('application/problem+json') .type('application/problem+json')
@@ -62,20 +47,6 @@ export class HttpExceptionFilter implements ExceptionFilter {
}); });
} }
// ponytail: stack содержит текст message в первой строке; оставляем только кадры, message не пишем.
private logUnhandled(exception: unknown, code: string): void {
const error = exception instanceof Error ? exception : undefined;
const frames = (error?.stack ?? '')
.split('\n')
.filter((line) => line.startsWith(' at '))
.join('\n');
this.logger.event('error', 'http.request.unhandled', {
code,
errorName: error?.name ?? typeof exception,
errorStack: frames,
});
}
private codeFor(status: number, payload: unknown): string { private codeFor(status: number, payload: unknown): string {
if (typeof payload === 'object' && payload !== null && 'code' in payload) { if (typeof payload === 'object' && payload !== null && 'code' in payload) {
const code = (payload as { code?: unknown }).code; const code = (payload as { code?: unknown }).code;
-5
View File
@@ -24,7 +24,6 @@ function completion(request: Request, response: Response, value: { responseTime:
status: response.statusCode, status: response.statusCode,
durationMs: Math.round(value.responseTime), durationMs: Math.round(value.responseTime),
...(typeof response.locals.publicErrorCode === 'string' ? { code: response.locals.publicErrorCode } : {}), ...(typeof response.locals.publicErrorCode === 'string' ? { code: response.locals.publicErrorCode } : {}),
...(typeof response.locals.invalidFields === 'string' ? { invalidFields: response.locals.invalidFields } : {}),
}; };
} }
@@ -32,10 +31,6 @@ export function loggingOptions(config: ConfigService<Environment, true>): Option
return { return {
level: config.getOrThrow('LOG_LEVEL'), level: config.getOrThrow('LOG_LEVEL'),
messageKey: 'message', messageKey: 'message',
// ponytail: development-only pretty output; production never loads pino-pretty.
...(process.env['NODE_ENV'] === 'development'
? { transport: { target: 'pino-pretty', options: { colorize: true, singleLine: true, messageKey: 'message' } } }
: {}),
genReqId: (_request, response) => { genReqId: (_request, response) => {
const id = randomUUID(); const id = randomUUID();
response.setHeader('X-Request-ID', id); response.setHeader('X-Request-ID', id);
@@ -14,12 +14,9 @@ const allowedFields = new Set([
'count', 'count',
'durationMs', 'durationMs',
'environment', 'environment',
'errorName',
'errorStack',
'found', 'found',
'grpcCode', 'grpcCode',
'headersReceived', 'headersReceived',
'invalidFields',
'method', 'method',
'networkMs', 'networkMs',
'operation', 'operation',
+1 -1
View File
@@ -37,7 +37,7 @@ export function configureApp(app: INestApplication): void {
exceptionFactory: (message) => new BadRequestException({ message }), exceptionFactory: (message) => new BadRequestException({ message }),
}), }),
); );
app.useGlobalFilters(new HttpExceptionFilter(app.get(StructuredLogger))); app.useGlobalFilters(new HttpExceptionFilter());
app.enableShutdownHooks(); app.enableShutdownHooks();
} }
+13 -34
View File
@@ -32,7 +32,6 @@ describe('Authentication (e2e)', () => {
pinoHttp: { pinoHttp: {
...loggingOptions(config), ...loggingOptions(config),
level: 'info', level: 'info',
transport: undefined,
stream: { write: (line: string) => logs.push(JSON.parse(line) as Record<string, unknown>) }, stream: { write: (line: string) => logs.push(JSON.parse(line) as Record<string, unknown>) },
}, },
assignResponse: true, assignResponse: true,
@@ -540,14 +539,7 @@ describe('Authentication (e2e)', () => {
'X-Request-ID', 'X-Request-ID',
); );
expect(logs.filter((entry) => entry.requestId === response.headers['x-request-id'])).toEqual([ expect(logs.filter((entry) => entry.requestId === response.headers['x-request-id'])).toEqual([
expect.objectContaining({ expect.objectContaining({ level: 40, message: 'http.request.completed', status: 401, code: 'UNAUTHORIZED' }),
level: 40,
message: 'http.request.completed',
method: 'GET',
route: '/api/v1/auth/me',
status: 401,
code: 'UNAUTHORIZED',
}),
]); ]);
}); });
@@ -559,7 +551,7 @@ describe('Authentication (e2e)', () => {
new Error('operation failed\npassword: SYNTHETIC_AUDIT_SECRET'), new Error('operation failed\npassword: SYNTHETIC_AUDIT_SECRET'),
); );
await request(app.getHttpServer()) const response = await request(app.getHttpServer())
.post('/api/v1/auth/login') .post('/api/v1/auth/login')
.set('X-Request-ID', clientRequestId) .set('X-Request-ID', clientRequestId)
.send({ email: 'user@example.com', password: 'a secure password' }) .send({ email: 'user@example.com', password: 'a secure password' })
@@ -569,30 +561,17 @@ describe('Authentication (e2e)', () => {
expect(body).toEqual({ status: 500, code: 'INTERNAL_SERVER_ERROR' }), expect(body).toEqual({ status: 500, code: 'INTERNAL_SERVER_ERROR' }),
); );
expect(logs).toEqual( const completed = logs.filter((entry) => entry.requestId === response.headers['x-request-id']);
expect.arrayContaining([ expect(completed).toEqual([
expect.objectContaining({ expect.objectContaining({
method: 'POST', requestId: response.headers['x-request-id'],
route: '/api/v1/auth/login', clientRequestId,
status: 500, status: 500,
code: 'INTERNAL_SERVER_ERROR', code: 'INTERNAL_SERVER_ERROR',
level: 50, level: 50,
message: 'http.request.completed', message: 'http.request.completed',
}), }),
]), ]);
);
expect(logs).toEqual(
expect.arrayContaining([
expect.objectContaining({
clientRequestId,
code: 'INTERNAL_SERVER_ERROR',
level: 50,
message: 'http.request.unhandled',
errorName: 'Error',
errorStack: expect.stringContaining(' at ') as unknown,
}),
]),
);
expect(JSON.stringify(logs)).not.toContain( expect(JSON.stringify(logs)).not.toContain(
'SYNTHETIC_AUDIT_SECRET', 'SYNTHETIC_AUDIT_SECRET',
); );