Merge branch 'geo-fix'
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
import { generateSecureBase58Token } from "@reviq/utils";
|
||||
import { base58 } from "@scure/base";
|
||||
|
||||
// Re-export generateSecureBase58Token from shared utils
|
||||
export { generateSecureBase58Token } from "@reviq/utils";
|
||||
// Re-export for convenience
|
||||
export { generateSecureBase58Token };
|
||||
|
||||
/**
|
||||
* Token prefix for all RevIQ API tokens
|
||||
@@ -59,10 +60,40 @@ export const generateSessionToken = (): string => {
|
||||
};
|
||||
|
||||
/**
|
||||
* Generate a device fingerprint (UUID v4)
|
||||
* Device fingerprint prefix for new fingerprints
|
||||
*/
|
||||
export const DEVICE_FINGERPRINT_PREFIX = "device_";
|
||||
|
||||
/**
|
||||
* Generate a device fingerprint (base58 with device_ prefix)
|
||||
*/
|
||||
export const generateDeviceFingerprint = (): string => {
|
||||
return crypto.randomUUID();
|
||||
return generateSecureBase58Token(DEVICE_FINGERPRINT_PREFIX);
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if a string is a valid device fingerprint.
|
||||
* Accepts both new format (device_ prefix) and legacy UUIDs.
|
||||
*/
|
||||
export const isValidDeviceFingerprint = (fingerprint: string): boolean => {
|
||||
// New format: device_ prefix with base58
|
||||
if (fingerprint.startsWith(DEVICE_FINGERPRINT_PREFIX)) {
|
||||
const base58Part = fingerprint.slice(DEVICE_FINGERPRINT_PREFIX.length);
|
||||
if (base58Part.length === 0) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
base58.decode(base58Part);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy format: UUID v4
|
||||
const uuidRegex =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
return uuidRegex.test(fingerprint);
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
222
apps/api-server/src/utils/geo.test.ts
Normal file
222
apps/api-server/src/utils/geo.test.ts
Normal file
@@ -0,0 +1,222 @@
|
||||
import { beforeEach, describe, expect, test } from "bun:test";
|
||||
import {
|
||||
_resetForTesting,
|
||||
_setReaderForTesting,
|
||||
extractClientIP,
|
||||
getGeoInfo,
|
||||
getUserAgent,
|
||||
lookupGeoFromIP,
|
||||
} from "./geo.js";
|
||||
|
||||
const createHeaders = (entries: Record<string, string>): Headers => {
|
||||
return new Headers(entries);
|
||||
};
|
||||
|
||||
describe("extractClientIP", () => {
|
||||
test("extracts from CF-Connecting-IP", () => {
|
||||
const headers = createHeaders({ "CF-Connecting-IP": "1.2.3.4" });
|
||||
expect(extractClientIP(headers)).toBe("1.2.3.4");
|
||||
});
|
||||
|
||||
test("extracts from True-Client-IP", () => {
|
||||
const headers = createHeaders({ "True-Client-IP": "5.6.7.8" });
|
||||
expect(extractClientIP(headers)).toBe("5.6.7.8");
|
||||
});
|
||||
|
||||
test("extracts from X-Real-IP", () => {
|
||||
const headers = createHeaders({ "X-Real-IP": "10.20.30.40" });
|
||||
expect(extractClientIP(headers)).toBe("10.20.30.40");
|
||||
});
|
||||
|
||||
test("extracts first IP from X-Forwarded-For", () => {
|
||||
const headers = createHeaders({
|
||||
"X-Forwarded-For": "100.1.2.3, 200.4.5.6, 10.0.0.1",
|
||||
});
|
||||
expect(extractClientIP(headers)).toBe("100.1.2.3");
|
||||
});
|
||||
|
||||
test("extracts from X-Client-IP", () => {
|
||||
const headers = createHeaders({ "X-Client-IP": "192.168.1.1" });
|
||||
expect(extractClientIP(headers)).toBe("192.168.1.1");
|
||||
});
|
||||
|
||||
test("prioritizes CF-Connecting-IP over others", () => {
|
||||
const headers = createHeaders({
|
||||
"CF-Connecting-IP": "1.1.1.1",
|
||||
"True-Client-IP": "2.2.2.2",
|
||||
"X-Real-IP": "3.3.3.3",
|
||||
"X-Forwarded-For": "4.4.4.4",
|
||||
"X-Client-IP": "5.5.5.5",
|
||||
});
|
||||
expect(extractClientIP(headers)).toBe("1.1.1.1");
|
||||
});
|
||||
|
||||
test("returns null when no IP headers present", () => {
|
||||
expect(extractClientIP(createHeaders({}))).toBeNull();
|
||||
});
|
||||
|
||||
test("trims whitespace", () => {
|
||||
const headers = createHeaders({ "CF-Connecting-IP": " 1.2.3.4 " });
|
||||
expect(extractClientIP(headers)).toBe("1.2.3.4");
|
||||
});
|
||||
|
||||
test("handles IPv6", () => {
|
||||
const headers = createHeaders({
|
||||
"CF-Connecting-IP": "2001:0db8:85a3::8a2e:0370:7334",
|
||||
});
|
||||
expect(extractClientIP(headers)).toBe("2001:0db8:85a3::8a2e:0370:7334");
|
||||
});
|
||||
});
|
||||
|
||||
describe("lookupGeoFromIP", () => {
|
||||
beforeEach(() => {
|
||||
_resetForTesting();
|
||||
});
|
||||
|
||||
test("returns nulls when reader not initialized", () => {
|
||||
expect(lookupGeoFromIP("8.8.8.8")).toEqual({
|
||||
city: null,
|
||||
region: null,
|
||||
country: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("returns geo data from reader", () => {
|
||||
_setReaderForTesting({
|
||||
get: (ip: string) =>
|
||||
ip === "8.8.8.8"
|
||||
? {
|
||||
city: { names: { en: "Mountain View" } },
|
||||
subdivisions: [{ names: { en: "California" } }],
|
||||
country: { iso_code: "US" },
|
||||
}
|
||||
: null,
|
||||
} as never);
|
||||
|
||||
expect(lookupGeoFromIP("8.8.8.8")).toEqual({
|
||||
city: "Mountain View",
|
||||
region: "California",
|
||||
country: "US",
|
||||
});
|
||||
});
|
||||
|
||||
test("returns nulls for unknown IP", () => {
|
||||
_setReaderForTesting({ get: () => null } as never);
|
||||
expect(lookupGeoFromIP("0.0.0.0")).toEqual({
|
||||
city: null,
|
||||
region: null,
|
||||
country: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("handles partial geo data", () => {
|
||||
_setReaderForTesting({
|
||||
get: () => ({ country: { iso_code: "DE" } }),
|
||||
} as never);
|
||||
|
||||
expect(lookupGeoFromIP("1.2.3.4")).toEqual({
|
||||
city: null,
|
||||
region: null,
|
||||
country: "DE",
|
||||
});
|
||||
});
|
||||
|
||||
test("handles reader errors gracefully", () => {
|
||||
_setReaderForTesting({
|
||||
get: () => {
|
||||
throw new Error("Lookup failed");
|
||||
},
|
||||
} as never);
|
||||
|
||||
expect(lookupGeoFromIP("invalid")).toEqual({
|
||||
city: null,
|
||||
region: null,
|
||||
country: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getGeoInfo", () => {
|
||||
beforeEach(() => {
|
||||
_resetForTesting();
|
||||
});
|
||||
|
||||
test("uses Cloudflare geo headers when present", () => {
|
||||
const headers = createHeaders({
|
||||
"CF-Connecting-IP": "1.2.3.4",
|
||||
"CF-IPCountry": "US",
|
||||
"CF-IPCity": "San Francisco",
|
||||
"CF-Region": "California",
|
||||
});
|
||||
|
||||
expect(getGeoInfo(headers)).toEqual({
|
||||
ip: "1.2.3.4",
|
||||
city: "San Francisco",
|
||||
region: "California",
|
||||
country: "US",
|
||||
});
|
||||
});
|
||||
|
||||
test("prefers CF headers over GeoIP lookup", () => {
|
||||
_setReaderForTesting({
|
||||
get: () => ({
|
||||
city: { names: { en: "Wrong" } },
|
||||
country: { iso_code: "XX" },
|
||||
}),
|
||||
} as never);
|
||||
|
||||
const headers = createHeaders({
|
||||
"CF-Connecting-IP": "1.2.3.4",
|
||||
"CF-IPCountry": "US",
|
||||
});
|
||||
|
||||
expect(getGeoInfo(headers).country).toBe("US");
|
||||
});
|
||||
|
||||
test("falls back to GeoIP lookup when no CF geo headers", () => {
|
||||
_setReaderForTesting({
|
||||
get: () => ({
|
||||
city: { names: { en: "Berlin" } },
|
||||
subdivisions: [{ names: { en: "Berlin" } }],
|
||||
country: { iso_code: "DE" },
|
||||
}),
|
||||
} as never);
|
||||
|
||||
const headers = createHeaders({ "X-Real-IP": "1.2.3.4" });
|
||||
|
||||
expect(getGeoInfo(headers)).toEqual({
|
||||
ip: "1.2.3.4",
|
||||
city: "Berlin",
|
||||
region: "Berlin",
|
||||
country: "DE",
|
||||
});
|
||||
});
|
||||
|
||||
test("returns IP even without geo data", () => {
|
||||
const headers = createHeaders({ "X-Forwarded-For": "203.0.113.50" });
|
||||
const result = getGeoInfo(headers);
|
||||
|
||||
expect(result.ip).toBe("203.0.113.50");
|
||||
expect(result.city).toBeNull();
|
||||
});
|
||||
|
||||
test("returns all nulls when no headers", () => {
|
||||
expect(getGeoInfo(createHeaders({}))).toEqual({
|
||||
ip: null,
|
||||
city: null,
|
||||
region: null,
|
||||
country: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getUserAgent", () => {
|
||||
test("returns User-Agent header", () => {
|
||||
const headers = createHeaders({ "User-Agent": "Mozilla/5.0 Chrome/120" });
|
||||
expect(getUserAgent(headers)).toBe("Mozilla/5.0 Chrome/120");
|
||||
});
|
||||
|
||||
test('returns "Unknown" when missing', () => {
|
||||
expect(getUserAgent(createHeaders({}))).toBe("Unknown");
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,6 @@
|
||||
import type { CityResponse, Reader } from "maxmind";
|
||||
import { open } from "maxmind";
|
||||
|
||||
export interface GeoInfo {
|
||||
ip: string | null;
|
||||
city: string | null;
|
||||
@@ -5,37 +8,152 @@ export interface GeoInfo {
|
||||
country: string | null;
|
||||
}
|
||||
|
||||
/** Default path for GeoLite2-City database */
|
||||
const DEFAULT_GEOIP_PATH = "/usr/share/GeoIP/GeoLite2-City.mmdb";
|
||||
|
||||
// Module-level reader instance
|
||||
let geoReader: Reader<CityResponse> | null = null;
|
||||
let initialized = false;
|
||||
|
||||
/**
|
||||
* Extract geolocation info from request headers
|
||||
* Supports Cloudflare headers in production, falls back to standard headers
|
||||
* @param headers - Request headers
|
||||
* @returns Geolocation information extracted from headers
|
||||
* Initialize the GeoIP database reader.
|
||||
* Uses GEOIP_DATABASE_PATH env var, defaults to /usr/share/GeoIP/GeoLite2-City.mmdb
|
||||
*/
|
||||
export const initGeoReader = async (): Promise<void> => {
|
||||
if (initialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
const dbPath = Bun.env.GEOIP_DATABASE_PATH ?? DEFAULT_GEOIP_PATH;
|
||||
|
||||
try {
|
||||
geoReader = await open<CityResponse>(dbPath);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
console.warn(`GeoIP database not available at ${dbPath}: ${message}`);
|
||||
}
|
||||
|
||||
initialized = true;
|
||||
};
|
||||
|
||||
// ===== Test Helpers =====
|
||||
// These are exported for testing only. Do not use in production code.
|
||||
|
||||
/** @internal Reset state for testing */
|
||||
export const _resetForTesting = (): void => {
|
||||
geoReader = null;
|
||||
initialized = false;
|
||||
};
|
||||
|
||||
/** @internal Set a mock reader for testing */
|
||||
export const _setReaderForTesting = (
|
||||
reader: Reader<CityResponse> | null,
|
||||
): void => {
|
||||
geoReader = reader;
|
||||
initialized = true;
|
||||
};
|
||||
|
||||
// ===== Public API =====
|
||||
|
||||
/**
|
||||
* Extract the client IP address from request headers.
|
||||
* Checks headers in priority order:
|
||||
* 1. CF-Connecting-IP (Cloudflare)
|
||||
* 2. True-Client-IP (Cloudflare Enterprise / Akamai)
|
||||
* 3. X-Real-IP (nginx, other proxies)
|
||||
* 4. X-Forwarded-For (first IP in chain)
|
||||
* 5. X-Client-IP (some proxies)
|
||||
*/
|
||||
export const extractClientIP = (headers: Headers): string | null => {
|
||||
const cfIP = headers.get("CF-Connecting-IP");
|
||||
if (cfIP) {
|
||||
return cfIP.trim();
|
||||
}
|
||||
|
||||
const trueClientIP = headers.get("True-Client-IP");
|
||||
if (trueClientIP) {
|
||||
return trueClientIP.trim();
|
||||
}
|
||||
|
||||
const realIP = headers.get("X-Real-IP");
|
||||
if (realIP) {
|
||||
return realIP.trim();
|
||||
}
|
||||
|
||||
const forwardedFor = headers.get("X-Forwarded-For");
|
||||
if (forwardedFor) {
|
||||
const firstIP = forwardedFor.split(",")[0]?.trim();
|
||||
if (firstIP) {
|
||||
return firstIP;
|
||||
}
|
||||
}
|
||||
|
||||
const clientIP = headers.get("X-Client-IP");
|
||||
if (clientIP) {
|
||||
return clientIP.trim();
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Look up geo information from an IP address using the GeoIP database.
|
||||
* Returns null values if the database isn't initialized or IP is unknown.
|
||||
*/
|
||||
export const lookupGeoFromIP = (
|
||||
ip: string,
|
||||
): { city: string | null; region: string | null; country: string | null } => {
|
||||
if (!geoReader) {
|
||||
return { city: null, region: null, country: null };
|
||||
}
|
||||
|
||||
try {
|
||||
const result = geoReader.get(ip);
|
||||
if (!result) {
|
||||
return { city: null, region: null, country: null };
|
||||
}
|
||||
|
||||
return {
|
||||
city: result.city?.names.en ?? null,
|
||||
region: result.subdivisions?.[0]?.names.en ?? null,
|
||||
country: result.country?.iso_code ?? null,
|
||||
};
|
||||
} catch {
|
||||
return { city: null, region: null, country: null };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Extract geolocation info from request headers.
|
||||
* Uses Cloudflare headers when available, falls back to GeoIP database lookup.
|
||||
*/
|
||||
export const getGeoInfo = (headers: Headers): GeoInfo => {
|
||||
// Try Cloudflare headers first (production)
|
||||
const cfIP = headers.get("CF-Connecting-IP");
|
||||
const ip = extractClientIP(headers);
|
||||
|
||||
// Try Cloudflare geo headers first
|
||||
const cfCountry = headers.get("CF-IPCountry");
|
||||
const cfCity = headers.get("CF-IPCity");
|
||||
const cfRegion = headers.get("CF-Region");
|
||||
|
||||
// Fallback to X-Forwarded-For or X-Real-IP
|
||||
const forwardedFor = headers.get("X-Forwarded-For");
|
||||
const realIP = headers.get("X-Real-IP");
|
||||
if (cfCountry || cfCity || cfRegion) {
|
||||
return {
|
||||
ip,
|
||||
city: cfCity ?? null,
|
||||
region: cfRegion ?? null,
|
||||
country: cfCountry ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
const ip = cfIP ?? realIP ?? forwardedFor?.split(",")[0]?.trim() ?? null;
|
||||
// Fall back to GeoIP database lookup
|
||||
if (ip) {
|
||||
return { ip, ...lookupGeoFromIP(ip) };
|
||||
}
|
||||
|
||||
return {
|
||||
ip,
|
||||
city: cfCity ?? null,
|
||||
region: cfRegion ?? null,
|
||||
country: cfCountry ?? null,
|
||||
};
|
||||
return { ip: null, city: null, region: null, country: null };
|
||||
};
|
||||
|
||||
/**
|
||||
* Extract User-Agent from request headers
|
||||
* @param headers - Request headers
|
||||
* @returns User-Agent string or "Unknown" if not present
|
||||
* Extract User-Agent from request headers.
|
||||
*/
|
||||
export const getUserAgent = (headers: Headers): string => {
|
||||
return headers.get("User-Agent") ?? "Unknown";
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
* Unit tests for passkey-helpers utility functions
|
||||
*/
|
||||
|
||||
import type { PasskeyRow } from "../../utils/passkey-helpers.js";
|
||||
import type { PasskeyRow } from "./passkey-helpers.js";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
base64urlToUint8Array,
|
||||
formatPasskeyDate,
|
||||
parsePasskeyRow,
|
||||
uint8ArrayToBase64url,
|
||||
} from "../../utils/passkey-helpers.js";
|
||||
} from "./passkey-helpers.js";
|
||||
|
||||
describe("base64urlToUint8Array", () => {
|
||||
test("converts base64url string to Uint8Array", () => {
|
||||
Reference in New Issue
Block a user