refactor: modularize backend security and observability
This commit is contained in:
43
backend/utils/url.js
Normal file
43
backend/utils/url.js
Normal file
@@ -0,0 +1,43 @@
|
||||
function sanitizeHttpBaseUrl(rawValue) {
|
||||
if (!rawValue) return null;
|
||||
|
||||
try {
|
||||
const url = new URL(rawValue);
|
||||
if (!['http:', 'https:'].includes(url.protocol)) return null;
|
||||
|
||||
url.search = '';
|
||||
url.hash = '';
|
||||
url.pathname = url.pathname.replace(/\/+$/, '');
|
||||
return url.toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildHttpDownloadUrl(rawBaseUrl, filePath) {
|
||||
const baseUrl = sanitizeHttpBaseUrl(rawBaseUrl);
|
||||
if (!baseUrl || !filePath) return null;
|
||||
|
||||
try {
|
||||
const url = new URL(baseUrl);
|
||||
const normalizedPath = filePath.startsWith('/') ? filePath : `/${filePath}`;
|
||||
const safeSegments = normalizedPath
|
||||
.split('/')
|
||||
.filter(Boolean)
|
||||
.map((segment) => encodeURIComponent(segment));
|
||||
const safePath = safeSegments.length ? `/${safeSegments.join('/')}` : '';
|
||||
|
||||
const basePath = url.pathname.replace(/\/+$/, '');
|
||||
url.pathname = `${basePath}${safePath || '/'}` || '/';
|
||||
url.search = '';
|
||||
url.hash = '';
|
||||
return url.toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildHttpDownloadUrl,
|
||||
sanitizeHttpBaseUrl
|
||||
};
|
||||
Reference in New Issue
Block a user