2026-06-22 14:59:24 +08:00
|
|
|
// 用法: node scripts/hash-users.js
|
2026-06-22 15:20:20 +08:00
|
|
|
// 读取 users.json 中的明文密码,哈希后写回
|
2026-06-22 14:59:24 +08:00
|
|
|
|
|
|
|
|
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");
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-22 15:20:20 +08:00
|
|
|
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;
|
2026-06-22 14:59:24 +08:00
|
|
|
|
|
|
|
|
const salt = randomBytes(16).toString("hex");
|
2026-06-22 15:20:20 +08:00
|
|
|
const passwordHash = hashPassword(user.password, salt);
|
|
|
|
|
user.passwordHash = passwordHash;
|
|
|
|
|
user.salt = salt;
|
|
|
|
|
delete user.password;
|
|
|
|
|
changed = true;
|
|
|
|
|
}
|
2026-06-22 14:59:24 +08:00
|
|
|
|
2026-06-22 15:20:20 +08:00
|
|
|
if (changed) {
|
|
|
|
|
fs.writeFileSync(usersPath, JSON.stringify(data, null, 2) + "\n");
|
|
|
|
|
console.log("密码哈希完成");
|
|
|
|
|
} else {
|
|
|
|
|
console.log("所有密码已哈希,无需处理");
|
|
|
|
|
}
|