Files
Proxer-Downloader/lib/logging.js
T
2026-10-23 16:38:55 +02:00

58 lines
2.0 KiB
JavaScript

const { StringDecoder } = require('node:string_decoder');
const LOG_LIMIT = 16 * 1024;
function sanitizeLog(value, secrets = []) {
if (value === undefined || value === null) return '';
let text = String(value);
for (const secret of secrets) {
if (typeof secret === 'string' && secret.length) {
text = text.split(secret).join('[redacted]');
}
}
text = text
.replace(/https?:\/\/[^\s<>"']+/gi, '[redacted URL]')
.replace(/\b(?:mongodb(?:\+srv)?):\/\/[^\s<>"']+/gi, '[redacted database URL]')
.replace(/\b(token|cookie|authorization|password|mongo_uri|token_prefix)\s*[:=]\s*[^\r\n]+/gi, '$1=[redacted]')
.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
return text.length > LOG_LIMIT ? '[earlier log output omitted]\n' + text.slice(-LOG_LIMIT) : text;
}
// Buffer complete lines before redacting; credentials/URLs can cross pipe chunks.
function createLineSanitizer(onLine, { secrets = [], maxLineLength = 8192 } = {}) {
const decoder = new StringDecoder('utf8');
let pending = '';
let discarding = false;
function consume(text) {
for (const char of text) {
if (char === '\n' || char === '\r') {
if (discarding) onLine('[oversized log line omitted]\n');
else if (pending) onLine(sanitizeLog(pending, secrets) + '\n');
pending = '';
discarding = false;
} else if (!discarding) {
pending += char;
if (pending.length > maxLineLength) {
pending = '';
discarding = true;
}
}
}
}
return {
write(chunk) { consume(decoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)))); },
end() {
consume(decoder.end());
if (discarding) onLine('[oversized log line omitted]\n');
else if (pending) onLine(sanitizeLog(pending, secrets) + '\n');
pending = '';
discarding = false;
},
};
}
module.exports = { LOG_LIMIT, sanitizeLog, createLineSanitizer };