From 225f0bb54d9b43f46710ff511ebbd9376c19a78d Mon Sep 17 00:00:00 2001 From: Ian Langworth Date: Fri, 14 Jun 2024 21:24:32 -0700 Subject: [PATCH] Add more logging around Maxmind DB download --- lib/geoip.ts | 17 ++++++++++++++++- middleware.ts | 2 +- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/geoip.ts b/lib/geoip.ts index a9d41a0..6ae3120 100644 --- a/lib/geoip.ts +++ b/lib/geoip.ts @@ -15,6 +15,10 @@ const filename = "GeoLite2-Country.mmdb"; const path = (process.env.DATA_DIR || "/tmp") + "/" + filename; const url = process.env.MAXMIND_GEOLITE2_COUNTRY_URL; +const debug = (...args: any[]) => { + if (process.env.DEBUG) console.log("[DEBUG]", ...args); +}; + const download = async () => { if (!url) throw "Cannot download Maxmind DB: Missing env var"; @@ -39,20 +43,31 @@ const download = async () => { const data = Buffer.concat(chunks); writeFileSync(path, data); console.log(`Wrote ${path} (${data.length} bytes)`); + console.log(`stat ${path}: ${JSON.stringify(statSync(path), null, 2)}`); } }); console.log(`Downloading ${filename}...`); + debug(`GET ${url}`); get(url, (res) => { - res.pipe(createGunzip()).pipe(extract); + if (res.statusCode === 200) { + res.pipe(createGunzip()).pipe(extract); + } else { + reject( + `Failed to download Maxmind DB: ${res.statusCode} ${res.statusMessage}`, + ); + } }); }); }; export const getCountryForIP = async (ip: string) => { if (existsSync(path)) { + debug("Maxmind DB exists", path); const maxAge = DateTime.now().minus({ weeks: 1 }); + debug("Maxmind DB maxAge", maxAge.toISO()); const lastModified = DateTime.fromJSDate(statSync(path).mtime); + debug("Maxmind DB lastModified", lastModified.toISO()); if (lastModified < maxAge) { console.log("Maxmind DB is older than 1 week - redownloading"); await download(); diff --git a/middleware.ts b/middleware.ts index 4ae9480..4b9b46c 100644 --- a/middleware.ts +++ b/middleware.ts @@ -21,7 +21,7 @@ export function middleware(req: NextRequest) { const [username, password] = atob(auth.substring(5)).split(":"); if (username !== HARDCODED_USERNAME || password !== secret) - throw new Error(`Invalid credentials from ${ip}`); + throw new Error("Invalid credentials"); return NextResponse.next(); } catch (err) { console.log(`Authentication error: ${err} from ${ip}`);