gen-account.mjs
1.03 KB
import { scrypt, randomBytes } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const here = path.dirname(fileURLToPath(import.meta.url));
const ACCOUNTS_PATH = path.resolve(here, '../data/accounts.json');
const [username, password] = process.argv.slice(2);
if (!username || !password) {
console.error('用法: pnpm --filter @hm/server gen:account <用户名> <密码>');
process.exit(1);
}
const salt = randomBytes(16);
const derived = scrypt(password, salt, 64).toString('hex');
const entry = { username, hash: `${salt.toString('hex')}:${derived}` };
const accounts = existsSync(ACCOUNTS_PATH)
? JSON.parse(readFileSync(ACCOUNTS_PATH, 'utf-8'))
: [];
const idx = accounts.findIndex((a) => a.username === username);
if (idx >= 0) accounts[idx] = entry;
else accounts.push(entry);
writeFileSync(ACCOUNTS_PATH, JSON.stringify(accounts, null, 2) + '\n', 'utf-8');
console.log(`已写入账号 "${username}" -> ${ACCOUNTS_PATH}`);