homebridge-melcloud-control 4.0.0-beta.375 → 4.0.0-beta.376

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "displayName": "MELCloud Control",
3
3
  "name": "homebridge-melcloud-control",
4
- "version": "4.0.0-beta.375",
4
+ "version": "4.0.0-beta.376",
5
5
  "description": "Homebridge plugin to control Mitsubishi Air Conditioner, Heat Pump and Energy Recovery Ventilation.",
6
6
  "license": "MIT",
7
7
  "author": "grzegorz914",
@@ -1,8 +1,8 @@
1
1
  import axios from 'axios';
2
2
  import crypto from 'crypto';
3
- import { JSDOM } from 'jsdom';
4
3
  import { wrapper } from 'axios-cookiejar-support';
5
4
  import { CookieJar } from 'tough-cookie';
5
+ import { JSDOM } from 'jsdom';
6
6
  import EventEmitter from 'events';
7
7
 
8
8
  const MOBILE_USER_AGENT = 'MonitorAndControl.App.Mobile/35 CFNetwork/3860.100.1 Darwin/25.0.0';
@@ -21,12 +21,8 @@ class MelCloudHomeToken extends EventEmitter {
21
21
  this.logError = config.logError;
22
22
 
23
23
  const jar = new CookieJar();
24
- this.axiosInstance = wrapper(axios.create({
25
- headers: { 'User-Agent': MOBILE_USER_AGENT },
26
- jar,
27
- withCredentials: true,
28
- maxRedirects: 0,
29
- }));
24
+ this.axiosInstance = wrapper(axios.create({ jar, withCredentials: true }));
25
+ this.client.defaults.headers['User-Agent'] = MOBILE_USER_AGENT;
30
26
  }
31
27
 
32
28
  generatePKCE() {
@@ -36,80 +32,124 @@ class MelCloudHomeToken extends EventEmitter {
36
32
  }
37
33
 
38
34
  generateState() {
39
- return crypto.randomBytes(16).toString('hex');
35
+ return crypto.randomBytes(32).toString('hex');
40
36
  }
41
37
 
42
38
  async getLoginPage(authUrl) {
43
- const res = await this.axiosInstance.get(authUrl);
39
+ const res = await this.client.get(authUrl, { maxRedirects: 10 });
44
40
  return { url: res.request.res.responseUrl };
45
41
  }
46
42
 
47
43
  async getTokens(code, codeVerifier) {
48
- const tokenData = new URLSearchParams({
49
- grant_type: 'authorization_code',
50
- code,
51
- redirect_uri: REDIRECT_URI,
52
- client_id: CLIENT_ID,
53
- code_verifier: codeVerifier,
54
- });
55
-
56
44
  try {
57
- const res = await this.axiosInstance.post(
58
- TOKEN_ENDPOINT,
59
- tokenData.toString(),
60
- { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
61
- );
62
-
63
- this.emit('warn', `Tokens: ${JSON.stringify(res.data)}`);
64
- return res.data;
45
+ const tokenData = new URLSearchParams({
46
+ grant_type: 'authorization_code',
47
+ code: code,
48
+ redirect_uri: REDIRECT_URI,
49
+ client_id: CLIENT_ID,
50
+ code_verifier: codeVerifier,
51
+ });
52
+
53
+ const tokenResponse = await this.client.post(TOKEN_ENDPOINT, tokenData.toString(), {
54
+ headers: {
55
+ 'Content-Type': 'application/x-www-form-urlencoded',
56
+ 'Authorization': 'Basic aG9tZW1vYmlsZTo=',
57
+ },
58
+ });
59
+
60
+ const tokens = tokenResponse.data;
61
+ this.emit('warn', `Token ${JSON.stringify(tokens)}`);
62
+ return tokens;
65
63
  } catch (error) {
66
- throw new Error(`Token request failed: ${error.response?.data || error.message}`);
64
+ throw new Error(`Failed to obtain OAuth token: ${error}`);
67
65
  }
68
66
  }
69
67
 
70
68
  async loginToMelCloudHome(url) {
71
- const resp = await this.axiosInstance.get(url);
72
- const dom = new JSDOM(resp.data);
73
- const csrf = dom.window.document.querySelector('input[name="_csrf"]')?.value;
74
- if (!csrf) throw new Error('No CSRF token found');
75
-
76
- const formData = new URLSearchParams({
77
- _csrf: csrf,
78
- username: this.user,
79
- password: this.passwd,
80
- });
81
-
82
- let next = url;
83
- for (let i = 0; i < 10 && next; i++) {
84
- const res = await this.axiosInstance.post(next, formData.toString(), {
85
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
86
- validateStatus: s => [200, 302].includes(s),
69
+ try {
70
+ // Step 1: Pobierz stronę logowania, żeby uzyskać sesję + token _csrf
71
+ const getResp = await this.client.get(url, {
72
+ headers: {
73
+ 'User-Agent': MOBILE_USER_AGENT,
74
+ 'Accept': 'text/html',
75
+ }
76
+ });
77
+
78
+ const cookies = getResp.headers['set-cookie'] || [];
79
+ const dom = new JSDOM(getResp.data);
80
+ const csrf = dom.window.document.querySelector('input[name="_csrf"]')?.value;
81
+ if (!csrf) {
82
+ if (this.logWarn) this.emit('warn', `CSRF token not found`);
83
+ return null;
84
+ }
85
+
86
+ // Step 2: Przygotuj dane logowania
87
+ const formData = new URLSearchParams({
88
+ _csrf: csrf,
89
+ username: this.user,
90
+ password: this.passwd,
87
91
  });
88
92
 
89
- next = res.headers.location;
90
- if (next && next.includes('code=')) {
91
- const code = new URL(next).searchParams.get('code');
92
- this.emit('warn', `Code found: ${code}`);
93
- return code;
93
+ if (this.logWarn) this.emit('warn', `Redirect URL: ${url}`);
94
+
95
+ // Step 3: Wyślij POST z danymi logowania
96
+ const response = await this.client.post(url, formData.toString(), {
97
+ headers: {
98
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
99
+ 'Accept-Language': 'en-US,en;q=0.9',
100
+ 'Content-Type': 'application/x-www-form-urlencoded',
101
+ 'Content-Length': formData.toString().length,
102
+ 'Cookie': cookies,
103
+ 'Origin': 'https://live-melcloudhome.auth.eu-west-1.amazoncognito.com',
104
+ 'Referer': url,
105
+ },
106
+ maxRedirects: 0,
107
+ validateStatus: status => [200, 302, 400].includes(status),
108
+ });
109
+
110
+ if (response.status === 400) if (this.logWarn) this.emit('warn', `Login failed (bad request or invalid credentials: ${response.data}`);
111
+ if (response.status === 302 && response.headers.location) {
112
+ // Login success — mamy redirect z "code="
113
+ const redirectUrl = response.headers.location;
114
+ if (this.logWarn) this.emit('warn', `Redirect URL: ${redirectUrl}`);
115
+ if (this.logWarn) this.emit('warn', `Response headers: ${response.headers}`);
116
+
117
+ const match = redirectUrl.match(/[?&]code=([^&]+)/);
118
+ if (match) {
119
+ const code = match[1];
120
+ if (this.logWarn) this.emit('warn', `Redirect URL found code: ${code}`);
121
+ return code;
122
+ } else {
123
+ if (this.logWarn) this.emit('warn', `Redirect URL found, but no "code=" param: ${redirectUrl}`);
124
+ return null;
125
+ }
94
126
  }
127
+
128
+ return null;
129
+ } catch (error) {
130
+ throw new Error(`Login to MELCloud Home error: ${error}`);
95
131
  }
96
- throw new Error('Authorization code not found');
97
132
  }
98
133
 
99
134
  async buildAuthorizeUrl() {
100
- const pkce = this.generatePKCE();
101
- const state = this.generateState();
102
- const authUrl = new URL(AUTHORIZE_ENDPOINT);
103
- authUrl.searchParams.set('client_id', CLIENT_ID);
104
- authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
105
- authUrl.searchParams.set('response_type', 'code');
106
- authUrl.searchParams.set('scope', SCOPE);
107
- authUrl.searchParams.set('code_challenge', pkce.challenge);
108
- authUrl.searchParams.set('code_challenge_method', 'S256');
109
- authUrl.searchParams.set('state', state);
110
-
111
- const loginPage = await this.getLoginPage(authUrl.toString());
112
- return { codeVerifier: pkce.verifier, url: loginPage.url };
135
+ try {
136
+ const pkce = this.generatePKCE();
137
+ const state = this.generateState();
138
+ const authUrl = new URL(AUTHORIZE_ENDPOINT);
139
+ authUrl.searchParams.set('client_id', CLIENT_ID);
140
+ authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
141
+ authUrl.searchParams.set('response_type', 'code');
142
+ authUrl.searchParams.set('scope', SCOPE);
143
+ authUrl.searchParams.set('code_challenge', pkce.challenge);
144
+ authUrl.searchParams.set('code_challenge_method', 'S256');
145
+ authUrl.searchParams.set('state', state);
146
+
147
+ const loginPage = await this.getLoginPage(authUrl.toString());
148
+ const data = { codeVerifier: pkce.verifier, url: loginPage.url }
149
+ return data;
150
+ } catch (error) {
151
+ throw new Error(`Failed to obtain OAuth link: ${error}`);
152
+ }
113
153
  }
114
154
  }
115
155
 
@@ -119,4 +159,3 @@ export default MelCloudHomeToken;
119
159
 
120
160
 
121
161
 
122
-