homebridge-melcloud-control 4.0.0-beta.391 → 4.0.0-beta.393

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.391",
4
+ "version": "4.0.0-beta.393",
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,16 +1,16 @@
1
- import axios from 'axios';
2
1
  import crypto from 'crypto';
3
2
  import { wrapper } from 'axios-cookiejar-support';
4
3
  import { CookieJar } from 'tough-cookie';
5
- import { JSDOM } from 'jsdom';
4
+ import axios from 'axios';
6
5
  import EventEmitter from 'events';
6
+ import puppeteer from 'puppeteer';
7
7
 
8
- const MOBILE_USER_AGENT = 'MonitorAndControl.App.Mobile/35 CFNetwork/3860.100.1 Darwin/25.0.0';
9
8
  const CLIENT_ID = 'homemobile';
10
9
  const REDIRECT_URI = 'melcloudhome://';
11
10
  const SCOPE = 'openid profile email offline_access IdentityServerApi';
12
11
  const TOKEN_ENDPOINT = 'https://auth.melcloudhome.com/connect/token';
13
12
  const AUTHORIZE_ENDPOINT = 'https://auth.melcloudhome.com/connect/authorize';
13
+ const MOBILE_USER_AGENT = 'MonitorAndControl.App.Mobile/35 CFNetwork/3860.100.1 Darwin/25.0.0';
14
14
 
15
15
  class MelCloudHomeToken extends EventEmitter {
16
16
  constructor(config) {
@@ -35,228 +35,80 @@ class MelCloudHomeToken extends EventEmitter {
35
35
  return crypto.randomBytes(32).toString('hex');
36
36
  }
37
37
 
38
- async getLoginPage(authUrl) {
39
- const res = await this.client.get(authUrl, { maxRedirects: 10 });
40
- return { url: res.request.res.responseUrl };
38
+ async buildAuthorizeUrl() {
39
+ const pkce = this.generatePKCE();
40
+ const state = this.generateState();
41
+ const authUrl = new URL(AUTHORIZE_ENDPOINT);
42
+ authUrl.searchParams.set('client_id', CLIENT_ID);
43
+ authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
44
+ authUrl.searchParams.set('response_type', 'code');
45
+ authUrl.searchParams.set('scope', SCOPE);
46
+ authUrl.searchParams.set('code_challenge', pkce.challenge);
47
+ authUrl.searchParams.set('code_challenge_method', 'S256');
48
+ authUrl.searchParams.set('state', state);
49
+ return { url: authUrl.toString(), codeVerifier: pkce.verifier };
41
50
  }
42
51
 
43
- async getTokens(code, codeVerifier) {
52
+ async loginToMelCloudHome(authUrl) {
44
53
  try {
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
- this.emit('warn', `Code used: ${code}`);
54
- this.emit('warn', `Verifier: ${codeVerifier}`);
55
- this.emit('warn', `Redirect URI: ${REDIRECT_URI}`);
56
-
57
- const tokenResponse = await this.client.post(TOKEN_ENDPOINT, tokenData.toString(), {
58
- headers: {
59
- 'Content-Type': 'application/x-www-form-urlencoded'
60
- },
61
- });
62
-
63
- const tokens = tokenResponse.data;
64
- this.emit('warn', `Token ${JSON.stringify(tokens)}`);
65
- return tokens;
66
- } catch (error) {
67
- if (error.response) {
68
- this.emit('warn', `Token error response: ${JSON.stringify(error.response.data)}`);
69
- }
70
- throw new Error(`Failed to obtain OAuth token: ${error}`);
71
- }
72
- }
73
-
74
- async extractCodeFromResponse(data, headers, followRedirect) {
75
- return new Promise(async (resolve, reject) => {
76
- try {
77
- const locationHeader = headers['location'] || headers['Location'];
78
-
79
- // 1️⃣ Location header
80
- if (locationHeader && locationHeader.startsWith('melcloudhome://')) {
81
- const match = locationHeader.match(/[?&]code=([^&]+)/);
82
- if (match) {
83
- this.emit('warn', `Found code in Location header: ${match[1]}`);
84
- resolve(match[1]);
85
- return;
86
- }
87
- }
88
-
89
- // 2️⃣ form_post HTML
90
- const formCodeMatch = data.match(/name="code"\s+value="([^"]+)"/);
91
- const formStateMatch = data.match(/name="state"\s+value="([^"]+)"/);
92
- const formActionMatch = data.match(/action="([^"]+)"/);
93
-
94
- if (formCodeMatch && formStateMatch && formActionMatch) {
95
- this.emit('warn', 'Found form_post response, submitting to callback endpoint...');
96
- try {
97
- const code = await this.submitFormPost(formActionMatch[1], formCodeMatch[1], formStateMatch[1]);
98
- this.emit('warn', `submitFormPost returned code: ${code}`);
99
- resolve(code);
100
- return;
101
- } catch (err) {
102
- this.emit('warn', `submitFormPost failed: ${err}`);
103
- reject(err);
104
- return;
105
- }
106
- }
54
+ this.emit('warn', `Opening Puppeteer for auth URL`);
55
+ const browser = await puppeteer.launch({ headless: true });
56
+ const page = await browser.newPage();
57
+ await page.setUserAgent(MOBILE_USER_AGENT);
107
58
 
108
- // 3️⃣ JS redirect w body
109
- const bodyCodeMatch = data.match(/melcloudhome:\/\/[^"'\s]*[?&]code=([^&"'\s]+)/);
110
- if (bodyCodeMatch) {
111
- this.emit('warn', `Found code in response body: ${bodyCodeMatch[1]}`);
112
- resolve(bodyCodeMatch[1]);
113
- return;
114
- }
59
+ await page.goto(authUrl, { waitUntil: 'networkidle0' });
115
60
 
116
- // 4️⃣ Follow redirect
117
- if (locationHeader && ['301', '302', '303'].includes(headers['status'] || '')) {
118
- this.emit('warn', `Following redirect to ${locationHeader}`);
119
- try {
120
- const code = await followRedirect(locationHeader);
121
- resolve(code);
122
- return;
123
- } catch (err) {
124
- this.emit('warn', `Follow redirect failed: ${err}`);
125
- reject(err);
126
- return;
127
- }
128
- }
61
+ // Wpisz login i hasło
62
+ await page.type('input[name="username"]', this.user);
63
+ await page.type('input[name="password"]', this.passwd);
129
64
 
130
- this.emit('warn', 'Authorization code not found in response');
131
- reject(new Error('Authorization code not found'));
132
- } catch (error) {
133
- this.emit('warn', `extractCodeFromResponse error: ${error}`);
134
- reject(error);
135
- }
136
- });
137
- }
65
+ // Kliknij przycisk login
66
+ await Promise.all([
67
+ page.click('button[type="submit"]'),
68
+ page.waitForNavigation({ waitUntil: 'networkidle0' })
69
+ ]);
138
70
 
139
- // submitFormPost w JS
140
- async submitFormPost(actionUrl, code, state) {
141
- const formData = new URLSearchParams({ code, state });
142
- this.emit('warn', `Submitting form_post to ${actionUrl}`);
143
- const res = await this.client.post(actionUrl, formData.toString(), {
144
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
145
- maxRedirects: 0,
146
- validateStatus: status => [200, 302, 303].includes(status),
147
- });
71
+ const redirectedUrl = page.url();
72
+ await browser.close();
148
73
 
149
- const location = res.headers['location'];
150
- if (location) {
151
- const match = location.match(/[?&]code=([^&]+)/);
74
+ const match = redirectedUrl.match(/[?&]code=([^&]+)/);
152
75
  if (match) {
153
- this.emit('warn', `Form post redirect returned code: ${match[1]}`);
154
- return match[1];
155
- }
156
- }
157
-
158
- this.emit('warn', 'Code not found after form_post submission');
159
- throw new Error('Code not found after form_post submission');
160
- }
161
-
162
-
163
- async loginToMelCloudHome(url) {
164
- try {
165
- // Step 1: Pobierz stronę logowania
166
- const getResp = await this.client.get(url, {
167
- headers: { 'Accept': 'text/html' }
168
- });
169
-
170
- const cookies = getResp.headers['set-cookie'] || [];
171
- const dom = new JSDOM(getResp.data);
172
- const csrf = dom.window.document.querySelector('input[name="_csrf"]')?.value;
173
- if (!csrf) {
174
- this.emit('warn', `CSRF token not found`);
175
- return null;
176
- }
177
-
178
- // Step 2: Przygotuj dane logowania
179
- const formData = new URLSearchParams({
180
- _csrf: csrf,
181
- username: this.user,
182
- password: this.passwd,
183
- });
184
-
185
- // Step 3: Wyślij POST z danymi logowania
186
- const response = await this.client.post(url, formData.toString(), {
187
- headers: {
188
- 'User-Agent': MOBILE_USER_AGENT,
189
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
190
- 'Accept-Language': 'en-US,en;q=0.9',
191
- 'Content-Type': 'application/x-www-form-urlencoded',
192
- 'Content-Length': formData.toString().length,
193
- 'Cookie': cookies.join('; '),
194
- 'Origin': 'https://live-melcloudhome.auth.eu-west-1.amazoncognito.com',
195
- 'Referer': url,
196
- },
197
- maxRedirects: 0,
198
- validateStatus: status => [200, 302, 400].includes(status),
199
- });
200
-
201
- if (response.status === 400) {
202
- this.emit('warn', `Login failed (bad request or invalid credentials): ${response.data}`);
76
+ const code = match[1];
77
+ this.emit('warn', `Authorization code obtained: ${code}`);
78
+ return code;
79
+ } else {
80
+ this.emit('warn', `Authorization code not found in Puppeteer redirect`);
203
81
  return null;
204
82
  }
205
83
 
206
- // Step 4: Pobierz Authorization Code
207
- if (response.status === 200 || response.status === 302) {
208
- try {
209
- const code = await this.extractCodeFromResponse(
210
- response.data, // HTML lub body
211
- response.headers, // nagłówki
212
- async (url) => { // followRedirect
213
- const r = await this.client.get(url, {
214
- maxRedirects: 0,
215
- validateStatus: status => [200, 302, 303].includes(status),
216
- });
217
- return this.extractCodeFromResponse(r.data, r.headers, followRedirect);
218
- }
219
- );
220
-
221
- if (code) {
222
- this.emit('warn', `Authorization code obtained: ${code}`);
223
- return code;
224
- } else {
225
- this.emit('warn', 'Authorization code not found in response');
226
- return null;
227
- }
228
- } catch (err) {
229
- this.emit('warn', `extractCodeFromResponse error: ${err}`);
230
- return null;
231
- }
232
- }
233
-
84
+ } catch (err) {
85
+ this.emit('warn', `loginToMelCloudHome error: ${err}`);
234
86
  return null;
235
-
236
- } catch (error) {
237
- throw new Error(`Login to MELCloud Home error: ${error}`);
238
87
  }
239
88
  }
240
89
 
90
+ async getTokens(code, codeVerifier) {
91
+ const tokenData = new URLSearchParams({
92
+ grant_type: 'authorization_code',
93
+ code: code,
94
+ redirect_uri: REDIRECT_URI,
95
+ client_id: CLIENT_ID,
96
+ code_verifier: codeVerifier
97
+ });
241
98
 
242
- async buildAuthorizeUrl() {
243
99
  try {
244
- const pkce = this.generatePKCE();
245
- const state = this.generateState();
246
- const authUrl = new URL(AUTHORIZE_ENDPOINT);
247
- authUrl.searchParams.set('client_id', CLIENT_ID);
248
- authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
249
- authUrl.searchParams.set('response_type', 'code');
250
- authUrl.searchParams.set('scope', SCOPE);
251
- authUrl.searchParams.set('code_challenge', pkce.challenge);
252
- authUrl.searchParams.set('code_challenge_method', 'S256');
253
- authUrl.searchParams.set('state', state);
100
+ const tokenResponse = await this.client.post(TOKEN_ENDPOINT, tokenData.toString(), {
101
+ headers: {
102
+ 'Content-Type': 'application/x-www-form-urlencoded',
103
+ 'Authorization': 'Basic aG9tZW1vYmlsZTo='
104
+ }
105
+ });
254
106
 
255
- const loginPage = await this.getLoginPage(authUrl.toString());
256
- const data = { codeVerifier: pkce.verifier, url: loginPage.url }
257
- return data;
258
- } catch (error) {
259
- throw new Error(`Failed to obtain OAuth link: ${error}`);
107
+ const tokens = tokenResponse.data;
108
+ this.emit('warn', `Token obtained: ${JSON.stringify(tokens)}`);
109
+ return tokens;
110
+ } catch (err) {
111
+ throw new Error(`Failed to obtain OAuth token: ${err}`);
260
112
  }
261
113
  }
262
114
  }
@@ -267,3 +119,4 @@ export default MelCloudHomeToken;
267
119
 
268
120
 
269
121
 
122
+