@lock-dev/ip-filter
Version:
IP filtering module for lock.dev security framework
238 lines (232 loc) • 7.18 kB
JavaScript
import {
MemoryIPCacheStore,
RedisIPCacheStore,
UpstashIPCacheStore,
createCacheStore
} from "./chunk-H7CN3B64.mjs";
// src/types.ts
var IPFilterEventType = /* @__PURE__ */ ((IPFilterEventType2) => {
IPFilterEventType2["IP_BLOCKED"] = "ip.blocked";
IPFilterEventType2["IP_ALLOWED"] = "ip.allowed";
IPFilterEventType2["IP_FILTER_ERROR"] = "ip.error";
return IPFilterEventType2;
})(IPFilterEventType || {});
// src/index.ts
import { createModule } from "@lock-dev/core";
import { registerModule } from "@lock-dev/core";
// src/utils/extract-ip.ts
function extractIp(req, ipHeaders = ["cf-connecting-ip", "x-forwarded-for", "x-real-ip"], useRemoteAddress = true) {
for (const header of ipHeaders) {
const headerValue = req.headers?.[header] || req.headers?.[header.toLowerCase()];
if (headerValue) {
if (typeof headerValue === "string" && headerValue.includes(",")) {
const firstIp = headerValue.split(",")[0].trim();
if (firstIp) return firstIp;
} else {
return headerValue;
}
}
}
if (useRemoteAddress) {
const connection = req.connection || req.socket || req.info;
if (connection?.remoteAddress) {
return connection.remoteAddress;
}
if (req.ip) {
return req.ip;
}
if (req.socket?.remoteAddress) {
return req.socket.remoteAddress;
}
}
return null;
}
function cleanIp(ip) {
if (ip.startsWith("::ffff:")) {
return ip.substring(7);
}
return ip;
}
// src/utils/ip-matcher.ts
import * as ipaddr from "ipaddr.js";
function ipInCidr(ip, cidr) {
try {
const addr = ipaddr.parse(ip);
const range = ipaddr.parseCIDR(cidr);
return addr.kind() === range[0].kind() && addr.match(range);
} catch (error) {
console.error(`Error checking IP ${ip} against CIDR ${cidr}:`, error);
return false;
}
}
function ipEquals(ip1, ip2) {
try {
const addr1 = ipaddr.parse(ip1);
const addr2 = ipaddr.parse(ip2);
return addr1.kind() === addr2.kind() && addr1.toString() === addr2.toString();
} catch (error) {
console.error(`Error comparing IPs ${ip1} and ${ip2}:`, error);
return false;
}
}
function isIpInList(ip, list) {
try {
const parsedIp = ipaddr.parse(ip);
const normalizedIp = parsedIp.toString();
return list.some((entry) => {
if (entry.includes("/")) {
return ipInCidr(normalizedIp, entry);
}
return ipEquals(normalizedIp, entry);
});
} catch (error) {
console.error(`Error checking IP ${ip} against list:`, error);
return false;
}
}
function normalizeIp(ip) {
try {
return ipaddr.parse(ip).toString();
} catch (error) {
return null;
}
}
function isValidIpOrCidr(input) {
try {
if (input.includes("/")) {
ipaddr.parseCIDR(input);
} else {
ipaddr.parse(input);
}
return true;
} catch (error) {
return false;
}
}
// src/index.ts
var DEFAULT_CONFIG = {
mode: "blacklist",
ipHeaders: ["cf-connecting-ip", "x-forwarded-for", "x-real-ip"],
useRemoteAddress: true,
blockStatusCode: 403,
blockMessage: "Access denied based on your IP address",
storage: "memory",
cacheTtl: 36e5,
cacheSize: 1e4,
failBehavior: "open"
};
var ipCache = null;
var ipFilter = createModule({
name: "ip-filter",
defaultConfig: DEFAULT_CONFIG,
async check(context, config) {
try {
if (!ipCache) {
try {
ipCache = await createCacheStore(config);
} catch (cacheError) {
console.error(`Failed to initialize IP filter cache: ${cacheError.message}`);
const { MemoryIPCacheStore: MemoryIPCacheStore2 } = await import("./storage-RUPMMYH3.mjs");
ipCache = new MemoryIPCacheStore2(config);
await ipCache.init();
}
}
const ip = extractIp(context.request, config.ipHeaders, config.useRemoteAddress);
if (!ip) {
console.warn("No IP address could be extracted from the request");
return {
passed: config.failBehavior === "open",
reason: config.failBehavior === "closed" ? "ip.blocked" /* IP_BLOCKED */ : void 0,
data: { error: "Could not determine client IP address" },
severity: "medium"
};
}
try {
let cacheKey = `${ip}:${config.mode}:${config.ipAddresses.join(",")}`;
let ipMatched = await ipCache.get(cacheKey);
if (ipMatched === null) {
ipMatched = isIpInList(ip, config.ipAddresses);
await ipCache.set(cacheKey, ipMatched);
}
const isBlocked = config.mode === "blacklist" && ipMatched || config.mode === "whitelist" && !ipMatched;
if (isBlocked) {
if (config.logBlocked) {
const logFn = config.logFunction || console.log;
logFn(`IP blocked: ${ip}`, { matched: ipMatched, mode: config.mode });
}
return {
passed: false,
reason: "ip.blocked" /* IP_BLOCKED */,
data: { ip, matched: ipMatched },
severity: "medium"
};
}
if (config.logAllowed) {
const logFn = config.logFunction || console.log;
logFn(`IP allowed: ${ip}`, { matched: ipMatched, mode: config.mode });
}
return {
passed: true,
reason: "ip.allowed" /* IP_ALLOWED */,
data: { ip, matched: ipMatched },
severity: "low"
};
} catch (matchError) {
console.error(`Error during IP matching for ${ip}:`, matchError);
if (config.failBehavior === "closed") {
return {
passed: false,
reason: "ip.error" /* IP_FILTER_ERROR */,
data: { error: "IP matching failed", ip },
severity: "medium"
};
}
return { passed: true };
}
} catch (error) {
console.error(`Unexpected error in ip-filter module:`, error);
return {
passed: config.failBehavior !== "closed",
reason: config.failBehavior === "closed" ? "ip.error" /* IP_FILTER_ERROR */ : void 0,
data: config.failBehavior === "closed" ? { error: "IP-filter module failed" } : void 0,
severity: "medium"
};
}
},
async handleFailure(context, reason, data) {
const config = context.data.get("ip-filter:config");
const res = context.response;
if (res.headersSent || res.writableEnded) {
return;
}
if (typeof res.status === "function") {
return res.status(config.blockStatusCode ?? 403).json({
error: config.blockMessage ?? "Access denied based on your IP address"
});
} else if (typeof res.statusCode === "number") {
res.statusCode = config.blockStatusCode ?? 403;
res.setHeader("Content-Type", "application/json");
return res.end(
JSON.stringify({
error: config.blockMessage ?? "Access denied based on your IP address"
})
);
}
}
});
registerModule("ipFilter", ipFilter);
export {
IPFilterEventType,
MemoryIPCacheStore,
RedisIPCacheStore,
UpstashIPCacheStore,
cleanIp,
createCacheStore,
extractIp,
ipEquals,
ipFilter,
ipInCidr,
isIpInList,
isValidIpOrCidr,
normalizeIp
};