feat(logging): emit sanitized structured app logs

This commit is contained in:
Do Siki
2026-09-28 09:51:40 +02:00
parent 2ad3e75c87
commit b5a8936f42
26 changed files with 429 additions and 574 deletions
+1 -11
View File
@@ -74,9 +74,6 @@ jest.mock('winston', () => ({
}
}))
// Mock winston-loki
jest.mock('winston-loki', () => jest.fn().mockImplementation(() => ({ name: 'loki' })))
// Let individual test files handle their own logger mocks
// This allows for more specific testing of the logger module itself
@@ -133,12 +130,6 @@ if (!global.process.env) {
// Logger will be mocked by the winston mock above
// Mock Loki transport
jest.mock('winston-loki', () => jest.fn(() => ({
log: jest.fn(),
close: jest.fn()
})))
// Mock Next.js router
jest.mock('next/router', () => ({
useRouter: () => ({
@@ -261,7 +252,6 @@ global.NextResponse = {
// Set up environment variables for tests
process.env.MONGODB_URI = 'mongodb://localhost:27017/test'
process.env.MONGODB_DB = 'test'
process.env.LOKI_HOST = 'http://loki:3100'
process.env.NODE_ENV = 'test'
process.env.NEXT_PUBLIC_CONTACT_EMAIL = 'info@mozdit.hu'
process.env.NEXT_PUBLIC_SITE_URL = 'https://localhost:3000'
@@ -274,4 +264,4 @@ afterEach(() => {
})
// Import React Testing Library DOM (using require for Jest setup files)
require('@testing-library/jest-dom')
require('@testing-library/jest-dom')
+1 -480
View File
@@ -40,8 +40,7 @@
"tsx": "^4.23.13",
"typescript": "^5",
"undici": "^7.15.0",
"winston": "^3.11",
"winston-loki": "^6.0"
"winston": "^3.11"
}
},
"node_modules/@adobe/css-tools": {
@@ -2974,306 +2973,6 @@
"sparse-bitfield": "^3.0.3"
}
},
"node_modules/@napi-rs/snappy-android-arm-eabi": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-android-arm-eabi/-/snappy-android-arm-eabi-7.3.2.tgz",
"integrity": "sha512-fX0+uNXt+tIqxjUUKh3uekIz5jW7rKsFVCZb/OR1+u5u8XCR28RcMTucMTjhcmMibg0PvYRZLxbICuP1Wx1UWQ==",
"cpu": [
"arm"
],
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-android-arm64": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-android-arm64/-/snappy-android-arm64-7.3.2.tgz",
"integrity": "sha512-FlN/GGHkQa2SB8y+LXhJky8U133MJb6jqikYgmjQjHRwElB+/5pTtMqLQg2pwJ/70ISAxN5Ct9JlaHadp6Rs+A==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-darwin-arm64": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-darwin-arm64/-/snappy-darwin-arm64-7.3.2.tgz",
"integrity": "sha512-2j5cHSb34BdnQxBITdXa4NkbPrVc00yI/8BT0laD29Qm7nTXKoUNKYEpD8KYV3IvP2UxFDK7n0nMRqhuo2+fug==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-darwin-x64": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-darwin-x64/-/snappy-darwin-x64-7.3.2.tgz",
"integrity": "sha512-1Har7sh2PMZE8L5hWhuVQMQKmFZwJiSUoCzhCvhKIB983Ei+obqXWewrhxoaShc3fYrc4YS9hXnnLoFCDLzH1g==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-freebsd-x64": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-freebsd-x64/-/snappy-freebsd-x64-7.3.2.tgz",
"integrity": "sha512-oNc4JG+yCAEVRy8e6vKAYJsJpyrXQGl7q4JqX981FRTBGYUISwR4pNgYsBypOj8SUFRYoS/FdG61/ptyh00Hbw==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-arm-gnueabihf": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-arm-gnueabihf/-/snappy-linux-arm-gnueabihf-7.3.2.tgz",
"integrity": "sha512-CUOPVs/bCRKghcpsuxw6/t0BnVV25ZRDXC9qQSuR+KSEbXrQPahDuWyJIvI7KM70P1s2lvmdK4WXWag/tl5Y4A==",
"cpu": [
"arm"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-arm64-gnu": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-arm64-gnu/-/snappy-linux-arm64-gnu-7.3.2.tgz",
"integrity": "sha512-AKqTWTHzw4DIrzA/qQkUozFfQTMQlYbm2WjFfrzebcRB8+o8BpffyUbvqDS/HsOHw9L53x+jqMFOAAjU5rECvg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-arm64-musl": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-arm64-musl/-/snappy-linux-arm64-musl-7.3.2.tgz",
"integrity": "sha512-rUhajSc4PgFZ2DkG3CTOke7LfoQylkKF4uV90DgedbKUjXI61henWSe8I8XhzJEcrpmBFz3udmihJaj172+2iw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-ppc64-gnu": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-ppc64-gnu/-/snappy-linux-ppc64-gnu-7.3.2.tgz",
"integrity": "sha512-3BqNK9nhBIoUeUeOgY3W/99ArChbKzzHjj4vD0kbkk7eADBatcGTxUzrSIhULlH9vifF28thQQeCu0q/EfpU3A==",
"cpu": [
"ppc64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-riscv64-gnu": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-riscv64-gnu/-/snappy-linux-riscv64-gnu-7.3.2.tgz",
"integrity": "sha512-dvlKU473USFBpIZoJ1eUFGj90LNzv6SvkY3bJZ1c0BKRTvEJ9DRNIjmdN+bHCZznwxn2UrR1Tv2MWqMM0Ww/cQ==",
"cpu": [
"riscv64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-s390x-gnu": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-s390x-gnu/-/snappy-linux-s390x-gnu-7.3.2.tgz",
"integrity": "sha512-+cNweOf2Z7FC7AyFdrX2L8sCoNx34fc2QGsEBtTQ7H2nj6K2byxcIs1pWT7tPrrBFk24SMw2DtgDf+fUtat1/g==",
"cpu": [
"s390x"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-x64-gnu": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-x64-gnu/-/snappy-linux-x64-gnu-7.3.2.tgz",
"integrity": "sha512-eW1uzodlmb0RitoP1I4xVGRqE50WUOB5T2G6GPceqlwXLs1UzgSpgwZuNbQ7LbRyXI7jK897ukeBBkVOIvhkoQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-x64-musl": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-x64-musl/-/snappy-linux-x64-musl-7.3.2.tgz",
"integrity": "sha512-WBmgzN4P6SmKXUxy936Jz2r+sKwHqqosZIxOg8QLJNoIr72eCmoINaolg6AuVCyuPUb9tc2GdPwag4p27gTIOQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-openharmony-arm64": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-openharmony-arm64/-/snappy-openharmony-arm64-7.3.2.tgz",
"integrity": "sha512-iZwgBJ8cz79UgBO5eoojObIYV2mKpjF2aGSlixB3R9QJfRaNPeACTShYcd8Bc5QheSPcJjqTswiI/7xIFdcDDw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-wasm32-wasi": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-wasm32-wasi/-/snappy-wasm32-wasi-7.3.2.tgz",
"integrity": "sha512-ChdMipqIoFg5ysLciGJ5wLoSsXQMo7Zh8+35du4aEO/vrxVyZ12UMyv6+zEn8sBCrY+3e9A+2YOpryZP2BfKiQ==",
"cpu": [
"wasm32"
],
"license": "MIT",
"optional": true,
"dependencies": {
"@napi-rs/wasm-runtime": "^1.0.3"
},
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/@napi-rs/snappy-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.0.3.tgz",
"integrity": "sha512-rZxtMsLwjdXkMUGC3WwsPwLNVqVqnTJT6MNIB6e+5fhMcSCPP0AOsNWuMQ5mdCq6HNjs/ZeWAEchpqeprqBD2Q==",
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/core": "^1.4.5",
"@emnapi/runtime": "^1.4.5",
"@tybys/wasm-util": "^0.10.0"
}
},
"node_modules/@napi-rs/snappy-win32-arm64-msvc": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-win32-arm64-msvc/-/snappy-win32-arm64-msvc-7.3.2.tgz",
"integrity": "sha512-RAmh06bNKk5wHoOfX6wkFo8FZBKNkSH5J9Q4O648uZpXorf8ZaVQKSpIQaXTZICBVF6+2540FjYGctvhL1b4yw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-win32-ia32-msvc": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-win32-ia32-msvc/-/snappy-win32-ia32-msvc-7.3.2.tgz",
"integrity": "sha512-OP8ySMUm9EEtihDbgqXCcvPFLcD3iAZhy+fZ7sSQhRQHqRxJ4dfAl98Eaec1nIK63pg/FNKJqTHZfCgnmUSL8g==",
"cpu": [
"ia32"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-win32-x64-msvc": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-win32-x64-msvc/-/snappy-win32-x64-msvc-7.3.2.tgz",
"integrity": "sha512-fqPHzNVFy5Wrg/U91dsafIaZ6thTyRcK1xU8KLw384MRkaTI3HA4cs66Om8l33P0gHhnvUZOSlvjJEjEXyAH0Q==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/wasm-runtime": {
"version": "0.2.12",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz",
@@ -3719,72 +3418,6 @@
"url": "https://opencollective.com/preact"
}
},
"node_modules/@protobufjs/aspromise": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",
"integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/base64": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",
"integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/codegen": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz",
"integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/eventemitter": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz",
"integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/fetch": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz",
"integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@protobufjs/aspromise": "^1.1.1"
}
},
"node_modules/@protobufjs/float": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",
"integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/path": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",
"integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/pool": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",
"integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/utf8": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz",
"integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@rtsao/scc": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz",
@@ -5497,16 +5130,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/async-exit-hook": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/async-exit-hook/-/async-exit-hook-2.0.1.tgz",
"integrity": "sha512-NW2cX8m1Q7KPA7a5M2ULQeZ2wR5qI5PAbw5L0UOMxdioVk9PMZ0h1TmyZEkPYrCvYjDlFICusOu1dlEKAAeXBw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.12.0"
}
},
"node_modules/async-function": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz",
@@ -5829,19 +5452,6 @@
"integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==",
"license": "Apache-2.0"
},
"node_modules/btoa": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/btoa/-/btoa-1.2.1.tgz",
"integrity": "sha512-SB4/MIGlsiVkMcHmT+pSmIPoNDoHg+7cMzmt3Uxt628MTz2487DKSqK/fuhFBrkuqrYv5UCEnACpF4dTFNKc/g==",
"dev": true,
"license": "(MIT OR Apache-2.0)",
"bin": {
"btoa": "bin/btoa.js"
},
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
@@ -10803,13 +10413,6 @@
"node": ">= 12.0.0"
}
},
"node_modules/long": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
"integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/longest-streak": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",
@@ -12885,30 +12488,6 @@
"react-is": "^16.13.1"
}
},
"node_modules/protobufjs": {
"version": "7.6.5",
"resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.5.tgz",
"integrity": "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==",
"dev": true,
"hasInstallScript": true,
"license": "BSD-3-Clause",
"dependencies": {
"@protobufjs/aspromise": "^1.1.2",
"@protobufjs/base64": "^1.1.2",
"@protobufjs/codegen": "^2.0.5",
"@protobufjs/eventemitter": "^1.1.1",
"@protobufjs/fetch": "^1.1.1",
"@protobufjs/float": "^1.0.2",
"@protobufjs/path": "^1.1.2",
"@protobufjs/pool": "^1.1.0",
"@protobufjs/utf8": "^1.1.1",
"@types/node": ">=13.7.0",
"long": "^5.3.2"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/psl": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz",
@@ -13756,40 +13335,6 @@
"node": ">=8"
}
},
"node_modules/snappy": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/snappy/-/snappy-7.3.2.tgz",
"integrity": "sha512-cEA4Wi0huhCIlGDG+/27q0hELqIe9TBcrOToO4HsAE1n/3ibO9SsbtbRB5pAHHTGw8ihrhG700XOOqyxvwSxng==",
"license": "MIT",
"optional": true,
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"optionalDependencies": {
"@napi-rs/snappy-android-arm-eabi": "7.3.2",
"@napi-rs/snappy-android-arm64": "7.3.2",
"@napi-rs/snappy-darwin-arm64": "7.3.2",
"@napi-rs/snappy-darwin-x64": "7.3.2",
"@napi-rs/snappy-freebsd-x64": "7.3.2",
"@napi-rs/snappy-linux-arm-gnueabihf": "7.3.2",
"@napi-rs/snappy-linux-arm64-gnu": "7.3.2",
"@napi-rs/snappy-linux-arm64-musl": "7.3.2",
"@napi-rs/snappy-linux-ppc64-gnu": "7.3.2",
"@napi-rs/snappy-linux-riscv64-gnu": "7.3.2",
"@napi-rs/snappy-linux-s390x-gnu": "7.3.2",
"@napi-rs/snappy-linux-x64-gnu": "7.3.2",
"@napi-rs/snappy-linux-x64-musl": "7.3.2",
"@napi-rs/snappy-openharmony-arm64": "7.3.2",
"@napi-rs/snappy-wasm32-wasi": "7.3.2",
"@napi-rs/snappy-win32-arm64-msvc": "7.3.2",
"@napi-rs/snappy-win32-ia32-msvc": "7.3.2",
"@napi-rs/snappy-win32-x64-msvc": "7.3.2"
}
},
"node_modules/sonic-boom": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz",
@@ -14874,13 +14419,6 @@
"requires-port": "^1.0.0"
}
},
"node_modules/url-polyfill": {
"version": "1.1.13",
"resolved": "https://registry.npmjs.org/url-polyfill/-/url-polyfill-1.1.13.tgz",
"integrity": "sha512-tXzkojrv2SujumYthZ/WjF7jaSfNhSXlYMpE5AYdL2I3D7DCeo+mch8KtW2rUuKjDg+3VXODXHVgipt8yGY/eQ==",
"dev": true,
"license": "MIT"
},
"node_modules/use-context-selector": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/use-context-selector/-/use-context-selector-2.0.0.tgz",
@@ -15156,23 +14694,6 @@
"node": ">= 12.0.0"
}
},
"node_modules/winston-loki": {
"version": "6.1.3",
"resolved": "https://registry.npmjs.org/winston-loki/-/winston-loki-6.1.3.tgz",
"integrity": "sha512-DjWtJ230xHyYQWr9mZJa93yhwHttn3JEtSYWP8vXZWJOahiQheUhf+88dSIidbGXB3u0oLweV6G1vkL/ouT62Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"async-exit-hook": "2.0.1",
"btoa": "^1.2.1",
"protobufjs": "^7.2.4",
"url-polyfill": "^1.1.12",
"winston-transport": "^4.3.0"
},
"optionalDependencies": {
"snappy": "^7.2.2"
}
},
"node_modules/winston-transport": {
"version": "4.9.0",
"resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.9.0.tgz",
+1 -2
View File
@@ -64,7 +64,6 @@
"tsx": "^4.23.13",
"typescript": "^5",
"undici": "^7.15.0",
"winston": "^3.11",
"winston-loki": "^6.0"
"winston": "^3.11"
}
}
+4 -1
View File
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import { createComponentLogger, getSafeErrorDetails } from '@/lib/logger'
interface ContactFormData {
name: string
@@ -10,6 +11,8 @@ interface ContactFormData {
gdprConsent: boolean
}
const contactLogger = createComponentLogger('contact-api')
// Simple spam protection - rate limiting by IP
const rateLimitMap = new Map<string, { count: number; timestamp: number }>()
const RATE_LIMIT_WINDOW = 60 * 1000 // 1 minute
@@ -138,7 +141,7 @@ export async function POST(request: NextRequest) {
)
} catch (error) {
console.error('Contact form error:', error)
contactLogger.error('Contact form submission failed', getSafeErrorDetails(error))
return NextResponse.json(
{ error: 'Szerver hiba történt. Kérjük, próbálja újra később.' },
{ status: 500 }
+23 -7
View File
@@ -8,13 +8,22 @@ import { getPayload } from 'payload'
const mockCreate = jest.fn()
// Mock the logger to avoid complex setup
jest.mock('@/lib/logger', () => ({
createComponentLogger: () => ({
info: jest.fn(),
error: jest.fn(),
warn: jest.fn(),
})
}))
jest.mock('@/lib/logger', () => {
const mockLoggerError = jest.fn()
return {
mockLoggerError,
createComponentLogger: () => ({
info: jest.fn(),
error: mockLoggerError,
warn: jest.fn(),
}),
getSafeErrorDetails: (error: unknown) => ({
errorName: error instanceof Error ? error.name : 'Error'
})
}
})
const { mockLoggerError } = jest.requireMock('@/lib/logger')
// WHY mock the resolved relative path instead of the '@payload-config' alias:
// next/jest's SWC transform rewrites the tsconfig path alias to a real
@@ -34,6 +43,7 @@ jest.mock('payload', () => ({
describe('/api/contact Unit Tests', () => {
beforeEach(() => {
mockCreate.mockReset()
mockLoggerError.mockReset()
;(getPayload as jest.Mock).mockClear()
})
@@ -78,6 +88,12 @@ describe('/api/contact Unit Tests', () => {
expect(response.status).toBe(500)
expect(mockCreate).toHaveBeenCalledTimes(1)
expect(mockLoggerError).toHaveBeenCalledWith('Contact form submission failed', { errorName: 'Error' })
const serializedLogs = JSON.stringify(mockLoggerError.mock.calls)
expect(serializedLogs).not.toContain(validData.name)
expect(serializedLogs).not.toContain(validData.email)
expect(serializedLogs).not.toContain(validData.subject)
expect(serializedLogs).not.toContain(validData.message)
})
it('rejects an over-long message before persisting', async () => {
+16 -1
View File
@@ -1,6 +1,19 @@
import { GET, HEAD } from './route'
import { NextRequest } from 'next/server'
jest.mock('@/lib/logger', () => {
const mockHealthLoggerError = jest.fn()
return {
mockHealthLoggerError,
createComponentLogger: () => ({ error: mockHealthLoggerError }),
getSafeErrorDetails: (error: unknown) => ({
errorName: error instanceof Error ? error.name : 'Error'
})
}
})
const { mockHealthLoggerError } = jest.requireMock('@/lib/logger')
// Mock the process object for tests
const mockProcess = {
uptime: jest.fn().mockReturnValue(1234),
@@ -13,6 +26,7 @@ const mockProcess = {
const originalProcess = global.process
beforeEach(() => {
global.process = { ...originalProcess, ...mockProcess } as any
mockHealthLoggerError.mockReset()
})
afterEach(() => {
@@ -69,6 +83,7 @@ describe('/api/health', () => {
expect(data.status).toBe('error')
expect(data).toHaveProperty('timestamp')
expect(data).toHaveProperty('message', 'Health check failed')
expect(mockHealthLoggerError).toHaveBeenCalledWith('Health check failed', { errorName: 'Error' })
// Restore process.uptime
global.process.uptime = originalUptime
@@ -83,4 +98,4 @@ describe('/api/health', () => {
expect(response.headers.get('Cache-Control')).toBe('no-cache, no-store, must-revalidate')
})
})
})
})
+5 -2
View File
@@ -1,4 +1,7 @@
import { NextResponse } from 'next/server';
import { createComponentLogger, getSafeErrorDetails } from '@/lib/logger'
const healthLogger = createComponentLogger('health-api')
export async function GET() {
try {
@@ -23,7 +26,7 @@ export async function GET() {
},
});
} catch (error) {
console.error('Health check error:', error);
healthLogger.error('Health check failed', getSafeErrorDetails(error))
return NextResponse.json(
{
status: 'error',
@@ -43,4 +46,4 @@ export async function HEAD() {
'Cache-Control': 'no-cache, no-store, must-revalidate',
},
});
}
}
+89 -14
View File
@@ -2,7 +2,6 @@ import winston from 'winston'
// Get the mocked winston from jest setup
const mockedWinston = winston as jest.Mocked<typeof winston>
const mockedLokiTransport = require('winston-loki') as jest.MockedFunction<any>
describe('Logger', () => {
beforeEach(() => {
@@ -10,10 +9,7 @@ describe('Logger', () => {
// Reset process.env
process.env = {
...process.env,
NODE_ENV: 'test',
LOKI_HOST: undefined,
LOKI_USERNAME: undefined,
LOKI_PASSWORD: undefined
NODE_ENV: 'test'
}
})
@@ -34,6 +30,7 @@ describe('Logger', () => {
level: 'debug',
format: 'combined-format',
defaultMeta: expect.objectContaining({
component: 'application',
service: 'mozdit-web',
environment: 'development'
}),
@@ -44,10 +41,73 @@ describe('Logger', () => {
)
})
it.skip('should include Loki transport when LOKI_HOST is provided', () => {
// This test is complex to implement due to module loading order with mocks
// The Loki transport functionality is tested in integration tests
// Skipping for now as core logger functionality is verified by other tests
it('should use structured console logging in production', () => {
;(process.env as unknown as Record<string, string>).NODE_ENV = 'production'
require('./logger')
const activeWinston = require('winston') as jest.Mocked<typeof winston>
expect(activeWinston.createLogger).toHaveBeenCalledWith(
expect.objectContaining({
level: 'info',
defaultMeta: expect.objectContaining({
service: 'mozdit-web',
environment: 'production'
}),
transports: [expect.objectContaining({ name: 'console' })]
})
)
expect(activeWinston.format.json).toHaveBeenCalled()
})
it('should keep development console output readable', () => {
;(process.env as unknown as Record<string, string>).NODE_ENV = 'development'
require('./logger')
const activeWinston = require('winston') as jest.Mocked<typeof winston>
expect(activeWinston.transports.Console).toHaveBeenCalledWith(
expect.objectContaining({
level: 'debug',
format: 'combined-format',
handleExceptions: true,
handleRejections: true
})
)
})
it('should omit error messages and stacks from safe error details', () => {
const { getSafeErrorDetails } = require('./logger')
const sensitiveError = new Error('failed for alice@example.com with password=private')
sensitiveError.stack = `${sensitiveError.stack}\nrequest body: private contact message`
const details = getSafeErrorDetails(sensitiveError)
expect(details).toEqual({ errorName: 'Error' })
expect(JSON.stringify(details)).not.toContain('alice@example.com')
expect(JSON.stringify(details)).not.toContain('private')
})
it('should omit sensitive fields from timing metadata', async () => {
const { withTiming, logger } = require('./logger')
const operation = jest.fn().mockResolvedValue('success')
await withTiming('contact-persist', operation, {
requestId: 'request-123',
email: 'alice@example.com',
message: 'private contact message'
})
expect(logger.debug).toHaveBeenNthCalledWith(
1,
expect.stringContaining('Started contact-persist'),
{ requestId: 'request-123' }
)
expect(logger.debug).toHaveBeenNthCalledWith(
2,
expect.stringContaining('Completed contact-persist'),
expect.objectContaining({ requestId: 'request-123', duration: expect.any(Number) })
)
})
it('should create component loggers with correct metadata', () => {
@@ -78,19 +138,19 @@ describe('Logger', () => {
const { withTiming, logger } = require('./logger')
const mockOperation = jest.fn().mockResolvedValue('success')
const result = await withTiming('test-operation', mockOperation, { test: 'metadata' })
const result = await withTiming('test-operation', mockOperation, { requestId: '1234567890-abcdef12' })
expect(result).toBe('success')
expect(logger.debug).toHaveBeenCalledTimes(2) // Start and complete
expect(logger.debug).toHaveBeenNthCalledWith(1,
expect.stringContaining('Started test-operation'),
{ test: 'metadata' }
{ requestId: '1234567890-abcdef12' }
)
expect(logger.debug).toHaveBeenNthCalledWith(2,
expect.stringContaining('Completed test-operation'),
expect.objectContaining({
duration: expect.any(Number),
test: 'metadata'
requestId: '1234567890-abcdef12'
})
)
})
@@ -109,8 +169,23 @@ describe('Logger', () => {
expect.stringContaining('Failed test-operation'),
expect.objectContaining({
duration: expect.any(Number),
error: expect.any(Error)
errorName: 'Error'
})
)
})
})
it('should allow only safe diagnostic metadata fields', () => {
const { sanitizeLogMetadata } = require('./logger')
expect(sanitizeLogMetadata({
requestId: '1234567890-abcdef12',
duration: 42,
email: 'alice@example.com',
message: 'private contact message',
custom: 'user supplied'
})).toEqual({
requestId: '1234567890-abcdef12',
duration: 42
})
})
})
+62 -27
View File
@@ -1,5 +1,4 @@
import winston from 'winston'
import LokiTransport from 'winston-loki'
import { randomUUID } from 'crypto'
const isDevelopment = process.env.NODE_ENV === 'development'
@@ -28,29 +27,8 @@ const consoleFormat = winston.format.combine(
})
)
// Transports configuration
// Application logs stay on stdout/stderr; a host-level collector owns forwarding.
const transports: winston.transport[] = [
// Loki transport for centralized logging
...(process.env.LOKI_HOST
? [
new LokiTransport({
host: process.env.LOKI_HOST,
labels: {
app: 'mozdit-web',
environment: process.env.NODE_ENV || 'development',
service: 'frontend'
},
basicAuth: process.env.LOKI_USERNAME && process.env.LOKI_PASSWORD
? `${process.env.LOKI_USERNAME}:${process.env.LOKI_PASSWORD}`
: undefined,
json: true,
format: winston.format.json(),
onConnectionError: (err: Error) => console.error('Loki connection error:', err)
})
]
: []),
// Console for development logging
new winston.transports.Console({
level: isDevelopment ? 'debug' : 'info',
format: isDevelopment ? consoleFormat : structuredFormat,
@@ -64,6 +42,7 @@ export const logger = winston.createLogger({
level: isDevelopment ? 'debug' : 'info',
format: structuredFormat,
defaultMeta: {
component: 'application',
service: 'mozdit-web',
version: process.env.DEPLOY_VERSION || process.env.npm_package_version || '1.0.0',
environment: process.env.NODE_ENV || 'development'
@@ -84,6 +63,56 @@ export const dbLogger = logger.child({ component: 'database' })
export const authLogger = logger.child({ component: 'auth' })
export const errorLogger = logger.child({ component: 'error' })
const SAFE_ERROR_IDENTIFIER = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/
const SAFE_ERROR_CODE = /^[A-Za-z0-9_-]{1,64}$/
const SAFE_LOG_LABEL = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/
const SAFE_LOG_FIELDS = new Set([
'component',
'duration',
'environment',
'errorCode',
'errorName',
'operation',
'requestId',
'service',
'version'
])
export function getSafeErrorDetails(error: unknown): Record<string, string | number> {
const details: Record<string, string | number> = {
errorName: error instanceof Error && SAFE_ERROR_IDENTIFIER.test(error.name)
? error.name
: 'Error'
}
if (error && typeof error === 'object' && 'code' in error) {
const code = error.code
if (typeof code === 'number' && Number.isFinite(code)) details.errorCode = code
if (typeof code === 'string' && SAFE_ERROR_CODE.test(code)) details.errorCode = code
}
return details
}
export function sanitizeLogMetadata(metadata: Record<string, unknown>): Record<string, unknown> {
const safeMetadata: Record<string, unknown> = {}
for (const [key, value] of Object.entries(metadata)) {
if (!SAFE_LOG_FIELDS.has(key)) continue
if (key === 'duration' && typeof value === 'number' && Number.isFinite(value)) {
safeMetadata[key] = value
continue
}
if (key === 'errorCode' && typeof value === 'number' && Number.isFinite(value)) {
safeMetadata[key] = value
continue
}
if (typeof value === 'string' && SAFE_LOG_LABEL.test(value)) safeMetadata[key] = value
}
return safeMetadata
}
// Request ID generator for correlation
export const generateRequestId = (): string =>
`${Date.now()}-${randomUUID().slice(0, 8)}`
@@ -95,16 +124,22 @@ export const withTiming = async <T>(
metadata: Record<string, unknown> = {}
): Promise<T> => {
const startTime = Date.now()
logger.debug(`Started ${operation}`, metadata)
const safeOperation = SAFE_LOG_LABEL.test(operation) ? operation : 'operation'
const safeMetadata = sanitizeLogMetadata(metadata)
logger.debug(`Started ${safeOperation}`, safeMetadata)
try {
const result = await fn()
const duration = Date.now() - startTime
logger.debug(`Completed ${operation} in ${duration}ms`, { ...metadata, duration })
logger.debug(`Completed ${safeOperation} in ${duration}ms`, { ...safeMetadata, duration })
return result
} catch (error) {
const duration = Date.now() - startTime
logger.error(`Failed ${operation} in ${duration}ms`, { ...metadata, duration, error })
logger.error(`Failed ${safeOperation} in ${duration}ms`, {
...safeMetadata,
...getSafeErrorDetails(error),
duration
})
throw error
}
}
@@ -118,4 +153,4 @@ const gracefulShutdown = () => {
process.on('SIGTERM', gracefulShutdown)
process.on('SIGINT', gracefulShutdown)
export default logger
export default logger
+11
View File
@@ -17,6 +17,15 @@ const mockClient = {
db: jest.fn().mockReturnValue(mockDb)
}
const mockMongoLoggerError = jest.fn()
jest.mock('./logger', () => ({
dbLogger: { error: mockMongoLoggerError },
getSafeErrorDetails: (error: unknown) => ({
errorName: error instanceof Error ? error.name : 'Error'
})
}))
// The connect method should resolve to the client itself
mockClient.connect.mockResolvedValue(mockClient)
@@ -39,6 +48,7 @@ describe('MongoDB Connection (Unit Tests)', () => {
MONGODB_DB: 'test'
}
jest.clearAllMocks()
mockMongoLoggerError.mockReset()
// Reset the mock implementation
MockedMongoClient.mockImplementation(() => mockClient as any)
@@ -116,6 +126,7 @@ describe('MongoDB Connection (Unit Tests)', () => {
const result = await checkMongoConnection()
expect(result).toBe(false)
expect(mockMongoLoggerError).toHaveBeenCalledWith('MongoDB connection check failed', { errorName: 'Error' })
})
})
+2 -1
View File
@@ -1,4 +1,5 @@
import { MongoClient, Db } from 'mongodb'
import { dbLogger, getSafeErrorDetails } from './logger'
// WHY this file only exposes getDb/checkMongoConnection now: it used to also
// export getCollection(), used by src/app/api/contact/route.ts for a raw,
@@ -63,7 +64,7 @@ export async function checkMongoConnection(): Promise<boolean> {
await db.admin().ping()
return true
} catch (error) {
console.error('MongoDB connection check failed:', error)
dbLogger.error('MongoDB connection check failed', getSafeErrorDetails(error))
return false
}
}