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 PasswordPolicyService_exports = {};
__export(PasswordPolicyService_exports, {
  PasswordPolicyService: () => PasswordPolicyService
});
module.exports = __toCommonJS(PasswordPolicyService_exports);
var import_server = require("@tego/server");
var geoip = __toESM(require("geoip-lite"));
var import_constants = require("../../constants");
var _logger_dec, _app_dec, _db_dec, _PasswordPolicyService_decorators, _init;
_PasswordPolicyService_decorators = [(0, import_server.Service)()], _db_dec = [(0, import_server.Db)()], _app_dec = [(0, import_server.App)()], _logger_dec = [(0, import_server.InjectLog)()];
class PasswordPolicyService {
  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.config = void 0;
    // 内存缓存，用于存储最近的失败记录
    this.failureRecords = /* @__PURE__ */ new Map();
    // 缓存前缀
    this.CACHE_PREFIX = import_constants.COLLECTION_PASSWORD_POLICY;
    // 缓存过期时间（毫秒）
    this.CACHE_TTL = 5 * 60 * 1e3;
  }
  // 5分钟
  async load() {
    this.addMiddleWare();
    this.app.on("afterStart", async () => {
      const config = await this.db.getRepository(import_constants.COLLECTION_PASSWORD_POLICY).findOne();
      await this.refreshConfig(config);
      await this.initLockedUsersCache();
      this.setupLockedUsersListener();
    });
    this.db.on(`${import_constants.COLLECTION_PASSWORD_POLICY}.afterSave`, async (model) => {
      await this.refreshConfig(model);
    });
  }
  /**
   * 获取用户锁定信息的缓存键
   * @param userId 用户ID
   * @returns 缓存键
   */
  getUserLockCacheKey(userId) {
    return `${this.CACHE_PREFIX}:locked:${userId}`;
  }
  /**
   * 初始化被锁定用户的缓存
   */
  async initLockedUsersCache() {
    try {
      const now = /* @__PURE__ */ new Date();
      const lockedUsersRepo = this.db.getRepository("userLocks");
      const lockedUsers = await lockedUsersRepo.find({
        filter: {
          expireAt: {
            $gt: now
          }
        }
      });
      for (const user of lockedUsers) {
        const userId = user.get("userId");
        const expireAt = user.get("expireAt");
        await this.app.cache.set(
          this.getUserLockCacheKey(userId),
          {
            id: userId,
            expireAt,
            lastChecked: now
          },
          this.CACHE_TTL
        );
      }
      this.logger.info(`Loaded ${lockedUsers.length} locked users into cache`);
    } catch (error) {
      this.logger.error("Failed to load locked users into cache:", error);
    }
  }
  /**
   * 设置监听userLocks表变动的事件
   */
  setupLockedUsersListener() {
    this.app.db.on("userLocks.afterCreate", async (model) => {
      const userId = model.get("userId");
      const expireAt = model.get("expireAt");
      await this.app.cache.set(
        this.getUserLockCacheKey(userId),
        {
          id: userId,
          expireAt,
          lastChecked: /* @__PURE__ */ new Date()
        },
        this.CACHE_TTL
      );
      this.logger.info(`Added user ${userId} to locked users cache`);
    });
    this.app.db.on("userLocks.afterUpdate", async (model) => {
      const userId = model.get("userId");
      if (!userId && model.previous("userId")) {
        const userId2 = model.previous("userId");
        await this.app.cache.del(this.getUserLockCacheKey(userId2));
        await this.clearUserFailRecords(userId2);
        this.logger.info(`Removed user ${userId2} from locked users cache (deleted)`);
        return;
      }
      const expireAt = model.get("expireAt");
      const now = /* @__PURE__ */ new Date();
      if (expireAt > now) {
        await this.app.cache.set(
          this.getUserLockCacheKey(userId),
          {
            id: userId,
            expireAt,
            lastChecked: now
          },
          this.CACHE_TTL
        );
        this.logger.info(`Updated user ${userId} in locked users cache`);
      } else {
        await this.app.cache.del(this.getUserLockCacheKey(userId));
        await this.clearUserFailRecords(userId);
        this.logger.info(`Removed user ${userId} from locked users cache (expired)`);
      }
    });
    this.app.db.on("userLocks.afterDestroy", async (model) => {
      const userId = model.get("userId");
      await this.app.cache.del(this.getUserLockCacheKey(userId));
      await this.clearUserFailRecords(userId);
      this.logger.info(`Removed user ${userId} from locked users cache (deleted)`);
    });
  }
  /**
   * 清空用户的登录失败记录
   * @param userId 用户ID
   */
  async clearUserFailRecords(userId) {
    try {
      await this.db.getRepository("signInFails").update({
        filter: {
          userId
        },
        values: {
          status: false
        }
      });
      this.failureRecords.delete(userId);
      this.logger.info(`Cleared sign-in failure records for user ${userId}`);
    } catch (error) {
      this.logger.error(`Failed to clear sign-in failure records for user ${userId}:`, error);
    }
  }
  /**
   * 检查用户是否被锁定
   * @param userId 用户ID
   * @returns 如果用户被锁定，返回true；否则返回false
   */
  async isUserLocked(userId) {
    const now = /* @__PURE__ */ new Date();
    const cacheKey = this.getUserLockCacheKey(userId);
    const cachedInfo = await this.app.cache.get(cacheKey);
    if (cachedInfo) {
      const isCacheExpired = now.getTime() - cachedInfo.lastChecked.getTime() > this.CACHE_TTL;
      if (isCacheExpired) {
        this.refreshLockedUserCache(userId);
      }
      if (!cachedInfo.expireAt) {
        return false;
      }
      if (cachedInfo.expireAt > now) {
        return true;
      } else {
        cachedInfo.expireAt = null;
        cachedInfo.lastChecked = now;
        await this.app.cache.set(cacheKey, cachedInfo, this.CACHE_TTL);
        await this.clearUserFailRecords(userId);
        return false;
      }
    }
    return await this.checkAndCacheLockedUser(userId);
  }
  /**
   * 从数据库检查并缓存用户锁定状态
   * @param userId 用户ID
   * @returns 如果用户被锁定，返回true；否则返回false
   */
  async checkAndCacheLockedUser(userId) {
    var _a;
    try {
      const now = /* @__PURE__ */ new Date();
      const userRepository = this.db.getRepository("users");
      const user = await userRepository.findOne({
        fields: ["id"],
        filter: { id: userId },
        appends: ["lock"]
      });
      const cacheKey = this.getUserLockCacheKey(userId);
      if (user && ((_a = user.lock) == null ? void 0 : _a.expireAt) && user.lock.expireAt > now) {
        await this.app.cache.set(
          cacheKey,
          {
            id: userId,
            expireAt: user.lock.expireAt,
            lastChecked: now
          },
          this.CACHE_TTL
        );
        return true;
      } else {
        await this.app.cache.set(
          cacheKey,
          {
            id: userId,
            expireAt: null,
            // null表示未被锁定
            lastChecked: now
          },
          this.CACHE_TTL
        );
        return false;
      }
    } catch (error) {
      this.logger.error(`Error checking locked status for user ${userId}:`, error);
      return false;
    }
  }
  /**
   * 在后台刷新用户锁定缓存
   * @param userId 用户ID
   */
  async refreshLockedUserCache(userId) {
    var _a;
    try {
      const now = /* @__PURE__ */ new Date();
      const userRepository = this.db.getRepository("users");
      const user = await userRepository.findOne({
        fields: ["id"],
        filter: { id: userId },
        appends: ["lock"]
      });
      const cacheKey = this.getUserLockCacheKey(userId);
      if (user && ((_a = user.lock) == null ? void 0 : _a.expireAt) && user.lock.expireAt > now) {
        await this.app.cache.set(
          cacheKey,
          {
            id: userId,
            expireAt: user.lock.expireAt,
            lastChecked: now
          },
          this.CACHE_TTL
        );
      } else {
        const existingInfo = await this.app.cache.get(cacheKey);
        if (existingInfo) {
          existingInfo.expireAt = null;
          existingInfo.lastChecked = now;
          await this.app.cache.set(cacheKey, existingInfo, this.CACHE_TTL);
        } else {
          await this.app.cache.set(
            cacheKey,
            {
              id: userId,
              expireAt: null,
              lastChecked: now
            },
            this.CACHE_TTL
          );
        }
      }
    } catch (error) {
      this.logger.error(`Error refreshing locked cache for user ${userId}:`, error);
    }
  }
  async refreshConfig(config) {
    this.config = {
      windowSeconds: (config == null ? void 0 : config.get("windowSeconds")) || import_constants.WINDOW_SECONDS,
      // 默认5分钟
      maxAttempts: (config == null ? void 0 : config.get("maxAttempts")) ?? 0,
      // 默认0，表示不启用防护
      lockSeconds: (config == null ? void 0 : config.get("lockSeconds")) || import_constants.LOCK_SECONDS,
      // 默认30分钟
      strictLock: (config == null ? void 0 : config.get("strictLock")) || false
      // 锁定时候禁止任意api
    };
    if (this.config.maxAttempts > 0) {
      await this.loadRecentRecords();
    } else {
      this.logger.info("Sign-in failure protection is disabled (maxAttempts = 0)");
    }
  }
  addMiddleWare() {
    this.app.resourcer.use(
      async (ctx, next) => {
        var _a;
        const { resourceName, actionName } = ctx.action.params;
        if (resourceName === "auth" && actionName === "signIn") {
          const { account, password, email } = ctx.action.params.values;
          if (account && password) {
            const filter = email ? { email } : {
              $or: [{ username: account }, { email: account }]
            };
            const userRepository = ctx.db.getRepository("users");
            const user = await userRepository.findOne({
              fields: ["id", "password"],
              filter,
              appends: ["lock"]
            });
            if (user) {
              if (((_a = user.lock) == null ? void 0 : _a.expireAt) && user.lock.expireAt > /* @__PURE__ */ new Date()) {
                ctx.throw(403, ctx.t("User has been locked", { ns: import_constants.NAMESPACE }));
              }
              const field = userRepository.collection.getField("password");
              const valid = await field.verify(password, user.password);
              if (!valid) {
                await this.recordFailedAttempt(user, ctx.state.clientIp);
              } else {
                await this.resetFailedAttempts(user.id);
              }
            }
          }
        }
        await next();
      },
      {
        tag: "lockUserByPasswordPolicy",
        before: "auth"
      }
    );
    this.app.resourcer.use(
      async (ctx, next) => {
        var _a;
        if (((_a = this.config) == null ? void 0 : _a.strictLock) && ctx.state.currentUser) {
          const userId = ctx.state.currentUser.id;
          const isLocked = await this.isUserLocked(userId);
          if (isLocked) {
            ctx.throw(403, ctx.t("User has been locked", { ns: import_constants.NAMESPACE }));
          }
        }
        await next();
      },
      { tag: "lockAllResource", after: "auth", before: "acl" }
    );
  }
  /**
   * 从数据库加载最近的失败记录到内存
   */
  async loadRecentRecords() {
    try {
      const cutoffTime = /* @__PURE__ */ new Date();
      cutoffTime.setSeconds(cutoffTime.getSeconds() - Math.max(this.config.windowSeconds, this.config.lockSeconds));
      const records = await this.db.getRepository("signInFails").find({
        filter: {
          createdAt: {
            $gt: cutoffTime
          },
          status: true
        }
      });
      this.failureRecords.clear();
      records.forEach((record) => {
        const userId = record.get("userId");
        const createdAt = record.get("createdAt");
        const userRecords = this.failureRecords.get(userId) || [];
        userRecords.push({ userId, createdAt });
        this.failureRecords.set(userId, userRecords);
      });
      this.logger.info(`Loaded ${records.length} recent sign-in failure records into cache`);
    } catch (error) {
      this.logger.error("Failed to load recent sign-in failure records:", error);
    }
  }
  /**
   * 获取IP地址的地理位置信息
   * @param ip IP地址
   * @returns 地理位置信息
   */
  getGeoLocation(ip) {
    try {
      if (!ip || ip === "127.0.0.1" || ip === "localhost" || ip.startsWith("192.168.") || ip.startsWith("10.")) {
        return { country: "Local", region: "Local", city: "Local" };
      }
      const geo = geoip.lookup(ip);
      if (!geo) {
        return {};
      }
      return {
        country: geo.country,
        region: geo.region,
        city: geo.city
      };
    } catch (error) {
      this.logger.error(`Failed to get geo location for IP ${ip}:`, error);
      return {};
    }
  }
  /**
   * 记录登录失败
   * @param username 用户名
   */
  async recordFailedAttempt(user, ip) {
    var _a, _b;
    try {
      const now = /* @__PURE__ */ new Date();
      if (this.config.maxAttempts === 0) {
        await this.recordFailedAttemptToDb(user, ip, now, false);
        return;
      }
      if (((_a = user.lock) == null ? void 0 : _a.expireAt) && now > user.lock.expireAt) {
        await this.resetFailedAttempts(user.id);
      } else if (this.getRecentFailureCount(user.id) + 1 >= this.config.maxAttempts) {
        if (!((_b = user.lock) == null ? void 0 : _b.expireAt) || now > user.lock.expireAt) {
          const lockExpireAt = new Date(now);
          lockExpireAt.setSeconds(lockExpireAt.getSeconds() + this.config.lockSeconds);
          await this.db.sequelize.transaction(async (transaction) => {
            const existOne = await this.db.getRepository("userLocks").findOne({
              filter: {
                userId: user.id
              },
              transaction
            });
            if (existOne) {
              await existOne.update(
                {
                  expireAt: lockExpireAt
                },
                {
                  transaction
                }
              );
            } else {
              await this.db.getRepository("userLocks").create({
                values: {
                  userId: user.id,
                  expireAt: lockExpireAt
                },
                transaction
              });
            }
          });
          await this.app.cache.set(
            this.getUserLockCacheKey(user.id),
            {
              id: user.id,
              expireAt: lockExpireAt,
              lastChecked: now
            },
            this.CACHE_TTL
          );
        }
      }
      const record = await this.recordFailedAttemptToDb(user, ip, now, true);
      if (this.failureRecords.get(user.id)) {
        this.failureRecords.get(user.id).push({
          userId: user.id,
          createdAt: record.get("createdAt")
        });
      } else {
        this.failureRecords.set(user.id, [
          {
            userId: user.id,
            createdAt: record.get("createdAt")
          }
        ]);
      }
    } catch (error) {
      this.logger.error("Failed to record sign-in failure:", error);
      throw error;
    }
  }
  async recordFailedAttemptToDb(user, ip, now, recordUser = false) {
    let geoLocation = {};
    if (ip) {
      geoLocation = this.getGeoLocation(ip);
    }
    const address = `${geoLocation.country || ""} ${geoLocation.region || ""} ${geoLocation.city || ""}`.trim();
    return this.db.getRepository("signInFails").create({
      values: {
        userId: user.id,
        status: recordUser,
        ip,
        address,
        createdAt: now
      }
    });
  }
  /**
   * 获取最近的失败次数（从内存缓存中获取）
   */
  getRecentFailureCount(userId) {
    if (this.config.maxAttempts === 0) {
      return 0;
    }
    const userRecords = this.failureRecords.get(userId) || [];
    const windowStart = /* @__PURE__ */ new Date();
    windowStart.setSeconds(windowStart.getSeconds() - this.config.windowSeconds);
    return userRecords.filter((record) => record.createdAt > windowStart).length;
  }
  /**
   * 重置用户的失败记录
   * @param username 用户名
   */
  async resetFailedAttempts(userId) {
    if (this.config.maxAttempts === 0) {
      return;
    }
    try {
      await this.db.getRepository("userLocks").destroy({
        filter: {
          userId
        }
      });
      this.logger.info(`Reset sign-in failure records for user ${userId}`);
    } catch (error) {
      this.logger.error(`Failed to reset sign-in failure records for user ${userId}:`, error);
      throw error;
    }
  }
}
_init = __decoratorStart(null);
__decorateElement(_init, 5, "db", _db_dec, PasswordPolicyService);
__decorateElement(_init, 5, "app", _app_dec, PasswordPolicyService);
__decorateElement(_init, 5, "logger", _logger_dec, PasswordPolicyService);
PasswordPolicyService = __decorateElement(_init, 0, "PasswordPolicyService", _PasswordPolicyService_decorators, PasswordPolicyService);
__runInitializers(_init, 1, PasswordPolicyService);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PasswordPolicyService
});
