52 lines
1.8 KiB
JavaScript
52 lines
1.8 KiB
JavaScript
import { describe, it, before, after } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { hashPassword, verifyPassword } from '../utils/crypto.js';
|
|
|
|
describe('crypto 工具', () => {
|
|
it('bcrypt 加密后验证应通过', async () => {
|
|
const passwd = 'test123456';
|
|
const hash = await hashPassword(passwd);
|
|
assert.ok(hash.startsWith('$2'), 'bcrypt hash 应以 $2 开头');
|
|
|
|
const { valid, needsUpgrade } = await verifyPassword(passwd, hash, '');
|
|
assert.equal(valid, true);
|
|
assert.equal(needsUpgrade, false);
|
|
});
|
|
|
|
it('错误密码验证应失败', async () => {
|
|
const hash = await hashPassword('correct');
|
|
const { valid } = await verifyPassword('wrong', hash, '');
|
|
assert.equal(valid, false);
|
|
});
|
|
|
|
it('兼容旧 MD5 密码验证', async () => {
|
|
const passwd = 'mypass';
|
|
const salt = 'abc123';
|
|
const crypto = await import('crypto');
|
|
const md5Hash = crypto.createHash('md5').update(passwd + salt).digest('hex');
|
|
|
|
const { valid, needsUpgrade } = await verifyPassword(passwd, md5Hash, salt);
|
|
assert.equal(valid, true);
|
|
assert.equal(needsUpgrade, true, 'MD5 密码应标记为需要升级');
|
|
});
|
|
|
|
it('MD5 密码错误时应返回 false', async () => {
|
|
const salt = 'abc123';
|
|
const crypto = await import('crypto');
|
|
const md5Hash = crypto.createHash('md5').update('correct' + salt).digest('hex');
|
|
|
|
const { valid } = await verifyPassword('wrong', md5Hash, salt);
|
|
assert.equal(valid, false);
|
|
});
|
|
|
|
it('空 salt 时 MD5 也能验证', async () => {
|
|
const passwd = 'test';
|
|
const crypto = await import('crypto');
|
|
const md5Hash = crypto.createHash('md5').update(passwd + '').digest('hex');
|
|
|
|
const { valid, needsUpgrade } = await verifyPassword(passwd, md5Hash, '');
|
|
assert.equal(valid, true);
|
|
assert.equal(needsUpgrade, true);
|
|
});
|
|
});
|