server.js 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  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(`用户名: ${credentials.username}`);
  581. console.log(`密码: ${'*'.repeat(credentials.password.length)}`);
  582. console.log(`企业代码: ${entCode}`);
  583. // 构建查询参数
  584. const params = new URLSearchParams({
  585. [usernameParam]: credentials.username,
  586. [passwordParam]: credentials.password,
  587. ent_code: entCode,
  588. code: 'undefined',
  589. mySel: 'undefined',
  590. saveCookie: saveCookie,
  591. isOnly: isOnly,
  592. _: Date.now().toString() // 时间戳,防止缓存
  593. });
  594. const loginUrlWithParams = `${targetBaseUrl}${loginUrl}?${params.toString()}`;
  595. console.log(`发送登录请求到: ${loginUrlWithParams}`);
  596. try {
  597. const loginResponse = await axios.get(loginUrlWithParams, {
  598. headers: {
  599. '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',
  600. 'Accept': '*/*',
  601. 'Referer': `${targetBaseUrl}/`
  602. },
  603. withCredentials: true,
  604. maxRedirects: 0,
  605. validateStatus: function (status) {
  606. return status >= 200 && status < 400;
  607. }
  608. });
  609. console.log(`登录响应状态码: ${loginResponse.status}`);
  610. console.log(`响应数据: ${loginResponse.data}`);
  611. // 检查登录是否成功(响应内容为 "ok")
  612. const responseText = loginResponse.data?.toString().trim() || '';
  613. const isSuccess = responseText.toLowerCase() === successResponse.toLowerCase();
  614. console.log(`响应内容: "${responseText}"`);
  615. console.log(`成功标识: ${successResponse}, 匹配结果: ${isSuccess}`);
  616. if (isSuccess) {
  617. const cookies = loginResponse.headers['set-cookie'] || [];
  618. console.log(`登录成功!获取到 ${cookies.length} 个 Cookie`);
  619. cookies.forEach((cookie, index) => {
  620. console.log(`Cookie ${index + 1}: ${cookie.substring(0, 100)}...`);
  621. });
  622. return {
  623. success: true,
  624. cookies: cookies,
  625. redirectUrl: successRedirectUrl ? `${targetBaseUrl}${successRedirectUrl}` : null,
  626. response: loginResponse.data
  627. };
  628. } else {
  629. console.error(`登录失败!响应内容: "${responseText}"`);
  630. return {
  631. success: false,
  632. message: `登录失败,响应: ${responseText}`,
  633. response: loginResponse.data
  634. };
  635. }
  636. } catch (error) {
  637. console.error('登录请求异常:', error.message);
  638. if (error.response) {
  639. console.error('响应状态:', error.response.status);
  640. console.error('响应数据:', error.response.data);
  641. return {
  642. success: false,
  643. message: `登录失败: ${error.response.status} - ${error.response.data}`,
  644. response: error.response.data
  645. };
  646. }
  647. return {
  648. success: false,
  649. message: `登录失败: ${error.message}`,
  650. response: null
  651. };
  652. }
  653. }
  654. // 处理普通表单登录(未加密)
  655. async function handlePlainFormLogin(config, credentials) {
  656. const { targetBaseUrl, loginUrl, loginMethodConfig } = config;
  657. const { usernameField, passwordField, captchaField, contentType, successCode, successField } = loginMethodConfig;
  658. console.log('=== 普通表单登录 ===');
  659. console.log(`目标URL: ${targetBaseUrl}${loginUrl}`);
  660. console.log(`用户名: ${credentials.username}`);
  661. console.log(`密码: ${'*'.repeat(credentials.password.length)}`);
  662. console.log(`内容类型: ${contentType}`);
  663. console.log(`成功标识字段: ${successField || 'code'}, 成功值: ${successCode}`);
  664. // 构建请求数据
  665. const requestData = {
  666. [usernameField]: credentials.username,
  667. [passwordField]: credentials.password
  668. };
  669. if (captchaField) {
  670. requestData[captchaField] = '';
  671. }
  672. // 发送登录请求
  673. const headers = {};
  674. let requestBody;
  675. if (contentType === 'application/x-www-form-urlencoded') {
  676. headers['Content-Type'] = 'application/x-www-form-urlencoded';
  677. requestBody = new URLSearchParams(requestData).toString();
  678. } else if (contentType === 'application/json') {
  679. headers['Content-Type'] = 'application/json';
  680. requestBody = JSON.stringify(requestData);
  681. } else {
  682. requestBody = requestData;
  683. }
  684. console.log(`发送登录请求到: ${targetBaseUrl}${loginUrl}`);
  685. console.log(`请求头:`, JSON.stringify(headers, null, 2));
  686. console.log(`请求体:`, contentType === 'application/json' ? requestBody : requestBody.substring(0, 200) + '...');
  687. const loginResponse = await axios.post(
  688. `${targetBaseUrl}${loginUrl}`,
  689. requestBody,
  690. {
  691. headers,
  692. withCredentials: true,
  693. maxRedirects: 0,
  694. validateStatus: function (status) {
  695. return status >= 200 && status < 400;
  696. }
  697. }
  698. );
  699. console.log(`登录响应状态码: ${loginResponse.status}`);
  700. console.log(`响应数据:`, JSON.stringify(loginResponse.data, null, 2));
  701. // 检查登录是否成功
  702. const responseData = loginResponse.data || {};
  703. const successValue = successField ? responseData[successField] : responseData.code;
  704. console.log(`成功标识值: ${successValue}, 期望值: ${successCode}`);
  705. if (successValue === successCode) {
  706. const cookies = loginResponse.headers['set-cookie'] || [];
  707. console.log(`登录成功!获取到 ${cookies.length} 个 Cookie`);
  708. cookies.forEach((cookie, index) => {
  709. console.log(`Cookie ${index + 1}: ${cookie.substring(0, 100)}...`);
  710. });
  711. return {
  712. success: true,
  713. cookies: cookies,
  714. response: loginResponse.data
  715. };
  716. } else {
  717. console.error(`登录失败!响应:`, responseData);
  718. return {
  719. success: false,
  720. message: responseData.msg || responseData.message || '登录失败',
  721. response: responseData
  722. };
  723. }
  724. }
  725. // 通用的自动登录端点
  726. app.get('/api/auto-login/:siteId', async (req, res) => {
  727. const startTime = Date.now();
  728. const requestId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  729. // 立即输出日志,确认请求已到达
  730. console.log('\n' + '='.repeat(80));
  731. console.log(`[${requestId}] ⚡⚡⚡ 收到自动登录请求!⚡⚡⚡`);
  732. console.log(`[${requestId}] 时间: ${new Date().toISOString()}`);
  733. console.log(`[${requestId}] 请求路径: ${req.path}`);
  734. console.log(`[${requestId}] 请求方法: ${req.method}`);
  735. console.log(`[${requestId}] 完整URL: ${req.protocol}://${req.get('host')}${req.originalUrl}`);
  736. console.log(`[${requestId}] 客户端IP: ${req.ip || req.connection.remoteAddress || req.socket.remoteAddress}`);
  737. console.log(`[${requestId}] User-Agent: ${req.get('user-agent') || 'Unknown'}`);
  738. try {
  739. const { siteId } = req.params;
  740. console.log(`[${requestId}] 网站ID: ${siteId}`);
  741. // 获取网站配置
  742. const config = autoLoginConfig[siteId];
  743. if (!config) {
  744. console.error(`[${requestId}] 错误: 未找到网站ID "${siteId}" 的配置`);
  745. console.error(`[${requestId}] 可用的网站ID: ${Object.keys(autoLoginConfig).join(', ') || '无'}`);
  746. return res.status(404).json({
  747. success: false,
  748. message: `未找到网站ID "${siteId}" 的配置`,
  749. availableSites: Object.keys(autoLoginConfig)
  750. });
  751. }
  752. console.log(`[${requestId}] 网站名称: ${config.name}`);
  753. console.log(`[${requestId}] 目标地址: ${config.targetBaseUrl}`);
  754. console.log(`[${requestId}] 登录方法: ${config.loginMethod}`);
  755. // 获取登录凭据(优先使用环境变量)
  756. const envUsername = process.env[config.credentials.envUsername];
  757. const envPassword = process.env[config.credentials.envPassword];
  758. const credentials = {
  759. username: envUsername || config.credentials.username,
  760. password: envPassword || config.credentials.password
  761. };
  762. console.log(`[${requestId}] 凭据来源: ${envUsername ? '环境变量' : '配置文件'}`);
  763. console.log(`[${requestId}] 用户名: ${credentials.username}`);
  764. console.log(`[${requestId}] 密码: ${'*'.repeat(credentials.password.length)}`);
  765. if (!credentials.username || !credentials.password) {
  766. console.error(`[${requestId}] 错误: 登录凭据未配置`);
  767. return res.status(400).json({
  768. success: false,
  769. message: '登录凭据未配置'
  770. });
  771. }
  772. // 根据登录方法处理登录
  773. let loginResult;
  774. console.log(`[${requestId}] 开始执行登录...`);
  775. switch (config.loginMethod) {
  776. case 'rsa-encrypted-form':
  777. loginResult = await handleRSAEncryptedFormLogin(config, credentials);
  778. break;
  779. case 'plain-form':
  780. loginResult = await handlePlainFormLogin(config, credentials);
  781. break;
  782. case 'home-assistant':
  783. loginResult = await handleHomeAssistantLogin(config, credentials);
  784. break;
  785. case 'get-query-login':
  786. loginResult = await handleGetQueryLogin(config, credentials);
  787. break;
  788. default:
  789. console.error(`[${requestId}] 错误: 不支持的登录方法: ${config.loginMethod}`);
  790. return res.status(400).json({
  791. success: false,
  792. message: `不支持的登录方法: ${config.loginMethod}`
  793. });
  794. }
  795. if (!loginResult.success) {
  796. console.error(`[${requestId}] 登录失败:`, loginResult.message);
  797. console.error(`[${requestId}] 失败响应:`, JSON.stringify(loginResult.response, null, 2));
  798. const duration = Date.now() - startTime;
  799. console.log(`[${requestId}] 总耗时: ${duration}ms`);
  800. console.log('='.repeat(80) + '\n');
  801. // 返回错误页面而不是 JSON
  802. const errorHtml = `
  803. <!DOCTYPE html>
  804. <html lang="zh-CN">
  805. <head>
  806. <meta charset="UTF-8">
  807. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  808. <title>自动登录失败</title>
  809. <style>
  810. body {
  811. display: flex;
  812. justify-content: center;
  813. align-items: center;
  814. height: 100vh;
  815. margin: 0;
  816. font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  817. background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  818. }
  819. .error-container {
  820. background: white;
  821. padding: 40px;
  822. border-radius: 12px;
  823. box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  824. max-width: 600px;
  825. text-align: center;
  826. }
  827. .error-icon {
  828. font-size: 64px;
  829. margin-bottom: 20px;
  830. }
  831. .error-title {
  832. font-size: 24px;
  833. color: #e74c3c;
  834. margin-bottom: 15px;
  835. }
  836. .error-message {
  837. font-size: 16px;
  838. color: #666;
  839. margin-bottom: 20px;
  840. line-height: 1.6;
  841. }
  842. .error-details {
  843. background: #f8f9fa;
  844. padding: 15px;
  845. border-radius: 8px;
  846. margin-top: 20px;
  847. text-align: left;
  848. font-size: 14px;
  849. color: #555;
  850. }
  851. .error-details pre {
  852. margin: 0;
  853. white-space: pre-wrap;
  854. word-wrap: break-word;
  855. }
  856. </style>
  857. </head>
  858. <body>
  859. <div class="error-container">
  860. <div class="error-icon">❌</div>
  861. <div class="error-title">自动登录失败</div>
  862. <div class="error-message">${loginResult.message}</div>
  863. <div class="error-details">
  864. <strong>请求ID:</strong> ${requestId}<br>
  865. <strong>网站:</strong> ${config.name}<br>
  866. <strong>详细信息:</strong>
  867. <pre>${JSON.stringify(loginResult.response, null, 2)}</pre>
  868. </div>
  869. <button onclick="window.history.back()" style="margin-top: 20px; padding: 10px 20px; background: #3498db; color: white; border: none; border-radius: 6px; cursor: pointer;">返回</button>
  870. </div>
  871. </body>
  872. </html>
  873. `;
  874. return res.status(500).send(errorHtml);
  875. }
  876. console.log(`[${requestId}] 登录成功!`);
  877. // OAuth2 跨端口:调试页面方案
  878. if (config.loginMethod === 'home-assistant' && loginResult.useEnhancedRedirect) {
  879. console.log(`[${requestId}] 🚀 Home Assistant OAuth2 - 调试重定向方案`);
  880. console.log(`[${requestId}] Token 已获取: ${loginResult.tokens.access_token.substring(0, 30)}...`);
  881. console.log(`[${requestId}] Authorization Code: ${loginResult.redirectUrl.match(/code=([^&]+)/)?.[1]}`);
  882. console.log(`[${requestId}] 重定向 URL: ${loginResult.redirectUrl}`);
  883. const magicLink = loginResult.redirectUrl;
  884. const authCode = magicLink.match(/code=([^&]+)/)?.[1] || 'unknown';
  885. const targetBaseUrl = loginResult.targetBaseUrl || config.targetBaseUrl;
  886. // 生成调试页面
  887. const debugHtml = `
  888. <!DOCTYPE html>
  889. <html lang="zh-CN">
  890. <head>
  891. <meta charset="UTF-8">
  892. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  893. <title>Home Assistant OAuth2 调试</title>
  894. <style>
  895. body {
  896. font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  897. background: #1e1e1e;
  898. color: #d4d4d4;
  899. padding: 20px;
  900. margin: 0;
  901. }
  902. .container {
  903. max-width: 1000px;
  904. margin: 0 auto;
  905. }
  906. h1 {
  907. color: #4ec9b0;
  908. border-bottom: 2px solid #4ec9b0;
  909. padding-bottom: 10px;
  910. }
  911. .section {
  912. background: #252526;
  913. border: 1px solid #3e3e42;
  914. border-radius: 8px;
  915. padding: 20px;
  916. margin: 20px 0;
  917. }
  918. .section h2 {
  919. color: #569cd6;
  920. margin-top: 0;
  921. }
  922. pre {
  923. background: #1e1e1e;
  924. border: 1px solid #3e3e42;
  925. border-radius: 4px;
  926. padding: 15px;
  927. overflow-x: auto;
  928. }
  929. .success { color: #4ec9b0; }
  930. .warning { color: #ce9178; }
  931. .error { color: #f48771; }
  932. .button {
  933. background: #0e639c;
  934. color: white;
  935. border: none;
  936. padding: 12px 24px;
  937. border-radius: 6px;
  938. font-size: 16px;
  939. cursor: pointer;
  940. margin: 10px 5px;
  941. }
  942. .button:hover { background: #1177bb; }
  943. .button.secondary {
  944. background: #3e3e42;
  945. }
  946. .button.secondary:hover { background: #505050; }
  947. #log {
  948. background: #1e1e1e;
  949. border: 1px solid #3e3e42;
  950. border-radius: 4px;
  951. padding: 15px;
  952. max-height: 300px;
  953. overflow-y: auto;
  954. font-family: 'Consolas', 'Monaco', monospace;
  955. font-size: 12px;
  956. }
  957. .log-entry {
  958. margin: 5px 0;
  959. padding: 5px;
  960. border-left: 3px solid #569cd6;
  961. padding-left: 10px;
  962. }
  963. </style>
  964. </head>
  965. <body>
  966. <div class="container">
  967. <h1>🔍 Home Assistant OAuth2 登录调试</h1>
  968. <div class="section">
  969. <h2>✅ 后端登录成功</h2>
  970. <p>Authorization Code 已获取,Token 已验证。</p>
  971. <p><strong class="success">Authorization Code:</strong> <code>${authCode.substring(0, 20)}...</code></p>
  972. </div>
  973. <div class="section">
  974. <h2>📋 OAuth2 跨端口问题分析</h2>
  975. <p class="warning">⚠️ 检测到跨端口场景:</p>
  976. <ul>
  977. <li>Node.js 后端:<code>222.243.138.146:8889</code></li>
  978. <li>Home Assistant:<code>222.243.138.146:8123</code></li>
  979. <li>localStorage 隔离:不同端口无法共享 Token</li>
  980. </ul>
  981. </div>
  982. <div class="section">
  983. <h2>🎯 手动测试步骤</h2>
  984. <p>请按以下步骤测试,帮助我们诊断问题:</p>
  985. <h3>测试 1:直接访问魔术链接</h3>
  986. <p>复制下面的 URL 到新标签页,看是否能登录:</p>
  987. <pre>${magicLink}</pre>
  988. <button class="button" onclick="window.open('${magicLink}', '_blank')">
  989. 🔗 在新标签页打开
  990. </button>
  991. <h3>测试 2:在当前标签页跳转</h3>
  992. <p>让当前页面跳转过去(可能有更好的效果):</p>
  993. <button class="button secondary" onclick="window.location.href='${magicLink}'">
  994. ➡️ 当前标签页跳转
  995. </button>
  996. <h3>测试 3:iframe 预加载然后跳转</h3>
  997. <p>使用 iframe 预加载,5秒后跳转:</p>
  998. <button class="button secondary" onclick="testIframeMethod()">
  999. 🔄 使用 iframe 方案
  1000. </button>
  1001. </div>
  1002. <div class="section">
  1003. <h2>📊 实时日志</h2>
  1004. <div id="log"></div>
  1005. </div>
  1006. <div class="section">
  1007. <h2>💡 建议</h2>
  1008. <p>如果以上测试都失败,强烈建议使用 <strong class="success">Trusted Networks</strong> 方案:</p>
  1009. <ul>
  1010. <li>✅ 官方支持,100% 可靠</li>
  1011. <li>✅ 无需复杂的 OAuth2 流程</li>
  1012. <li>✅ 零延迟,直接登录</li>
  1013. </ul>
  1014. <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')">
  1015. 📖 查看 Trusted Networks 配置
  1016. </button>
  1017. </div>
  1018. </div>
  1019. <iframe id="testFrame" style="display:none;"></iframe>
  1020. <script>
  1021. const logDiv = document.getElementById('log');
  1022. const iframe = document.getElementById('testFrame');
  1023. function addLog(msg, type = 'info') {
  1024. const entry = document.createElement('div');
  1025. entry.className = 'log-entry';
  1026. entry.textContent = new Date().toLocaleTimeString() + ' - ' + msg;
  1027. logDiv.appendChild(entry);
  1028. logDiv.scrollTop = logDiv.scrollHeight;
  1029. console.log('[调试] ' + msg);
  1030. }
  1031. function testIframeMethod() {
  1032. addLog('开始 iframe 测试...');
  1033. addLog('加载 URL: ${magicLink}');
  1034. let loaded = false;
  1035. iframe.onload = function() {
  1036. if (!loaded) {
  1037. loaded = true;
  1038. addLog('✓ iframe 加载完成');
  1039. addLog('等待 5 秒后跳转...');
  1040. let countdown = 5;
  1041. const timer = setInterval(function() {
  1042. countdown--;
  1043. addLog('倒计时: ' + countdown + '秒');
  1044. if (countdown <= 0) {
  1045. clearInterval(timer);
  1046. addLog('正在跳转到 Home Assistant...');
  1047. window.location.href = '${targetBaseUrl}';
  1048. }
  1049. }, 1000);
  1050. }
  1051. };
  1052. iframe.onerror = function(e) {
  1053. addLog('✗ iframe 加载失败: ' + e, 'error');
  1054. };
  1055. iframe.src = '${magicLink.replace(/'/g, "\\'")}';
  1056. }
  1057. addLog('后端 OAuth2 登录成功');
  1058. addLog('Authorization Code: ${authCode.substring(0, 20)}...');
  1059. addLog('请选择测试方法');
  1060. </script>
  1061. </body>
  1062. </html>
  1063. `;
  1064. console.log(`[${requestId}] 返回调试页面,供手动测试`);
  1065. console.log(`[${requestId}] 魔术链接: ${magicLink}`);
  1066. console.log(`[${requestId}] 目标地址: ${targetBaseUrl}`);
  1067. console.log(`[${requestId}] 总耗时: ${Date.now() - startTime}ms`);
  1068. console.log('='.repeat(80) + '\n');
  1069. return res.send(debugHtml);
  1070. }
  1071. // 对于 Home Assistant,如果使用传统 redirect 方式(降级方案)
  1072. if (config.loginMethod === 'home-assistant' && loginResult.redirectUrl) {
  1073. console.log(`[${requestId}] Home Assistant 登录成功,使用传统 redirect 方式(降级)`);
  1074. console.log(`[${requestId}] 重定向到: ${loginResult.redirectUrl}`);
  1075. // 使用中间页面而不是直接 redirect
  1076. // 这样可以添加延迟,让 HA 前端有时间处理 code
  1077. const intermediateHtml = `
  1078. <!DOCTYPE html>
  1079. <html lang="zh-CN">
  1080. <head>
  1081. <meta charset="UTF-8">
  1082. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1083. <title>正在登录 Home Assistant...</title>
  1084. <style>
  1085. body {
  1086. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  1087. color: white;
  1088. font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  1089. display: flex;
  1090. justify-content: center;
  1091. align-items: center;
  1092. height: 100vh;
  1093. margin: 0;
  1094. }
  1095. .container { text-align: center; }
  1096. .loader {
  1097. border: 4px solid rgba(255, 255, 255, 0.3);
  1098. border-top: 4px solid white;
  1099. border-radius: 50%;
  1100. width: 50px;
  1101. height: 50px;
  1102. animation: spin 1s linear infinite;
  1103. margin: 0 auto 20px;
  1104. }
  1105. @keyframes spin {
  1106. 0% { transform: rotate(0deg); }
  1107. 100% { transform: rotate(360deg); }
  1108. }
  1109. h2 { margin: 0 0 10px 0; }
  1110. p { margin: 5px 0; opacity: 0.9; font-size: 14px; }
  1111. </style>
  1112. </head>
  1113. <body>
  1114. <div class="container">
  1115. <div class="loader"></div>
  1116. <h2>正在登录...</h2>
  1117. <p>准备进入 Home Assistant</p>
  1118. </div>
  1119. <iframe id="authFrame" style="display:none;"></iframe>
  1120. <script>
  1121. // 使用 iframe 预加载带有 code 的 URL
  1122. // 让 HA 前端在后台完成 code → token 的交换
  1123. const authUrl = "${loginResult.redirectUrl}";
  1124. const targetUrl = "${config.targetBaseUrl}";
  1125. const iframe = document.getElementById('authFrame');
  1126. console.log('[降级方案] 使用 iframe 预加载:', authUrl);
  1127. // 设置 iframe 超时
  1128. let loaded = false;
  1129. iframe.onload = function() {
  1130. if (!loaded) {
  1131. loaded = true;
  1132. console.log('[降级方案] iframe 加载完成,等待 HA 处理 code...');
  1133. // 给 HA 足够时间处理 code
  1134. setTimeout(function() {
  1135. console.log('[降级方案] 跳转到主页');
  1136. window.location.href = targetUrl;
  1137. }, 2000);
  1138. }
  1139. };
  1140. // 加载带有 code 的 URL
  1141. iframe.src = authUrl;
  1142. // 保险起见,10秒后强制跳转
  1143. setTimeout(function() {
  1144. if (!loaded) {
  1145. console.log('[降级方案] 超时,强制跳转');
  1146. window.location.href = targetUrl;
  1147. }
  1148. }, 10000);
  1149. </script>
  1150. </body>
  1151. </html>
  1152. `;
  1153. console.log(`[${requestId}] 总耗时: ${Date.now() - startTime}ms`);
  1154. console.log('='.repeat(80) + '\n');
  1155. return res.send(intermediateHtml);
  1156. }
  1157. // 对于 GET 查询登录,如果有 redirectUrl,直接重定向
  1158. if (config.loginMethod === 'get-query-login' && loginResult.redirectUrl) {
  1159. console.log(`[${requestId}] GET 查询登录成功,重定向到: ${loginResult.redirectUrl}`);
  1160. console.log(`[${requestId}] 总耗时: ${Date.now() - startTime}ms`);
  1161. console.log('='.repeat(80) + '\n');
  1162. // 设置 Cookie 后重定向
  1163. loginResult.cookies.forEach((cookie, index) => {
  1164. let modifiedCookie = cookie.replace(/Domain=[^;]+/i, `Domain=${config.targetDomain}`);
  1165. res.setHeader('Set-Cookie', modifiedCookie);
  1166. console.log(`[${requestId}] 设置 Cookie ${index + 1}: ${modifiedCookie.substring(0, 80)}...`);
  1167. });
  1168. return res.redirect(loginResult.redirectUrl);
  1169. }
  1170. // 解析 Cookie
  1171. const cookieData = parseCookies(loginResult.cookies);
  1172. console.log(`[${requestId}] 解析到 ${cookieData.length} 个 Cookie:`);
  1173. cookieData.forEach((cookie, index) => {
  1174. console.log(`[${requestId}] Cookie ${index + 1}: ${cookie.name} = ${cookie.value.substring(0, 20)}...`);
  1175. });
  1176. // 生成跳转 HTML
  1177. let redirectUrl = `http://${config.targetHost}/`;
  1178. console.log(`[${requestId}] 生成跳转页面,目标: ${redirectUrl}`);
  1179. const html = generateRedirectHTML(
  1180. cookieData,
  1181. config.targetHost,
  1182. config.targetDomain,
  1183. requestId,
  1184. redirectUrl,
  1185. null
  1186. );
  1187. // 在响应头中设置 Cookie
  1188. console.log(`[${requestId}] 设置响应头 Cookie...`);
  1189. loginResult.cookies.forEach((cookie, index) => {
  1190. // 修改 Cookie 的 Domain,移除端口号
  1191. let modifiedCookie = cookie.replace(/Domain=[^;]+/i, `Domain=${config.targetDomain}`);
  1192. res.setHeader('Set-Cookie', modifiedCookie);
  1193. console.log(`[${requestId}] 设置 Cookie ${index + 1}: ${modifiedCookie.substring(0, 80)}...`);
  1194. });
  1195. const duration = Date.now() - startTime;
  1196. console.log(`[${requestId}] 总耗时: ${duration}ms`);
  1197. console.log(`[${requestId}] 返回跳转页面`);
  1198. console.log('='.repeat(80) + '\n');
  1199. res.send(html);
  1200. } catch (error) {
  1201. const duration = Date.now() - startTime;
  1202. console.error(`[${requestId}] 自动登录异常:`, error.message);
  1203. console.error(`[${requestId}] 错误堆栈:`, error.stack);
  1204. if (error.response) {
  1205. console.error(`[${requestId}] 响应状态:`, error.response.status);
  1206. console.error(`[${requestId}] 响应头:`, JSON.stringify(error.response.headers, null, 2));
  1207. console.error(`[${requestId}] 响应数据:`, JSON.stringify(error.response.data, null, 2));
  1208. }
  1209. if (error.request) {
  1210. console.error(`[${requestId}] 请求信息:`, {
  1211. url: error.config?.url,
  1212. method: error.config?.method,
  1213. headers: error.config?.headers
  1214. });
  1215. }
  1216. console.log(`[${requestId}] 总耗时: ${duration}ms`);
  1217. console.log('='.repeat(80) + '\n');
  1218. res.status(500).json({
  1219. success: false,
  1220. message: '自动登录失败: ' + error.message,
  1221. error: process.env.NODE_ENV === 'development' ? error.stack : undefined
  1222. });
  1223. }
  1224. });
  1225. // Home Assistant 登录代理端点(解决浏览器 CORS 问题)
  1226. app.post('/api/home-assistant-proxy/login-flow', async (req, res) => {
  1227. try {
  1228. const targetBaseUrl = req.body.targetBaseUrl;
  1229. console.log('[代理] 创建 Home Assistant 登录流程:', targetBaseUrl);
  1230. const response = await axios.post(
  1231. `${targetBaseUrl}/auth/login_flow`,
  1232. {
  1233. client_id: `${targetBaseUrl}/`,
  1234. handler: ['homeassistant', null],
  1235. redirect_uri: `${targetBaseUrl}/`
  1236. },
  1237. {
  1238. headers: {
  1239. 'Content-Type': 'application/json'
  1240. }
  1241. }
  1242. );
  1243. res.json(response.data);
  1244. } catch (error) {
  1245. console.error('[代理] 创建登录流程失败:', error.message);
  1246. res.status(500).json({ error: error.message });
  1247. }
  1248. });
  1249. app.post('/api/home-assistant-proxy/login', async (req, res) => {
  1250. try {
  1251. const { targetBaseUrl, flowId, username, password } = req.body;
  1252. console.log('[代理] 提交 Home Assistant 登录凭据:', targetBaseUrl, flowId);
  1253. const response = await axios.post(
  1254. `${targetBaseUrl}/auth/login_flow/${flowId}`,
  1255. {
  1256. username: username,
  1257. password: password,
  1258. client_id: `${targetBaseUrl}/`
  1259. },
  1260. {
  1261. headers: {
  1262. 'Content-Type': 'application/json'
  1263. }
  1264. }
  1265. );
  1266. res.json(response.data);
  1267. } catch (error) {
  1268. console.error('[代理] 登录失败:', error.message);
  1269. res.status(500).json({ error: error.message });
  1270. }
  1271. });
  1272. // 获取所有配置的网站列表
  1273. app.get('/api/auto-login', (req, res) => {
  1274. const sites = Object.keys(autoLoginConfig).map(siteId => ({
  1275. id: siteId,
  1276. name: autoLoginConfig[siteId].name,
  1277. endpoint: `/api/auto-login/${siteId}`
  1278. }));
  1279. res.json({ sites });
  1280. });
  1281. // 健康检查端点
  1282. app.get('/api/health', (req, res) => {
  1283. res.json({
  1284. status: 'ok',
  1285. timestamp: new Date().toISOString(),
  1286. port: PORT,
  1287. configuredSites: Object.keys(autoLoginConfig)
  1288. });
  1289. });
  1290. // 测试端点 - 用于验证配置
  1291. app.get('/api/test/:siteId', (req, res) => {
  1292. const { siteId } = req.params;
  1293. const config = autoLoginConfig[siteId];
  1294. if (!config) {
  1295. return res.json({
  1296. success: false,
  1297. message: `未找到网站ID "${siteId}" 的配置`,
  1298. availableSites: Object.keys(autoLoginConfig)
  1299. });
  1300. }
  1301. const envUsername = process.env[config.credentials.envUsername];
  1302. const envPassword = process.env[config.credentials.envPassword];
  1303. const credentials = {
  1304. username: envUsername || config.credentials.username,
  1305. password: envPassword || config.credentials.password
  1306. };
  1307. res.json({
  1308. success: true,
  1309. siteId,
  1310. config: {
  1311. name: config.name,
  1312. targetBaseUrl: config.targetBaseUrl,
  1313. loginMethod: config.loginMethod,
  1314. loginUrl: config.loginUrl,
  1315. hasCredentials: !!(credentials.username && credentials.password),
  1316. credentialsSource: envUsername ? '环境变量' : '配置文件',
  1317. username: credentials.username,
  1318. passwordLength: credentials.password ? credentials.password.length : 0
  1319. }
  1320. });
  1321. });
  1322. app.listen(PORT, '0.0.0.0', () => {
  1323. console.log('\n' + '='.repeat(80));
  1324. console.log('🚀 后端服务器启动成功!');
  1325. console.log('='.repeat(80));
  1326. console.log(`📍 本地地址: http://localhost:${PORT}`);
  1327. console.log(`📍 服务器地址: http://0.0.0.0:${PORT}`);
  1328. console.log(`📍 外部访问: http://222.243.138.146:${PORT} (通过防火墙端口映射)`);
  1329. console.log(`\n📋 已配置的自动登录网站: ${Object.keys(autoLoginConfig).join(', ') || '无'}`);
  1330. console.log(`\n🔗 可用端点:`);
  1331. console.log(` - 健康检查: http://localhost:${PORT}/api/health`);
  1332. console.log(` - 测试配置: http://localhost:${PORT}/api/test/:siteId`);
  1333. console.log(` - 自动登录: http://localhost:${PORT}/api/auto-login/:siteId`);
  1334. console.log(`\n💡 提示: 确保防火墙已配置端口映射 (前端:8888, 后端:8889 -> 外网)`);
  1335. console.log('='.repeat(80) + '\n');
  1336. });