mirror of
https://github.com/mileswolfallen2/miles-web.git
synced 2026-12-05 16:20:44 +00:00
Add comprehensive test suite for application functionality
- Implement tests for HTTP API endpoints, ensuring correct responses and security headers. - Create configuration tests to validate loading of defaults and environment overrides. - Add tests for FEDL service to verify data handling and snapshot functionality. - Introduce GitHub service tests to check API data normalization and caching behavior. - Develop monitor service tests for network checks and uptime calculations. - Implement persistence tests to ensure database migrations are idempotent and data persists across restarts. - Add vault service tests for session management and brute-force protection mechanisms. - Include helper functions for test context creation and JSON response handling.
This commit is contained in:
1 parent
84b7a7e302
commit
c250653961
55 files changed
+8174
-226
No files matched your search
@@ -0,0 +1,37 @@
|
||||
export function parseCookies(header) {
|
||||
const out = {};
|
||||
if (!header) return out;
|
||||
for (const part of header.split(';')) {
|
||||
const eq = part.indexOf('=');
|
||||
if (eq === -1) continue;
|
||||
const name = part.slice(0, eq).trim();
|
||||
if (!name) continue;
|
||||
let value = part.slice(eq + 1).trim();
|
||||
if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
|
||||
out[name] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function serializeCookie(name, value, options = {}) {
|
||||
const {
|
||||
path = '/',
|
||||
maxAge,
|
||||
expires,
|
||||
httpOnly = true,
|
||||
secure = false,
|
||||
sameSite = 'Strict'
|
||||
} = options;
|
||||
|
||||
const parts = [`${name}=${value}`, `Path=${path}`];
|
||||
if (maxAge !== undefined) parts.push(`Max-Age=${Math.max(0, Math.floor(maxAge))}`);
|
||||
if (expires) parts.push(`Expires=${expires.toUTCString()}`);
|
||||
if (httpOnly) parts.push('HttpOnly');
|
||||
if (secure) parts.push('Secure');
|
||||
if (sameSite) parts.push(`SameSite=${sameSite}`);
|
||||
return parts.join('; ');
|
||||
}
|
||||
|
||||
export function clearCookie(name, options = {}) {
|
||||
return serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) });
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
export function sha256Hex(value) {
|
||||
return crypto.createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
|
||||
export function hmacHex(secret, value) {
|
||||
return crypto.createHmac('sha256', secret).update(value).digest('hex');
|
||||
}
|
||||
|
||||
export function randomHex(bytes = 32) {
|
||||
return crypto.randomBytes(bytes).toString('hex');
|
||||
}
|
||||
|
||||
export function safeEqualHex(a, b) {
|
||||
if (typeof a !== 'string' || typeof b !== 'string') return false;
|
||||
if (a.length !== b.length || a.length % 2 !== 0) return false;
|
||||
try {
|
||||
return crypto.timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function signValue(secret, value) {
|
||||
return hmacHex(secret, value);
|
||||
}
|
||||
|
||||
export function verifySignature(secret, value, signature) {
|
||||
return safeEqualHex(signValue(secret, value), signature);
|
||||
}
|
||||
|
||||
export function dayKey(date = new Date()) {
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Daily rotating key. Hashing an IP with this key gives a stable
|
||||
* anonymous identifier for the day, but cannot be reversed.
|
||||
*/
|
||||
export function dailyKey(secret, date = new Date(), scope = 'analytics') {
|
||||
return hmacHex(secret, `${scope}:${dayKey(date)}`);
|
||||
}
|
||||
|
||||
export function hashIp(secret, ip, { date = new Date(), scope = 'analytics' } = {}) {
|
||||
const key = dailyKey(secret, date, scope);
|
||||
return hmacHex(key, String(ip || 'unknown')).slice(0, 32);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* Minimal .env loader. No dependency, no variable expansion.
|
||||
* Existing process env values always win.
|
||||
*/
|
||||
export function loadEnv(file = path.resolve(process.cwd(), '.env')) {
|
||||
let text;
|
||||
try {
|
||||
text = fs.readFileSync(file, 'utf8');
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
|
||||
const loaded = {};
|
||||
for (const rawLine of text.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const eq = line.indexOf('=');
|
||||
if (eq === -1) continue;
|
||||
let key = line.slice(0, eq).trim();
|
||||
if (key.startsWith('export ')) key = key.slice(7).trim();
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue;
|
||||
let value = line.slice(eq + 1).trim();
|
||||
if (
|
||||
(value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))
|
||||
) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
// Basic escape support for double-quoted values.
|
||||
value = value.replace(/\\n/g, '\n').replace(/\\r/g, '\r');
|
||||
if (process.env[key] === undefined) {
|
||||
process.env[key] = value;
|
||||
loaded[key] = value;
|
||||
}
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
export class AppError extends Error {
|
||||
constructor(status, code, message, details, expose = status < 500) {
|
||||
super(message);
|
||||
this.name = 'AppError';
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
this.details = details;
|
||||
this.expose = expose;
|
||||
}
|
||||
}
|
||||
|
||||
export const badRequest = (message = 'Invalid request', details) =>
|
||||
new AppError(400, 'bad_request', message, details);
|
||||
export const unauthorized = (message = 'Unauthorized') =>
|
||||
new AppError(401, 'unauthorized', message);
|
||||
export const forbidden = (message = 'Forbidden') =>
|
||||
new AppError(403, 'forbidden', message);
|
||||
export const notFound = (message = 'Not found') =>
|
||||
new AppError(404, 'not_found', message);
|
||||
export const tooManyRequests = (message = 'Too many requests', retryAfterMs) =>
|
||||
new AppError(429, 'rate_limited', message, { retryAfterMs });
|
||||
export const unavailable = (message = 'Service unavailable') =>
|
||||
new AppError(503, 'unavailable', message);
|
||||
@@ -0,0 +1,141 @@
|
||||
import { badRequest, tooManyRequests } from './errors.js';
|
||||
|
||||
export function sendJson(res, status, data, extraHeaders = {}) {
|
||||
const body = JSON.stringify(data);
|
||||
res.writeHead(status, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
'Cache-Control': 'no-store',
|
||||
...extraHeaders
|
||||
});
|
||||
res.end(body);
|
||||
}
|
||||
|
||||
export function sendText(res, status, text, extraHeaders = {}) {
|
||||
res.writeHead(status, {
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'Content-Length': Buffer.byteLength(text),
|
||||
'Cache-Control': 'no-store',
|
||||
...extraHeaders
|
||||
});
|
||||
res.end(text);
|
||||
}
|
||||
|
||||
export function sendError(res, error, extraHeaders = {}) {
|
||||
const status = error.status || 500;
|
||||
const payload = {
|
||||
error: {
|
||||
code: error.code || 'internal_error',
|
||||
message: error.expose === false ? 'Internal server error' : error.message || 'Internal server error'
|
||||
}
|
||||
};
|
||||
if (error.details && error.expose !== false) payload.error.details = error.details;
|
||||
const headers = { ...extraHeaders };
|
||||
if (status === 429 && error.details?.retryAfterMs) {
|
||||
headers['Retry-After'] = String(Math.max(1, Math.ceil(error.details.retryAfterMs / 1000)));
|
||||
}
|
||||
sendJson(res, status, payload, headers);
|
||||
}
|
||||
|
||||
export function getClientIp(req, { trustProxy = false } = {}) {
|
||||
if (trustProxy) {
|
||||
const cf = req.headers['cf-connecting-ip'];
|
||||
if (typeof cf === 'string' && cf.trim()) return cf.trim();
|
||||
const xff = req.headers['x-forwarded-for'];
|
||||
if (typeof xff === 'string' && xff.trim()) return xff.split(',')[0].trim();
|
||||
}
|
||||
return req.socket?.remoteAddress || 'unknown';
|
||||
}
|
||||
|
||||
export function applySecurityHeaders(res, { production = false } = {}) {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('X-Frame-Options', 'DENY');
|
||||
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||
res.setHeader('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');
|
||||
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
|
||||
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
|
||||
if (production) {
|
||||
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
|
||||
}
|
||||
}
|
||||
|
||||
export function corsFor(origin, allowedOrigins) {
|
||||
if (!origin) return {};
|
||||
if (!allowedOrigins.has(origin)) return null;
|
||||
return {
|
||||
'Access-Control-Allow-Origin': origin,
|
||||
'Access-Control-Allow-Credentials': 'true',
|
||||
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type',
|
||||
'Access-Control-Max-Age': '600',
|
||||
Vary: 'Origin'
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Read and parse a request body with a hard size limit.
|
||||
* Supports JSON and (for the vault login form) urlencoded bodies.
|
||||
*/
|
||||
export function readBody(req, { limitBytes = 16384, timeoutMs = 10000 } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const declared = Number(req.headers['content-length'] || 0);
|
||||
if (declared && declared > limitBytes) {
|
||||
reject(badRequest('Request body too large'));
|
||||
return;
|
||||
}
|
||||
|
||||
let size = 0;
|
||||
const chunks = [];
|
||||
let settled = false;
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
req.destroy();
|
||||
reject(tooManyRequests('Request body timeout'));
|
||||
}, timeoutMs);
|
||||
|
||||
function finish(fn) {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
fn();
|
||||
}
|
||||
|
||||
req.on('data', (chunk) => {
|
||||
if (settled) return;
|
||||
size += chunk.length;
|
||||
if (size > limitBytes) {
|
||||
finish(() => {
|
||||
req.destroy();
|
||||
reject(badRequest('Request body too large'));
|
||||
});
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
|
||||
req.on('error', (err) => finish(() => reject(err)));
|
||||
req.on('end', () => {
|
||||
finish(() => {
|
||||
const raw = Buffer.concat(chunks).toString('utf8');
|
||||
if (!raw) return resolve({ raw: '', json: {}, type: 'empty' });
|
||||
const contentType = String(req.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
|
||||
if (contentType === 'application/x-www-form-urlencoded') {
|
||||
return resolve({ raw, json: Object.fromEntries(new URLSearchParams(raw)), type: 'form' });
|
||||
}
|
||||
if (contentType !== 'application/json' && contentType !== 'text/json') {
|
||||
return reject(badRequest('Expected application/json'));
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
return reject(badRequest('Expected a JSON object'));
|
||||
}
|
||||
resolve({ raw, json: parsed, type: 'json' });
|
||||
} catch {
|
||||
reject(badRequest('Malformed JSON'));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
const LEVELS = { error: 0, warn: 1, info: 2, debug: 3 };
|
||||
|
||||
export function createLogger({ level = 'info', name = 'dashboard' } = {}) {
|
||||
const threshold = LEVELS[level] ?? LEVELS.info;
|
||||
|
||||
function write(lvl, message, fields = {}) {
|
||||
if ((LEVELS[lvl] ?? LEVELS.info) > threshold) return;
|
||||
const entry = {
|
||||
ts: new Date().toISOString(),
|
||||
level: lvl,
|
||||
logger: name,
|
||||
msg: message,
|
||||
...fields
|
||||
};
|
||||
const line = JSON.stringify(entry);
|
||||
if (lvl === 'error' || lvl === 'warn') process.stderr.write(line + '\n');
|
||||
else process.stdout.write(line + '\n');
|
||||
}
|
||||
|
||||
return {
|
||||
level,
|
||||
error: (msg, fields) => write('error', msg, fields),
|
||||
warn: (msg, fields) => write('warn', msg, fields),
|
||||
info: (msg, fields) => write('info', msg, fields),
|
||||
debug: (msg, fields) => write('debug', msg, fields),
|
||||
child: (fields) => {
|
||||
const parent = createLogger({ level, name });
|
||||
return {
|
||||
...parent,
|
||||
error: (msg, f = {}) => parent.error(msg, { ...fields, ...f }),
|
||||
warn: (msg, f = {}) => parent.warn(msg, { ...fields, ...f }),
|
||||
info: (msg, f = {}) => parent.info(msg, { ...fields, ...f }),
|
||||
debug: (msg, f = {}) => parent.debug(msg, { ...fields, ...f }),
|
||||
child: parent.child
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Small in-memory sliding-window rate limiter.
|
||||
* Single-process by design; the vault login also has a DB-backed limit
|
||||
* so brute-force protection survives restarts.
|
||||
*/
|
||||
export function createRateLimiter({ now = () => Date.now(), maxEntries = 20000 } = {}) {
|
||||
const buckets = new Map();
|
||||
|
||||
function hit(key, { limit, windowMs }) {
|
||||
const t = now();
|
||||
const cutoff = t - windowMs;
|
||||
let hits = buckets.get(key) || [];
|
||||
hits = hits.filter((ts) => ts > cutoff);
|
||||
|
||||
if (hits.length >= limit) {
|
||||
buckets.set(key, hits);
|
||||
const retryAfterMs = Math.max(0, hits[0] + windowMs - t);
|
||||
return { allowed: false, remaining: 0, retryAfterMs };
|
||||
}
|
||||
|
||||
hits.push(t);
|
||||
buckets.set(key, hits);
|
||||
|
||||
if (buckets.size > maxEntries) {
|
||||
for (const [k, list] of buckets) {
|
||||
if (!list.length || list[list.length - 1] <= cutoff) buckets.delete(k);
|
||||
}
|
||||
}
|
||||
|
||||
return { allowed: true, remaining: Math.max(0, limit - hits.length), retryAfterMs: 0 };
|
||||
}
|
||||
|
||||
function reset(key) {
|
||||
buckets.delete(key);
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
const cutoff = now() - 60 * 60 * 1000;
|
||||
for (const [key, list] of buckets) {
|
||||
const kept = list.filter((ts) => ts > cutoff);
|
||||
if (kept.length) buckets.set(key, kept);
|
||||
else buckets.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
return { hit, reset, cleanup, buckets };
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import fs from 'node:fs';
|
||||
import fsp from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
|
||||
const MIME = new Map(Object.entries({
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.htm': 'text/html; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': 'text/javascript; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.map': 'application/json; charset=utf-8',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
'.md': 'text/plain; charset=utf-8',
|
||||
'.xml': 'application/xml; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.avif': 'image/avif',
|
||||
'.ico': 'image/x-icon',
|
||||
'.woff': 'font/woff',
|
||||
'.woff2': 'font/woff2',
|
||||
'.ttf': 'font/ttf',
|
||||
'.otf': 'font/otf',
|
||||
'.mp3': 'audio/mpeg',
|
||||
'.wav': 'audio/wav',
|
||||
'.ogg': 'audio/ogg',
|
||||
'.mp4': 'video/mp4',
|
||||
'.webm': 'video/webm',
|
||||
'.wasm': 'application/wasm',
|
||||
'.data': 'application/octet-stream',
|
||||
'.unityweb': 'application/octet-stream',
|
||||
'.mem': 'application/octet-stream',
|
||||
'.pck': 'application/octet-stream',
|
||||
'.zip': 'application/zip'
|
||||
}));
|
||||
|
||||
const DENY_SEGMENTS = new Set([
|
||||
'.git',
|
||||
'.github',
|
||||
'node_modules',
|
||||
'server',
|
||||
'tests',
|
||||
'data',
|
||||
'docs',
|
||||
'share-server'
|
||||
]);
|
||||
|
||||
const DENY_FILES = new Set([
|
||||
'.env',
|
||||
'.env.local',
|
||||
'.env.example',
|
||||
'.DS_Store',
|
||||
'package.json',
|
||||
'package-lock.json'
|
||||
]);
|
||||
|
||||
function contentType(file) {
|
||||
return MIME.get(path.extname(file).toLowerCase()) || 'application/octet-stream';
|
||||
}
|
||||
|
||||
function cacheControl(file) {
|
||||
return path.extname(file).toLowerCase() === '.html'
|
||||
? 'no-cache'
|
||||
: 'public, max-age=3600';
|
||||
}
|
||||
|
||||
export async function resolveStaticPath(root, rawPathname) {
|
||||
let pathname;
|
||||
try {
|
||||
pathname = decodeURIComponent(rawPathname);
|
||||
} catch {
|
||||
return { error: 400 };
|
||||
}
|
||||
if (!pathname.startsWith('/') || pathname.includes('\\') || pathname.includes('\0')) {
|
||||
return { error: 400 };
|
||||
}
|
||||
if (pathname.length > 2048) return { error: 414 };
|
||||
|
||||
const normalized = path.posix.normalize(pathname);
|
||||
if (normalized.includes('..')) return { error: 403 };
|
||||
|
||||
let relative = normalized.replace(/^\/+/, '');
|
||||
if (!relative || normalized.endsWith('/')) relative = path.posix.join(relative, 'index.html');
|
||||
|
||||
const segments = relative.split('/').filter(Boolean);
|
||||
for (const segment of segments) {
|
||||
if (segment.startsWith('.') || DENY_SEGMENTS.has(segment)) return { error: 403 };
|
||||
}
|
||||
if (DENY_FILES.has(segments[segments.length - 1])) return { error: 403 };
|
||||
if (/\.(db|db-wal|db-shm|sqlite|sqlite3)$/i.test(relative)) return { error: 403 };
|
||||
|
||||
const resolved = path.resolve(root, relative);
|
||||
const rootWithSep = root.endsWith(path.sep) ? root : root + path.sep;
|
||||
if (resolved !== root && !resolved.startsWith(rootWithSep)) return { error: 403 };
|
||||
|
||||
try {
|
||||
const realRoot = await fsp.realpath(root);
|
||||
const realFile = await fsp.realpath(resolved);
|
||||
const realRootWithSep = realRoot.endsWith(path.sep) ? realRoot : realRoot + path.sep;
|
||||
if (realFile !== realRoot && !realFile.startsWith(realRootWithSep)) return { error: 403 };
|
||||
const stat = await fsp.stat(realFile);
|
||||
if (stat.isDirectory()) {
|
||||
const indexFile = path.join(realFile, 'index.html');
|
||||
const indexStat = await fsp.stat(indexFile);
|
||||
return { file: indexFile, stat: indexStat };
|
||||
}
|
||||
return { file: realFile, stat };
|
||||
} catch {
|
||||
return { error: 404 };
|
||||
}
|
||||
}
|
||||
|
||||
function parseRange(header, size) {
|
||||
if (!header) return null;
|
||||
const match = String(header).match(/^bytes=(\d*)-(\d*)$/);
|
||||
if (!match) return { invalid: true };
|
||||
const [, startRaw, endRaw] = match;
|
||||
let start = startRaw === '' ? null : Number.parseInt(startRaw, 10);
|
||||
let end = endRaw === '' ? null : Number.parseInt(endRaw, 10);
|
||||
if (start === null && end === null) return { invalid: true };
|
||||
if (start === null) {
|
||||
start = Math.max(0, size - end);
|
||||
end = size - 1;
|
||||
} else if (end === null || end >= size) {
|
||||
end = size - 1;
|
||||
}
|
||||
if (start < 0 || start >= size || end < start) return { invalid: true };
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
export async function sendFile(req, res, file, stat, { status = 200, cache = null, contentTypeOverride = null } = {}) {
|
||||
const type = contentTypeOverride || contentType(file);
|
||||
const headers = {
|
||||
'Content-Type': type,
|
||||
'Content-Length': stat.size,
|
||||
'Cache-Control': cache || cacheControl(file),
|
||||
'Accept-Ranges': 'bytes'
|
||||
};
|
||||
|
||||
const range = parseRange(req.headers.range, stat.size);
|
||||
if (range?.invalid) {
|
||||
res.writeHead(416, { 'Content-Range': `bytes */${stat.size}`, 'Cache-Control': 'no-store' });
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (range) {
|
||||
const length = range.end - range.start + 1;
|
||||
res.writeHead(206, {
|
||||
...headers,
|
||||
'Content-Length': length,
|
||||
'Content-Range': `bytes ${range.start}-${range.end}/${stat.size}`
|
||||
});
|
||||
if (req.method === 'HEAD') return res.end();
|
||||
fs.createReadStream(file, { start: range.start, end: range.end }).pipe(res);
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(status, headers);
|
||||
if (req.method === 'HEAD') return res.end();
|
||||
fs.createReadStream(file).pipe(res);
|
||||
}
|
||||
|
||||
export async function serveStatic(req, res, { root, pathname, notFoundFile = null, cache = null }) {
|
||||
const result = await resolveStaticPath(root, pathname);
|
||||
if (result.error === 404) {
|
||||
if (notFoundFile) {
|
||||
try {
|
||||
const stat = await fsp.stat(notFoundFile);
|
||||
await sendFile(req, res, notFoundFile, stat, { status: 404, cache: 'no-store' });
|
||||
return true;
|
||||
} catch {
|
||||
// fall through
|
||||
}
|
||||
}
|
||||
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
|
||||
res.end('Not found');
|
||||
return true;
|
||||
}
|
||||
if (result.error) {
|
||||
res.writeHead(result.error, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
|
||||
res.end(result.error === 403 ? 'Forbidden' : 'Bad request');
|
||||
return true;
|
||||
}
|
||||
await sendFile(req, res, result.file, result.stat, { cache });
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
const BOT_RE = /bot|crawler|spider|slurp|bingpreview|facebookexternalhit|headless|lighthouse|pagespeed|curl\/|wget\/|python-requests|go-http-client|httpclient|scrapy|semrush|ahrefs|mj12|dotbot|petalbot|yandex|baiduspider|duckduckbot|applebot|archive\.org/i;
|
||||
const PATH_RE = /^\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]*$/;
|
||||
const HOST_RE = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
|
||||
|
||||
export function clampInt(value, fallback, min, max) {
|
||||
const n = Number.parseInt(value, 10);
|
||||
if (!Number.isFinite(n)) return fallback;
|
||||
return Math.min(max, Math.max(min, n));
|
||||
}
|
||||
|
||||
export function limitString(value, maxLength) {
|
||||
if (typeof value !== 'string') return '';
|
||||
return value.length > maxLength ? value.slice(0, maxLength) : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a page path for analytics. Returns null for anything that is
|
||||
* not a safe, same-site path.
|
||||
*/
|
||||
export function normalizePath(raw) {
|
||||
if (typeof raw !== 'string' || raw.length > 1024) return null;
|
||||
let value = raw.trim().split('#')[0].split('?')[0];
|
||||
if (!value.startsWith('/')) return null;
|
||||
if (value.includes('\\') || value.includes('\0')) return null;
|
||||
|
||||
let decoded;
|
||||
try {
|
||||
decoded = decodeURIComponent(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (decoded.includes('..') || decoded.includes('\\') || decoded.includes('\0')) return null;
|
||||
if (!PATH_RE.test(decoded)) return null;
|
||||
|
||||
decoded = decoded.replace(/\/{2,}/g, '/');
|
||||
if (decoded === '/index.html') decoded = '/';
|
||||
if (decoded.length > 1) decoded = decoded.replace(/\/+$/, '');
|
||||
if (!decoded.startsWith('/')) decoded = '/' + decoded;
|
||||
return decoded;
|
||||
}
|
||||
|
||||
export function referrerDomain(raw) {
|
||||
if (typeof raw !== 'string' || !raw || raw.length > 2048) return null;
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
|
||||
const host = url.hostname.toLowerCase();
|
||||
if (!HOST_RE.test(host)) return null;
|
||||
return host.slice(0, 255);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function isLikelyBot(userAgent) {
|
||||
if (!userAgent) return true;
|
||||
return BOT_RE.test(userAgent);
|
||||
}
|
||||
|
||||
export function parseBoolean(value, fallback = false) {
|
||||
if (value === undefined || value === null || value === '') return fallback;
|
||||
return /^(1|true|yes|on)$/i.test(String(value));
|
||||
}
|
||||
Reference in new issue
Block a user