Initial ByteGeist Toolbox uptime checker
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
npm-debug.log
|
||||
.git
|
||||
.gitignore
|
||||
tests
|
||||
.env
|
||||
@@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
.env
|
||||
npm-debug.log*
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
# Use a small official Node.js image.
|
||||
FROM node:22-alpine
|
||||
|
||||
# Set the working directory inside the container.
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files first so Docker can cache dependency installs.
|
||||
COPY package*.json ./
|
||||
|
||||
# Install production dependencies only.
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
# Copy the rest of the project files.
|
||||
COPY . .
|
||||
|
||||
# Document the port used by the application.
|
||||
EXPOSE 3001
|
||||
|
||||
# Start the Node.js server.
|
||||
CMD ["npm", "start"]
|
||||
@@ -0,0 +1,12 @@
|
||||
services:
|
||||
bytegeist-toolbox:
|
||||
build: .
|
||||
container_name: bytegeist-toolbox
|
||||
restart: unless-stopped
|
||||
|
||||
ports:
|
||||
- "3001:3001"
|
||||
|
||||
environment:
|
||||
PORT: 3001
|
||||
NODE_ENV: production
|
||||
Generated
+1253
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "bytegeist-toolbox",
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"scripts": {
|
||||
"start": "node src/server.js",
|
||||
"dev": "nodemon src/server.js",
|
||||
"test": "node --test"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^5.2.1",
|
||||
"express-rate-limit": "^8.6.0",
|
||||
"ipaddr.js": "^2.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.1.14"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// Get references to the page elements we need to update.
|
||||
const form = document.getElementById("uptime-form");
|
||||
const urlInput = document.getElementById("url-input");
|
||||
const checkButton = document.getElementById("check-button");
|
||||
const statusMessage = document.getElementById("status-message");
|
||||
const resultPanel = document.getElementById("result-panel");
|
||||
|
||||
const onlineBadge = document.getElementById("online-badge");
|
||||
const statusCode = document.getElementById("status-code");
|
||||
const responseTime = document.getElementById("response-time");
|
||||
const redirectCount = document.getElementById("redirect-count");
|
||||
const checkedAt = document.getElementById("checked-at");
|
||||
const finalUrl = document.getElementById("final-url");
|
||||
|
||||
// Listen for the form submission.
|
||||
form.addEventListener("submit", async (event) => {
|
||||
// Prevent the browser from reloading the page.
|
||||
event.preventDefault();
|
||||
|
||||
const url = urlInput.value.trim();
|
||||
|
||||
// Reset the interface before starting a new check.
|
||||
statusMessage.textContent = "Checking website...";
|
||||
statusMessage.className = "status-message";
|
||||
resultPanel.hidden = true;
|
||||
checkButton.disabled = true;
|
||||
checkButton.textContent = "Checking...";
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/uptime", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ url }),
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
// Handle API-level errors.
|
||||
if (!response.ok) {
|
||||
throw new Error(result.error || "The request failed.");
|
||||
}
|
||||
|
||||
// Handle unreachable or blocked destinations.
|
||||
if (!result.online) {
|
||||
throw new Error(result.error || "The website could not be reached.");
|
||||
}
|
||||
|
||||
// Fill in the successful result.
|
||||
onlineBadge.textContent = "Online";
|
||||
onlineBadge.className = "status-badge online";
|
||||
|
||||
statusCode.textContent = result.statusCode;
|
||||
responseTime.textContent = `${result.responseTimeMs} ms`;
|
||||
redirectCount.textContent = result.redirectCount;
|
||||
checkedAt.textContent = new Date(result.checkedAt).toLocaleString();
|
||||
|
||||
finalUrl.textContent = result.finalUrl;
|
||||
finalUrl.href = result.finalUrl;
|
||||
|
||||
statusMessage.textContent = "Website check completed.";
|
||||
resultPanel.hidden = false;
|
||||
} catch (error) {
|
||||
// Show a safe, readable message to the user.
|
||||
statusMessage.textContent = error.message;
|
||||
statusMessage.className = "status-message error";
|
||||
|
||||
onlineBadge.textContent = "Offline";
|
||||
onlineBadge.className = "status-badge offline";
|
||||
} finally {
|
||||
// Restore the button whether the request succeeded or failed.
|
||||
checkButton.disabled = false;
|
||||
checkButton.textContent = "Check Website";
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
|
||||
<!-- Makes the page scale correctly on phones and tablets. -->
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<title>ByteGeist Toolbox</title>
|
||||
|
||||
<!-- Load the stylesheet from the public folder. -->
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<main class="page-shell">
|
||||
<section class="tool-panel">
|
||||
<header class="tool-header">
|
||||
<p class="eyebrow">BYTEGEIST TOOLBOX</p>
|
||||
<h1>Website Uptime Checker</h1>
|
||||
<p class="description">
|
||||
Check whether a public website is reachable and see its status code,
|
||||
response time, redirects, and final destination.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<form id="uptime-form" class="uptime-form">
|
||||
<label for="url-input">Website URL</label>
|
||||
|
||||
<div class="input-row">
|
||||
<input
|
||||
id="url-input"
|
||||
name="url"
|
||||
type="url"
|
||||
placeholder="https://example.com"
|
||||
autocomplete="url"
|
||||
required
|
||||
>
|
||||
|
||||
<button id="check-button" type="submit">
|
||||
Check Website
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<!-- JavaScript updates this message during loading and errors. -->
|
||||
<p id="status-message" class="status-message" aria-live="polite"></p>
|
||||
|
||||
<!-- Hidden until a result is returned. -->
|
||||
<section id="result-panel" class="result-panel" hidden>
|
||||
<div class="result-heading">
|
||||
<h2>Check Result</h2>
|
||||
<span id="online-badge" class="status-badge"></span>
|
||||
</div>
|
||||
|
||||
<dl class="result-grid">
|
||||
<div>
|
||||
<dt>Status code</dt>
|
||||
<dd id="status-code">-</dd>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<dt>Response time</dt>
|
||||
<dd id="response-time">-</dd>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<dt>Redirects</dt>
|
||||
<dd id="redirect-count">-</dd>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<dt>Checked at</dt>
|
||||
<dd id="checked-at">-</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div class="final-url-block">
|
||||
<span>Final URL</span>
|
||||
<a
|
||||
id="final-url"
|
||||
href="#"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
></a>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<!-- Load the browser JavaScript after the HTML is available. -->
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,236 @@
|
||||
/* Use predictable sizing for every element. */
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
|
||||
--background: #080c14;
|
||||
--surface: #111827;
|
||||
--surface-light: #182235;
|
||||
--border: #2b3952;
|
||||
--text: #edf4ff;
|
||||
--muted: #9eabc0;
|
||||
--accent: #4ca6ff;
|
||||
--accent-hover: #78bcff;
|
||||
--success: #49d17d;
|
||||
--danger: #ff6b73;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
background:
|
||||
radial-gradient(circle at top, #17253b 0%, var(--background) 42%);
|
||||
color: var(--text);
|
||||
font-family:
|
||||
Inter,
|
||||
ui-sans-serif,
|
||||
system-ui,
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
"Segoe UI",
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
button,
|
||||
input {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.page-shell {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-height: 100vh;
|
||||
padding: 32px 20px;
|
||||
}
|
||||
|
||||
.tool-panel {
|
||||
width: min(760px, 100%);
|
||||
padding: 32px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
background: rgba(17, 24, 39, 0.96);
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
margin: 0 0 8px;
|
||||
color: var(--accent);
|
||||
font-size: 0.78rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.16em;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
p {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin-bottom: 12px;
|
||||
font-size: clamp(2rem, 5vw, 3.25rem);
|
||||
line-height: 1.05;
|
||||
}
|
||||
|
||||
.description {
|
||||
max-width: 62ch;
|
||||
margin-bottom: 28px;
|
||||
color: var(--muted);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.uptime-form label {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.input-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
input {
|
||||
min-width: 0;
|
||||
padding: 13px 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: #0b1220;
|
||||
color: var(--text);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
input:focus {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px rgba(76, 166, 255, 0.16);
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 13px 18px;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
background: var(--accent);
|
||||
color: #04101c;
|
||||
font-weight: 750;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
cursor: wait;
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
.status-message {
|
||||
min-height: 24px;
|
||||
margin: 18px 0 0;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.status-message.error {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.result-panel {
|
||||
margin-top: 24px;
|
||||
padding: 22px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: var(--surface-light);
|
||||
}
|
||||
|
||||
.result-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.result-heading h2 {
|
||||
margin-bottom: 0;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
padding: 5px 10px;
|
||||
border-radius: 999px;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 750;
|
||||
}
|
||||
|
||||
.status-badge.online {
|
||||
background: rgba(73, 209, 125, 0.14);
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.status-badge.offline {
|
||||
background: rgba(255, 107, 115, 0.14);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.result-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.result-grid div {
|
||||
padding: 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: #0d1523;
|
||||
}
|
||||
|
||||
.result-grid dt,
|
||||
.final-url-block span {
|
||||
margin-bottom: 6px;
|
||||
color: var(--muted);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.result-grid dd {
|
||||
margin: 0;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.final-url-block {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
margin-top: 14px;
|
||||
padding: 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: #0d1523;
|
||||
}
|
||||
|
||||
.final-url-block a {
|
||||
color: var(--accent);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.tool-panel {
|
||||
padding: 24px 18px;
|
||||
}
|
||||
|
||||
.input-row {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.result-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
button {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Import the rate-limiting middleware.
|
||||
const rateLimit = require("express-rate-limit");
|
||||
|
||||
// Limit how often one IP address can use the uptime checker.
|
||||
const uptimeRateLimiter = rateLimit({
|
||||
// Count requests inside a 15-minute window.
|
||||
windowMs: 15 * 60 * 1000,
|
||||
|
||||
// Allow 30 checks per IP during that window.
|
||||
limit: 30,
|
||||
|
||||
// Return modern rate-limit headers.
|
||||
standardHeaders: true,
|
||||
|
||||
// Disable older legacy headers.
|
||||
legacyHeaders: false,
|
||||
|
||||
// Return a clear JSON message when the limit is reached.
|
||||
message: {
|
||||
error: "Too many website checks. Please try again later.",
|
||||
},
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
uptimeRateLimiter,
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
const express = require("express");
|
||||
const { checkWebsite } = require("../services/uptimeService");
|
||||
const { uptimeRateLimiter } = require("../middleware/rateLimit");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// POST /api/uptime
|
||||
router.post("/", uptimeRateLimiter, async (req, res) => {
|
||||
const { url } = req.body;
|
||||
|
||||
// Confirm that a URL was submitted as text.
|
||||
if (typeof url !== "string" || url.trim() === "") {
|
||||
return res.status(400).json({
|
||||
error: "A URL is required.",
|
||||
});
|
||||
}
|
||||
|
||||
// Prevent excessively long input.
|
||||
if (url.length > 2048) {
|
||||
return res.status(400).json({
|
||||
error: "The URL is too long.",
|
||||
});
|
||||
}
|
||||
|
||||
const result = await checkWebsite(url.trim());
|
||||
|
||||
return res.json(result);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,38 @@
|
||||
// Import Express so we can create the web server.
|
||||
const express = require("express");
|
||||
|
||||
// Import path so we can safely point Express to the public folder.
|
||||
const path = require("path");
|
||||
|
||||
// Import the uptime API route.
|
||||
const uptimeRouter = require("./routes/uptime");
|
||||
|
||||
// Create the Express application.
|
||||
const app = express();
|
||||
|
||||
// Use the PORT environment variable if one exists.
|
||||
// Otherwise, use port 3001 for local development.
|
||||
const PORT = process.env.PORT || 3001;
|
||||
|
||||
// Allow the server to read JSON request bodies.
|
||||
app.use(express.json());
|
||||
|
||||
// Serve the files inside the public folder.
|
||||
app.use(express.static(path.join(__dirname, "..", "public")));
|
||||
|
||||
// Handle website uptime checks.
|
||||
app.use("/api/uptime", uptimeRouter);
|
||||
|
||||
// Simple health-check route.
|
||||
app.get("/health", (req, res) => {
|
||||
res.json({
|
||||
status: "ok",
|
||||
service: "bytegeist-toolbox",
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
// Start the web server.
|
||||
app.listen(PORT, () => {
|
||||
console.log(`ByteGeist Toolbox running at http://localhost:${PORT}`);
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
const { validatePublicUrl } = require("./urlSecurityService");
|
||||
|
||||
// Maximum number of redirects the checker will follow.
|
||||
const MAX_REDIRECTS = 5;
|
||||
|
||||
// Maximum time allowed for each request.
|
||||
const REQUEST_TIMEOUT_MS = 5000;
|
||||
|
||||
// Check whether an HTTP status code represents a redirect.
|
||||
function isRedirectStatus(statusCode) {
|
||||
return [301, 302, 303, 307, 308].includes(statusCode);
|
||||
}
|
||||
|
||||
// Check a public website and safely follow redirects.
|
||||
async function checkWebsite(submittedUrl) {
|
||||
const startTime = Date.now();
|
||||
|
||||
let currentUrl = submittedUrl;
|
||||
let redirectCount = 0;
|
||||
|
||||
try {
|
||||
while (redirectCount <= MAX_REDIRECTS) {
|
||||
// Validate the current URL before every request.
|
||||
// This prevents redirects from reaching private systems.
|
||||
const validatedUrl = await validatePublicUrl(currentUrl);
|
||||
|
||||
const response = await fetch(validatedUrl, {
|
||||
method: "GET",
|
||||
|
||||
// We handle redirects ourselves so every destination can be checked.
|
||||
redirect: "manual",
|
||||
|
||||
// Stop waiting after five seconds.
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
|
||||
headers: {
|
||||
// Identify the service instead of pretending to be a browser.
|
||||
"User-Agent": "ByteGeist-Toolbox/1.0",
|
||||
},
|
||||
});
|
||||
|
||||
// Check whether the response wants to redirect somewhere else.
|
||||
if (isRedirectStatus(response.status)) {
|
||||
const location = response.headers.get("location");
|
||||
|
||||
if (!location) {
|
||||
throw new Error("The website returned an invalid redirect.");
|
||||
}
|
||||
|
||||
redirectCount += 1;
|
||||
|
||||
if (redirectCount > MAX_REDIRECTS) {
|
||||
throw new Error("The website redirected too many times.");
|
||||
}
|
||||
|
||||
// Convert relative redirects such as /login into complete URLs.
|
||||
currentUrl = new URL(location, validatedUrl).toString();
|
||||
|
||||
// Continue the loop and validate the redirect destination.
|
||||
continue;
|
||||
}
|
||||
|
||||
const responseTimeMs = Date.now() - startTime;
|
||||
|
||||
// Cancel the response body because we only need status information.
|
||||
// This avoids downloading an entire website.
|
||||
if (response.body) {
|
||||
await response.body.cancel();
|
||||
}
|
||||
|
||||
return {
|
||||
online: true,
|
||||
statusCode: response.status,
|
||||
responseTimeMs,
|
||||
finalUrl: validatedUrl.toString(),
|
||||
redirectCount,
|
||||
checkedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error("The website redirected too many times.");
|
||||
} catch (error) {
|
||||
if (error.name === "TimeoutError") {
|
||||
return {
|
||||
online: false,
|
||||
error: "The website took too long to respond.",
|
||||
checkedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
online: false,
|
||||
error: error.message || "The website could not be reached.",
|
||||
checkedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
checkWebsite,
|
||||
};
|
||||
@@ -0,0 +1,119 @@
|
||||
// Import DNS tools so we can resolve domain names before requesting them.
|
||||
const dns = require("dns").promises;
|
||||
|
||||
// Import Node's IP address checker.
|
||||
const net = require("net");
|
||||
|
||||
// Import ipaddr.js so we can classify IPv4 and IPv6 addresses.
|
||||
const ipaddr = require("ipaddr.js");
|
||||
|
||||
// Check whether an IP address belongs to a blocked private or local range.
|
||||
function isPrivateIp(ipAddress) {
|
||||
try {
|
||||
const address = ipaddr.parse(ipAddress);
|
||||
|
||||
// ipaddr.js labels addresses with ranges such as:
|
||||
// private, loopback, linkLocal, multicast, and unspecified.
|
||||
const blockedRanges = [
|
||||
"private",
|
||||
"loopback",
|
||||
"linkLocal",
|
||||
"uniqueLocal",
|
||||
"multicast",
|
||||
"unspecified",
|
||||
"reserved",
|
||||
"broadcast",
|
||||
"carrierGradeNat",
|
||||
];
|
||||
|
||||
return blockedRanges.includes(address.range());
|
||||
} catch {
|
||||
// An address that cannot be parsed should not be trusted.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Validate a URL before the server makes a request.
|
||||
async function validatePublicUrl(urlValue) {
|
||||
let parsedUrl;
|
||||
|
||||
try {
|
||||
// Convert the submitted text into a proper URL object.
|
||||
parsedUrl = new URL(urlValue);
|
||||
} catch {
|
||||
throw new Error("Enter a valid URL.");
|
||||
}
|
||||
|
||||
// Only allow normal website protocols.
|
||||
if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
|
||||
throw new Error("Only HTTP and HTTPS URLs are allowed.");
|
||||
}
|
||||
|
||||
// Do not allow usernames or passwords inside the URL.
|
||||
if (parsedUrl.username || parsedUrl.password) {
|
||||
throw new Error("URLs containing usernames or passwords are not allowed.");
|
||||
}
|
||||
|
||||
// Initially allow only normal HTTP and HTTPS ports.
|
||||
const allowedPorts = ["", "80", "443"];
|
||||
|
||||
if (!allowedPorts.includes(parsedUrl.port)) {
|
||||
throw new Error("Only ports 80 and 443 are allowed.");
|
||||
}
|
||||
|
||||
const hostname = parsedUrl.hostname.toLowerCase();
|
||||
|
||||
// Block common local hostnames.
|
||||
const blockedHostnames = [
|
||||
"localhost",
|
||||
"localhost.localdomain",
|
||||
"host.docker.internal",
|
||||
];
|
||||
|
||||
if (
|
||||
blockedHostnames.includes(hostname) ||
|
||||
hostname.endsWith(".localhost") ||
|
||||
hostname.endsWith(".local")
|
||||
) {
|
||||
throw new Error("Local and private network addresses are not allowed.");
|
||||
}
|
||||
|
||||
// If the hostname is already an IP address, inspect it directly.
|
||||
if (net.isIP(hostname)) {
|
||||
if (isPrivateIp(hostname)) {
|
||||
throw new Error("Local and private network addresses are not allowed.");
|
||||
}
|
||||
|
||||
return parsedUrl;
|
||||
}
|
||||
|
||||
let resolvedAddresses;
|
||||
|
||||
try {
|
||||
// Resolve every IP address associated with the hostname.
|
||||
resolvedAddresses = await dns.lookup(hostname, {
|
||||
all: true,
|
||||
verbatim: true,
|
||||
});
|
||||
} catch {
|
||||
throw new Error("The hostname could not be resolved.");
|
||||
}
|
||||
|
||||
if (resolvedAddresses.length === 0) {
|
||||
throw new Error("The hostname did not resolve to an IP address.");
|
||||
}
|
||||
|
||||
// Reject the hostname if any resolved address is private or local.
|
||||
for (const result of resolvedAddresses) {
|
||||
if (isPrivateIp(result.address)) {
|
||||
throw new Error("Local and private network addresses are not allowed.");
|
||||
}
|
||||
}
|
||||
|
||||
return parsedUrl;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
validatePublicUrl,
|
||||
isPrivateIp,
|
||||
};
|
||||
@@ -0,0 +1,114 @@
|
||||
// Import Node's built-in test tools.
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
// Import the functions we want to test.
|
||||
const {
|
||||
isPrivateIp,
|
||||
validatePublicUrl,
|
||||
} = require("../src/services/urlSecurityService");
|
||||
|
||||
|
||||
// ---------------------------------------------------------
|
||||
// isPrivateIp() tests
|
||||
// ---------------------------------------------------------
|
||||
|
||||
test("blocks IPv4 loopback addresses", () => {
|
||||
assert.equal(isPrivateIp("127.0.0.1"), true);
|
||||
});
|
||||
|
||||
test("blocks private 10.x.x.x addresses", () => {
|
||||
assert.equal(isPrivateIp("10.0.0.1"), true);
|
||||
});
|
||||
|
||||
test("blocks private 172.16.x.x addresses", () => {
|
||||
assert.equal(isPrivateIp("172.16.0.1"), true);
|
||||
});
|
||||
|
||||
test("blocks private 192.168.x.x addresses", () => {
|
||||
assert.equal(isPrivateIp("192.168.1.1"), true);
|
||||
});
|
||||
|
||||
test("blocks link-local addresses", () => {
|
||||
assert.equal(isPrivateIp("169.254.1.1"), true);
|
||||
});
|
||||
|
||||
test("blocks IPv6 loopback", () => {
|
||||
assert.equal(isPrivateIp("::1"), true);
|
||||
});
|
||||
|
||||
test("allows a public IPv4 address", () => {
|
||||
assert.equal(isPrivateIp("1.1.1.1"), false);
|
||||
});
|
||||
|
||||
test("blocks malformed IP addresses", () => {
|
||||
assert.equal(isPrivateIp("not-an-ip"), true);
|
||||
});
|
||||
|
||||
|
||||
// ---------------------------------------------------------
|
||||
// validatePublicUrl() tests
|
||||
// ---------------------------------------------------------
|
||||
|
||||
test("accepts a public HTTP URL using a public IP", async () => {
|
||||
const result = await validatePublicUrl("http://1.1.1.1");
|
||||
|
||||
assert.equal(result.protocol, "http:");
|
||||
assert.equal(result.hostname, "1.1.1.1");
|
||||
});
|
||||
|
||||
test("accepts a public HTTPS URL using a public IP", async () => {
|
||||
const result = await validatePublicUrl("https://1.1.1.1");
|
||||
|
||||
assert.equal(result.protocol, "https:");
|
||||
assert.equal(result.hostname, "1.1.1.1");
|
||||
});
|
||||
|
||||
test("rejects localhost", async () => {
|
||||
await assert.rejects(
|
||||
validatePublicUrl("http://localhost"),
|
||||
/Local and private network addresses are not allowed/
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects localhost subdomains", async () => {
|
||||
await assert.rejects(
|
||||
validatePublicUrl("http://test.localhost"),
|
||||
/Local and private network addresses are not allowed/
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects private IP addresses", async () => {
|
||||
await assert.rejects(
|
||||
validatePublicUrl("http://192.168.1.1"),
|
||||
/Local and private network addresses are not allowed/
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects unsupported protocols", async () => {
|
||||
await assert.rejects(
|
||||
validatePublicUrl("ftp://example.com"),
|
||||
/Only HTTP and HTTPS URLs are allowed/
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects URLs containing credentials", async () => {
|
||||
await assert.rejects(
|
||||
validatePublicUrl("https://username:password@example.com"),
|
||||
/URLs containing usernames or passwords are not allowed/
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects nonstandard ports", async () => {
|
||||
await assert.rejects(
|
||||
validatePublicUrl("https://example.com:8080"),
|
||||
/Only ports 80 and 443 are allowed/
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects malformed URLs", async () => {
|
||||
await assert.rejects(
|
||||
validatePublicUrl("this is not a URL"),
|
||||
/Enter a valid URL/
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user