auth.ts 1.36 KB
import { scryptSync, timingSafeEqual } from 'node:crypto';
import { existsSync, readFileSync } 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');

export interface Account {
  username: string;
  /** scrypt 哈希,格式 `salt(hex):derived(hex)`,salt 16 字节 / derived 64 字节 */
  hash: string;
}

function splitHash(stored: string): { salt: Buffer; derived: Buffer } {
  const [saltHex, derivedHex] = stored.split(':');
  if (!saltHex || !derivedHex) throw new Error('账号哈希格式非法');
  return { salt: Buffer.from(saltHex, 'hex'), derived: Buffer.from(derivedHex, 'hex') };
}

/** 用账号里存的 salt 对输入密码做 scrypt,timingSafeEqual 防时序侧信道 */
export function verifyPassword(password: string, stored: string): boolean {
  const { salt, derived } = splitHash(stored);
  const tryDerived = scryptSync(password, salt, derived.length);
  return timingSafeEqual(derived, tryDerived);
}

export function loadAccounts(): Account[] {
  if (!existsSync(ACCOUNTS_PATH)) return [];
  return JSON.parse(readFileSync(ACCOUNTS_PATH, 'utf-8')) as Account[];
}

export function findAccount(username: string): Account | undefined {
  return loadAccounts().find((a) => a.username === username);
}