Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added debug/logging feature #33

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions HOSTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ This guide will walk you through the process of setting up your own instance of
`HOME_DOMAIN` | The host to enable `/stat` endpoint
`USE_LOCAL_DNS` | Default is `false`, so the Google DNS is used. Set it to `true` if you want to use the DNS resolver of your own host
`CACHE_EXPIRY_SECONDS` | Option to override the default cache TTL of 86400 seconds (1 day)
`DEBUG_MODE` | Default is `false`; set to true to enable debug mode. Messages will be shown in the console
`DEBUG_LEVEL` | Default level is 1 and can be set up to level 3 for maximum information

If `WHITELIST_HOSTS` is set, `BLACKLIST_HOSTS` is ignored. Both is mutually exclusive.

Expand Down
11 changes: 9 additions & 2 deletions src/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
validateCAARecords,
isExceedHostLimit,
isHttpCodeAllowed,
debugOutput,
getExpiryDate
} from "./util.js";

Expand Down Expand Up @@ -108,6 +109,7 @@ const listener = async function (req, res) {
res.write('Host header is required');
return;
}
debugOutput(1, `Received HTTP request for ${host}`);
if (host === process.env.HOME_DOMAIN) {
// handle CORS
res.setHeader('Access-Control-Allow-Origin', '*');
Expand Down Expand Up @@ -141,6 +143,7 @@ const listener = async function (req, res) {
totalSize += chunk.length;
// Disconnect if the data stream is too large
if (totalSize > MAX_DATA_SIZE) {
debugOutput(3, `Data stream for request ${host} too large`);
req.destroy();
return;
}
Expand All @@ -162,6 +165,7 @@ const listener = async function (req, res) {
if (cacheExists) {
// Remove the cache entry
resolveCache.delete(domain);
debugOutput(1, `Cache cleared for ${domain}`);
}
}
}
Expand All @@ -176,7 +180,10 @@ const listener = async function (req, res) {
if (!cache || (Date.now() > cache.expire)) {
cache = await buildCache(host);
resolveCache.set(host, cache);
}
debugOutput(1, `No cache found for ${host}, storing new data`);
} else {
debugOutput(1, `Found cache for ${host}, using stored data`);
}
if (cache.blacklisted) {
if (blacklistRedirectUrl) {
res.writeHead(302, {
Expand Down Expand Up @@ -208,4 +215,4 @@ export {
listener,
pruneCache,
buildCache,
}
}
62 changes: 61 additions & 1 deletion src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ let whitelistMap = null;
* @type {number | null}
*/
let cacheExpirySeconds = null;
/**
* @type {boolean | null}
*/
let debugMode = null
/**
* @type {number | null}
*/
let debugLevel = null

export function getExpiryDate() {
if (cacheExpirySeconds === null) {
Expand Down Expand Up @@ -96,6 +104,8 @@ export function clearConfig() {
useLocalDNS = null;
blacklistRedirectUrl = null;
cacheExpirySeconds = null;
debugMode = null;
debugLevel = null;
}

/**
Expand Down Expand Up @@ -138,6 +148,51 @@ export function isHostBlacklisted(domain = '', mockEnv = undefined) {
}
}

/**
* Returns the current date and time in the format: "YYYY-MM-DD HH:MM:SS".
*
* @returns {string} The current date and time as a formatted string.
*/
export function CurrentDate() {
const now = new Date();

return (
now.getFullYear() + '-' +
String(now.getMonth() + 1).padStart(2, '0') + '-' +
String(now.getDate()).padStart(2, '0') + ' ' +
String(now.getHours()).padStart(2, '0') + ':' +
String(now.getMinutes()).padStart(2, '0') + ':' +
String(now.getSeconds()).padStart(2, '0')
);
}

/**
* Outputs debug messages to the console based on the specified debug level.
* Debugging is controlled by the `DEBUG_MODE` and `DEBUG_LEVEL` environment variables.
*
* @param {number} level - The debug level of the message (1 - 3).
* @param {string} msg - The debug message to output.
*
*/
export function debugOutput(level,msg) {
if (debugMode === null) {
debugMode = process.env.DEBUG_MODE == 'true';
}
if (debugLevel === null) {
debugLevel = process.env.DEBUG_LEVEL || 1;
}
if (debugMode) {
const date = CurrentDate();
if (level === 1 && debugLevel === 1 ) {
console.log(`[${date}] ${msg}`);
} else if (level <= 2 && debugLevel <= 2 ) {
console.log(`[${date}] ${msg}`);
} else if (level <=3 & debugLevel <= 3) {
console.log(`[${date}] ${msg}`);
}
}
}

/**
* @param {string} host
*/
Expand Down Expand Up @@ -201,6 +256,7 @@ const parseTxtRecordData = (value) => {
export async function validateCAARecords(host, mockResolve = undefined) {
if (useLocalDNS === null) {
useLocalDNS = process.env.USE_LOCAL_DNS == 'true';
debugOutput(3, `useLocalDNS: ${useLocalDNS}`);
}
let issueRecords;
if (useLocalDNS && !mockResolve) {
Expand All @@ -226,6 +282,7 @@ export async function validateCAARecords(host, mockResolve = undefined) {
return null;
}

debugOutput(3, `issueRecords for ${host}: ${issueRecords}`);
return issueRecords;
}

Expand All @@ -247,6 +304,7 @@ export async function findTxtRecord(host, mockResolve = undefined) {
const resolved = await Promise.any(resolvePromises).catch(() => null);

if (resolved) {
debugOutput(2, `findTxtRecord for ${host}: ${resolved}`);
for (const record of resolved) {
const joinedRecord = record.join(';');
const txtData = parseTxtRecordData(joinedRecord);
Expand All @@ -271,6 +329,7 @@ export async function findTxtRecord(host, mockResolve = undefined) {
}
const txtData = parseTxtRecordData(head.data);
if (!txtData[recordParamDestUrl]) continue;
debugOutput(2, `findTxtRecord for ${host}: ${txtData[recordParamDestUrl]}`);
return {
url: txtData[recordParamDestUrl],
httpStatus: txtData[recordParamHttpStatus],
Expand All @@ -286,6 +345,7 @@ export async function findTxtRecord(host, mockResolve = undefined) {
*/
export function getCertExpiry(cert) {
const x509 = forge.pki.certificateFromPem(cert);
debugOutput(3, `LE cert expire after: ${x509.validity.notAfter.getTime()}`);
return x509.validity.notAfter.getTime()
}

Expand Down Expand Up @@ -337,4 +397,4 @@ export function combineURLs(baseURL, relativeURL) {
*/
export function isMainProcess(metaURL) {
return [process.argv[1], process.env.pm_exec_path].includes(fileURLToPath(metaURL));
}
}
Loading