server.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. import express from 'express';
  2. import cors from 'cors';
  3. import axios from 'axios';
  4. import nodeRSA from 'node-rsa';
  5. import cookieParser from 'cookie-parser';
  6. import { readFileSync } from 'fs';
  7. import { fileURLToPath } from 'url';
  8. import { dirname, join } from 'path';
  9. import { CookieJar } from 'tough-cookie';
  10. import { wrapper } from 'axios-cookiejar-support';
  11. // node-rsa 是 CommonJS 模块,需要使用默认导入
  12. const NodeRSA = nodeRSA;
  13. const __filename = fileURLToPath(import.meta.url);
  14. const __dirname = dirname(__filename);
  15. const app = express();
  16. const PORT = process.env.PORT || 8889;
  17. // 中间件
  18. app.use(cors({
  19. origin: true,
  20. credentials: true
  21. }));
  22. app.use(express.json());
  23. app.use(express.urlencoded({ extended: true }));
  24. app.use(cookieParser());
  25. // 请求日志中间件(用于调试)
  26. app.use((req, res, next) => {
  27. console.log(`[请求] ${req.method} ${req.path} - ${new Date().toISOString()}`);
  28. next();
  29. });
  30. // 加载自动登录配置
  31. let autoLoginConfig = {};
  32. try {
  33. const configPath = join(__dirname, 'auto-login-config.json');
  34. console.log('正在加载自动登录配置文件:', configPath);
  35. const configData = readFileSync(configPath, 'utf-8');
  36. autoLoginConfig = JSON.parse(configData);
  37. console.log('✓ 已加载自动登录配置');
  38. console.log(' 配置的网站数量:', Object.keys(autoLoginConfig).length);
  39. console.log(' 网站列表:', Object.keys(autoLoginConfig).join(', '));
  40. Object.keys(autoLoginConfig).forEach(siteId => {
  41. const site = autoLoginConfig[siteId];
  42. console.log(` - ${siteId}: ${site.name} (${site.loginMethod})`);
  43. });
  44. } catch (error) {
  45. console.error('✗ 加载自动登录配置失败:', error.message);
  46. console.error(' 错误堆栈:', error.stack);
  47. console.log('将使用默认配置');
  48. }
  49. // RSA 加密函数
  50. // 注意:JSEncrypt 使用 PKCS1 填充,需要匹配
  51. function encryptWithRSA(text, publicKey) {
  52. try {
  53. const key = new NodeRSA(publicKey, 'public', {
  54. encryptionScheme: 'pkcs1' // 使用 PKCS1 填充,与 JSEncrypt 兼容
  55. });
  56. const encrypted = key.encrypt(text, 'base64');
  57. console.log(`RSA加密: "${text}" -> 长度 ${encrypted.length}`);
  58. return encrypted;
  59. } catch (error) {
  60. console.error('RSA加密失败:', error.message);
  61. throw error;
  62. }
  63. }
  64. // 解析 Cookie
  65. function parseCookies(setCookieHeaders) {
  66. return setCookieHeaders.map(cookie => {
  67. const match = cookie.match(/^([^=]+)=([^;]+)/);
  68. if (match) {
  69. const name = match[1];
  70. const value = match[2];
  71. // 提取其他属性
  72. const pathMatch = cookie.match(/Path=([^;]+)/);
  73. const expiresMatch = cookie.match(/Expires=([^;]+)/);
  74. const maxAgeMatch = cookie.match(/Max-Age=([^;]+)/);
  75. const httpOnlyMatch = cookie.match(/HttpOnly/);
  76. const secureMatch = cookie.match(/Secure/);
  77. const sameSiteMatch = cookie.match(/SameSite=([^;]+)/);
  78. return {
  79. name,
  80. value,
  81. path: pathMatch ? pathMatch[1] : '/',
  82. expires: expiresMatch ? expiresMatch[1] : null,
  83. maxAge: maxAgeMatch ? maxAgeMatch[1] : null,
  84. httpOnly: !!httpOnlyMatch,
  85. secure: !!secureMatch,
  86. sameSite: sameSiteMatch ? sameSiteMatch[1] : null
  87. };
  88. }
  89. return null;
  90. }).filter(Boolean);
  91. }
  92. // 生成跳转 HTML
  93. function generateRedirectHTML(cookieData, targetHost, targetDomain, requestId = '', customUrl = null) {
  94. const targetUrl = customUrl || `http://${targetHost}/`;
  95. return `
  96. <!DOCTYPE html>
  97. <html lang="zh-CN">
  98. <head>
  99. <meta charset="UTF-8">
  100. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  101. <title>自动登录中...</title>
  102. <style>
  103. body {
  104. display: flex;
  105. justify-content: center;
  106. align-items: center;
  107. height: 100vh;
  108. margin: 0;
  109. font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  110. background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  111. }
  112. .loading {
  113. text-align: center;
  114. }
  115. .spinner {
  116. border: 4px solid #f3f3f3;
  117. border-top: 4px solid #3498db;
  118. border-radius: 50%;
  119. width: 50px;
  120. height: 50px;
  121. animation: spin 1s linear infinite;
  122. margin: 0 auto 20px;
  123. }
  124. @keyframes spin {
  125. 0% { transform: rotate(0deg); }
  126. 100% { transform: rotate(360deg); }
  127. }
  128. .message {
  129. color: #333;
  130. font-size: 18px;
  131. }
  132. </style>
  133. </head>
  134. <body>
  135. <div class="loading">
  136. <div class="spinner"></div>
  137. <div class="message">正在自动登录,请稍候...</div>
  138. </div>
  139. <iframe id="cookieFrame" style="display:none;"></iframe>
  140. <script>
  141. (function() {
  142. const requestId = '${requestId}';
  143. const cookies = ${JSON.stringify(cookieData)};
  144. const targetUrl = '${targetUrl}';
  145. const targetDomain = '${targetDomain}';
  146. console.log('========================================');
  147. console.log('[浏览器端] 自动登录脚本开始执行');
  148. console.log('[浏览器端] 请求ID:', requestId);
  149. console.log('[浏览器端] 目标URL:', targetUrl);
  150. console.log('[浏览器端] 目标域名:', targetDomain);
  151. console.log('[浏览器端] Cookie 数量:', cookies.length);
  152. console.log('[浏览器端] Cookie 详情:', cookies);
  153. // 方法1: 尝试直接设置 Cookie(可能因为跨域限制而失败)
  154. if (cookies.length > 0) {
  155. console.log('[浏览器端] 开始尝试设置 Cookie...');
  156. let successCount = 0;
  157. let failCount = 0;
  158. cookies.forEach(function(cookie) {
  159. try {
  160. // 构建 Cookie 字符串
  161. let cookieStr = cookie.name + '=' + cookie.value;
  162. cookieStr += '; path=' + (cookie.path || '/');
  163. if (cookie.maxAge) {
  164. cookieStr += '; max-age=' + cookie.maxAge;
  165. }
  166. if (cookie.expires) {
  167. cookieStr += '; expires=' + cookie.expires;
  168. }
  169. if (cookie.secure) {
  170. cookieStr += '; secure';
  171. }
  172. if (cookie.sameSite) {
  173. cookieStr += '; samesite=' + cookie.sameSite;
  174. }
  175. // 注意:Domain 属性无法通过 JavaScript 设置跨域 Cookie
  176. // 但我们可以尝试设置(浏览器会忽略跨域的 Domain)
  177. if (cookie.domain) {
  178. cookieStr += '; domain=' + cookie.domain;
  179. }
  180. document.cookie = cookieStr;
  181. console.log('[浏览器端] ✓ 尝试设置 Cookie:', cookie.name);
  182. successCount++;
  183. // 验证 Cookie 是否设置成功
  184. const allCookies = document.cookie;
  185. if (allCookies.indexOf(cookie.name + '=') !== -1) {
  186. console.log('[浏览器端] ✓ Cookie 设置成功:', cookie.name);
  187. } else {
  188. console.warn('[浏览器端] ⚠ Cookie 可能未设置成功:', cookie.name, '(可能是跨域限制)');
  189. }
  190. } catch(e) {
  191. console.error('[浏览器端] ✗ 设置 Cookie 失败:', cookie.name, e);
  192. failCount++;
  193. }
  194. });
  195. console.log('[浏览器端] Cookie 设置结果: 成功 ' + successCount + ', 失败 ' + failCount);
  196. } else {
  197. console.log('[浏览器端] 没有 Cookie 需要设置,直接跳转');
  198. }
  199. // 方法2: 使用隐藏的 iframe 加载目标站点,让服务器设置 Cookie
  200. // 然后跳转到目标站点
  201. console.log('[浏览器端] 创建隐藏 iframe 加载目标站点...');
  202. const iframe = document.getElementById('cookieFrame');
  203. iframe.onload = function() {
  204. console.log('[浏览器端] iframe 加载完成');
  205. };
  206. iframe.onerror = function(error) {
  207. console.error('[浏览器端] iframe 加载失败:', error);
  208. };
  209. iframe.src = targetUrl;
  210. // 延迟跳转,确保 iframe 加载完成
  211. setTimeout(function() {
  212. console.log('[浏览器端] 准备跳转到目标站点:', targetUrl);
  213. console.log('[浏览器端] 当前页面 Cookie:', document.cookie);
  214. console.log('========================================');
  215. window.location.href = targetUrl;
  216. }, 1500);
  217. })();
  218. </script>
  219. </body>
  220. </html>
  221. `;
  222. }
  223. // 处理 RSA 加密表单登录
  224. async function handleRSAEncryptedFormLogin(config, credentials) {
  225. const { targetBaseUrl, loginUrl, loginMethodConfig } = config;
  226. const { publicKey, usernameField, passwordField, captchaField, captchaRequired, contentType, successCode, successField } = loginMethodConfig;
  227. console.log('=== RSA 加密表单登录 ===');
  228. console.log(`目标URL: ${targetBaseUrl}${loginUrl}`);
  229. console.log(`用户名: ${credentials.username}`);
  230. console.log(`密码: ${'*'.repeat(credentials.password.length)}`);
  231. console.log(`内容类型: ${contentType}`);
  232. console.log(`成功标识字段: ${successField || 'code'}, 成功值: ${successCode}`);
  233. // 加密用户名和密码
  234. const usernameEncrypted = encryptWithRSA(credentials.username, publicKey);
  235. const passwordEncrypted = encryptWithRSA(credentials.password, publicKey);
  236. console.log('用户名和密码已加密');
  237. console.log(`加密后用户名长度: ${usernameEncrypted.length}`);
  238. console.log(`加密后密码长度: ${passwordEncrypted.length}`);
  239. // 构建请求数据
  240. const requestData = {
  241. [usernameField]: usernameEncrypted,
  242. [passwordField]: passwordEncrypted
  243. };
  244. if (captchaField) {
  245. requestData[captchaField] = captchaRequired ? '' : '';
  246. }
  247. // 发送登录请求
  248. const headers = {};
  249. let requestBody;
  250. if (contentType === 'application/x-www-form-urlencoded') {
  251. headers['Content-Type'] = 'application/x-www-form-urlencoded';
  252. requestBody = new URLSearchParams(requestData).toString();
  253. } else if (contentType === 'application/json') {
  254. headers['Content-Type'] = 'application/json';
  255. requestBody = JSON.stringify(requestData);
  256. } else {
  257. requestBody = requestData;
  258. }
  259. console.log(`发送登录请求到: ${targetBaseUrl}${loginUrl}`);
  260. // 添加可能需要的请求头(模拟浏览器请求)
  261. headers['Referer'] = `${targetBaseUrl}/`;
  262. headers['Origin'] = targetBaseUrl;
  263. headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
  264. headers['Accept'] = 'application/json, text/javascript, */*; q=0.01';
  265. headers['Accept-Language'] = 'zh-CN,zh;q=0.9,en;q=0.8';
  266. headers['X-Requested-With'] = 'XMLHttpRequest';
  267. console.log(`请求头:`, JSON.stringify(headers, null, 2));
  268. console.log(`请求体长度: ${requestBody.length} 字符`);
  269. console.log(`请求体内容预览: ${requestBody.substring(0, 300)}...`);
  270. // 先访问登录页面获取可能的session cookie
  271. console.log('先访问登录页面获取session...');
  272. try {
  273. const loginPageResponse = await axios.get(`${targetBaseUrl}/`, {
  274. headers: {
  275. 'User-Agent': headers['User-Agent']
  276. },
  277. withCredentials: true,
  278. maxRedirects: 5
  279. });
  280. console.log('登录页面访问成功,获取到的Cookie:', loginPageResponse.headers['set-cookie'] || []);
  281. } catch (error) {
  282. console.log('访问登录页面失败(可能不需要):', error.message);
  283. }
  284. const loginResponse = await axios.post(
  285. `${targetBaseUrl}${loginUrl}`,
  286. requestBody,
  287. {
  288. headers,
  289. withCredentials: true,
  290. maxRedirects: 0,
  291. validateStatus: function (status) {
  292. return status >= 200 && status < 400;
  293. }
  294. }
  295. );
  296. console.log(`登录响应状态码: ${loginResponse.status}`);
  297. console.log(`响应头:`, JSON.stringify(loginResponse.headers, null, 2));
  298. console.log(`响应数据:`, JSON.stringify(loginResponse.data, null, 2));
  299. // 检查登录是否成功
  300. const responseData = loginResponse.data || {};
  301. const successValue = successField ? responseData[successField] : responseData.code;
  302. console.log(`成功标识值: ${successValue}, 期望值: ${successCode}`);
  303. if (successValue === successCode) {
  304. const cookies = loginResponse.headers['set-cookie'] || [];
  305. console.log(`登录成功!获取到 ${cookies.length} 个 Cookie`);
  306. cookies.forEach((cookie, index) => {
  307. console.log(`Cookie ${index + 1}: ${cookie.substring(0, 100)}...`);
  308. });
  309. return {
  310. success: true,
  311. cookies: cookies,
  312. response: loginResponse.data
  313. };
  314. } else {
  315. console.error(`登录失败!响应:`, responseData);
  316. return {
  317. success: false,
  318. message: responseData.msg || responseData.message || '登录失败',
  319. response: responseData
  320. };
  321. }
  322. }
  323. // 处理 Home Assistant 登录(OAuth2 流程)
  324. async function handleHomeAssistantLogin(config, credentials) {
  325. const { targetBaseUrl } = config;
  326. console.log('=== Home Assistant 登录 ===');
  327. console.log(`目标URL: ${targetBaseUrl}`);
  328. console.log(`用户名: ${credentials.username}`);
  329. console.log(`密码: ${'*'.repeat(credentials.password.length)}`);
  330. // 创建 Cookie jar 来保持会话
  331. const cookieJar = new CookieJar();
  332. const client = wrapper(axios.create({
  333. jar: cookieJar,
  334. withCredentials: true
  335. }));
  336. const baseHeaders = {
  337. 'Content-Type': 'application/json',
  338. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  339. 'Accept': 'application/json, text/plain, */*',
  340. 'Origin': targetBaseUrl,
  341. 'Referer': `${targetBaseUrl}/`
  342. };
  343. // 先访问首页获取初始 Cookie(如果需要)
  344. let initialCookies = [];
  345. try {
  346. console.log('访问首页获取初始 Cookie...');
  347. const homeResponse = await client.get(`${targetBaseUrl}/`, {
  348. headers: {
  349. 'User-Agent': baseHeaders['User-Agent']
  350. },
  351. maxRedirects: 5
  352. });
  353. initialCookies = homeResponse.headers['set-cookie'] || [];
  354. console.log(`获取到 ${initialCookies.length} 个初始 Cookie`);
  355. // 从 Cookie jar 中获取 Cookie
  356. const jarCookies = await cookieJar.getCookies(targetBaseUrl);
  357. console.log(`Cookie jar 中有 ${jarCookies.length} 个 Cookie`);
  358. } catch (error) {
  359. console.log('访问首页失败(可能不需要):', error.message);
  360. }
  361. // 步骤1: 创建登录流程
  362. console.log('步骤1: 创建登录流程...');
  363. let flowResponse;
  364. try {
  365. flowResponse = await client.post(
  366. `${targetBaseUrl}/auth/login_flow`,
  367. {
  368. client_id: `${targetBaseUrl}/`,
  369. handler: ['homeassistant', null],
  370. redirect_uri: `${targetBaseUrl}/`
  371. },
  372. {
  373. headers: baseHeaders,
  374. maxRedirects: 0,
  375. validateStatus: function (status) {
  376. return status >= 200 && status < 500;
  377. }
  378. }
  379. );
  380. } catch (error) {
  381. console.error('创建登录流程失败:', error.message);
  382. if (error.response) {
  383. console.error('响应状态:', error.response.status);
  384. console.error('响应数据:', JSON.stringify(error.response.data, null, 2));
  385. return {
  386. success: false,
  387. message: `创建登录流程失败: ${error.response.status} - ${JSON.stringify(error.response.data)}`,
  388. response: error.response.data
  389. };
  390. }
  391. return {
  392. success: false,
  393. message: `创建登录流程失败: ${error.message}`,
  394. response: null
  395. };
  396. }
  397. console.log(`流程创建响应状态码: ${flowResponse.status}`);
  398. console.log(`流程创建响应数据:`, JSON.stringify(flowResponse.data, null, 2));
  399. if (flowResponse.status !== 200) {
  400. return {
  401. success: false,
  402. message: `创建登录流程失败,状态码: ${flowResponse.status}`,
  403. response: flowResponse.data
  404. };
  405. }
  406. const flowId = flowResponse.data?.flow_id;
  407. if (!flowId) {
  408. console.error('无法获取 flow_id');
  409. return {
  410. success: false,
  411. message: '无法获取 flow_id',
  412. response: flowResponse.data
  413. };
  414. }
  415. console.log(`获取到 flow_id: ${flowId}`);
  416. // 步骤2: 提交用户名和密码
  417. console.log('步骤2: 提交用户名和密码...');
  418. let loginResponse;
  419. try {
  420. loginResponse = await client.post(
  421. `${targetBaseUrl}/auth/login_flow/${flowId}`,
  422. {
  423. username: credentials.username,
  424. password: credentials.password,
  425. client_id: `${targetBaseUrl}/`
  426. },
  427. {
  428. headers: baseHeaders,
  429. maxRedirects: 0,
  430. validateStatus: function (status) {
  431. return status >= 200 && status < 500;
  432. }
  433. }
  434. );
  435. } catch (error) {
  436. console.error('提交登录信息失败:', error.message);
  437. if (error.response) {
  438. console.error('响应状态:', error.response.status);
  439. console.error('响应数据:', JSON.stringify(error.response.data, null, 2));
  440. return {
  441. success: false,
  442. message: `提交登录信息失败: ${error.response.status} - ${JSON.stringify(error.response.data)}`,
  443. response: error.response.data
  444. };
  445. }
  446. return {
  447. success: false,
  448. message: `提交登录信息失败: ${error.message}`,
  449. response: null
  450. };
  451. }
  452. console.log(`登录响应状态码: ${loginResponse.status}`);
  453. console.log(`登录响应数据:`, JSON.stringify(loginResponse.data, null, 2));
  454. // 检查登录是否成功
  455. const responseData = loginResponse.data || {};
  456. const responseType = responseData.type;
  457. console.log(`响应类型: ${responseType}`);
  458. // Home Assistant 登录成功时,type 为 "create_entry"
  459. if (responseType === 'create_entry') {
  460. // 从 Cookie jar 中获取所有 Cookie
  461. console.log('从 Cookie jar 中获取 Cookie...');
  462. const jarCookies = await cookieJar.getCookies(targetBaseUrl);
  463. console.log(`Cookie jar 中有 ${jarCookies.length} 个 Cookie`);
  464. // 合并所有请求的 Cookie(从响应头和 Cookie jar)
  465. const flowCookies = flowResponse.headers['set-cookie'] || [];
  466. const loginCookies = loginResponse.headers['set-cookie'] || [];
  467. const allCookies = [...initialCookies, ...flowCookies, ...loginCookies];
  468. // 从 Cookie jar 转换为 Set-Cookie 格式
  469. jarCookies.forEach(cookie => {
  470. let cookieStr = `${cookie.key}=${cookie.value}`;
  471. if (cookie.path) cookieStr += `; Path=${cookie.path}`;
  472. if (cookie.domain) cookieStr += `; Domain=${cookie.domain}`;
  473. if (cookie.expires) cookieStr += `; Expires=${cookie.expires.toUTCString()}`;
  474. if (cookie.maxAge) cookieStr += `; Max-Age=${cookie.maxAge}`;
  475. if (cookie.secure) cookieStr += `; Secure`;
  476. if (cookie.httpOnly) cookieStr += `; HttpOnly`;
  477. if (cookie.sameSite) cookieStr += `; SameSite=${cookie.sameSite}`;
  478. allCookies.push(cookieStr);
  479. });
  480. // 去重 Cookie(保留最后一个)
  481. const cookieMap = new Map();
  482. allCookies.forEach(cookie => {
  483. const name = cookie.split('=')[0];
  484. cookieMap.set(name, cookie);
  485. });
  486. let uniqueCookies = Array.from(cookieMap.values());
  487. console.log(`登录成功!获取到 ${uniqueCookies.length} 个唯一 Cookie`);
  488. uniqueCookies.forEach((cookie, index) => {
  489. console.log(`Cookie ${index + 1}: ${cookie.substring(0, 100)}...`);
  490. });
  491. // 步骤3: 处理 OAuth2 授权流程
  492. // 登录成功后,Home Assistant 需要完成 OAuth2 授权才能访问主页面
  493. console.log('步骤3: 处理 OAuth2 授权流程...');
  494. try {
  495. // 构建 state 参数(base64 编码的 JSON)
  496. const stateData = {
  497. hassUrl: targetBaseUrl,
  498. clientId: `${targetBaseUrl}/`
  499. };
  500. const state = Buffer.from(JSON.stringify(stateData)).toString('base64');
  501. // 构建授权 URL
  502. const redirectUri = `${targetBaseUrl}/?auth_callback=1`;
  503. const clientId = `${targetBaseUrl}/`;
  504. const authorizeUrl = `${targetBaseUrl}/auth/authorize?response_type=code&redirect_uri=${encodeURIComponent(redirectUri)}&client_id=${encodeURIComponent(clientId)}&state=${encodeURIComponent(state)}`;
  505. console.log(`访问授权端点: ${authorizeUrl}`);
  506. // 使用 Cookie jar 的客户端访问授权端点,跟随重定向
  507. const authorizeResponse = await client.get(authorizeUrl, {
  508. headers: {
  509. 'User-Agent': baseHeaders['User-Agent'],
  510. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  511. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  512. 'Referer': `${targetBaseUrl}/`
  513. },
  514. maxRedirects: 10, // 增加重定向次数
  515. validateStatus: function (status) {
  516. return status >= 200 && status < 400;
  517. }
  518. });
  519. console.log(`授权响应状态码: ${authorizeResponse.status}`);
  520. const finalUrl = authorizeResponse.request?.res?.responseUrl || authorizeResponse.config?.url || authorizeUrl;
  521. console.log(`授权最终 URL: ${finalUrl}`);
  522. // 检查是否是重定向到回调 URL
  523. if (finalUrl.includes('auth_callback=1') || finalUrl.includes('code=')) {
  524. console.log('检测到授权回调,访问回调 URL 获取 Cookie...');
  525. try {
  526. const callbackResponse = await client.get(finalUrl, {
  527. headers: {
  528. 'User-Agent': baseHeaders['User-Agent'],
  529. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  530. 'Referer': authorizeUrl
  531. },
  532. maxRedirects: 5,
  533. validateStatus: function (status) {
  534. return status >= 200 && status < 400;
  535. }
  536. });
  537. console.log(`回调响应状态码: ${callbackResponse.status}`);
  538. } catch (callbackError) {
  539. console.log('访问回调 URL 失败:', callbackError.message);
  540. }
  541. }
  542. // 尝试访问主页面来触发 Cookie 设置
  543. console.log('访问主页面以触发 Cookie 设置...');
  544. try {
  545. const homePageResponse = await client.get(`${targetBaseUrl}/`, {
  546. headers: {
  547. 'User-Agent': baseHeaders['User-Agent'],
  548. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  549. 'Referer': finalUrl
  550. },
  551. maxRedirects: 5,
  552. validateStatus: function (status) {
  553. return status >= 200 && status < 400;
  554. }
  555. });
  556. console.log(`主页面响应状态码: ${homePageResponse.status}`);
  557. } catch (homeError) {
  558. console.log('访问主页面失败:', homeError.message);
  559. }
  560. // 从 Cookie jar 中获取授权后的 Cookie
  561. const authorizeJarCookies = await cookieJar.getCookies(targetBaseUrl);
  562. console.log(`授权后 Cookie jar 中有 ${authorizeJarCookies.length} 个 Cookie`);
  563. // 获取授权响应中的 Cookie
  564. const authorizeCookies = authorizeResponse.headers['set-cookie'] || [];
  565. console.log(`授权响应获取到 ${authorizeCookies.length} 个 Cookie`);
  566. // 从 Cookie jar 转换为 Set-Cookie 格式并合并
  567. authorizeJarCookies.forEach(cookie => {
  568. let cookieStr = `${cookie.key}=${cookie.value}`;
  569. if (cookie.path) cookieStr += `; Path=${cookie.path}`;
  570. if (cookie.domain) cookieStr += `; Domain=${cookie.domain}`;
  571. if (cookie.expires) cookieStr += `; Expires=${cookie.expires.toUTCString()}`;
  572. if (cookie.maxAge) cookieStr += `; Max-Age=${cookie.maxAge}`;
  573. if (cookie.secure) cookieStr += `; Secure`;
  574. if (cookie.httpOnly) cookieStr += `; HttpOnly`;
  575. if (cookie.sameSite) cookieStr += `; SameSite=${cookie.sameSite}`;
  576. cookieMap.set(cookie.key, cookieStr);
  577. });
  578. // 合并授权响应中的 Cookie
  579. authorizeCookies.forEach(cookie => {
  580. const name = cookie.split('=')[0];
  581. cookieMap.set(name, cookie);
  582. });
  583. uniqueCookies = Array.from(cookieMap.values());
  584. console.log(`授权完成!最终获取到 ${uniqueCookies.length} 个唯一 Cookie`);
  585. // 如果还是没有 Cookie,尝试使用登录结果中的 token
  586. if (uniqueCookies.length === 0 && responseData.result) {
  587. console.log(`尝试使用登录结果中的 token: ${responseData.result}`);
  588. // 这里可以尝试使用 token 来获取访问令牌
  589. // 但 Home Assistant 的 token 通常需要通过浏览器来设置 Cookie
  590. }
  591. } catch (error) {
  592. console.log('授权流程失败(可能不需要):', error.message);
  593. if (error.response) {
  594. console.log('授权响应状态:', error.response.status);
  595. console.log('授权响应 URL:', error.response.request?.res?.responseUrl || error.config?.url);
  596. }
  597. // 授权失败不影响登录,继续使用已有的 Cookie
  598. }
  599. return {
  600. success: true,
  601. cookies: uniqueCookies,
  602. response: loginResponse.data
  603. };
  604. } else {
  605. console.error(`登录失败!响应:`, responseData);
  606. const errorMessage = responseData.errors?.base?.[0]
  607. || responseData.errors?.username?.[0]
  608. || responseData.errors?.password?.[0]
  609. || responseData.message
  610. || `登录失败,响应类型: ${responseType}`;
  611. return {
  612. success: false,
  613. message: errorMessage,
  614. response: responseData
  615. };
  616. }
  617. }
  618. // 处理普通表单登录(未加密)
  619. async function handlePlainFormLogin(config, credentials) {
  620. const { targetBaseUrl, loginUrl, loginMethodConfig } = config;
  621. const { usernameField, passwordField, captchaField, contentType, successCode, successField } = loginMethodConfig;
  622. console.log('=== 普通表单登录 ===');
  623. console.log(`目标URL: ${targetBaseUrl}${loginUrl}`);
  624. console.log(`用户名: ${credentials.username}`);
  625. console.log(`密码: ${'*'.repeat(credentials.password.length)}`);
  626. console.log(`内容类型: ${contentType}`);
  627. console.log(`成功标识字段: ${successField || 'code'}, 成功值: ${successCode}`);
  628. // 构建请求数据
  629. const requestData = {
  630. [usernameField]: credentials.username,
  631. [passwordField]: credentials.password
  632. };
  633. if (captchaField) {
  634. requestData[captchaField] = '';
  635. }
  636. // 发送登录请求
  637. const headers = {};
  638. let requestBody;
  639. if (contentType === 'application/x-www-form-urlencoded') {
  640. headers['Content-Type'] = 'application/x-www-form-urlencoded';
  641. requestBody = new URLSearchParams(requestData).toString();
  642. } else if (contentType === 'application/json') {
  643. headers['Content-Type'] = 'application/json';
  644. requestBody = JSON.stringify(requestData);
  645. } else {
  646. requestBody = requestData;
  647. }
  648. console.log(`发送登录请求到: ${targetBaseUrl}${loginUrl}`);
  649. console.log(`请求头:`, JSON.stringify(headers, null, 2));
  650. console.log(`请求体:`, contentType === 'application/json' ? requestBody : requestBody.substring(0, 200) + '...');
  651. const loginResponse = await axios.post(
  652. `${targetBaseUrl}${loginUrl}`,
  653. requestBody,
  654. {
  655. headers,
  656. withCredentials: true,
  657. maxRedirects: 0,
  658. validateStatus: function (status) {
  659. return status >= 200 && status < 400;
  660. }
  661. }
  662. );
  663. console.log(`登录响应状态码: ${loginResponse.status}`);
  664. console.log(`响应数据:`, JSON.stringify(loginResponse.data, null, 2));
  665. // 检查登录是否成功
  666. const responseData = loginResponse.data || {};
  667. const successValue = successField ? responseData[successField] : responseData.code;
  668. console.log(`成功标识值: ${successValue}, 期望值: ${successCode}`);
  669. if (successValue === successCode) {
  670. const cookies = loginResponse.headers['set-cookie'] || [];
  671. console.log(`登录成功!获取到 ${cookies.length} 个 Cookie`);
  672. cookies.forEach((cookie, index) => {
  673. console.log(`Cookie ${index + 1}: ${cookie.substring(0, 100)}...`);
  674. });
  675. return {
  676. success: true,
  677. cookies: cookies,
  678. response: loginResponse.data
  679. };
  680. } else {
  681. console.error(`登录失败!响应:`, responseData);
  682. return {
  683. success: false,
  684. message: responseData.msg || responseData.message || '登录失败',
  685. response: responseData
  686. };
  687. }
  688. }
  689. // 通用的自动登录端点
  690. app.get('/api/auto-login/:siteId', async (req, res) => {
  691. const startTime = Date.now();
  692. const requestId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  693. // 立即输出日志,确认请求已到达
  694. console.log('\n' + '='.repeat(80));
  695. console.log(`[${requestId}] ⚡⚡⚡ 收到自动登录请求!⚡⚡⚡`);
  696. console.log(`[${requestId}] 时间: ${new Date().toISOString()}`);
  697. console.log(`[${requestId}] 请求路径: ${req.path}`);
  698. console.log(`[${requestId}] 请求方法: ${req.method}`);
  699. console.log(`[${requestId}] 完整URL: ${req.protocol}://${req.get('host')}${req.originalUrl}`);
  700. console.log(`[${requestId}] 客户端IP: ${req.ip || req.connection.remoteAddress || req.socket.remoteAddress}`);
  701. console.log(`[${requestId}] User-Agent: ${req.get('user-agent') || 'Unknown'}`);
  702. try {
  703. const { siteId } = req.params;
  704. console.log(`[${requestId}] 网站ID: ${siteId}`);
  705. // 获取网站配置
  706. const config = autoLoginConfig[siteId];
  707. if (!config) {
  708. console.error(`[${requestId}] 错误: 未找到网站ID "${siteId}" 的配置`);
  709. console.error(`[${requestId}] 可用的网站ID: ${Object.keys(autoLoginConfig).join(', ') || '无'}`);
  710. return res.status(404).json({
  711. success: false,
  712. message: `未找到网站ID "${siteId}" 的配置`,
  713. availableSites: Object.keys(autoLoginConfig)
  714. });
  715. }
  716. console.log(`[${requestId}] 网站名称: ${config.name}`);
  717. console.log(`[${requestId}] 目标地址: ${config.targetBaseUrl}`);
  718. console.log(`[${requestId}] 登录方法: ${config.loginMethod}`);
  719. // 获取登录凭据(优先使用环境变量)
  720. const envUsername = process.env[config.credentials.envUsername];
  721. const envPassword = process.env[config.credentials.envPassword];
  722. const credentials = {
  723. username: envUsername || config.credentials.username,
  724. password: envPassword || config.credentials.password
  725. };
  726. console.log(`[${requestId}] 凭据来源: ${envUsername ? '环境变量' : '配置文件'}`);
  727. console.log(`[${requestId}] 用户名: ${credentials.username}`);
  728. console.log(`[${requestId}] 密码: ${'*'.repeat(credentials.password.length)}`);
  729. if (!credentials.username || !credentials.password) {
  730. console.error(`[${requestId}] 错误: 登录凭据未配置`);
  731. return res.status(400).json({
  732. success: false,
  733. message: '登录凭据未配置'
  734. });
  735. }
  736. // 根据登录方法处理登录
  737. let loginResult;
  738. console.log(`[${requestId}] 开始执行登录...`);
  739. switch (config.loginMethod) {
  740. case 'rsa-encrypted-form':
  741. loginResult = await handleRSAEncryptedFormLogin(config, credentials);
  742. break;
  743. case 'plain-form':
  744. loginResult = await handlePlainFormLogin(config, credentials);
  745. break;
  746. case 'home-assistant':
  747. loginResult = await handleHomeAssistantLogin(config, credentials);
  748. break;
  749. default:
  750. console.error(`[${requestId}] 错误: 不支持的登录方法: ${config.loginMethod}`);
  751. return res.status(400).json({
  752. success: false,
  753. message: `不支持的登录方法: ${config.loginMethod}`
  754. });
  755. }
  756. if (!loginResult.success) {
  757. console.error(`[${requestId}] 登录失败:`, loginResult.message);
  758. console.error(`[${requestId}] 失败响应:`, JSON.stringify(loginResult.response, null, 2));
  759. const duration = Date.now() - startTime;
  760. console.log(`[${requestId}] 总耗时: ${duration}ms`);
  761. console.log('='.repeat(80) + '\n');
  762. // 返回错误页面而不是 JSON
  763. const errorHtml = `
  764. <!DOCTYPE html>
  765. <html lang="zh-CN">
  766. <head>
  767. <meta charset="UTF-8">
  768. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  769. <title>自动登录失败</title>
  770. <style>
  771. body {
  772. display: flex;
  773. justify-content: center;
  774. align-items: center;
  775. height: 100vh;
  776. margin: 0;
  777. font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  778. background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  779. }
  780. .error-container {
  781. background: white;
  782. padding: 40px;
  783. border-radius: 12px;
  784. box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  785. max-width: 600px;
  786. text-align: center;
  787. }
  788. .error-icon {
  789. font-size: 64px;
  790. margin-bottom: 20px;
  791. }
  792. .error-title {
  793. font-size: 24px;
  794. color: #e74c3c;
  795. margin-bottom: 15px;
  796. }
  797. .error-message {
  798. font-size: 16px;
  799. color: #666;
  800. margin-bottom: 20px;
  801. line-height: 1.6;
  802. }
  803. .error-details {
  804. background: #f8f9fa;
  805. padding: 15px;
  806. border-radius: 8px;
  807. margin-top: 20px;
  808. text-align: left;
  809. font-size: 14px;
  810. color: #555;
  811. }
  812. .error-details pre {
  813. margin: 0;
  814. white-space: pre-wrap;
  815. word-wrap: break-word;
  816. }
  817. </style>
  818. </head>
  819. <body>
  820. <div class="error-container">
  821. <div class="error-icon">❌</div>
  822. <div class="error-title">自动登录失败</div>
  823. <div class="error-message">${loginResult.message}</div>
  824. <div class="error-details">
  825. <strong>请求ID:</strong> ${requestId}<br>
  826. <strong>网站:</strong> ${config.name}<br>
  827. <strong>详细信息:</strong>
  828. <pre>${JSON.stringify(loginResult.response, null, 2)}</pre>
  829. </div>
  830. <button onclick="window.history.back()" style="margin-top: 20px; padding: 10px 20px; background: #3498db; color: white; border: none; border-radius: 6px; cursor: pointer;">返回</button>
  831. </div>
  832. </body>
  833. </html>
  834. `;
  835. return res.status(500).send(errorHtml);
  836. }
  837. console.log(`[${requestId}] 登录成功!`);
  838. // 解析 Cookie
  839. const cookieData = parseCookies(loginResult.cookies);
  840. console.log(`[${requestId}] 解析到 ${cookieData.length} 个 Cookie:`);
  841. cookieData.forEach((cookie, index) => {
  842. console.log(`[${requestId}] Cookie ${index + 1}: ${cookie.name} = ${cookie.value.substring(0, 20)}...`);
  843. });
  844. // 生成跳转 HTML(添加更多调试信息)
  845. // 对于 Home Assistant,如果没有 Cookie,直接跳转到授权端点
  846. let redirectUrl = `http://${config.targetHost}/`;
  847. if (config.loginMethod === 'home-assistant' && cookieData.length === 0) {
  848. // 构建授权 URL 让浏览器处理
  849. const stateData = {
  850. hassUrl: config.targetBaseUrl,
  851. clientId: `${config.targetBaseUrl}/`
  852. };
  853. const state = Buffer.from(JSON.stringify(stateData)).toString('base64');
  854. const redirectUri = `${config.targetBaseUrl}/?auth_callback=1`;
  855. const clientId = `${config.targetBaseUrl}/`;
  856. redirectUrl = `${config.targetBaseUrl}/auth/authorize?response_type=code&redirect_uri=${encodeURIComponent(redirectUri)}&client_id=${encodeURIComponent(clientId)}&state=${encodeURIComponent(state)}`;
  857. console.log(`[${requestId}] Home Assistant 无 Cookie,跳转到授权端点: ${redirectUrl}`);
  858. }
  859. console.log(`[${requestId}] 生成跳转页面,目标: ${redirectUrl}`);
  860. const html = generateRedirectHTML(
  861. cookieData,
  862. config.targetHost,
  863. config.targetDomain,
  864. requestId,
  865. redirectUrl
  866. );
  867. // 在响应头中设置 Cookie
  868. console.log(`[${requestId}] 设置响应头 Cookie...`);
  869. loginResult.cookies.forEach((cookie, index) => {
  870. // 修改 Cookie 的 Domain,移除端口号
  871. let modifiedCookie = cookie.replace(/Domain=[^;]+/i, `Domain=${config.targetDomain}`);
  872. res.setHeader('Set-Cookie', modifiedCookie);
  873. console.log(`[${requestId}] 设置 Cookie ${index + 1}: ${modifiedCookie.substring(0, 80)}...`);
  874. });
  875. const duration = Date.now() - startTime;
  876. console.log(`[${requestId}] 总耗时: ${duration}ms`);
  877. console.log(`[${requestId}] 返回跳转页面`);
  878. console.log('='.repeat(80) + '\n');
  879. res.send(html);
  880. } catch (error) {
  881. const duration = Date.now() - startTime;
  882. console.error(`[${requestId}] 自动登录异常:`, error.message);
  883. console.error(`[${requestId}] 错误堆栈:`, error.stack);
  884. if (error.response) {
  885. console.error(`[${requestId}] 响应状态:`, error.response.status);
  886. console.error(`[${requestId}] 响应头:`, JSON.stringify(error.response.headers, null, 2));
  887. console.error(`[${requestId}] 响应数据:`, JSON.stringify(error.response.data, null, 2));
  888. }
  889. if (error.request) {
  890. console.error(`[${requestId}] 请求信息:`, {
  891. url: error.config?.url,
  892. method: error.config?.method,
  893. headers: error.config?.headers
  894. });
  895. }
  896. console.log(`[${requestId}] 总耗时: ${duration}ms`);
  897. console.log('='.repeat(80) + '\n');
  898. res.status(500).json({
  899. success: false,
  900. message: '自动登录失败: ' + error.message,
  901. error: process.env.NODE_ENV === 'development' ? error.stack : undefined
  902. });
  903. }
  904. });
  905. // 获取所有配置的网站列表
  906. app.get('/api/auto-login', (req, res) => {
  907. const sites = Object.keys(autoLoginConfig).map(siteId => ({
  908. id: siteId,
  909. name: autoLoginConfig[siteId].name,
  910. endpoint: `/api/auto-login/${siteId}`
  911. }));
  912. res.json({ sites });
  913. });
  914. // 健康检查端点
  915. app.get('/api/health', (req, res) => {
  916. res.json({
  917. status: 'ok',
  918. timestamp: new Date().toISOString(),
  919. port: PORT,
  920. configuredSites: Object.keys(autoLoginConfig)
  921. });
  922. });
  923. // 测试端点 - 用于验证配置
  924. app.get('/api/test/:siteId', (req, res) => {
  925. const { siteId } = req.params;
  926. const config = autoLoginConfig[siteId];
  927. if (!config) {
  928. return res.json({
  929. success: false,
  930. message: `未找到网站ID "${siteId}" 的配置`,
  931. availableSites: Object.keys(autoLoginConfig)
  932. });
  933. }
  934. const envUsername = process.env[config.credentials.envUsername];
  935. const envPassword = process.env[config.credentials.envPassword];
  936. const credentials = {
  937. username: envUsername || config.credentials.username,
  938. password: envPassword || config.credentials.password
  939. };
  940. res.json({
  941. success: true,
  942. siteId,
  943. config: {
  944. name: config.name,
  945. targetBaseUrl: config.targetBaseUrl,
  946. loginMethod: config.loginMethod,
  947. loginUrl: config.loginUrl,
  948. hasCredentials: !!(credentials.username && credentials.password),
  949. credentialsSource: envUsername ? '环境变量' : '配置文件',
  950. username: credentials.username,
  951. passwordLength: credentials.password ? credentials.password.length : 0
  952. }
  953. });
  954. });
  955. app.listen(PORT, '0.0.0.0', () => {
  956. console.log('\n' + '='.repeat(80));
  957. console.log('🚀 后端服务器启动成功!');
  958. console.log('='.repeat(80));
  959. console.log(`📍 本地地址: http://localhost:${PORT}`);
  960. console.log(`📍 服务器地址: http://0.0.0.0:${PORT}`);
  961. console.log(`📍 外部访问: http://222.243.138.146:${PORT} (通过防火墙端口映射)`);
  962. console.log(`\n📋 已配置的自动登录网站: ${Object.keys(autoLoginConfig).join(', ') || '无'}`);
  963. console.log(`\n🔗 可用端点:`);
  964. console.log(` - 健康检查: http://localhost:${PORT}/api/health`);
  965. console.log(` - 测试配置: http://localhost:${PORT}/api/test/:siteId`);
  966. console.log(` - 自动登录: http://localhost:${PORT}/api/auto-login/:siteId`);
  967. console.log(`\n💡 提示: 确保防火墙已配置端口映射 (前端:8888, 后端:8889 -> 外网)`);
  968. console.log('='.repeat(80) + '\n');
  969. });