// services/api/test/password.spec.ts —— 密码哈希纯函数单测(Task 12 Part A)。 // 断言 @node-rs/argon2 语义:argon2id 编码格式($argon2... 开头)、正确口令验证 // 通过、错误口令拒绝、同口令两次哈希不同(随机盐)、空口令直接拒绝。 import { hashPassword, verifyPassword, } from '../src/auth/password'; describe('hashPassword / verifyPassword', () => { const plain = 'correct-horse-battery-staple'; it('returns an argon2 hash distinct from the plain text', async () => { const hashed = await hashPassword(plain); expect(typeof hashed).toBe('string'); expect(hashed.length).toBeGreaterThan(0); expect(hashed).not.toBe(plain); expect(hashed.startsWith('$argon2')).toBe(true); }); it('verifies the correct password', async () => { const hashed = await hashPassword(plain); await expect(verifyPassword(hashed, plain)).resolves.toBe(true); }); it('rejects a wrong password', async () => { const hashed = await hashPassword(plain); await expect(verifyPassword(hashed, 'wrong-password')).resolves.toBe(false); }); it('produces different hashes for the same password (random salt)', async () => { const [a, b] = await Promise.all([hashPassword(plain), hashPassword(plain)]); expect(a).not.toBe(b); // 且两条哈希都能通过校验(各自携带自己的盐)。 await expect(verifyPassword(a, plain)).resolves.toBe(true); await expect(verifyPassword(b, plain)).resolves.toBe(true); }); it('rejects an empty password (never hash empty strings)', async () => { await expect(hashPassword('')).rejects.toThrow(/empty/i); }); });