var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __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 PasswordStrengthService_exports = {};
__export(PasswordStrengthService_exports, {
  PasswordStrengthService: () => PasswordStrengthService
});
module.exports = __toCommonJS(PasswordStrengthService_exports);
var import_server = require("@tego/server");
var import_constants = require("../../constants");
var _logger_dec, _app_dec, _db_dec, _PasswordStrengthService_decorators, _init;
_PasswordStrengthService_decorators = [(0, import_server.Service)()], _db_dec = [(0, import_server.Db)()], _app_dec = [(0, import_server.App)()], _logger_dec = [(0, import_server.InjectLog)()];
class PasswordStrengthService {
  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;
  }
  async load() {
    this.addMiddleware();
    this.app.on("afterStart", async () => {
      const config = await this.db.getRepository("passwordStrengthConfig").findOne();
      await this.refreshConfig(config);
    });
    this.db.on("passwordStrengthConfig.afterSave", async (model) => {
      await this.refreshConfig(model);
    });
  }
  async refreshConfig(config) {
    this.config = {
      minLength: config == null ? void 0 : config.get("minLength"),
      strengthLevel: (config == null ? void 0 : config.get("strengthLevel")) || 0,
      notContainUsername: (config == null ? void 0 : config.get("notContainUsername")) || false,
      historyCount: (config == null ? void 0 : config.get("historyCount")) || 0
    };
    this.logger.info("Password strength configuration loaded:", this.config);
  }
  addMiddleware() {
    this.app.resourcer.use(
      async (ctx, next) => {
        var _a, _b, _c;
        const { resourceName, actionName } = ctx.action.params;
        if (resourceName === "users" && (actionName === "create" || actionName === "update")) {
          const values = ctx.action.params.values;
          if (values && values.password) {
            const username = values.username || await this.getUsernameById(ctx, values.id);
            await this.validatePasswordStrength(ctx, values.password, username);
            if (actionName === "update" && values.id && this.config.historyCount > 0) {
              await this.validatePasswordHistory(ctx, values.password, values.id);
            }
          }
        } else if (resourceName === "auth" && actionName === "signUp") {
          const { username, password } = ctx.action.params.values;
          await this.validatePasswordStrength(ctx, password, username);
        } else if (resourceName === "auth" && actionName === "changePassword") {
          const { newPassword } = ctx.action.params.values;
          await this.validatePasswordStrength(ctx, newPassword, (_a = ctx.state.currentUser) == null ? void 0 : _a.username);
          await this.validatePasswordHistory(ctx, newPassword, (_b = ctx.state.currentUser) == null ? void 0 : _b.id);
        }
        await next();
        if (resourceName === "users" && actionName === "update" && ctx.action.params.values.password || resourceName === "auth" && actionName === "changePassword") {
          const userId = ctx.action.params.values.id || ((_c = ctx.state.currentUser) == null ? void 0 : _c.id);
          const password = ctx.action.params.values.password || ctx.action.params.values.newPassword;
          if (userId && password && this.config.historyCount > 0) {
            await this.savePasswordHistory(userId, password);
          }
        }
      },
      {
        tag: "passwordStrengthValidator",
        after: "acl"
      }
    );
  }
  /**
   * 获取用户名通过ID
   */
  async getUsernameById(ctx, userId) {
    if (!userId) return null;
    try {
      const user = await this.db.getRepository("users").findOne({
        filterByTk: userId,
        fields: ["username"]
      });
      return (user == null ? void 0 : user.username) || null;
    } catch (error) {
      this.logger.error(`Failed to get username for user ${userId}:`, error);
      return null;
    }
  }
  /**
   * 验证密码强度
   */
  async validatePasswordStrength(ctx, password, username) {
    try {
      if (this.config.minLength && password.length < this.config.minLength) {
        ctx.throw(
          400,
          ctx.t("Password must be at least {{length}} characters long", {
            ns: import_constants.NAMESPACE,
            length: this.config.minLength
          })
        );
      }
      if (this.config.notContainUsername && username && password.toLowerCase().includes(username.toLowerCase())) {
        ctx.throw(400, ctx.t("Password cannot contain username", { ns: import_constants.NAMESPACE }));
      }
      if (this.config.strengthLevel > 0) {
        const hasLowerCase = /[a-z]/.test(password);
        const hasUpperCase = /[A-Z]/.test(password);
        const hasDigit = /\d/.test(password);
        const hasSymbol = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(password);
        switch (this.config.strengthLevel) {
          case 1:
            if (!(hasLowerCase || hasUpperCase) || !hasDigit) {
              ctx.throw(400, ctx.t("Password must contain both letters and numbers", { ns: import_constants.NAMESPACE }));
            }
            break;
          case 2:
            if (!(hasLowerCase || hasUpperCase) || !hasDigit || !hasSymbol) {
              ctx.throw(400, ctx.t("Password must contain letters, numbers, and symbols", { ns: import_constants.NAMESPACE }));
            }
            break;
          case 3:
            if (!hasLowerCase || !hasUpperCase || !hasDigit) {
              ctx.throw(
                400,
                ctx.t("Password must contain numbers, uppercase and lowercase letters", { ns: import_constants.NAMESPACE })
              );
            }
            break;
          case 4:
            if (!hasLowerCase || !hasUpperCase || !hasDigit || !hasSymbol) {
              ctx.throw(
                400,
                ctx.t("Password must contain numbers, uppercase and lowercase letters, and symbols", { ns: import_constants.NAMESPACE })
              );
            }
            break;
          case 5:
            const typesCount = [hasLowerCase, hasUpperCase, hasDigit, hasSymbol].filter(Boolean).length;
            if (typesCount < 3) {
              ctx.throw(
                400,
                ctx.t(
                  "Password must contain at least 3 of the following: numbers, uppercase letters, lowercase letters, and symbols",
                  { ns: import_constants.NAMESPACE }
                )
              );
            }
            break;
        }
      }
    } catch (error) {
      if (error.status === 400) {
        throw error;
      }
      this.logger.error("Failed to validate password strength:", error);
      ctx.throw(400, ctx.t("Failed to validate password strength", { ns: import_constants.NAMESPACE }));
    }
  }
  /**
   * 验证密码历史
   */
  async validatePasswordHistory(ctx, newPassword, userId) {
    if (this.config.historyCount <= 0) {
      return;
    }
    try {
      const passwordHistoryRepo = this.db.getRepository("passwordHistory");
      const historyRecords = await passwordHistoryRepo.find({
        filter: {
          userId
        },
        sort: ["-createdAt"],
        limit: this.config.historyCount
      });
      if (historyRecords.length === 0) {
        return;
      }
      const field = passwordHistoryRepo.collection.getField("password");
      for (const record of historyRecords) {
        const historyPassword = record.get("password");
        const isMatch = await field.verify(newPassword, historyPassword);
        if (isMatch) {
          ctx.throw(
            400,
            ctx.t("Password has been used recently. Please choose a different password.", { ns: import_constants.NAMESPACE })
          );
        }
      }
    } catch (error) {
      if (error.status === 400) {
        throw error;
      }
      this.logger.error(`Failed to validate password history for user ${userId}:`, error);
      ctx.throw(400, ctx.t("Failed to validate password history", { ns: import_constants.NAMESPACE }));
    }
  }
  /**
   * 保存密码历史
   */
  async savePasswordHistory(userId, password) {
    if (this.config.historyCount <= 0) {
      return;
    }
    try {
      const passwordHistoryRepo = this.db.getRepository("passwordHistory");
      await passwordHistoryRepo.create({
        values: {
          userId,
          password
        }
      });
      const count = await passwordHistoryRepo.count({
        filter: {
          userId
        }
      });
      if (count > this.config.historyCount) {
        const oldestRecords = await passwordHistoryRepo.find({
          filter: {
            userId
          },
          sort: ["createdAt"],
          limit: count - this.config.historyCount
        });
        if (oldestRecords.length > 0) {
          await passwordHistoryRepo.destroy({
            filter: {
              id: {
                $in: oldestRecords.map((record) => record.get("id"))
              }
            }
          });
        }
      }
      this.logger.info(`Saved password history for user ${userId}`);
    } catch (error) {
      this.logger.error(`Failed to save password history for user ${userId}:`, error);
    }
  }
}
_init = __decoratorStart(null);
__decorateElement(_init, 5, "db", _db_dec, PasswordStrengthService);
__decorateElement(_init, 5, "app", _app_dec, PasswordStrengthService);
__decorateElement(_init, 5, "logger", _logger_dec, PasswordStrengthService);
PasswordStrengthService = __decorateElement(_init, 0, "PasswordStrengthService", _PasswordStrengthService_decorators, PasswordStrengthService);
__runInitializers(_init, 1, PasswordStrengthService);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PasswordStrengthService
});
