Files
pdnode-account/test-rate-limit.js
Bret 9262ef4076 支持速率限制
然后把oauth单独放一个页面
一些UI调整
2025-07-30 12:19:38 -07:00

133 lines
3.0 KiB
JavaScript

const axios = require('axios');
const BASE_URL = 'http://localhost:3000';
// 测试速率限制的函数
async function testRateLimit(endpoint, method = 'GET', data = null, description) {
console.log(`\n测试 ${description} 的速率限制...`);
try {
const config = {
method,
url: `${BASE_URL}${endpoint}`,
headers: {
'Content-Type': 'application/json'
}
};
if (data) {
config.data = data;
}
const response = await axios(config);
console.log(`✅ 请求成功: ${response.status}`);
return true;
} catch (error) {
if (error.response?.status === 429) {
console.log(`⏰ 速率限制触发: ${error.response.data.message}`);
return false;
} else {
console.log(`❌ 请求失败: ${error.response?.data?.message || error.message}`);
return false;
}
}
}
// 测试登录速率限制
async function testLoginRateLimit() {
console.log('\n=== 测试登录速率限制 ===');
for (let i = 1; i <= 7; i++) {
const success = await testRateLimit(
'/api/auth/login',
'POST',
{
username: `testuser${i}`,
password: 'testpass123'
},
`登录尝试 ${i}`
);
if (!success) {
console.log('✅ 登录速率限制正常工作');
break;
}
if (i === 6) {
console.log('⚠️ 登录速率限制可能未生效');
}
}
}
// 测试OAuth授权速率限制
async function testOAuthRateLimit() {
console.log('\n=== 测试OAuth授权速率限制 ===');
for (let i = 1; i <= 5; i++) {
const success = await testRateLimit(
'/api/oauth/authorize?response_type=code&client_id=test&redirect_uri=http://localhost:3000/callback&scope=read&state=test',
'GET',
null,
`OAuth授权请求 ${i}`
);
if (!success) {
console.log('✅ OAuth授权速率限制正常工作');
break;
}
if (i === 4) {
console.log('⚠️ OAuth授权速率限制可能未生效');
}
}
}
// 测试通用速率限制
async function testGeneralRateLimit() {
console.log('\n=== 测试通用速率限制 ===');
for (let i = 1; i <= 105; i++) {
const success = await testRateLimit(
'/health',
'GET',
null,
`健康检查请求 ${i}`
);
if (!success) {
console.log('✅ 通用速率限制正常工作');
break;
}
if (i === 101) {
console.log('⚠️ 通用速率限制可能未生效');
}
}
}
// 主测试函数
async function runTests() {
console.log('🚀 开始测试速率限制功能...');
try {
await testGeneralRateLimit();
await testLoginRateLimit();
await testOAuthRateLimit();
console.log('\n✅ 速率限制测试完成');
} catch (error) {
console.error('❌ 测试过程中发生错误:', error.message);
}
}
// 运行测试
if (require.main === module) {
runTests();
}
module.exports = {
testRateLimit,
testLoginRateLimit,
testOAuthRateLimit,
testGeneralRateLimit
};