fix: handle non-JSON responses in carbon.js to prevent crash

When the WebsiteCarbon API is protected by Cloudflare and requests
originate from datacenter IPs, Cloudflare may return an HTML challenge
page instead of JSON. This caused JSON.parse() to throw an uncaught
SyntaxError exception, crashing the entire application.

This fix:
- Checks if the response starts with HTML markers before parsing
- Wraps JSON.parse in try-catch for additional safety
- Returns a descriptive error message instead of crashing

Fixes #268
This commit is contained in:
Sid 2026-01-08 21:54:20 +05:30
commit a163c356b9

View file

@ -29,7 +29,17 @@ const carbonHandler = async (url) => {
data += chunk;
});
res.on('end', () => {
resolve(JSON.parse(data));
// Check if response looks like HTML (e.g., Cloudflare challenge page)
const trimmedData = data.trim();
if (trimmedData.startsWith('<!DOCTYPE') || trimmedData.startsWith('<html') || trimmedData.startsWith('<')) {
reject(new Error('WebsiteCarbon API returned HTML instead of JSON. This may be due to Cloudflare protection when running from a datacenter IP.'));
return;
}
try {
resolve(JSON.parse(data));
} catch (parseError) {
reject(new Error(`Failed to parse WebsiteCarbon API response as JSON: ${parseError.message}`));
}
});
}).on('error', reject);
});