import { describe, it, expect, vi, beforeAll } from 'vitest' /** * 后台管理员认证单测: * - hashPassword / verifyPassword:scrypt 哈希与校验(格式 scrypt$N$r$p$salt$hash) * - 异常/非法存储串一律校验失败,防绕过 */ vi.mock('../server/utils/db', () => ({ getDb: vi.fn(() => { throw new Error('db not used in these tests') }), })) vi.mock('h3', () => ({ createError: (o: unknown) => o, getCookie: () => null, setCookie: () => {}, deleteCookie: () => {}, })) import { hashPassword, verifyPassword } from '../server/utils/adminAuth' describe('admin password hashing', () => { it('hashes and verifies a correct password', () => { const hash = hashPassword('correct horse battery staple') expect(hash.startsWith('scrypt$')).toBe(true) expect(verifyPassword('correct horse battery staple', hash)).toBe(true) }) it('rejects a wrong password', () => { const hash = hashPassword('right-password') expect(verifyPassword('wrong-password', hash)).toBe(false) }) it('produces unique salts (same password, different hashes)', () => { const a = hashPassword('same-pass') const b = hashPassword('same-pass') expect(a).not.toBe(b) expect(verifyPassword('same-pass', a)).toBe(true) expect(verifyPassword('same-pass', b)).toBe(true) }) it('rejects malformed / foreign stored values', () => { expect(verifyPassword('x', '')).toBe(false) expect(verifyPassword('x', 'plaintext')).toBe(false) expect(verifyPassword('x', 'bcrypt$abcdef')).toBe(false) expect(verifyPassword('x', 'scrypt$16384$8$1$salt$nothex')).toBe(false) }) })