@lock-dev/geo-block
Version:
Geographic blocking module for lock.dev security framework
64 lines (63 loc) • 1.88 kB
JavaScript
import * as maxmind from 'maxmind';
import * as fs from 'fs';
/**
* MaxMind geo lookup provider
*/
export class MaxMindProvider {
/**
* Create a new MaxMind provider
* @param config Configuration options
*/
constructor(config) {
this.initialized = false;
if (!config.maxmindDbPath) {
throw new Error('MaxMind database path must be provided');
}
this.dbPath = config.maxmindDbPath;
}
/**
* Initialize the MaxMind database reader
*/
async init() {
if (this.initialized)
return;
try {
// Verify database file exists
if (!fs.existsSync(this.dbPath)) {
throw new Error(`MaxMind database file not found at: ${this.dbPath}`);
}
// Open the database
this.reader = await maxmind.open(this.dbPath);
this.initialized = true;
}
catch (error) {
throw new Error(`Failed to initialize MaxMind database: ${error instanceof Error ? error.message : String(error)}`);
}
}
/**
* Look up geographic information for an IP address
* @param ip IP address to look up
*/
async lookup(ip) {
if (!this.initialized) {
await this.init();
}
try {
const result = this.reader.get(ip);
if (!result) {
return {};
}
return {
country: result.country?.iso_code,
region: result.subdivisions?.[0]?.iso_code,
city: result.city?.names?.en,
latitude: result.location?.latitude,
longitude: result.location?.longitude,
};
}
catch (error) {
console.error(`Error looking up IP ${ip}:`, error);
return {};
}
}
}