| 1 | import path from 'node:path'; |
| 2 | import fs from 'node:fs'; |
| 3 | import { getIpAddress } from '../express-common.js'; |
| 4 | import { color, getConfigValue } from '../util.js'; |
| 5 | |
| 6 | const enableAccessLog = getConfigValue('logging.enableAccessLog', true, 'boolean'); |
| 7 | |
| 8 | const knownIPs = new Set(); |
| 9 | |
| 10 | export const getAccessLogPath = () => path.join(globalThis.DATA_ROOT, 'access.log'); |
| 11 | |
| 12 | export function migrateAccessLog() { |
| 13 | try { |
| 14 | if (!fs.existsSync('access.log')) { |
| 15 | return; |
| 16 | } |
| 17 | const logPath = getAccessLogPath(); |
| 18 | if (fs.existsSync(logPath)) { |
| 19 | return; |
| 20 | } |
| 21 | fs.renameSync('access.log', logPath); |
| 22 | console.log(color.yellow('Migrated access.log to new location:'), logPath); |
| 23 | } catch (e) { |
| 24 | console.error('Failed to migrate access log:', e); |
| 25 | console.info('Please move access.log to the data directory manually.'); |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * Creates middleware for logging access and new connections |
| 31 | * @returns {import('express').RequestHandler} |
| 32 | */ |
| 33 | export default function accessLoggerMiddleware() { |
| 34 | return function (req, res, next) { |
| 35 | const clientIp = getIpAddress(req, true); |
| 36 | const userAgent = req.headers['user-agent']; |
| 37 | |
| 38 | if (!knownIPs.has(clientIp)) { |
| 39 | // Log new connection |
| 40 | knownIPs.add(clientIp); |
| 41 | |
| 42 | // Write to access log if enabled |
| 43 | if (enableAccessLog) { |
| 44 | console.info(color.yellow(`New connection from ${clientIp}; User Agent: ${userAgent}\n`)); |
| 45 | const logPath = getAccessLogPath(); |
| 46 | const timestamp = new Date().toISOString(); |
| 47 | const log = `${timestamp} ${clientIp} ${userAgent}\n`; |
| 48 | |
| 49 | fs.appendFile(logPath, log, (err) => { |
| 50 | if (err) { |
| 51 | console.error('Failed to write access log:', err); |
| 52 | } |
| 53 | }); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | next(); |
| 58 | }; |
| 59 | } |