完善了安全功能

This commit is contained in:
lik
2026-06-12 15:24:20 +08:00
parent fba44ca015
commit ddcf200de2
12 changed files with 904 additions and 207 deletions

51
test/crypto.test.js Normal file
View File

@@ -0,0 +1,51 @@
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);
});
});