Repository navigation
feat(web): fill view locations from a GeoIP database when self-hosted #4158
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
Open
hjescalona
wants to merge
6
commits into
CapSoftware:main
Choose a base branch
from
Solomedia:feat/self-hosted-geoip
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+263
−8
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
2d00a30
feat(web): fill view locations from a GeoIP database when self-hosted
hjescalona a1afacb
test(web): cover the GeoIP fallback in the analytics track route
hjescalona f18f387
fix(web): locate views by X-Real-IP instead of the last forwarded hop
hjescalona edfbad0
docs: document CAP_GEOIP_DATABASE_PATH for self-hosted view locations
hjescalona e4d3731
docs(web): explain the Docker Compose setup for the GeoIP database
hjescalona 8bf8098
Merge branch 'main' into feat/self-hosted-geoip
hjescalona File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| import { describe, expect, it, vi } from "vitest"; | ||
| import { | ||
| type GeoIpReader, | ||
| geoIpLocation, | ||
| lookupLocation, | ||
| } from "@/lib/visitor-location"; | ||
|
|
||
| vi.mock("@cap/env", () => ({ | ||
| serverEnv: () => ({ | ||
| CAP_GEOIP_DATABASE_PATH: "/nonexistent/dbip-city-lite.mmdb", | ||
| }), | ||
| })); | ||
|
|
||
| describe("geoIpLocation", () => { | ||
| it("returns null and warns once when the database file is missing", () => { | ||
| const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); | ||
| expect(geoIpLocation("8.8.8.8")).toBeNull(); | ||
| expect(geoIpLocation("1.1.1.1")).toBeNull(); | ||
| expect(warn).toHaveBeenCalledTimes(1); | ||
| warn.mockRestore(); | ||
| }); | ||
| }); | ||
|
|
||
| const readerWith = (records: Record<string, unknown>): GeoIpReader => ({ | ||
| get: (ip) => { | ||
| if (ip === "not-an-ip") throw new Error("Invalid IP address"); | ||
| return (records[ip] ?? null) as ReturnType<GeoIpReader["get"]>; | ||
| }, | ||
| }); | ||
|
|
||
| describe("lookupLocation", () => { | ||
| it("reads country, region and city from a GeoIP2 City record", () => { | ||
| const reader = readerWith({ | ||
| "81.2.69.142": { | ||
| country: { iso_code: "GB" }, | ||
| subdivisions: [{ iso_code: "ENG", names: { en: "England" } }], | ||
| city: { names: { en: "London" } }, | ||
| }, | ||
| }); | ||
| expect(lookupLocation(reader, "81.2.69.142")).toEqual({ | ||
| country: "GB", | ||
| region: "ENG", | ||
| city: "London", | ||
| }); | ||
| }); | ||
|
|
||
| // DB-IP Lite has subdivision names but no subdivision codes. | ||
| it("falls back to the subdivision name when it has no code", () => { | ||
| const reader = readerWith({ | ||
| "190.202.0.1": { | ||
| country: { iso_code: "VE" }, | ||
| subdivisions: [{ names: { en: "Zulia" } }], | ||
| city: { names: { en: "San Carlos del Zulia" } }, | ||
| }, | ||
| }); | ||
| expect(lookupLocation(reader, "190.202.0.1")).toEqual({ | ||
| country: "VE", | ||
| region: "Zulia", | ||
| city: "San Carlos del Zulia", | ||
| }); | ||
| }); | ||
|
|
||
| it("keeps the country when the record has no region or city", () => { | ||
| const reader = readerWith({ | ||
| "2001:db8::1": { country: { iso_code: "us" } }, | ||
| }); | ||
| expect(lookupLocation(reader, "2001:db8::1")).toEqual({ | ||
| country: "US", | ||
| region: "", | ||
| city: "", | ||
| }); | ||
| }); | ||
|
|
||
| it("returns null for missing, unknown, private and invalid addresses", () => { | ||
| const reader = readerWith({ | ||
| "10.0.0.1": { country: {} }, | ||
| "203.0.113.9": { country: { iso_code: "EU1" } }, | ||
| }); | ||
| for (const ip of [ | ||
| null, | ||
| undefined, | ||
| "", | ||
| "127.0.0.1", | ||
| "10.0.0.1", | ||
| "203.0.113.9", | ||
| "not-an-ip", | ||
| ]) { | ||
| expect(lookupLocation(reader, ip)).toBeNull(); | ||
| } | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| import { readFileSync } from "node:fs"; | ||
| import { serverEnv } from "@cap/env"; | ||
| import { type CityResponse, Reader } from "mmdb-lib"; | ||
|
|
||
| export type VisitorLocation = { | ||
| country: string; | ||
| region: string; | ||
| city: string; | ||
| }; | ||
|
|
||
| type GeoIpRecord = { | ||
| country?: { iso_code?: string }; | ||
| subdivisions?: Array<{ iso_code?: string; names?: { en?: string } }>; | ||
| city?: { names?: { en?: string } }; | ||
| }; | ||
|
|
||
| export type GeoIpReader = { get(ip: string): GeoIpRecord | null }; | ||
|
|
||
| const MAX_LENGTH = 256; | ||
|
|
||
| const clean = (value: string | undefined) => | ||
| value?.trim().slice(0, MAX_LENGTH) ?? ""; | ||
|
|
||
| export function lookupLocation( | ||
| reader: GeoIpReader, | ||
| ip: string | null | undefined, | ||
| ): VisitorLocation | null { | ||
| if (!ip) return null; | ||
| let record: GeoIpRecord | null; | ||
| try { | ||
| record = reader.get(ip); | ||
| } catch { | ||
| return null; | ||
| } | ||
| const country = clean(record?.country?.iso_code).toUpperCase(); | ||
| if (!/^[A-Z]{2}$/.test(country)) return null; | ||
| const subdivision = record?.subdivisions?.[0]; | ||
| return { | ||
| country, | ||
| region: clean(subdivision?.iso_code || subdivision?.names?.en), | ||
| city: clean(record?.city?.names?.en), | ||
| }; | ||
| } | ||
|
|
||
| let reader: GeoIpReader | null | undefined; | ||
|
|
||
| function geoIpReader(): GeoIpReader | null { | ||
| if (reader !== undefined) return reader; | ||
| reader = null; | ||
| const path = serverEnv().CAP_GEOIP_DATABASE_PATH?.trim(); | ||
| if (!path) return reader; | ||
| try { | ||
| reader = new Reader<CityResponse>(readFileSync(path)); | ||
| } catch (error) { | ||
| console.warn( | ||
| `[geoip] Could not open ${path}; views keep no location`, | ||
| error, | ||
| ); | ||
| } | ||
| return reader; | ||
| } | ||
|
|
||
| export function geoIpLocation( | ||
| ip: string | null | undefined, | ||
| ): VisitorLocation | null { | ||
| const current = geoIpReader(); | ||
| return current ? lookupLocation(current, ip) : null; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.