test-api-403.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // 测试不同 headers 组合找出 403 的原因(本地调试:API_KEY=xxx node scripts/dev/test-api-403.js)
  2. const API_KEY = process.env.API_KEY ?? "";
  3. const BASE_URL = process.env.BASE_URL ?? "https://hub.linux.do/v1";
  4. if (!API_KEY) {
  5. console.error("请设置环境变量 API_KEY");
  6. process.exit(1);
  7. }
  8. async function testWithHeaders(testName, headers) {
  9. console.log(`\n=== ${testName} ===`);
  10. const url = `${BASE_URL}/models`;
  11. try {
  12. const response = await fetch(url, {
  13. method: "GET",
  14. headers: headers
  15. });
  16. console.log(`状态码: ${response.status} ${response.statusText}`);
  17. if (response.status === 403) {
  18. const text = await response.text();
  19. console.log(`403 响应: ${text.substring(0, 200)}`);
  20. } else if (response.ok) {
  21. console.log("✅ 成功");
  22. }
  23. return response.status;
  24. } catch (error) {
  25. console.error(`❌ 错误: ${error.message}`);
  26. return -1;
  27. }
  28. }
  29. async function runTests() {
  30. // 测试 1: 只有 Authorization
  31. await testWithHeaders("测试1: 只有 Authorization", {
  32. "Authorization": `Bearer ${API_KEY}`
  33. });
  34. // 测试 2: Authorization + Content-Type
  35. await testWithHeaders("测试2: Authorization + Content-Type", {
  36. "Authorization": `Bearer ${API_KEY}`,
  37. "Content-Type": "application/json"
  38. });
  39. // 测试 3: Authorization + Origin: 空字符串 (模拟软件中的行为)
  40. await testWithHeaders("测试3: Authorization + Origin: 空", {
  41. "Authorization": `Bearer ${API_KEY}`,
  42. "Origin": ""
  43. });
  44. // 测试 4: Authorization + Origin: http://localhost
  45. await testWithHeaders("测试4: Authorization + Origin: localhost", {
  46. "Authorization": `Bearer ${API_KEY}`,
  47. "Origin": "http://localhost"
  48. });
  49. // 测试 5: Authorization + Content-Type + Origin: 空
  50. await testWithHeaders("测试5: Authorization + Content-Type + Origin: 空", {
  51. "Authorization": `Bearer ${API_KEY}`,
  52. "Content-Type": "application/json",
  53. "Origin": ""
  54. });
  55. // 测试 6: 模拟软件 withCustomOriginHeader 的输出
  56. await testWithHeaders("测试6: 模拟软件的 headers (非本地端点)", {
  57. "Content-Type": "application/json",
  58. "Authorization": `Bearer ${API_KEY}`,
  59. "Origin": "" // 这是软件中对非本地端点设置的
  60. });
  61. // 测试 7: 不设置 Origin
  62. await testWithHeaders("测试7: 不设置 Origin", {
  63. "Content-Type": "application/json",
  64. "Authorization": `Bearer ${API_KEY}`
  65. });
  66. // 测试 8: 删除 Content-Type
  67. await testWithHeaders("测试8: 只有 Authorization + 兼容 headers", {
  68. "Authorization": `Bearer ${API_KEY}`,
  69. "Accept": "application/json",
  70. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) QMaiWrite"
  71. });
  72. }
  73. runTests();