// 用法: node scripts/hash-users.js // 读取 users.json 中的明文密码,哈希后写回 const { createHash, randomBytes } = require("crypto"); const fs = require("fs"); const path = require("path"); function hashPassword(password, salt) { return createHash("sha256").update(salt + password).digest("hex"); } const usersPath = path.join(__dirname, "..", "users.json"); if (!fs.existsSync(usersPath)) { console.error("users.json 不存在"); process.exit(1); } const data = JSON.parse(fs.readFileSync(usersPath, "utf-8")); const users = data.users || []; let changed = false; for (const user of users) { // 已经哈希过的跳过 if (user.passwordHash && user.salt) continue; // 没有明文密码的跳过 if (!user.password) continue; const salt = randomBytes(16).toString("hex"); const passwordHash = hashPassword(user.password, salt); user.passwordHash = passwordHash; user.salt = salt; delete user.password; changed = true; } if (changed) { fs.writeFileSync(usersPath, JSON.stringify(data, null, 2) + "\n"); console.log("密码哈希完成"); } else { console.log("所有密码已哈希,无需处理"); }