Skip to content
New issue

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

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

Already on GitHub? # to your account

Fix Cloudflare header encoding issue #3096

Merged
merged 1 commit into from
Dec 12, 2024
Merged
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
14 changes: 11 additions & 3 deletions src/lib/detect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ function getRegionCode(country: string, region: string) {
return region.includes('-') ? region : `${country}-${region}`;
}

function safeDecodeCfHeader(s: string | undefined | null): string | undefined | null {
if (s === undefined || s === null) {
return s;
}

return Buffer.from(s, 'latin1').toString('utf-8');
}

export async function getLocation(ip: string, req: NextApiRequestCollect) {
// Ignore local ips
if (await isLocalhost(ip)) {
Expand All @@ -75,9 +83,9 @@ export async function getLocation(ip: string, req: NextApiRequestCollect) {

// Cloudflare headers
if (req.headers['cf-ipcountry']) {
const country = safeDecodeURIComponent(req.headers['cf-ipcountry']);
const subdivision1 = safeDecodeURIComponent(req.headers['cf-region-code']);
const city = safeDecodeURIComponent(req.headers['cf-ipcity']);
const country = safeDecodeCfHeader(req.headers['cf-ipcountry']);
const subdivision1 = safeDecodeCfHeader(req.headers['cf-region-code']);
const city = safeDecodeCfHeader(req.headers['cf-ipcity']);

return {
country,
Expand Down