Skip to content

Commit

Permalink
Merge pull request #3096 from delemeator/bugfix/cf-header-encoding
Browse files Browse the repository at this point in the history
Fix Cloudflare header encoding issue
  • Loading branch information
mikecao authored Dec 12, 2024
2 parents bb5affe + 6138acc commit 8f40751
Showing 1 changed file with 11 additions and 3 deletions.
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

0 comments on commit 8f40751

Please sign in to comment.