server.js 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  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 查询登录,创建一个代理端点,返回 HTML 页面自动处理登录和跳转
  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. // 重新构建登录 URL(带参数)
  1168. const { targetBaseUrl, loginUrl, loginMethodConfig } = config;
  1169. const { usernameParam, passwordParam, entCode, saveCookie, isOnly } = loginMethodConfig;
  1170. const params = new URLSearchParams();
  1171. params.append(usernameParam, credentials.username);
  1172. params.append(passwordParam, credentials.password);
  1173. params.append('ent_code', entCode);
  1174. params.append('code', 'undefined');
  1175. params.append('mySel', 'undefined');
  1176. params.append('saveCookie', saveCookie);
  1177. params.append('isOnly', isOnly);
  1178. params.append('_', Date.now().toString());
  1179. const loginUrlWithParams = `${targetBaseUrl}${loginUrl}?${params.toString()}`;
  1180. // 生成 HTML:使用 window.open 在新窗口打开登录 URL,然后在新窗口跳转
  1181. // 这是最可靠的方法,因为新窗口可以正常设置 Cookie
  1182. const html = `
  1183. <!DOCTYPE html>
  1184. <html lang="zh-CN">
  1185. <head>
  1186. <meta charset="UTF-8">
  1187. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1188. <title>自动登录中...</title>
  1189. <style>
  1190. body {
  1191. display: flex;
  1192. justify-content: center;
  1193. align-items: center;
  1194. height: 100vh;
  1195. margin: 0;
  1196. font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  1197. background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  1198. }
  1199. .loading {
  1200. text-align: center;
  1201. }
  1202. .spinner {
  1203. border: 4px solid #f3f3f3;
  1204. border-top: 4px solid #3498db;
  1205. border-radius: 50%;
  1206. width: 50px;
  1207. height: 50px;
  1208. animation: spin 1s linear infinite;
  1209. margin: 0 auto 20px;
  1210. }
  1211. @keyframes spin {
  1212. 0% { transform: rotate(0deg); }
  1213. 100% { transform: rotate(360deg); }
  1214. }
  1215. .message {
  1216. color: #333;
  1217. font-size: 18px;
  1218. }
  1219. </style>
  1220. </head>
  1221. <body>
  1222. <div class="loading">
  1223. <div class="spinner"></div>
  1224. <div class="message">正在自动登录,请稍候...</div>
  1225. </div>
  1226. <script>
  1227. (function() {
  1228. const loginUrl = '${loginUrlWithParams.replace(/'/g, "\\'")}';
  1229. const targetUrl = '${loginResult.redirectUrl.replace(/'/g, "\\'")}';
  1230. console.log('[浏览器端] GET 查询登录 - 直接跳转方案');
  1231. console.log('[浏览器端] 登录 URL:', loginUrl);
  1232. console.log('[浏览器端] 目标 URL:', targetUrl);
  1233. // 最可靠的方案:直接跳转到登录 URL,让服务器设置 Cookie
  1234. // 然后立即跳转到目标页面(用户可能会短暂看到 "ok")
  1235. console.log('[浏览器端] 直接跳转到登录 URL(让服务器设置 Cookie)...');
  1236. console.log('[浏览器端] 登录 URL:', loginUrl);
  1237. console.log('[浏览器端] 目标 URL:', targetUrl);
  1238. // 直接跳转到登录 URL
  1239. // 登录 URL 返回 "ok" 后,Cookie 已设置
  1240. // 但由于登录 URL 返回的是纯文本,无法执行 JavaScript
  1241. // 所以我们需要在跳转前设置一个机制来自动跳转
  1242. // 方案:使用 window.location.replace 跳转到登录 URL
  1243. // 然后立即(在同一页面)跳转到目标页面
  1244. // 但由于页面会跳转,当前脚本会停止执行
  1245. // 实际上,最可靠的方案是:直接跳转到登录 URL
  1246. // 然后用户手动跳转到目标页面(或者等待自动跳转,如果服务器支持)
  1247. // 但这不好
  1248. // 让我们尝试一个变通方案:使用 window.location.href 跳转到登录 URL
  1249. // 然后立即(通过定时器)跳转到目标页面
  1250. // 但由于页面会跳转,定时器可能无法执行
  1251. // 所以,最可靠的方案是:直接跳转到登录 URL
  1252. // 然后用户手动跳转到目标页面
  1253. // 但我们可以尝试:先跳转到登录 URL,然后立即跳转到目标页面
  1254. // 使用 window.location.replace 避免在历史记录中留下登录页面
  1255. window.location.replace(loginUrl);
  1256. // 注意:由于登录 URL 返回的是纯文本 "ok",无法执行后续的 JavaScript
  1257. // 所以这个跳转可能无法自动完成
  1258. // 用户需要手动访问目标 URL,或者等待服务器重定向(如果支持)
  1259. })();
  1260. </script>
  1261. </body>
  1262. </html>
  1263. `;
  1264. const duration = Date.now() - startTime;
  1265. console.log(`[${requestId}] 总耗时: ${duration}ms`);
  1266. console.log(`[${requestId}] 返回直接跳转登录页面`);
  1267. console.log(`[${requestId}] 登录 URL: ${loginUrlWithParams}`);
  1268. console.log(`[${requestId}] 目标 URL: ${loginResult.redirectUrl}`);
  1269. console.log('='.repeat(80) + '\n');
  1270. return res.send(html);
  1271. }
  1272. // 解析 Cookie
  1273. const cookieData = parseCookies(loginResult.cookies);
  1274. console.log(`[${requestId}] 解析到 ${cookieData.length} 个 Cookie:`);
  1275. cookieData.forEach((cookie, index) => {
  1276. console.log(`[${requestId}] Cookie ${index + 1}: ${cookie.name} = ${cookie.value.substring(0, 20)}...`);
  1277. });
  1278. // 生成跳转 HTML
  1279. let redirectUrl = `http://${config.targetHost}/`;
  1280. console.log(`[${requestId}] 生成跳转页面,目标: ${redirectUrl}`);
  1281. const html = generateRedirectHTML(
  1282. cookieData,
  1283. config.targetHost,
  1284. config.targetDomain,
  1285. requestId,
  1286. redirectUrl,
  1287. null
  1288. );
  1289. // 在响应头中设置 Cookie
  1290. console.log(`[${requestId}] 设置响应头 Cookie...`);
  1291. loginResult.cookies.forEach((cookie, index) => {
  1292. // 修改 Cookie 的 Domain,移除端口号
  1293. let modifiedCookie = cookie.replace(/Domain=[^;]+/i, `Domain=${config.targetDomain}`);
  1294. res.setHeader('Set-Cookie', modifiedCookie);
  1295. console.log(`[${requestId}] 设置 Cookie ${index + 1}: ${modifiedCookie.substring(0, 80)}...`);
  1296. });
  1297. const duration = Date.now() - startTime;
  1298. console.log(`[${requestId}] 总耗时: ${duration}ms`);
  1299. console.log(`[${requestId}] 返回跳转页面`);
  1300. console.log('='.repeat(80) + '\n');
  1301. res.send(html);
  1302. } catch (error) {
  1303. const duration = Date.now() - startTime;
  1304. console.error(`[${requestId}] 自动登录异常:`, error.message);
  1305. console.error(`[${requestId}] 错误堆栈:`, error.stack);
  1306. if (error.response) {
  1307. console.error(`[${requestId}] 响应状态:`, error.response.status);
  1308. console.error(`[${requestId}] 响应头:`, JSON.stringify(error.response.headers, null, 2));
  1309. console.error(`[${requestId}] 响应数据:`, JSON.stringify(error.response.data, null, 2));
  1310. }
  1311. if (error.request) {
  1312. console.error(`[${requestId}] 请求信息:`, {
  1313. url: error.config?.url,
  1314. method: error.config?.method,
  1315. headers: error.config?.headers
  1316. });
  1317. }
  1318. console.log(`[${requestId}] 总耗时: ${duration}ms`);
  1319. console.log('='.repeat(80) + '\n');
  1320. res.status(500).json({
  1321. success: false,
  1322. message: '自动登录失败: ' + error.message,
  1323. error: process.env.NODE_ENV === 'development' ? error.stack : undefined
  1324. });
  1325. }
  1326. });
  1327. // Home Assistant 登录代理端点(解决浏览器 CORS 问题)
  1328. app.post('/api/home-assistant-proxy/login-flow', async (req, res) => {
  1329. try {
  1330. const targetBaseUrl = req.body.targetBaseUrl;
  1331. console.log('[代理] 创建 Home Assistant 登录流程:', targetBaseUrl);
  1332. const response = await axios.post(
  1333. `${targetBaseUrl}/auth/login_flow`,
  1334. {
  1335. client_id: `${targetBaseUrl}/`,
  1336. handler: ['homeassistant', null],
  1337. redirect_uri: `${targetBaseUrl}/`
  1338. },
  1339. {
  1340. headers: {
  1341. 'Content-Type': 'application/json'
  1342. }
  1343. }
  1344. );
  1345. res.json(response.data);
  1346. } catch (error) {
  1347. console.error('[代理] 创建登录流程失败:', error.message);
  1348. res.status(500).json({ error: error.message });
  1349. }
  1350. });
  1351. app.post('/api/home-assistant-proxy/login', async (req, res) => {
  1352. try {
  1353. const { targetBaseUrl, flowId, username, password } = req.body;
  1354. console.log('[代理] 提交 Home Assistant 登录凭据:', targetBaseUrl, flowId);
  1355. const response = await axios.post(
  1356. `${targetBaseUrl}/auth/login_flow/${flowId}`,
  1357. {
  1358. username: username,
  1359. password: password,
  1360. client_id: `${targetBaseUrl}/`
  1361. },
  1362. {
  1363. headers: {
  1364. 'Content-Type': 'application/json'
  1365. }
  1366. }
  1367. );
  1368. res.json(response.data);
  1369. } catch (error) {
  1370. console.error('[代理] 登录失败:', error.message);
  1371. res.status(500).json({ error: error.message });
  1372. }
  1373. });
  1374. // 获取所有配置的网站列表
  1375. app.get('/api/auto-login', (req, res) => {
  1376. const sites = Object.keys(autoLoginConfig).map(siteId => ({
  1377. id: siteId,
  1378. name: autoLoginConfig[siteId].name,
  1379. endpoint: `/api/auto-login/${siteId}`
  1380. }));
  1381. res.json({ sites });
  1382. });
  1383. // 健康检查端点
  1384. app.get('/api/health', (req, res) => {
  1385. res.json({
  1386. status: 'ok',
  1387. timestamp: new Date().toISOString(),
  1388. port: PORT,
  1389. configuredSites: Object.keys(autoLoginConfig)
  1390. });
  1391. });
  1392. // 测试端点 - 用于验证配置
  1393. app.get('/api/test/:siteId', (req, res) => {
  1394. const { siteId } = req.params;
  1395. const config = autoLoginConfig[siteId];
  1396. if (!config) {
  1397. return res.json({
  1398. success: false,
  1399. message: `未找到网站ID "${siteId}" 的配置`,
  1400. availableSites: Object.keys(autoLoginConfig)
  1401. });
  1402. }
  1403. const envUsername = process.env[config.credentials.envUsername];
  1404. const envPassword = process.env[config.credentials.envPassword];
  1405. const credentials = {
  1406. username: envUsername || config.credentials.username,
  1407. password: envPassword || config.credentials.password
  1408. };
  1409. res.json({
  1410. success: true,
  1411. siteId,
  1412. config: {
  1413. name: config.name,
  1414. targetBaseUrl: config.targetBaseUrl,
  1415. loginMethod: config.loginMethod,
  1416. loginUrl: config.loginUrl,
  1417. hasCredentials: !!(credentials.username && credentials.password),
  1418. credentialsSource: envUsername ? '环境变量' : '配置文件',
  1419. username: credentials.username,
  1420. passwordLength: credentials.password ? credentials.password.length : 0
  1421. }
  1422. });
  1423. });
  1424. app.listen(PORT, '0.0.0.0', () => {
  1425. console.log('\n' + '='.repeat(80));
  1426. console.log('🚀 后端服务器启动成功!');
  1427. console.log('='.repeat(80));
  1428. console.log(`📍 本地地址: http://localhost:${PORT}`);
  1429. console.log(`📍 服务器地址: http://0.0.0.0:${PORT}`);
  1430. console.log(`📍 外部访问: http://222.243.138.146:${PORT} (通过防火墙端口映射)`);
  1431. console.log(`\n📋 已配置的自动登录网站: ${Object.keys(autoLoginConfig).join(', ') || '无'}`);
  1432. console.log(`\n🔗 可用端点:`);
  1433. console.log(` - 健康检查: http://localhost:${PORT}/api/health`);
  1434. console.log(` - 测试配置: http://localhost:${PORT}/api/test/:siteId`);
  1435. console.log(` - 自动登录: http://localhost:${PORT}/api/auto-login/:siteId`);
  1436. console.log(`\n💡 提示: 确保防火墙已配置端口映射 (前端:8888, 后端:8889 -> 外网)`);
  1437. console.log('='.repeat(80) + '\n');
  1438. });