add-account.mjs 2.98 KB
// 交互式添加/更新账号。密码读入不回显,避免明文进 shell 历史 / 进程列表。
// 用法:  pnpm --filter @hm/server add:account [用户名]
//   省略用户名则交互询问;密码一律交互输入(不回显)。
import { scryptSync, randomBytes } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync, renameSync, mkdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { createInterface } from 'node:readline/promises';
import { stdin, stdout } from 'node:process';

const here = path.dirname(fileURLToPath(import.meta.url));
const ACCOUNTS_PATH = path.resolve(here, '../data/accounts.json');

/** 读一行(非 TTY 时按行读,便于管道测试) */
async function ask(prompt) {
  const rl = createInterface({ input: stdin, output: stdout });
  const ans = (await rl.question(prompt)).trim();
  rl.close();
  return ans;
}

/** 不回显读密码(TTY 走 raw mode;管道/非 TTY 降级为读一行) */
function askHidden(prompt) {
  return new Promise((resolve) => {
    if (!stdin.isTTY) {
      const rl = createInterface({ input: stdin });
      rl.once('line', (line) => {
        rl.close();
        stdout.write('\n');
        resolve(line);
      });
      stdout.write(prompt);
      return;
    }
    stdout.write(prompt);
    stdin.setRawMode(true);
    stdin.resume();
    let buf = '';
    const onData = (d) => {
      const s = d.toString();
      if (s === '\r' || s === '\n') {
        stdin.setRawMode(false);
        stdin.pause();
        stdin.removeListener('data', onData);
        stdout.write('\n');
        resolve(buf);
      } else if (s === '\u0003') {
        // Ctrl-C
        stdout.write('\n');
        process.exit(1);
      } else if (s === '\u007f' || s === '\b') {
        buf = buf.slice(0, -1);
      } else if (s >= ' ') {
        buf += s;
      }
    };
    stdin.on('data', onData);
  });
}

const argUser = process.argv[2];
const username = argUser ?? (await ask('用户名: '));
if (!username) {
  console.error('用户名不能为空');
  process.exit(1);
}

const password = await askHidden('密码: ');
if (!password) {
  console.error('密码不能为空');
  process.exit(1);
}

mkdirSync(path.dirname(ACCOUNTS_PATH), { recursive: true });
const accounts = existsSync(ACCOUNTS_PATH)
  ? JSON.parse(readFileSync(ACCOUNTS_PATH, 'utf-8'))
  : [];

const salt = randomBytes(16);
const derived = scryptSync(password, salt, 64).toString('hex');
const entry = { username, hash: `${salt.toString('hex')}:${derived}` };

const idx = accounts.findIndex((a) => a.username === username);
const mode = idx >= 0 ? '更新' : '新增';
if (idx >= 0) accounts[idx] = entry;
else accounts.push(entry);

// 原子写:先写临时文件再 rename,避免写到一半进程退出损坏数据
const tmp = ACCOUNTS_PATH + '.tmp';
writeFileSync(tmp, JSON.stringify(accounts, null, 2) + '\n', 'utf-8');
renameSync(tmp, ACCOUNTS_PATH);

console.log(`${mode}账号 "${username}" 成功 -> ${ACCOUNTS_PATH}`);