var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __decoratorStart = (base) => [, , , __create((base == null ? void 0 : base[__knownSymbol("metadata")]) ?? null)];
var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
var __runInitializers = (array, flags, self, value) => {
  for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
  return value;
};
var __decorateElement = (array, flags, name, decorators, target, extra) => {
  var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
  var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
  var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
  var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
    return __privateGet(this, extra);
  }, set [name](x) {
    return __privateSet(this, extra, x);
  } }, name));
  k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
  for (var i = decorators.length - 1; i >= 0; i--) {
    ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
    if (k) {
      ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
      if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
      if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
    }
    it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
    if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
    else if (typeof it !== "object" || it === null) __typeError("Object expected");
    else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
  }
  return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
var IPFilterService_exports = {};
__export(IPFilterService_exports, {
  IPFilterService: () => IPFilterService
});
module.exports = __toCommonJS(IPFilterService_exports);
var import_server = require("@tego/server");
var ipaddr = __toESM(require("ipaddr.js"));
var import_constants = require("../../constants");
var _logger_dec, _app_dec, _db_dec, _IPFilterService_decorators, _init;
_IPFilterService_decorators = [(0, import_server.Service)()], _db_dec = [(0, import_server.Db)()], _app_dec = [(0, import_server.App)()], _logger_dec = [(0, import_server.InjectLog)()];
class IPFilterService {
  constructor() {
    this.db = __runInitializers(_init, 8, this), __runInitializers(_init, 11, this);
    this.app = __runInitializers(_init, 12, this), __runInitializers(_init, 15, this);
    this.logger = __runInitializers(_init, 16, this), __runInitializers(_init, 19, this);
    // 缓存前缀
    this.CACHE_KEY = "ipFilter:config";
    // 缓存过期时间（毫秒）
    this.CACHE_TTL = 5 * 60 * 1e3;
    // 5分钟
    // 内存缓存
    this.config = {
      allowList: [],
      blockList: [],
      allowFirst: true,
      lastUpdated: /* @__PURE__ */ new Date(0)
      // 初始设置为过期
    };
  }
  async load() {
    this.addMiddleWare();
    this.setupIPFilterListener();
    this.app.on("afterStart", async () => {
      await this.initIPFilterConfig();
    });
  }
  /**
   * 初始化IP过滤器配置
   */
  async initIPFilterConfig() {
    try {
      const cachedConfig = await this.app.cache.get(this.CACHE_KEY);
      if (cachedConfig) {
        this.config = cachedConfig;
        this.logger.info("Loaded IP filter config from cache");
        return;
      }
      await this.loadConfigFromDBAtStart();
    } catch (error) {
      this.logger.error("Failed to initialize IP filter config:", error);
    }
  }
  async loadConfigFromDBAtStart() {
    try {
      const ipFilterRepo = this.db.getRepository("ipFilter");
      const ipFilter = await ipFilterRepo.findOne();
      if (ipFilter) {
        await this.loadConfigFromDB(ipFilter);
      } else {
        await this.createDefaultConfig();
      }
    } catch (error) {
      this.logger.error("Failed to init ip filter:", error);
    }
  }
  /**
   * 从数据库加载IP过滤器配置
   */
  async loadConfigFromDB(ipFilter) {
    try {
      const allowList = this.parseIPList(ipFilter.get("allowList") || "");
      const blockList = this.parseIPList(ipFilter.get("blockList") || "");
      const allowFirst = ipFilter.get("allowFirst") !== false;
      this.config = {
        allowList,
        blockList,
        allowFirst,
        lastUpdated: /* @__PURE__ */ new Date()
      };
      await this.app.cache.set(this.CACHE_KEY, this.config, this.CACHE_TTL);
      this.logger.info(`Loaded IP filter config: ${allowList.length} allowed, ${blockList.length} blocked`);
    } catch (error) {
      this.logger.error("Failed to load IP filter config from database:", error);
    }
  }
  /**
   * 创建默认配置
   */
  async createDefaultConfig() {
    try {
      const ipFilterRepo = this.db.getRepository("ipFilter");
      await ipFilterRepo.create({
        values: {
          allowList: "",
          blockList: "",
          allowFirst: true
        }
      });
      this.config = {
        allowList: [],
        blockList: [],
        allowFirst: true,
        lastUpdated: /* @__PURE__ */ new Date()
      };
      await this.app.cache.set(this.CACHE_KEY, this.config, this.CACHE_TTL);
      this.logger.info("Created default IP filter config");
    } catch (error) {
      this.logger.error("Failed to create default IP filter config:", error);
    }
  }
  /**
   * 解析IP列表文本为数组
   */
  parseIPList(ipListText) {
    if (!ipListText) return [];
    return ipListText.split("\n").map((ip) => ip.trim()).filter((ip) => ip && !ip.startsWith("#"));
  }
  /**
   * 设置监听ipFilter表变动的事件
   */
  setupIPFilterListener() {
    this.app.db.on("ipFilter.afterUpdate", async (model) => {
      await this.loadConfigFromDB(model);
      this.logger.info("IP filter config updated");
    });
  }
  /**
   * 添加IP过滤中间件
   */
  addMiddleWare() {
    this.app.resourcer.use(
      async (ctx, next) => {
        const clientIP = ctx.state.clientIp;
        const isAllowed = await this.isIPAllowed(clientIP);
        if (!isAllowed) {
          ctx.throw(403, ctx.t("Your IP address is not allowed to access this resource", { ns: import_constants.NAMESPACE }));
        }
        await next();
      },
      { tag: "ipFilterControl", before: "lockUserByPasswordPolicy" }
    );
  }
  /**
   * 检查IP是否被允许访问
   * @param ip 客户端IP地址
   * @returns 如果IP被允许访问，返回true；否则返回false
   */
  async isIPAllowed(ip) {
    try {
      const parsedIP = ipaddr.parse(ip);
      const inAllowList = this.isInList(parsedIP, this.config.allowList);
      const inBlockList = this.isInList(parsedIP, this.config.blockList);
      if (this.config.allowFirst) {
        return inAllowList || !inBlockList;
      } else {
        return !inBlockList && (inAllowList || this.config.allowList.length === 0);
      }
    } catch (error) {
      this.logger.error(`Error checking IP ${ip}:`, error);
      return true;
    }
  }
  /**
   * 检查IP是否在列表中
   * @param ip 解析后的IP地址
   * @param list IP地址列表
   * @returns 如果IP在列表中，返回true；否则返回false
   */
  isInList(ip, list) {
    for (const entry of list) {
      try {
        if (entry.includes("/")) {
          const cidr = ipaddr.parseCIDR(entry);
          if (ip.kind() === cidr[0].kind() && ip.match(cidr)) {
            return true;
          }
        } else {
          const listIP = ipaddr.parse(entry);
          if (ip.kind() === listIP.kind() && ip.toString() === listIP.toString()) {
            return true;
          }
        }
      } catch (error) {
        this.logger.error(`Invalid IP or CIDR in list: ${entry}`, error);
      }
    }
    return false;
  }
}
_init = __decoratorStart(null);
__decorateElement(_init, 5, "db", _db_dec, IPFilterService);
__decorateElement(_init, 5, "app", _app_dec, IPFilterService);
__decorateElement(_init, 5, "logger", _logger_dec, IPFilterService);
IPFilterService = __decorateElement(_init, 0, "IPFilterService", _IPFilterService_decorators, IPFilterService);
__runInitializers(_init, 1, IPFilterService);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  IPFilterService
});
