Files
massive-cloud/server/auth.security.test.ts

33 lines
1.2 KiB
TypeScript

import { beforeEach, describe, expect, it } from "vitest";
import {
hashPassword,
isLoginRateLimited,
recordLoginFailure,
resetLoginRateLimitForTests,
verifyPassword,
} from "./_core/auth";
describe("本地密码认证", () => {
beforeEach(() => resetLoginRateLimitForTests());
it("使用带随机盐的 scrypt 哈希校验密码", async () => {
const first = await hashPassword("correct-password");
const second = await hashPassword("correct-password");
expect(first).toMatch(/^scrypt\$/);
expect(first).not.toBe(second);
await expect(verifyPassword("correct-password", first)).resolves.toBe(true);
await expect(verifyPassword("wrong-password", first)).resolves.toBe(false);
});
it("拒绝少于 8 位的密码", async () => {
await expect(hashPassword("short")).rejects.toThrow("至少需要 8 位");
});
it("分别按 IP 和用户名限制连续失败", () => {
for (let i = 0; i < 5; i += 1) recordLoginFailure("10.0.0.1", "alice");
expect(isLoginRateLimited("10.0.0.1", "another-user")).toBe(true);
expect(isLoginRateLimited("another-ip", "ALICE")).toBe(true);
expect(isLoginRateLimited("another-ip", "bob")).toBe(false);
});
});