server.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526
  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, homeAssistantData = null) {
  94. const targetUrl = customUrl || `http://${targetHost}/`;
  95. const isHomeAssistant = homeAssistantData !== null;
  96. return `
  97. <!DOCTYPE html>
  98. <html lang="zh-CN">
  99. <head>
  100. <meta charset="UTF-8">
  101. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  102. <title>自动登录中...</title>
  103. <style>
  104. body {
  105. display: flex;
  106. justify-content: center;
  107. align-items: center;
  108. height: 100vh;
  109. margin: 0;
  110. font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  111. background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  112. }
  113. .loading {
  114. text-align: center;
  115. }
  116. .spinner {
  117. border: 4px solid #f3f3f3;
  118. border-top: 4px solid #3498db;
  119. border-radius: 50%;
  120. width: 50px;
  121. height: 50px;
  122. animation: spin 1s linear infinite;
  123. margin: 0 auto 20px;
  124. }
  125. @keyframes spin {
  126. 0% { transform: rotate(0deg); }
  127. 100% { transform: rotate(360deg); }
  128. }
  129. .message {
  130. color: #333;
  131. font-size: 18px;
  132. }
  133. </style>
  134. </head>
  135. <body>
  136. <div class="loading">
  137. <div class="spinner"></div>
  138. <div class="message">正在自动登录,请稍候...</div>
  139. </div>
  140. <iframe id="cookieFrame" style="display:none;"></iframe>
  141. <script>
  142. (function() {
  143. const requestId = '${requestId}';
  144. const cookies = ${JSON.stringify(cookieData)};
  145. const targetUrl = '${targetUrl}';
  146. const targetDomain = '${targetDomain}';
  147. const isHomeAssistant = ${isHomeAssistant};
  148. const homeAssistantData = ${homeAssistantData ? JSON.stringify(homeAssistantData) : 'null'};
  149. console.log('========================================');
  150. console.log('[浏览器端] 自动登录脚本开始执行');
  151. console.log('[浏览器端] 请求ID:', requestId);
  152. console.log('[浏览器端] 目标URL:', targetUrl);
  153. console.log('[浏览器端] 目标域名:', targetDomain);
  154. console.log('[浏览器端] Cookie 数量:', cookies.length);
  155. console.log('[浏览器端] Cookie 详情:', cookies);
  156. console.log('[浏览器端] 是否为 Home Assistant:', isHomeAssistant);
  157. console.log('[浏览器端] Home Assistant 数据:', homeAssistantData);
  158. // 方法1: 尝试直接设置 Cookie(可能因为跨域限制而失败)
  159. if (cookies.length > 0) {
  160. console.log('[浏览器端] 开始尝试设置 Cookie...');
  161. let successCount = 0;
  162. let failCount = 0;
  163. cookies.forEach(function(cookie) {
  164. try {
  165. // 构建 Cookie 字符串
  166. let cookieStr = cookie.name + '=' + cookie.value;
  167. cookieStr += '; path=' + (cookie.path || '/');
  168. if (cookie.maxAge) {
  169. cookieStr += '; max-age=' + cookie.maxAge;
  170. }
  171. if (cookie.expires) {
  172. cookieStr += '; expires=' + cookie.expires;
  173. }
  174. if (cookie.secure) {
  175. cookieStr += '; secure';
  176. }
  177. if (cookie.sameSite) {
  178. cookieStr += '; samesite=' + cookie.sameSite;
  179. }
  180. // 注意:Domain 属性无法通过 JavaScript 设置跨域 Cookie
  181. // 但我们可以尝试设置(浏览器会忽略跨域的 Domain)
  182. if (cookie.domain) {
  183. cookieStr += '; domain=' + cookie.domain;
  184. }
  185. document.cookie = cookieStr;
  186. console.log('[浏览器端] ✓ 尝试设置 Cookie:', cookie.name);
  187. successCount++;
  188. // 验证 Cookie 是否设置成功
  189. const allCookies = document.cookie;
  190. if (allCookies.indexOf(cookie.name + '=') !== -1) {
  191. console.log('[浏览器端] ✓ Cookie 设置成功:', cookie.name);
  192. } else {
  193. console.warn('[浏览器端] ⚠ Cookie 可能未设置成功:', cookie.name, '(可能是跨域限制)');
  194. }
  195. } catch(e) {
  196. console.error('[浏览器端] ✗ 设置 Cookie 失败:', cookie.name, e);
  197. failCount++;
  198. }
  199. });
  200. console.log('[浏览器端] Cookie 设置结果: 成功 ' + successCount + ', 失败 ' + failCount);
  201. } else {
  202. console.log('[浏览器端] 没有 Cookie 需要设置,直接跳转');
  203. }
  204. // 对于 Home Assistant,在浏览器端执行登录流程
  205. if (isHomeAssistant && homeAssistantData) {
  206. console.log('[浏览器端] Home Assistant 登录,在浏览器端执行登录流程');
  207. console.log('[浏览器端] 目标 URL:', homeAssistantData.targetBaseUrl);
  208. console.log('[浏览器端] 用户名:', homeAssistantData.username);
  209. // 异步执行登录流程(通过后端代理避免 CORS)
  210. async function loginHomeAssistant() {
  211. try {
  212. console.log('[浏览器端] 步骤1: 创建登录流程(通过代理)...');
  213. // 使用后端代理避免 CORS 问题
  214. const proxyBaseUrl = window.location.origin; // 后端服务器地址
  215. const flowResponse = await fetch(proxyBaseUrl + '/api/home-assistant-proxy/login-flow', {
  216. method: 'POST',
  217. headers: {
  218. 'Content-Type': 'application/json'
  219. },
  220. body: JSON.stringify({
  221. targetBaseUrl: homeAssistantData.targetBaseUrl
  222. })
  223. });
  224. if (!flowResponse.ok) {
  225. throw new Error('创建登录流程失败: ' + flowResponse.status);
  226. }
  227. const flowData = await flowResponse.json();
  228. console.log('[浏览器端] 流程创建响应:', flowData);
  229. if (!flowData.flow_id) {
  230. throw new Error('无法获取 flow_id');
  231. }
  232. console.log('[浏览器端] 步骤2: 提交用户名和密码(通过代理)...');
  233. const loginResponse = await fetch(proxyBaseUrl + '/api/home-assistant-proxy/login', {
  234. method: 'POST',
  235. headers: {
  236. 'Content-Type': 'application/json'
  237. },
  238. body: JSON.stringify({
  239. targetBaseUrl: homeAssistantData.targetBaseUrl,
  240. flowId: flowData.flow_id,
  241. username: homeAssistantData.username,
  242. password: homeAssistantData.password
  243. })
  244. });
  245. if (!loginResponse.ok) {
  246. throw new Error('登录失败: ' + loginResponse.status);
  247. }
  248. const loginData = await loginResponse.json();
  249. console.log('[浏览器端] 登录响应:', loginData);
  250. if (loginData.type === 'create_entry') {
  251. console.log('[浏览器端] 登录成功!准备跳转到授权端点...');
  252. // 构建授权 URL
  253. const stateData = {
  254. hassUrl: homeAssistantData.targetBaseUrl,
  255. clientId: homeAssistantData.targetBaseUrl + '/'
  256. };
  257. const state = btoa(JSON.stringify(stateData));
  258. const redirectUri = homeAssistantData.targetBaseUrl + '/?auth_callback=1';
  259. const clientId = homeAssistantData.targetBaseUrl + '/';
  260. const authorizeUrl = homeAssistantData.targetBaseUrl + '/auth/authorize?response_type=code&redirect_uri=' + encodeURIComponent(redirectUri) + '&client_id=' + encodeURIComponent(clientId) + '&state=' + encodeURIComponent(state);
  261. console.log('[浏览器端] 授权 URL:', authorizeUrl);
  262. console.log('[浏览器端] 跳转到授权端点...');
  263. console.log('========================================');
  264. window.location.href = authorizeUrl;
  265. } else {
  266. throw new Error('登录失败: ' + JSON.stringify(loginData));
  267. }
  268. } catch (error) {
  269. console.error('[浏览器端] 登录失败:', error);
  270. alert('自动登录失败: ' + error.message + '\\n\\n将跳转到登录页面,请手动登录。');
  271. window.location.href = targetUrl;
  272. }
  273. }
  274. // 执行登录
  275. loginHomeAssistant();
  276. return;
  277. }
  278. // 方法2: 使用隐藏的 iframe 加载目标站点,让服务器设置 Cookie
  279. // 然后跳转到目标站点
  280. console.log('[浏览器端] 创建隐藏 iframe 加载目标站点...');
  281. const iframe = document.getElementById('cookieFrame');
  282. iframe.onload = function() {
  283. console.log('[浏览器端] iframe 加载完成');
  284. };
  285. iframe.onerror = function(error) {
  286. console.error('[浏览器端] iframe 加载失败:', error);
  287. };
  288. iframe.src = targetUrl;
  289. // 延迟跳转,确保 iframe 加载完成
  290. setTimeout(function() {
  291. console.log('[浏览器端] 准备跳转到目标站点:', targetUrl);
  292. console.log('[浏览器端] 当前页面 Cookie:', document.cookie);
  293. console.log('========================================');
  294. window.location.href = targetUrl;
  295. }, 1500);
  296. })();
  297. </script>
  298. </body>
  299. </html>
  300. `;
  301. }
  302. // 处理 RSA 加密表单登录
  303. async function handleRSAEncryptedFormLogin(config, credentials) {
  304. const { targetBaseUrl, loginUrl, loginMethodConfig } = config;
  305. const { publicKey, usernameField, passwordField, captchaField, captchaRequired, contentType, successCode, successField } = loginMethodConfig;
  306. console.log('=== RSA 加密表单登录 ===');
  307. console.log(`目标URL: ${targetBaseUrl}${loginUrl}`);
  308. console.log(`用户名: ${credentials.username}`);
  309. console.log(`密码: ${'*'.repeat(credentials.password.length)}`);
  310. console.log(`内容类型: ${contentType}`);
  311. console.log(`成功标识字段: ${successField || 'code'}, 成功值: ${successCode}`);
  312. // 加密用户名和密码
  313. const usernameEncrypted = encryptWithRSA(credentials.username, publicKey);
  314. const passwordEncrypted = encryptWithRSA(credentials.password, publicKey);
  315. console.log('用户名和密码已加密');
  316. console.log(`加密后用户名长度: ${usernameEncrypted.length}`);
  317. console.log(`加密后密码长度: ${passwordEncrypted.length}`);
  318. // 构建请求数据
  319. const requestData = {
  320. [usernameField]: usernameEncrypted,
  321. [passwordField]: passwordEncrypted
  322. };
  323. if (captchaField) {
  324. requestData[captchaField] = captchaRequired ? '' : '';
  325. }
  326. // 发送登录请求
  327. const headers = {};
  328. let requestBody;
  329. if (contentType === 'application/x-www-form-urlencoded') {
  330. headers['Content-Type'] = 'application/x-www-form-urlencoded';
  331. requestBody = new URLSearchParams(requestData).toString();
  332. } else if (contentType === 'application/json') {
  333. headers['Content-Type'] = 'application/json';
  334. requestBody = JSON.stringify(requestData);
  335. } else {
  336. requestBody = requestData;
  337. }
  338. console.log(`发送登录请求到: ${targetBaseUrl}${loginUrl}`);
  339. // 添加可能需要的请求头(模拟浏览器请求)
  340. headers['Referer'] = `${targetBaseUrl}/`;
  341. headers['Origin'] = targetBaseUrl;
  342. 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';
  343. headers['Accept'] = 'application/json, text/javascript, */*; q=0.01';
  344. headers['Accept-Language'] = 'zh-CN,zh;q=0.9,en;q=0.8';
  345. headers['X-Requested-With'] = 'XMLHttpRequest';
  346. console.log(`请求头:`, JSON.stringify(headers, null, 2));
  347. console.log(`请求体长度: ${requestBody.length} 字符`);
  348. console.log(`请求体内容预览: ${requestBody.substring(0, 300)}...`);
  349. // 先访问登录页面获取可能的session cookie
  350. console.log('先访问登录页面获取session...');
  351. try {
  352. const loginPageResponse = await axios.get(`${targetBaseUrl}/`, {
  353. headers: {
  354. 'User-Agent': headers['User-Agent']
  355. },
  356. withCredentials: true,
  357. maxRedirects: 5
  358. });
  359. console.log('登录页面访问成功,获取到的Cookie:', loginPageResponse.headers['set-cookie'] || []);
  360. } catch (error) {
  361. console.log('访问登录页面失败(可能不需要):', error.message);
  362. }
  363. const loginResponse = await axios.post(
  364. `${targetBaseUrl}${loginUrl}`,
  365. requestBody,
  366. {
  367. headers,
  368. withCredentials: true,
  369. maxRedirects: 0,
  370. validateStatus: function (status) {
  371. return status >= 200 && status < 400;
  372. }
  373. }
  374. );
  375. console.log(`登录响应状态码: ${loginResponse.status}`);
  376. console.log(`响应头:`, JSON.stringify(loginResponse.headers, null, 2));
  377. console.log(`响应数据:`, JSON.stringify(loginResponse.data, null, 2));
  378. // 检查登录是否成功
  379. const responseData = loginResponse.data || {};
  380. const successValue = successField ? responseData[successField] : responseData.code;
  381. console.log(`成功标识值: ${successValue}, 期望值: ${successCode}`);
  382. if (successValue === successCode) {
  383. const cookies = loginResponse.headers['set-cookie'] || [];
  384. console.log(`登录成功!获取到 ${cookies.length} 个 Cookie`);
  385. cookies.forEach((cookie, index) => {
  386. console.log(`Cookie ${index + 1}: ${cookie.substring(0, 100)}...`);
  387. });
  388. return {
  389. success: true,
  390. cookies: cookies,
  391. response: loginResponse.data
  392. };
  393. } else {
  394. console.error(`登录失败!响应:`, responseData);
  395. return {
  396. success: false,
  397. message: responseData.msg || responseData.message || '登录失败',
  398. response: responseData
  399. };
  400. }
  401. }
  402. // 处理 Home Assistant 登录(OAuth2 流程 - 严格匹配 redirect_uri)
  403. async function handleHomeAssistantLogin(config, credentials) {
  404. const { targetBaseUrl } = config;
  405. console.log('=== Home Assistant 登录 (OAuth2 严格模式) ===');
  406. console.log(`目标URL: ${targetBaseUrl}`);
  407. console.log(`用户名: ${credentials.username}`);
  408. console.log(`密码: ${'*'.repeat(credentials.password.length)}`);
  409. // 基础请求头,伪装成浏览器
  410. const baseHeaders = {
  411. 'Content-Type': 'application/json',
  412. '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',
  413. 'Accept': 'application/json, text/plain, */*',
  414. 'Origin': targetBaseUrl,
  415. 'Referer': `${targetBaseUrl}/`
  416. };
  417. // 【关键】:OAuth2 协议要求 client_id 和 redirect_uri 在整个流程中完全一致
  418. const CLIENT_ID = `${targetBaseUrl}/`;
  419. const REDIRECT_URI = `${targetBaseUrl}/?auth_callback=1`;
  420. console.log('Client ID:', CLIENT_ID);
  421. console.log('Redirect URI:', REDIRECT_URI);
  422. try {
  423. // ==========================================
  424. // 步骤1: 创建登录流程 (Init Flow)
  425. // ==========================================
  426. console.log('[1/3] 初始化登录流程...');
  427. const flowResponse = await axios.post(
  428. `${targetBaseUrl}/auth/login_flow`,
  429. {
  430. client_id: CLIENT_ID,
  431. handler: ['homeassistant', null],
  432. redirect_uri: REDIRECT_URI // 【重要】:必须和最后跳转的地址完全一致
  433. },
  434. {
  435. headers: baseHeaders,
  436. validateStatus: function (status) {
  437. return status >= 200 && status < 500;
  438. }
  439. }
  440. );
  441. console.log(`流程创建响应状态码: ${flowResponse.status}`);
  442. console.log(`流程创建响应数据:`, JSON.stringify(flowResponse.data, null, 2));
  443. if (flowResponse.status !== 200) {
  444. return {
  445. success: false,
  446. message: `创建登录流程失败,状态码: ${flowResponse.status}`,
  447. response: flowResponse.data
  448. };
  449. }
  450. const flowId = flowResponse.data?.flow_id;
  451. if (!flowId) {
  452. console.error('无法获取 flow_id');
  453. return {
  454. success: false,
  455. message: '无法获取 flow_id',
  456. response: flowResponse.data
  457. };
  458. }
  459. console.log(`获取到 flow_id: ${flowId}`);
  460. // ==========================================
  461. // 步骤2: 提交用户名和密码 (Submit Credentials)
  462. // ==========================================
  463. console.log('[2/3] 提交用户名和密码...');
  464. const loginResponse = await axios.post(
  465. `${targetBaseUrl}/auth/login_flow/${flowId}`,
  466. {
  467. username: credentials.username,
  468. password: credentials.password,
  469. client_id: CLIENT_ID // 【重要】:必须和步骤1的 client_id 完全一致
  470. },
  471. {
  472. headers: baseHeaders,
  473. validateStatus: function (status) {
  474. return status >= 200 && status < 500;
  475. }
  476. }
  477. );
  478. console.log(`登录响应状态码: ${loginResponse.status}`);
  479. console.log(`登录响应数据:`, JSON.stringify(loginResponse.data, null, 2));
  480. // ==========================================
  481. // 步骤3: 换取 Token(全托管方案)
  482. // ==========================================
  483. const responseData = loginResponse.data || {};
  484. const responseType = responseData.type;
  485. console.log(`响应类型: ${responseType}`);
  486. // 如果登录成功,type 为 'create_entry',result 字段包含 Authorization Code
  487. if (responseData.result && responseType === 'create_entry') {
  488. const authCode = responseData.result;
  489. console.log('[3/4] 登录成功!获取到 Authorization Code:', authCode);
  490. console.log('[3/4] Node.js 将代替浏览器换取 Token...');
  491. try {
  492. // ==========================================
  493. // Node.js 直接换取 Token(避免前端路由抢跑问题)
  494. // ==========================================
  495. const tokenResponse = await axios.post(
  496. `${targetBaseUrl}/auth/token`,
  497. new URLSearchParams({
  498. grant_type: 'authorization_code',
  499. code: authCode,
  500. client_id: CLIENT_ID
  501. }).toString(),
  502. {
  503. headers: {
  504. 'Content-Type': 'application/x-www-form-urlencoded'
  505. }
  506. }
  507. );
  508. const tokens = tokenResponse.data;
  509. console.log('[4/4] ✅ Token 换取成功!');
  510. console.log(`Access Token: ${tokens.access_token.substring(0, 20)}...`);
  511. console.log(`Token 类型: ${tokens.token_type}`);
  512. console.log(`过期时间: ${tokens.expires_in}秒`);
  513. // OAuth2 跨端口方案:返回带有 code 的 URL,但使用增强的中间页面
  514. // 虽然获取了 Token,但由于跨端口限制,我们仍然使用 code 方式
  515. // 只是添加更好的处理逻辑
  516. const magicLink = `${REDIRECT_URI}&code=${encodeURIComponent(authCode)}`;
  517. return {
  518. success: true,
  519. useEnhancedRedirect: true, // 使用增强的重定向方案
  520. redirectUrl: magicLink,
  521. tokens: tokens, // 保留 Token 信息用于日志
  522. targetBaseUrl: targetBaseUrl,
  523. cookies: [],
  524. response: loginResponse.data
  525. };
  526. } catch (tokenError) {
  527. console.error('❌ Token 换取失败:', tokenError.message);
  528. if (tokenError.response) {
  529. console.error('Token 响应:', JSON.stringify(tokenError.response.data, null, 2));
  530. }
  531. // 如果 Token 换取失败,降级到传统方式
  532. console.log('⚠️ 降级到传统 redirect 方式...');
  533. const magicLink = `${REDIRECT_URI}&code=${encodeURIComponent(authCode)}`;
  534. return {
  535. success: true,
  536. redirectUrl: magicLink,
  537. cookies: [],
  538. response: loginResponse.data
  539. };
  540. }
  541. } else {
  542. console.error('❌ 登录失败!未返回 Authorization Code');
  543. console.error('响应数据:', responseData);
  544. // 提取错误信息
  545. const errorMessage = responseData.errors?.base?.[0]
  546. || responseData.errors?.username?.[0]
  547. || responseData.errors?.password?.[0]
  548. || responseData.message
  549. || `登录失败,响应类型: ${responseType}`;
  550. return {
  551. success: false,
  552. message: errorMessage,
  553. response: responseData
  554. };
  555. }
  556. } catch (error) {
  557. console.error('Home Assistant 登录流程异常:', error.message);
  558. if (error.response) {
  559. console.error('响应状态:', error.response.status);
  560. console.error('响应数据:', JSON.stringify(error.response.data, null, 2));
  561. return {
  562. success: false,
  563. message: `登录失败: ${error.response.status} - ${JSON.stringify(error.response.data)}`,
  564. response: error.response.data
  565. };
  566. }
  567. return {
  568. success: false,
  569. message: `登录失败: ${error.message}`,
  570. response: null
  571. };
  572. }
  573. }
  574. // 处理 GET 查询参数登录(OA系统等)
  575. async function handleGetQueryLogin(config, credentials) {
  576. const { targetBaseUrl, loginUrl, loginMethodConfig, successRedirectUrl } = config;
  577. const { usernameParam, passwordParam, entCode, saveCookie, isOnly, successResponse } = loginMethodConfig;
  578. console.log('=== GET 查询参数登录 ===');
  579. console.log(`目标URL: ${targetBaseUrl}${loginUrl}`);
  580. console.log(`用户名参数名: ${usernameParam}`);
  581. console.log(`密码参数名: ${passwordParam}`);
  582. console.log(`用户名: ${credentials.username}`);
  583. console.log(`密码: ${'*'.repeat(credentials.password.length)}`);
  584. console.log(`企业代码: ${entCode}`);
  585. // 构建查询参数 - 确保参数名正确
  586. const params = new URLSearchParams();
  587. params.append(usernameParam, credentials.username);
  588. params.append(passwordParam, credentials.password);
  589. params.append('ent_code', entCode);
  590. params.append('code', 'undefined');
  591. params.append('mySel', 'undefined');
  592. params.append('saveCookie', saveCookie);
  593. params.append('isOnly', isOnly);
  594. params.append('_', Date.now().toString()); // 实时时间戳,防止缓存
  595. const loginUrlWithParams = `${targetBaseUrl}${loginUrl}?${params.toString()}`;
  596. console.log(`发送登录请求到: ${loginUrlWithParams}`);
  597. try {
  598. const loginResponse = await axios.get(loginUrlWithParams, {
  599. headers: {
  600. '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',
  601. 'Accept': '*/*',
  602. 'Referer': `${targetBaseUrl}/`
  603. },
  604. withCredentials: true,
  605. maxRedirects: 0,
  606. validateStatus: function (status) {
  607. return status >= 200 && status < 400;
  608. }
  609. });
  610. console.log(`登录响应状态码: ${loginResponse.status}`);
  611. console.log(`响应数据: ${loginResponse.data}`);
  612. // 检查登录是否成功(响应内容为 "ok")
  613. const responseText = loginResponse.data?.toString().trim() || '';
  614. const isSuccess = responseText.toLowerCase() === successResponse.toLowerCase();
  615. console.log(`响应内容: "${responseText}"`);
  616. console.log(`成功标识: ${successResponse}, 匹配结果: ${isSuccess}`);
  617. if (isSuccess) {
  618. const cookies = loginResponse.headers['set-cookie'] || [];
  619. console.log(`登录成功!获取到 ${cookies.length} 个 Cookie`);
  620. cookies.forEach((cookie, index) => {
  621. console.log(`Cookie ${index + 1}: ${cookie.substring(0, 100)}...`);
  622. });
  623. return {
  624. success: true,
  625. cookies: cookies,
  626. redirectUrl: successRedirectUrl ? `${targetBaseUrl}${successRedirectUrl}` : null,
  627. response: loginResponse.data
  628. };
  629. } else {
  630. console.error(`登录失败!响应内容: "${responseText}"`);
  631. return {
  632. success: false,
  633. message: `登录失败,响应: ${responseText}`,
  634. response: loginResponse.data
  635. };
  636. }
  637. } catch (error) {
  638. console.error('登录请求异常:', error.message);
  639. if (error.response) {
  640. console.error('响应状态:', error.response.status);
  641. console.error('响应数据:', error.response.data);
  642. return {
  643. success: false,
  644. message: `登录失败: ${error.response.status} - ${error.response.data}`,
  645. response: error.response.data
  646. };
  647. }
  648. return {
  649. success: false,
  650. message: `登录失败: ${error.message}`,
  651. response: null
  652. };
  653. }
  654. }
  655. // 处理普通表单登录(未加密)
  656. async function handlePlainFormLogin(config, credentials) {
  657. const { targetBaseUrl, loginUrl, loginMethodConfig } = config;
  658. const { usernameField, passwordField, captchaField, contentType, successCode, successField } = loginMethodConfig;
  659. console.log('=== 普通表单登录 ===');
  660. console.log(`目标URL: ${targetBaseUrl}${loginUrl}`);
  661. console.log(`用户名: ${credentials.username}`);
  662. console.log(`密码: ${'*'.repeat(credentials.password.length)}`);
  663. console.log(`内容类型: ${contentType}`);
  664. console.log(`成功标识字段: ${successField || 'code'}, 成功值: ${successCode}`);
  665. // 构建请求数据
  666. const requestData = {
  667. [usernameField]: credentials.username,
  668. [passwordField]: credentials.password
  669. };
  670. if (captchaField) {
  671. requestData[captchaField] = '';
  672. }
  673. // 发送登录请求
  674. const headers = {};
  675. let requestBody;
  676. if (contentType === 'application/x-www-form-urlencoded') {
  677. headers['Content-Type'] = 'application/x-www-form-urlencoded';
  678. requestBody = new URLSearchParams(requestData).toString();
  679. } else if (contentType === 'application/json') {
  680. headers['Content-Type'] = 'application/json';
  681. requestBody = JSON.stringify(requestData);
  682. } else {
  683. requestBody = requestData;
  684. }
  685. console.log(`发送登录请求到: ${targetBaseUrl}${loginUrl}`);
  686. console.log(`请求头:`, JSON.stringify(headers, null, 2));
  687. console.log(`请求体:`, contentType === 'application/json' ? requestBody : requestBody.substring(0, 200) + '...');
  688. const loginResponse = await axios.post(
  689. `${targetBaseUrl}${loginUrl}`,
  690. requestBody,
  691. {
  692. headers,
  693. withCredentials: true,
  694. maxRedirects: 0,
  695. validateStatus: function (status) {
  696. return status >= 200 && status < 400;
  697. }
  698. }
  699. );
  700. console.log(`登录响应状态码: ${loginResponse.status}`);
  701. console.log(`响应数据:`, JSON.stringify(loginResponse.data, null, 2));
  702. // 检查登录是否成功
  703. const responseData = loginResponse.data || {};
  704. const successValue = successField ? responseData[successField] : responseData.code;
  705. console.log(`成功标识值: ${successValue}, 期望值: ${successCode}`);
  706. if (successValue === successCode) {
  707. const cookies = loginResponse.headers['set-cookie'] || [];
  708. console.log(`登录成功!获取到 ${cookies.length} 个 Cookie`);
  709. cookies.forEach((cookie, index) => {
  710. console.log(`Cookie ${index + 1}: ${cookie.substring(0, 100)}...`);
  711. });
  712. return {
  713. success: true,
  714. cookies: cookies,
  715. response: loginResponse.data
  716. };
  717. } else {
  718. console.error(`登录失败!响应:`, responseData);
  719. return {
  720. success: false,
  721. message: responseData.msg || responseData.message || '登录失败',
  722. response: responseData
  723. };
  724. }
  725. }
  726. // 通用的自动登录端点
  727. app.get('/api/auto-login/:siteId', async (req, res) => {
  728. const startTime = Date.now();
  729. const requestId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  730. // 立即输出日志,确认请求已到达
  731. console.log('\n' + '='.repeat(80));
  732. console.log(`[${requestId}] ⚡⚡⚡ 收到自动登录请求!⚡⚡⚡`);
  733. console.log(`[${requestId}] 时间: ${new Date().toISOString()}`);
  734. console.log(`[${requestId}] 请求路径: ${req.path}`);
  735. console.log(`[${requestId}] 请求方法: ${req.method}`);
  736. console.log(`[${requestId}] 完整URL: ${req.protocol}://${req.get('host')}${req.originalUrl}`);
  737. console.log(`[${requestId}] 客户端IP: ${req.ip || req.connection.remoteAddress || req.socket.remoteAddress}`);
  738. console.log(`[${requestId}] User-Agent: ${req.get('user-agent') || 'Unknown'}`);
  739. try {
  740. const { siteId } = req.params;
  741. console.log(`[${requestId}] 网站ID: ${siteId}`);
  742. // 获取网站配置
  743. const config = autoLoginConfig[siteId];
  744. if (!config) {
  745. console.error(`[${requestId}] 错误: 未找到网站ID "${siteId}" 的配置`);
  746. console.error(`[${requestId}] 可用的网站ID: ${Object.keys(autoLoginConfig).join(', ') || '无'}`);
  747. return res.status(404).json({
  748. success: false,
  749. message: `未找到网站ID "${siteId}" 的配置`,
  750. availableSites: Object.keys(autoLoginConfig)
  751. });
  752. }
  753. console.log(`[${requestId}] 网站名称: ${config.name}`);
  754. console.log(`[${requestId}] 目标地址: ${config.targetBaseUrl}`);
  755. console.log(`[${requestId}] 登录方法: ${config.loginMethod}`);
  756. // 获取登录凭据(优先使用环境变量)
  757. const envUsername = process.env[config.credentials.envUsername];
  758. const envPassword = process.env[config.credentials.envPassword];
  759. const credentials = {
  760. username: envUsername || config.credentials.username,
  761. password: envPassword || config.credentials.password
  762. };
  763. console.log(`[${requestId}] 凭据来源: ${envUsername ? '环境变量' : '配置文件'}`);
  764. console.log(`[${requestId}] 用户名: ${credentials.username}`);
  765. console.log(`[${requestId}] 密码: ${'*'.repeat(credentials.password.length)}`);
  766. if (!credentials.username || !credentials.password) {
  767. console.error(`[${requestId}] 错误: 登录凭据未配置`);
  768. return res.status(400).json({
  769. success: false,
  770. message: '登录凭据未配置'
  771. });
  772. }
  773. // 根据登录方法处理登录
  774. let loginResult;
  775. console.log(`[${requestId}] 开始执行登录...`);
  776. switch (config.loginMethod) {
  777. case 'rsa-encrypted-form':
  778. loginResult = await handleRSAEncryptedFormLogin(config, credentials);
  779. break;
  780. case 'plain-form':
  781. loginResult = await handlePlainFormLogin(config, credentials);
  782. break;
  783. case 'home-assistant':
  784. loginResult = await handleHomeAssistantLogin(config, credentials);
  785. break;
  786. case 'get-query-login':
  787. loginResult = await handleGetQueryLogin(config, credentials);
  788. break;
  789. default:
  790. console.error(`[${requestId}] 错误: 不支持的登录方法: ${config.loginMethod}`);
  791. return res.status(400).json({
  792. success: false,
  793. message: `不支持的登录方法: ${config.loginMethod}`
  794. });
  795. }
  796. if (!loginResult.success) {
  797. console.error(`[${requestId}] 登录失败:`, loginResult.message);
  798. console.error(`[${requestId}] 失败响应:`, JSON.stringify(loginResult.response, null, 2));
  799. const duration = Date.now() - startTime;
  800. console.log(`[${requestId}] 总耗时: ${duration}ms`);
  801. console.log('='.repeat(80) + '\n');
  802. // 返回错误页面而不是 JSON
  803. const errorHtml = `
  804. <!DOCTYPE html>
  805. <html lang="zh-CN">
  806. <head>
  807. <meta charset="UTF-8">
  808. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  809. <title>自动登录失败</title>
  810. <style>
  811. body {
  812. display: flex;
  813. justify-content: center;
  814. align-items: center;
  815. height: 100vh;
  816. margin: 0;
  817. font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  818. background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  819. }
  820. .error-container {
  821. background: white;
  822. padding: 40px;
  823. border-radius: 12px;
  824. box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  825. max-width: 600px;
  826. text-align: center;
  827. }
  828. .error-icon {
  829. font-size: 64px;
  830. margin-bottom: 20px;
  831. }
  832. .error-title {
  833. font-size: 24px;
  834. color: #e74c3c;
  835. margin-bottom: 15px;
  836. }
  837. .error-message {
  838. font-size: 16px;
  839. color: #666;
  840. margin-bottom: 20px;
  841. line-height: 1.6;
  842. }
  843. .error-details {
  844. background: #f8f9fa;
  845. padding: 15px;
  846. border-radius: 8px;
  847. margin-top: 20px;
  848. text-align: left;
  849. font-size: 14px;
  850. color: #555;
  851. }
  852. .error-details pre {
  853. margin: 0;
  854. white-space: pre-wrap;
  855. word-wrap: break-word;
  856. }
  857. </style>
  858. </head>
  859. <body>
  860. <div class="error-container">
  861. <div class="error-icon">❌</div>
  862. <div class="error-title">自动登录失败</div>
  863. <div class="error-message">${loginResult.message}</div>
  864. <div class="error-details">
  865. <strong>请求ID:</strong> ${requestId}<br>
  866. <strong>网站:</strong> ${config.name}<br>
  867. <strong>详细信息:</strong>
  868. <pre>${JSON.stringify(loginResult.response, null, 2)}</pre>
  869. </div>
  870. <button onclick="window.history.back()" style="margin-top: 20px; padding: 10px 20px; background: #3498db; color: white; border: none; border-radius: 6px; cursor: pointer;">返回</button>
  871. </div>
  872. </body>
  873. </html>
  874. `;
  875. return res.status(500).send(errorHtml);
  876. }
  877. console.log(`[${requestId}] 登录成功!`);
  878. // OAuth2 跨端口:调试页面方案
  879. if (config.loginMethod === 'home-assistant' && loginResult.useEnhancedRedirect) {
  880. console.log(`[${requestId}] 🚀 Home Assistant OAuth2 - 调试重定向方案`);
  881. console.log(`[${requestId}] Token 已获取: ${loginResult.tokens.access_token.substring(0, 30)}...`);
  882. console.log(`[${requestId}] Authorization Code: ${loginResult.redirectUrl.match(/code=([^&]+)/)?.[1]}`);
  883. console.log(`[${requestId}] 重定向 URL: ${loginResult.redirectUrl}`);
  884. const magicLink = loginResult.redirectUrl;
  885. const authCode = magicLink.match(/code=([^&]+)/)?.[1] || 'unknown';
  886. const targetBaseUrl = loginResult.targetBaseUrl || config.targetBaseUrl;
  887. // 生成调试页面
  888. const debugHtml = `
  889. <!DOCTYPE html>
  890. <html lang="zh-CN">
  891. <head>
  892. <meta charset="UTF-8">
  893. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  894. <title>Home Assistant OAuth2 调试</title>
  895. <style>
  896. body {
  897. font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  898. background: #1e1e1e;
  899. color: #d4d4d4;
  900. padding: 20px;
  901. margin: 0;
  902. }
  903. .container {
  904. max-width: 1000px;
  905. margin: 0 auto;
  906. }
  907. h1 {
  908. color: #4ec9b0;
  909. border-bottom: 2px solid #4ec9b0;
  910. padding-bottom: 10px;
  911. }
  912. .section {
  913. background: #252526;
  914. border: 1px solid #3e3e42;
  915. border-radius: 8px;
  916. padding: 20px;
  917. margin: 20px 0;
  918. }
  919. .section h2 {
  920. color: #569cd6;
  921. margin-top: 0;
  922. }
  923. pre {
  924. background: #1e1e1e;
  925. border: 1px solid #3e3e42;
  926. border-radius: 4px;
  927. padding: 15px;
  928. overflow-x: auto;
  929. }
  930. .success { color: #4ec9b0; }
  931. .warning { color: #ce9178; }
  932. .error { color: #f48771; }
  933. .button {
  934. background: #0e639c;
  935. color: white;
  936. border: none;
  937. padding: 12px 24px;
  938. border-radius: 6px;
  939. font-size: 16px;
  940. cursor: pointer;
  941. margin: 10px 5px;
  942. }
  943. .button:hover { background: #1177bb; }
  944. .button.secondary {
  945. background: #3e3e42;
  946. }
  947. .button.secondary:hover { background: #505050; }
  948. #log {
  949. background: #1e1e1e;
  950. border: 1px solid #3e3e42;
  951. border-radius: 4px;
  952. padding: 15px;
  953. max-height: 300px;
  954. overflow-y: auto;
  955. font-family: 'Consolas', 'Monaco', monospace;
  956. font-size: 12px;
  957. }
  958. .log-entry {
  959. margin: 5px 0;
  960. padding: 5px;
  961. border-left: 3px solid #569cd6;
  962. padding-left: 10px;
  963. }
  964. </style>
  965. </head>
  966. <body>
  967. <div class="container">
  968. <h1>🔍 Home Assistant OAuth2 登录调试</h1>
  969. <div class="section">
  970. <h2>✅ 后端登录成功</h2>
  971. <p>Authorization Code 已获取,Token 已验证。</p>
  972. <p><strong class="success">Authorization Code:</strong> <code>${authCode.substring(0, 20)}...</code></p>
  973. </div>
  974. <div class="section">
  975. <h2>📋 OAuth2 跨端口问题分析</h2>
  976. <p class="warning">⚠️ 检测到跨端口场景:</p>
  977. <ul>
  978. <li>Node.js 后端:<code>222.243.138.146:8889</code></li>
  979. <li>Home Assistant:<code>222.243.138.146:8123</code></li>
  980. <li>localStorage 隔离:不同端口无法共享 Token</li>
  981. </ul>
  982. </div>
  983. <div class="section">
  984. <h2>🎯 手动测试步骤</h2>
  985. <p>请按以下步骤测试,帮助我们诊断问题:</p>
  986. <h3>测试 1:直接访问魔术链接</h3>
  987. <p>复制下面的 URL 到新标签页,看是否能登录:</p>
  988. <pre>${magicLink}</pre>
  989. <button class="button" onclick="window.open('${magicLink}', '_blank')">
  990. 🔗 在新标签页打开
  991. </button>
  992. <h3>测试 2:在当前标签页跳转</h3>
  993. <p>让当前页面跳转过去(可能有更好的效果):</p>
  994. <button class="button secondary" onclick="window.location.href='${magicLink}'">
  995. ➡️ 当前标签页跳转
  996. </button>
  997. <h3>测试 3:iframe 预加载然后跳转</h3>
  998. <p>使用 iframe 预加载,5秒后跳转:</p>
  999. <button class="button secondary" onclick="testIframeMethod()">
  1000. 🔄 使用 iframe 方案
  1001. </button>
  1002. </div>
  1003. <div class="section">
  1004. <h2>📊 实时日志</h2>
  1005. <div id="log"></div>
  1006. </div>
  1007. <div class="section">
  1008. <h2>💡 建议</h2>
  1009. <p>如果以上测试都失败,强烈建议使用 <strong class="success">Trusted Networks</strong> 方案:</p>
  1010. <ul>
  1011. <li>✅ 官方支持,100% 可靠</li>
  1012. <li>✅ 无需复杂的 OAuth2 流程</li>
  1013. <li>✅ 零延迟,直接登录</li>
  1014. </ul>
  1015. <button class="button" onclick="alert('请在 Home Assistant 的 configuration.yaml 中配置:\\n\\nhomeassistant:\\n auth_providers:\\n - type: trusted_networks\\n trusted_networks:\\n - 118.251.191.88/32\\n trusted_users:\\n 118.251.191.88/32: YOUR_USER_ID\\n allow_bypass_login: true\\n - type: homeassistant')">
  1016. 📖 查看 Trusted Networks 配置
  1017. </button>
  1018. </div>
  1019. </div>
  1020. <iframe id="testFrame" style="display:none;"></iframe>
  1021. <script>
  1022. const logDiv = document.getElementById('log');
  1023. const iframe = document.getElementById('testFrame');
  1024. function addLog(msg, type = 'info') {
  1025. const entry = document.createElement('div');
  1026. entry.className = 'log-entry';
  1027. entry.textContent = new Date().toLocaleTimeString() + ' - ' + msg;
  1028. logDiv.appendChild(entry);
  1029. logDiv.scrollTop = logDiv.scrollHeight;
  1030. console.log('[调试] ' + msg);
  1031. }
  1032. function testIframeMethod() {
  1033. addLog('开始 iframe 测试...');
  1034. addLog('加载 URL: ${magicLink}');
  1035. let loaded = false;
  1036. iframe.onload = function() {
  1037. if (!loaded) {
  1038. loaded = true;
  1039. addLog('✓ iframe 加载完成');
  1040. addLog('等待 5 秒后跳转...');
  1041. let countdown = 5;
  1042. const timer = setInterval(function() {
  1043. countdown--;
  1044. addLog('倒计时: ' + countdown + '秒');
  1045. if (countdown <= 0) {
  1046. clearInterval(timer);
  1047. addLog('正在跳转到 Home Assistant...');
  1048. window.location.href = '${targetBaseUrl}';
  1049. }
  1050. }, 1000);
  1051. }
  1052. };
  1053. iframe.onerror = function(e) {
  1054. addLog('✗ iframe 加载失败: ' + e, 'error');
  1055. };
  1056. iframe.src = '${magicLink.replace(/'/g, "\\'")}';
  1057. }
  1058. addLog('后端 OAuth2 登录成功');
  1059. addLog('Authorization Code: ${authCode.substring(0, 20)}...');
  1060. addLog('请选择测试方法');
  1061. </script>
  1062. </body>
  1063. </html>
  1064. `;
  1065. console.log(`[${requestId}] 返回调试页面,供手动测试`);
  1066. console.log(`[${requestId}] 魔术链接: ${magicLink}`);
  1067. console.log(`[${requestId}] 目标地址: ${targetBaseUrl}`);
  1068. console.log(`[${requestId}] 总耗时: ${Date.now() - startTime}ms`);
  1069. console.log('='.repeat(80) + '\n');
  1070. return res.send(debugHtml);
  1071. }
  1072. // 对于 Home Assistant,如果使用传统 redirect 方式(降级方案)
  1073. if (config.loginMethod === 'home-assistant' && loginResult.redirectUrl) {
  1074. console.log(`[${requestId}] Home Assistant 登录成功,使用传统 redirect 方式(降级)`);
  1075. console.log(`[${requestId}] 重定向到: ${loginResult.redirectUrl}`);
  1076. // 使用中间页面而不是直接 redirect
  1077. // 这样可以添加延迟,让 HA 前端有时间处理 code
  1078. const intermediateHtml = `
  1079. <!DOCTYPE html>
  1080. <html lang="zh-CN">
  1081. <head>
  1082. <meta charset="UTF-8">
  1083. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1084. <title>正在登录 Home Assistant...</title>
  1085. <style>
  1086. body {
  1087. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  1088. color: white;
  1089. font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  1090. display: flex;
  1091. justify-content: center;
  1092. align-items: center;
  1093. height: 100vh;
  1094. margin: 0;
  1095. }
  1096. .container { text-align: center; }
  1097. .loader {
  1098. border: 4px solid rgba(255, 255, 255, 0.3);
  1099. border-top: 4px solid white;
  1100. border-radius: 50%;
  1101. width: 50px;
  1102. height: 50px;
  1103. animation: spin 1s linear infinite;
  1104. margin: 0 auto 20px;
  1105. }
  1106. @keyframes spin {
  1107. 0% { transform: rotate(0deg); }
  1108. 100% { transform: rotate(360deg); }
  1109. }
  1110. h2 { margin: 0 0 10px 0; }
  1111. p { margin: 5px 0; opacity: 0.9; font-size: 14px; }
  1112. </style>
  1113. </head>
  1114. <body>
  1115. <div class="container">
  1116. <div class="loader"></div>
  1117. <h2>正在登录...</h2>
  1118. <p>准备进入 Home Assistant</p>
  1119. </div>
  1120. <iframe id="authFrame" style="display:none;"></iframe>
  1121. <script>
  1122. // 使用 iframe 预加载带有 code 的 URL
  1123. // 让 HA 前端在后台完成 code → token 的交换
  1124. const authUrl = "${loginResult.redirectUrl}";
  1125. const targetUrl = "${config.targetBaseUrl}";
  1126. const iframe = document.getElementById('authFrame');
  1127. console.log('[降级方案] 使用 iframe 预加载:', authUrl);
  1128. // 设置 iframe 超时
  1129. let loaded = false;
  1130. iframe.onload = function() {
  1131. if (!loaded) {
  1132. loaded = true;
  1133. console.log('[降级方案] iframe 加载完成,等待 HA 处理 code...');
  1134. // 给 HA 足够时间处理 code
  1135. setTimeout(function() {
  1136. console.log('[降级方案] 跳转到主页');
  1137. window.location.href = targetUrl;
  1138. }, 2000);
  1139. }
  1140. };
  1141. // 加载带有 code 的 URL
  1142. iframe.src = authUrl;
  1143. // 保险起见,10秒后强制跳转
  1144. setTimeout(function() {
  1145. if (!loaded) {
  1146. console.log('[降级方案] 超时,强制跳转');
  1147. window.location.href = targetUrl;
  1148. }
  1149. }, 10000);
  1150. </script>
  1151. </body>
  1152. </html>
  1153. `;
  1154. console.log(`[${requestId}] 总耗时: ${Date.now() - startTime}ms`);
  1155. console.log('='.repeat(80) + '\n');
  1156. return res.send(intermediateHtml);
  1157. }
  1158. // 对于 GET 查询登录,如果有 redirectUrl,使用 HTML 页面设置 Cookie 后跳转
  1159. if (config.loginMethod === 'get-query-login' && loginResult.redirectUrl) {
  1160. console.log(`[${requestId}] GET 查询登录成功,重定向到: ${loginResult.redirectUrl}`);
  1161. // 解析 Cookie
  1162. const cookieData = parseCookies(loginResult.cookies);
  1163. console.log(`[${requestId}] 解析到 ${cookieData.length} 个 Cookie:`);
  1164. cookieData.forEach((cookie, index) => {
  1165. console.log(`[${requestId}] Cookie ${index + 1}: ${cookie.name} = ${cookie.value.substring(0, 20)}...`);
  1166. });
  1167. // 生成跳转 HTML,确保 Cookie 正确设置
  1168. const html = generateRedirectHTML(
  1169. cookieData,
  1170. config.targetHost,
  1171. config.targetDomain,
  1172. requestId,
  1173. loginResult.redirectUrl,
  1174. null
  1175. );
  1176. // 在响应头中设置 Cookie
  1177. console.log(`[${requestId}] 设置响应头 Cookie...`);
  1178. loginResult.cookies.forEach((cookie, index) => {
  1179. // 修改 Cookie 的 Domain,移除端口号
  1180. let modifiedCookie = cookie.replace(/Domain=[^;]+/i, `Domain=${config.targetDomain}`);
  1181. res.setHeader('Set-Cookie', modifiedCookie);
  1182. console.log(`[${requestId}] 设置 Cookie ${index + 1}: ${modifiedCookie.substring(0, 80)}...`);
  1183. });
  1184. const duration = Date.now() - startTime;
  1185. console.log(`[${requestId}] 总耗时: ${duration}ms`);
  1186. console.log(`[${requestId}] 返回跳转页面`);
  1187. console.log('='.repeat(80) + '\n');
  1188. return res.send(html);
  1189. }
  1190. // 解析 Cookie
  1191. const cookieData = parseCookies(loginResult.cookies);
  1192. console.log(`[${requestId}] 解析到 ${cookieData.length} 个 Cookie:`);
  1193. cookieData.forEach((cookie, index) => {
  1194. console.log(`[${requestId}] Cookie ${index + 1}: ${cookie.name} = ${cookie.value.substring(0, 20)}...`);
  1195. });
  1196. // 生成跳转 HTML
  1197. let redirectUrl = `http://${config.targetHost}/`;
  1198. console.log(`[${requestId}] 生成跳转页面,目标: ${redirectUrl}`);
  1199. const html = generateRedirectHTML(
  1200. cookieData,
  1201. config.targetHost,
  1202. config.targetDomain,
  1203. requestId,
  1204. redirectUrl,
  1205. null
  1206. );
  1207. // 在响应头中设置 Cookie
  1208. console.log(`[${requestId}] 设置响应头 Cookie...`);
  1209. loginResult.cookies.forEach((cookie, index) => {
  1210. // 修改 Cookie 的 Domain,移除端口号
  1211. let modifiedCookie = cookie.replace(/Domain=[^;]+/i, `Domain=${config.targetDomain}`);
  1212. res.setHeader('Set-Cookie', modifiedCookie);
  1213. console.log(`[${requestId}] 设置 Cookie ${index + 1}: ${modifiedCookie.substring(0, 80)}...`);
  1214. });
  1215. const duration = Date.now() - startTime;
  1216. console.log(`[${requestId}] 总耗时: ${duration}ms`);
  1217. console.log(`[${requestId}] 返回跳转页面`);
  1218. console.log('='.repeat(80) + '\n');
  1219. res.send(html);
  1220. } catch (error) {
  1221. const duration = Date.now() - startTime;
  1222. console.error(`[${requestId}] 自动登录异常:`, error.message);
  1223. console.error(`[${requestId}] 错误堆栈:`, error.stack);
  1224. if (error.response) {
  1225. console.error(`[${requestId}] 响应状态:`, error.response.status);
  1226. console.error(`[${requestId}] 响应头:`, JSON.stringify(error.response.headers, null, 2));
  1227. console.error(`[${requestId}] 响应数据:`, JSON.stringify(error.response.data, null, 2));
  1228. }
  1229. if (error.request) {
  1230. console.error(`[${requestId}] 请求信息:`, {
  1231. url: error.config?.url,
  1232. method: error.config?.method,
  1233. headers: error.config?.headers
  1234. });
  1235. }
  1236. console.log(`[${requestId}] 总耗时: ${duration}ms`);
  1237. console.log('='.repeat(80) + '\n');
  1238. res.status(500).json({
  1239. success: false,
  1240. message: '自动登录失败: ' + error.message,
  1241. error: process.env.NODE_ENV === 'development' ? error.stack : undefined
  1242. });
  1243. }
  1244. });
  1245. // Home Assistant 登录代理端点(解决浏览器 CORS 问题)
  1246. app.post('/api/home-assistant-proxy/login-flow', async (req, res) => {
  1247. try {
  1248. const targetBaseUrl = req.body.targetBaseUrl;
  1249. console.log('[代理] 创建 Home Assistant 登录流程:', targetBaseUrl);
  1250. const response = await axios.post(
  1251. `${targetBaseUrl}/auth/login_flow`,
  1252. {
  1253. client_id: `${targetBaseUrl}/`,
  1254. handler: ['homeassistant', null],
  1255. redirect_uri: `${targetBaseUrl}/`
  1256. },
  1257. {
  1258. headers: {
  1259. 'Content-Type': 'application/json'
  1260. }
  1261. }
  1262. );
  1263. res.json(response.data);
  1264. } catch (error) {
  1265. console.error('[代理] 创建登录流程失败:', error.message);
  1266. res.status(500).json({ error: error.message });
  1267. }
  1268. });
  1269. app.post('/api/home-assistant-proxy/login', async (req, res) => {
  1270. try {
  1271. const { targetBaseUrl, flowId, username, password } = req.body;
  1272. console.log('[代理] 提交 Home Assistant 登录凭据:', targetBaseUrl, flowId);
  1273. const response = await axios.post(
  1274. `${targetBaseUrl}/auth/login_flow/${flowId}`,
  1275. {
  1276. username: username,
  1277. password: password,
  1278. client_id: `${targetBaseUrl}/`
  1279. },
  1280. {
  1281. headers: {
  1282. 'Content-Type': 'application/json'
  1283. }
  1284. }
  1285. );
  1286. res.json(response.data);
  1287. } catch (error) {
  1288. console.error('[代理] 登录失败:', error.message);
  1289. res.status(500).json({ error: error.message });
  1290. }
  1291. });
  1292. // 获取所有配置的网站列表
  1293. app.get('/api/auto-login', (req, res) => {
  1294. const sites = Object.keys(autoLoginConfig).map(siteId => ({
  1295. id: siteId,
  1296. name: autoLoginConfig[siteId].name,
  1297. endpoint: `/api/auto-login/${siteId}`
  1298. }));
  1299. res.json({ sites });
  1300. });
  1301. // 健康检查端点
  1302. app.get('/api/health', (req, res) => {
  1303. res.json({
  1304. status: 'ok',
  1305. timestamp: new Date().toISOString(),
  1306. port: PORT,
  1307. configuredSites: Object.keys(autoLoginConfig)
  1308. });
  1309. });
  1310. // 测试端点 - 用于验证配置
  1311. app.get('/api/test/:siteId', (req, res) => {
  1312. const { siteId } = req.params;
  1313. const config = autoLoginConfig[siteId];
  1314. if (!config) {
  1315. return res.json({
  1316. success: false,
  1317. message: `未找到网站ID "${siteId}" 的配置`,
  1318. availableSites: Object.keys(autoLoginConfig)
  1319. });
  1320. }
  1321. const envUsername = process.env[config.credentials.envUsername];
  1322. const envPassword = process.env[config.credentials.envPassword];
  1323. const credentials = {
  1324. username: envUsername || config.credentials.username,
  1325. password: envPassword || config.credentials.password
  1326. };
  1327. res.json({
  1328. success: true,
  1329. siteId,
  1330. config: {
  1331. name: config.name,
  1332. targetBaseUrl: config.targetBaseUrl,
  1333. loginMethod: config.loginMethod,
  1334. loginUrl: config.loginUrl,
  1335. hasCredentials: !!(credentials.username && credentials.password),
  1336. credentialsSource: envUsername ? '环境变量' : '配置文件',
  1337. username: credentials.username,
  1338. passwordLength: credentials.password ? credentials.password.length : 0
  1339. }
  1340. });
  1341. });
  1342. app.listen(PORT, '0.0.0.0', () => {
  1343. console.log('\n' + '='.repeat(80));
  1344. console.log('🚀 后端服务器启动成功!');
  1345. console.log('='.repeat(80));
  1346. console.log(`📍 本地地址: http://localhost:${PORT}`);
  1347. console.log(`📍 服务器地址: http://0.0.0.0:${PORT}`);
  1348. console.log(`📍 外部访问: http://222.243.138.146:${PORT} (通过防火墙端口映射)`);
  1349. console.log(`\n📋 已配置的自动登录网站: ${Object.keys(autoLoginConfig).join(', ') || '无'}`);
  1350. console.log(`\n🔗 可用端点:`);
  1351. console.log(` - 健康检查: http://localhost:${PORT}/api/health`);
  1352. console.log(` - 测试配置: http://localhost:${PORT}/api/test/:siteId`);
  1353. console.log(` - 自动登录: http://localhost:${PORT}/api/auto-login/:siteId`);
  1354. console.log(`\n💡 提示: 确保防火墙已配置端口映射 (前端:8888, 后端:8889 -> 外网)`);
  1355. console.log('='.repeat(80) + '\n');
  1356. });