@gooin/garmin-connect 1.6.9 → 1.6.11

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.
Files changed (64) hide show
  1. package/dist/common/HttpClient.d.ts +38 -37
  2. package/dist/common/HttpClient.js +360 -332
  3. package/dist/common/HttpClient.js.map +1 -1
  4. package/dist/garmin/GarminConnect.d.ts +73 -84
  5. package/dist/garmin/GarminConnect.js +467 -470
  6. package/dist/garmin/GarminConnect.js.map +1 -1
  7. package/dist/garmin/UrlClass.d.ts +43 -43
  8. package/dist/garmin/UrlClass.js +124 -124
  9. package/dist/garmin/common/DateUtils.d.ts +6 -6
  10. package/dist/garmin/common/DateUtils.js +37 -37
  11. package/dist/garmin/common/HydrationUtils.d.ts +2 -2
  12. package/dist/garmin/common/HydrationUtils.js +15 -15
  13. package/dist/garmin/common/WeightUtils.d.ts +1 -1
  14. package/dist/garmin/common/WeightUtils.js +8 -8
  15. package/dist/garmin/types/activity.d.ts +408 -408
  16. package/dist/garmin/types/activity.js +26 -26
  17. package/dist/garmin/types/course.d.ts +146 -146
  18. package/dist/garmin/types/course.js +2 -2
  19. package/dist/garmin/types/golf.d.ts +67 -67
  20. package/dist/garmin/types/golf.js +2 -2
  21. package/dist/garmin/types/heartrate.d.ts +22 -22
  22. package/dist/garmin/types/heartrate.js +1 -1
  23. package/dist/garmin/types/hydration.d.ts +28 -28
  24. package/dist/garmin/types/hydration.js +1 -1
  25. package/dist/garmin/types/index.d.ts +558 -541
  26. package/dist/garmin/types/index.js +35 -16
  27. package/dist/garmin/types/index.js.map +1 -1
  28. package/dist/garmin/types/sleep.d.ts +120 -120
  29. package/dist/garmin/types/sleep.js +2 -2
  30. package/dist/garmin/types/weight.d.ts +42 -42
  31. package/dist/garmin/types/weight.js +2 -2
  32. package/dist/garmin/workouts/Running.d.ts +16 -16
  33. package/dist/garmin/workouts/Running.js +46 -46
  34. package/dist/garmin/workouts/templates/RunningTemplate.d.ts +68 -68
  35. package/dist/garmin/workouts/templates/RunningTemplate.js +77 -77
  36. package/dist/index.d.ts +1 -1
  37. package/dist/index.js +8 -8
  38. package/dist/utils.d.ts +3 -3
  39. package/dist/utils.js +36 -36
  40. package/package.json +3 -2
  41. package/dist/common/CFClient.d.ts +0 -22
  42. package/dist/common/CFClient.js +0 -137
  43. package/dist/common/CFClient.js.map +0 -1
  44. package/dist/common/DateUtils.d.ts +0 -1
  45. package/dist/common/DateUtils.js +0 -11
  46. package/dist/common/DateUtils.js.map +0 -1
  47. package/dist/garmin/GarminConnect copy.d.ts +0 -76
  48. package/dist/garmin/GarminConnect copy.js +0 -397
  49. package/dist/garmin/GarminConnect copy.js.map +0 -1
  50. package/dist/garmin/GarminConnect_new.d.ts +0 -76
  51. package/dist/garmin/GarminConnect_new.js +0 -397
  52. package/dist/garmin/GarminConnect_new.js.map +0 -1
  53. package/dist/garmin/GarminConnect_old.d.ts +0 -75
  54. package/dist/garmin/GarminConnect_old.js +0 -386
  55. package/dist/garmin/GarminConnect_old.js.map +0 -1
  56. package/dist/garmin/Urls copy.d.ts +0 -66
  57. package/dist/garmin/Urls copy.js +0 -109
  58. package/dist/garmin/Urls copy.js.map +0 -1
  59. package/dist/garmin/Urls.d.ts +0 -64
  60. package/dist/garmin/Urls.js +0 -104
  61. package/dist/garmin/Urls.js.map +0 -1
  62. package/dist/garmin/types.d.ts +0 -927
  63. package/dist/garmin/types.js +0 -17
  64. package/dist/garmin/types.js.map +0 -1
@@ -1,333 +1,361 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.HttpClient = void 0;
7
- const axios_1 = __importDefault(require("axios"));
8
- const form_data_1 = __importDefault(require("form-data"));
9
- const lodash_1 = __importDefault(require("lodash"));
10
- const luxon_1 = require("luxon");
11
- const oauth_1_0a_1 = __importDefault(require("oauth-1.0a"));
12
- const qs_1 = __importDefault(require("qs"));
13
- const node_crypto_1 = __importDefault(require("node:crypto"));
14
- const CSRF_RE = new RegExp('name="_csrf"\\s+value="(.+?)"');
15
- const TICKET_RE = new RegExp('ticket=([^"]+)"');
16
- const ACCOUNT_LOCKED_RE = new RegExp('var statuss*=s*"([^"]*)"');
17
- const PAGE_TITLE_RE = new RegExp('<title>([^<]*)</title>');
18
- const USER_AGENT_CONNECTMOBILE = 'com.garmin.android.apps.connectmobile';
19
- const USER_AGENT_BROWSER = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36';
20
- const OAUTH_CONSUMER_URL = 'https://thegarth.s3.amazonaws.com/oauth_consumer.json';
21
- // refresh token
22
- let isRefreshing = false;
23
- let refreshSubscribers = [];
24
- class HttpClient {
25
- constructor(url) {
26
- this.url = url;
27
- this.client = axios_1.default.create();
28
- this.client.interceptors.response.use((response) => response, async (error) => {
29
- var _a;
30
- const originalRequest = error.config;
31
- // console.log('originalRequest:', originalRequest)
32
- // Auto Refresh token
33
- if (((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.status) === 401 &&
34
- !(originalRequest === null || originalRequest === void 0 ? void 0 : originalRequest._retry)) {
35
- if (!this.oauth2Token) {
36
- return;
37
- }
38
- if (isRefreshing) {
39
- try {
40
- const token = await new Promise((resolve) => {
41
- refreshSubscribers.push((token) => {
42
- resolve(token);
43
- });
44
- });
45
- originalRequest.headers.Authorization = `Bearer ${token}`;
46
- return this.client(originalRequest);
47
- }
48
- catch (err) {
49
- console.log('err:', err);
50
- return Promise.reject(err);
51
- }
52
- }
53
- originalRequest._retry = true;
54
- isRefreshing = true;
55
- // console.log('interceptors: refreshOauth2Token start');
56
- await this.refreshOauth2Token();
57
- // console.log('interceptors: refreshOauth2Token end');
58
- isRefreshing = false;
59
- refreshSubscribers.forEach((subscriber) => subscriber(this.oauth2Token.access_token));
60
- refreshSubscribers = [];
61
- originalRequest.headers.Authorization = `Bearer ${this.oauth2Token.access_token}`;
62
- return this.client(originalRequest);
63
- }
64
- if (axios_1.default.isAxiosError(error)) {
65
- if (error === null || error === void 0 ? void 0 : error.response)
66
- this.handleError(error === null || error === void 0 ? void 0 : error.response);
67
- }
68
- throw error;
69
- });
70
- this.client.interceptors.request.use(async (config) => {
71
- if (this.oauth2Token) {
72
- config.headers.Authorization =
73
- 'Bearer ' + this.oauth2Token.access_token;
74
- }
75
- return config;
76
- });
77
- }
78
- async fetchOauthConsumer() {
79
- const response = await axios_1.default.get(OAUTH_CONSUMER_URL);
80
- this.OAUTH_CONSUMER = {
81
- key: response.data.consumer_key,
82
- secret: response.data.consumer_secret
83
- };
84
- }
85
- async checkTokenVaild() {
86
- if (this.oauth2Token) {
87
- if (this.oauth2Token.expires_at < luxon_1.DateTime.now().toSeconds()) {
88
- console.error('Token expired!');
89
- await this.refreshOauth2Token();
90
- }
91
- }
92
- }
93
- async get(url, config) {
94
- const response = await this.client.get(url, config);
95
- return response === null || response === void 0 ? void 0 : response.data;
96
- }
97
- async post(url, data, config) {
98
- const response = await this.client.post(url, data, config);
99
- return response === null || response === void 0 ? void 0 : response.data;
100
- }
101
- async put(url, data, config) {
102
- const response = await this.client.put(url, data, config);
103
- return response === null || response === void 0 ? void 0 : response.data;
104
- }
105
- async delete(url, config) {
106
- const response = await this.client.post(url, null, {
107
- ...config,
108
- headers: {
109
- ...config === null || config === void 0 ? void 0 : config.headers,
110
- 'X-Http-Method-Override': 'DELETE'
111
- }
112
- });
113
- return response === null || response === void 0 ? void 0 : response.data;
114
- }
115
- setCommonHeader(headers) {
116
- lodash_1.default.each(headers, (headerValue, key) => {
117
- this.client.defaults.headers.common[key] = headerValue;
118
- });
119
- }
120
- handleError(response) {
121
- this.handleHttpError(response);
122
- }
123
- handleHttpError(response) {
124
- const { status, statusText, data } = response;
125
- const msg = `ERROR: (${status}), ${statusText}, ${JSON.stringify(data)}`;
126
- console.error(msg);
127
- throw new Error(msg);
128
- }
129
- /**
130
- * Login to Garmin Connect
131
- * @param username
132
- * @param password
133
- * @returns {Promise<HttpClient>}
134
- */
135
- async login(username, password) {
136
- await this.fetchOauthConsumer();
137
- // Step1-3: Get ticket from page.
138
- const ticket = await this.getLoginTicket(username, password);
139
- // Step4: Oauth1
140
- const oauth1 = await this.getOauth1Token(ticket);
141
- // TODO: Handle MFA
142
- // Step 5: Oauth2
143
- await this.exchange(oauth1);
144
- return this;
145
- }
146
- async getLoginTicket(username, password) {
147
- // Step1: Set cookie
148
- const step1Params = {
149
- clientId: 'GarminConnect',
150
- locale: 'en',
151
- service: this.url.GC_MODERN
152
- };
153
- const step1Url = `${this.url.GARMIN_SSO_EMBED}?${qs_1.default.stringify(step1Params)}`;
154
- // console.log('login - step1Url:', step1Url);
155
- await this.client.get(step1Url);
156
- // Step2 Get _csrf
157
- const step2Params = {
158
- id: 'gauth-widget',
159
- embedWidget: true,
160
- locale: 'en',
161
- gauthHost: this.url.GARMIN_SSO_EMBED
162
- };
163
- const step2Url = `${this.url.SIGNIN_URL}?${qs_1.default.stringify(step2Params)}`;
164
- // console.log('login - step2Url:', step2Url);
165
- const step2Result = await this.get(step2Url);
166
- // console.log('login - step2Result:', step2Result)
167
- const csrfRegResult = CSRF_RE.exec(step2Result);
168
- if (!csrfRegResult) {
169
- throw new Error('login - csrf not found');
170
- }
171
- const csrf_token = csrfRegResult[1];
172
- // console.log('login - csrf:', csrf_token);
173
- // Step3 Get ticket
174
- const signinParams = {
175
- id: 'gauth-widget',
176
- embedWidget: true,
177
- clientId: 'GarminConnect',
178
- locale: 'en',
179
- gauthHost: this.url.GARMIN_SSO_EMBED,
180
- service: this.url.GARMIN_SSO_EMBED,
181
- source: this.url.GARMIN_SSO_EMBED,
182
- redirectAfterAccountLoginUrl: this.url.GARMIN_SSO_EMBED,
183
- redirectAfterAccountCreationUrl: this.url.GARMIN_SSO_EMBED
184
- };
185
- const step3Url = `${this.url.SIGNIN_URL}?${qs_1.default.stringify(signinParams)}`;
186
- // console.log('login - step3Url:', step3Url);
187
- const step3Form = new form_data_1.default();
188
- step3Form.append('username', username);
189
- step3Form.append('password', password);
190
- step3Form.append('embed', 'true');
191
- step3Form.append('_csrf', csrf_token);
192
- const step3Result = await this.post(step3Url, step3Form, {
193
- headers: {
194
- 'Content-Type': 'application/x-www-form-urlencoded',
195
- Dnt: 1,
196
- Origin: this.url.GARMIN_SSO_ORIGIN,
197
- Referer: this.url.SIGNIN_URL,
198
- 'User-Agent': USER_AGENT_BROWSER
199
- }
200
- });
201
- // console.log('step3Result:', step3Result)
202
- this.handleAccountLocked(step3Result);
203
- this.handlePageTitle(step3Result);
204
- this.handleMFA(step3Result);
205
- const ticketRegResult = TICKET_RE.exec(step3Result);
206
- if (!ticketRegResult) {
207
- throw new Error('login failed (Ticket not found or MFA), please check username and password');
208
- }
209
- const ticket = ticketRegResult[1];
210
- return ticket;
211
- }
212
- // TODO: Handle MFA
213
- handleMFA(htmlStr) { }
214
- // TODO: Handle Phone number
215
- handlePageTitle(htmlStr) {
216
- const pageTitileRegResult = PAGE_TITLE_RE.exec(htmlStr);
217
- if (pageTitileRegResult) {
218
- const title = pageTitileRegResult[1];
219
- console.log('login page title:', title);
220
- if (lodash_1.default.includes(title, 'Update Phone Number')) {
221
- // current I don't know where to update it
222
- // See: https://github.com/matin/garth/issues/19
223
- throw new Error('login failed (Update Phone number), please update your phone number, See: https://github.com/matin/garth/issues/19');
224
- }
225
- }
226
- }
227
- handleAccountLocked(htmlStr) {
228
- const accountLockedRegResult = ACCOUNT_LOCKED_RE.exec(htmlStr);
229
- if (accountLockedRegResult) {
230
- const msg = accountLockedRegResult[1];
231
- console.error(msg);
232
- throw new Error('login failed (AccountLocked), please open connect web page to unlock your account');
233
- }
234
- }
235
- async refreshOauth2Token() {
236
- if (!this.OAUTH_CONSUMER) {
237
- await this.fetchOauthConsumer();
238
- }
239
- if (!this.oauth2Token || !this.oauth1Token) {
240
- throw new Error('No Oauth2Token or Oauth1Token');
241
- }
242
- const oauth1 = {
243
- oauth: this.getOauthClient(this.OAUTH_CONSUMER),
244
- token: this.oauth1Token
245
- };
246
- await this.exchange(oauth1);
247
- console.log('Oauth2 token refreshed!');
248
- }
249
- async getOauth1Token(ticket) {
250
- if (!this.OAUTH_CONSUMER) {
251
- throw new Error('No OAUTH_CONSUMER');
252
- }
253
- const params = {
254
- ticket,
255
- 'login-url': this.url.GARMIN_SSO_EMBED,
256
- 'accepts-mfa-tokens': true
257
- };
258
- const url = `${this.url.OAUTH_URL}/preauthorized?${qs_1.default.stringify(params)}`;
259
- const oauth = this.getOauthClient(this.OAUTH_CONSUMER);
260
- const step4RequestData = {
261
- url: url,
262
- method: 'GET'
263
- };
264
- const headers = oauth.toHeader(oauth.authorize(step4RequestData));
265
- // console.log('getOauth1Token - headers:', headers);
266
- const response = await this.get(url, {
267
- headers: {
268
- ...headers,
269
- 'User-Agent': USER_AGENT_CONNECTMOBILE
270
- }
271
- });
272
- // console.log('getOauth1Token - response:', response);
273
- const token = qs_1.default.parse(response);
274
- // console.log('getOauth1Token - token:', token);
275
- this.oauth1Token = token;
276
- return { token, oauth };
277
- }
278
- getOauthClient(consumer) {
279
- const oauth = new oauth_1_0a_1.default({
280
- consumer: consumer,
281
- signature_method: 'HMAC-SHA1',
282
- hash_function(base_string, key) {
283
- return node_crypto_1.default
284
- .createHmac('sha1', key)
285
- .update(base_string)
286
- .digest('base64');
287
- }
288
- });
289
- return oauth;
290
- }
291
- //
292
- async exchange(oauth1) {
293
- const token = {
294
- key: oauth1.token.oauth_token,
295
- secret: oauth1.token.oauth_token_secret
296
- };
297
- // console.log('exchange - token:', token);
298
- const baseUrl = `${this.url.OAUTH_URL}/exchange/user/2.0`;
299
- const requestData = {
300
- url: baseUrl,
301
- method: 'POST',
302
- data: null
303
- };
304
- const step5AuthData = oauth1.oauth.authorize(requestData, token);
305
- // console.log('login - step5AuthData:', step5AuthData);
306
- const url = `${baseUrl}?${qs_1.default.stringify(step5AuthData)}`;
307
- // console.log('exchange - url:', url);
308
- this.oauth2Token = undefined;
309
- const response = await this.post(url, null, {
310
- headers: {
311
- 'User-Agent': USER_AGENT_CONNECTMOBILE,
312
- 'Content-Type': 'application/x-www-form-urlencoded'
313
- }
314
- });
315
- // console.log('exchange - response:', response);
316
- this.oauth2Token = this.setOauth2TokenExpiresAt(response);
317
- // console.log('exchange - oauth2Token:', this.oauth2Token);
318
- }
319
- setOauth2TokenExpiresAt(token) {
320
- // human readable date
321
- token['last_update_date'] = luxon_1.DateTime.now().toLocal().toString();
322
- token['expires_date'] = luxon_1.DateTime.fromSeconds(luxon_1.DateTime.now().toSeconds() + token['expires_in'])
323
- .toLocal()
324
- .toString();
325
- // timestamp for check expired
326
- token['expires_at'] = luxon_1.DateTime.now().toSeconds() + token['expires_in'];
327
- token['refresh_token_expires_at'] =
328
- luxon_1.DateTime.now().toSeconds() + token['refresh_token_expires_in'];
329
- return token;
330
- }
331
- }
332
- exports.HttpClient = HttpClient;
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.HttpClient = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const form_data_1 = __importDefault(require("form-data"));
9
+ const lodash_1 = __importDefault(require("lodash"));
10
+ const luxon_1 = require("luxon");
11
+ const oauth_1_0a_1 = __importDefault(require("oauth-1.0a"));
12
+ const qs_1 = __importDefault(require("qs"));
13
+ const node_crypto_1 = __importDefault(require("node:crypto"));
14
+ const CSRF_RE = new RegExp('name="_csrf"\\s+value="(.+?)"');
15
+ const TICKET_RE = new RegExp('ticket=([^"]+)"');
16
+ const ACCOUNT_LOCKED_RE = new RegExp('var statuss*=s*"([^"]*)"');
17
+ const PAGE_TITLE_RE = new RegExp('<title>([^<]*)</title>');
18
+ const USER_AGENT_CONNECTMOBILE = 'com.garmin.android.apps.connectmobile';
19
+ const USER_AGENT_BROWSER = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36';
20
+ const USER_AGENT_BROWSER_MAC = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
21
+ const OAUTH_CONSUMER_URL = 'https://thegarth.s3.amazonaws.com/oauth_consumer.json';
22
+ const HTTP_STATUS = {
23
+ UNAUTHORIZED: 401
24
+ };
25
+ let tokenRefreshPromise = null;
26
+ let refreshSubscribers = [];
27
+ class HttpClient {
28
+ constructor(url, config) {
29
+ var _a, _b;
30
+ this.url = url;
31
+ this.client = axios_1.default.create({
32
+ timeout: (_a = config === null || config === void 0 ? void 0 : config.timeout) !== null && _a !== void 0 ? _a : 5000,
33
+ timeoutErrorMessage: `Request Timeout: > ${(_b = config === null || config === void 0 ? void 0 : config.timeout) !== null && _b !== void 0 ? _b : 5000} ms`
34
+ /**
35
+ * Charles debugger: uncomment `proxy` and `httpsAgent`, then run bellow command.
36
+ * NODE_TLS_REJECT_UNAUTHORIZED=0 node test/sync.js
37
+ */
38
+ // proxy: {
39
+ // host: '127.0.0.1',
40
+ // port: 8888,
41
+ // protocol: 'http'
42
+ // },
43
+ // httpsAgent: new (require('https').Agent)({
44
+ // rejectUnauthorized: false
45
+ // })
46
+ });
47
+ this.config = config;
48
+ this.client.interceptors.response.use((response) => response, async (error) => {
49
+ var _a;
50
+ if (axios_1.default.isAxiosError(error) &&
51
+ error.code === 'ECONNABORTED') {
52
+ throw new Error(error.message || 'Request Timeout');
53
+ }
54
+ const originalRequest = error.config;
55
+ if (((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.status) === HTTP_STATUS.UNAUTHORIZED &&
56
+ !(originalRequest === null || originalRequest === void 0 ? void 0 : originalRequest._retry)) {
57
+ if (!this.oauth2Token) {
58
+ throw new Error('No OAuth2 token available');
59
+ }
60
+ originalRequest._retry = true;
61
+ try {
62
+ if (!tokenRefreshPromise) {
63
+ tokenRefreshPromise =
64
+ this.refreshOauth2Token().finally(() => {
65
+ tokenRefreshPromise = null;
66
+ });
67
+ }
68
+ await tokenRefreshPromise;
69
+ originalRequest.headers.Authorization = `Bearer ${this.oauth2Token.access_token}`;
70
+ return this.client(originalRequest);
71
+ }
72
+ catch (err) {
73
+ console.error('Token refresh failed:', err);
74
+ throw err;
75
+ }
76
+ }
77
+ if (axios_1.default.isAxiosError(error) && error.response) {
78
+ this.handleError(error.response);
79
+ }
80
+ else {
81
+ // 处理没有response的情况
82
+ throw new Error('Network error or unknown error occurred');
83
+ }
84
+ throw error;
85
+ });
86
+ this.client.interceptors.request.use(async (config) => {
87
+ if (this.oauth2Token) {
88
+ config.headers.Authorization =
89
+ 'Bearer ' + this.oauth2Token.access_token;
90
+ }
91
+ return config;
92
+ });
93
+ }
94
+ async fetchOauthConsumer() {
95
+ const response = await axios_1.default.get(OAUTH_CONSUMER_URL);
96
+ this.OAUTH_CONSUMER = {
97
+ key: response.data.consumer_key,
98
+ secret: response.data.consumer_secret
99
+ };
100
+ }
101
+ async checkTokenVaild() {
102
+ if (this.oauth2Token) {
103
+ if (this.oauth2Token.expires_at < luxon_1.DateTime.now().toSeconds()) {
104
+ console.error('Token expired!');
105
+ await this.refreshOauth2Token();
106
+ }
107
+ }
108
+ }
109
+ async get(url, config) {
110
+ const response = await this.client.get(url, config);
111
+ return response === null || response === void 0 ? void 0 : response.data;
112
+ }
113
+ async post(url, data, config) {
114
+ const response = await this.client.post(url, data, config);
115
+ return response === null || response === void 0 ? void 0 : response.data;
116
+ }
117
+ async put(url, data, config) {
118
+ const response = await this.client.put(url, data, config);
119
+ return response === null || response === void 0 ? void 0 : response.data;
120
+ }
121
+ async delete(url, config) {
122
+ const response = await this.client.post(url, null, {
123
+ ...config,
124
+ headers: {
125
+ ...config === null || config === void 0 ? void 0 : config.headers,
126
+ 'X-Http-Method-Override': 'DELETE'
127
+ }
128
+ });
129
+ return response === null || response === void 0 ? void 0 : response.data;
130
+ }
131
+ setCommonHeader(headers) {
132
+ lodash_1.default.each(headers, (headerValue, key) => {
133
+ this.client.defaults.headers.common[key] = headerValue;
134
+ });
135
+ }
136
+ handleError(response) {
137
+ this.handleHttpError(response);
138
+ }
139
+ handleHttpError(response) {
140
+ const { status, statusText, data } = response;
141
+ const errorMessage = {
142
+ status,
143
+ statusText,
144
+ data: typeof data === 'object' ? JSON.stringify(data) : data
145
+ };
146
+ console.error('HTTP Error:', errorMessage);
147
+ throw new Error(`HTTP Error (${status}): ${statusText}`);
148
+ }
149
+ /**
150
+ * Login to Garmin Connect
151
+ * @param username
152
+ * @param password
153
+ * @returns {Promise<HttpClient>}
154
+ */
155
+ async login(username, password) {
156
+ await this.fetchOauthConsumer();
157
+ // Step1-3: Get ticket from page.
158
+ const ticket = await this.getLoginTicket(username, password);
159
+ // Step4: Oauth1
160
+ const oauth1 = await this.getOauth1Token(ticket);
161
+ // TODO: Handle MFA
162
+ // Step 5: Oauth2
163
+ await this.exchange(oauth1);
164
+ return this;
165
+ }
166
+ async getLoginTicket(username, password) {
167
+ // Step1: Set cookie
168
+ const step1Params = {
169
+ clientId: 'GarminConnect',
170
+ locale: 'en',
171
+ service: this.url.GC_MODERN
172
+ };
173
+ const step1Url = `${this.url.GARMIN_SSO_EMBED}?${qs_1.default.stringify(step1Params)}`;
174
+ // console.log('login - step1Url:', step1Url);
175
+ await this.client.get(step1Url);
176
+ // Step2 Get _csrf
177
+ const step2Params = {
178
+ id: 'gauth-widget',
179
+ embedWidget: true,
180
+ locale: 'en',
181
+ gauthHost: this.url.GARMIN_SSO_EMBED
182
+ };
183
+ const step2Url = `${this.url.SIGNIN_URL}?${qs_1.default.stringify(step2Params)}`;
184
+ // console.log('login - step2Url:', step2Url);
185
+ const step2Result = await this.get(step2Url);
186
+ // console.log('login - step2Result:', step2Result)
187
+ const csrfRegResult = CSRF_RE.exec(step2Result);
188
+ if (!csrfRegResult) {
189
+ throw new Error('login - csrf not found');
190
+ }
191
+ const csrf_token = csrfRegResult[1];
192
+ // console.log('login - csrf:', csrf_token);
193
+ // Step3 Get ticket
194
+ const signinParams = {
195
+ id: 'gauth-widget',
196
+ embedWidget: true,
197
+ clientId: 'GarminConnect',
198
+ locale: 'en',
199
+ gauthHost: this.url.GARMIN_SSO_EMBED,
200
+ service: this.url.GARMIN_SSO_EMBED,
201
+ source: this.url.GARMIN_SSO_EMBED,
202
+ redirectAfterAccountLoginUrl: this.url.GARMIN_SSO_EMBED,
203
+ redirectAfterAccountCreationUrl: this.url.GARMIN_SSO_EMBED
204
+ };
205
+ const step3Url = `${this.url.SIGNIN_URL}?${qs_1.default.stringify(signinParams)}`;
206
+ // console.log('login - step3Url:', step3Url);
207
+ const step3Form = new form_data_1.default();
208
+ step3Form.append('username', username);
209
+ step3Form.append('password', password);
210
+ step3Form.append('embed', 'true');
211
+ step3Form.append('_csrf', csrf_token);
212
+ const step3Result = await this.post(step3Url, step3Form, {
213
+ headers: {
214
+ 'Content-Type': 'application/x-www-form-urlencoded',
215
+ Dnt: 1,
216
+ Origin: this.url.GARMIN_SSO_ORIGIN,
217
+ Referer: this.url.SIGNIN_URL,
218
+ 'User-Agent': USER_AGENT_BROWSER
219
+ }
220
+ });
221
+ // console.log('step3Result:', step3Result)
222
+ this.handleAccountLocked(step3Result);
223
+ this.handlePageTitle(step3Result);
224
+ this.handleMFA(step3Result);
225
+ const ticketRegResult = TICKET_RE.exec(step3Result);
226
+ if (!ticketRegResult) {
227
+ throw new Error('login failed (Ticket not found or MFA), please check username and password');
228
+ }
229
+ const ticket = ticketRegResult[1];
230
+ return ticket;
231
+ }
232
+ // TODO: Handle MFA
233
+ handleMFA(htmlStr) { }
234
+ // TODO: Handle Phone number
235
+ handlePageTitle(htmlStr) {
236
+ const pageTitileRegResult = PAGE_TITLE_RE.exec(htmlStr);
237
+ if (pageTitileRegResult) {
238
+ const title = pageTitileRegResult[1];
239
+ console.log('login page title:', title);
240
+ if (lodash_1.default.includes(title, 'Update Phone Number')) {
241
+ // current I don't know where to update it
242
+ // See: https://github.com/matin/garth/issues/19
243
+ throw new Error('login failed (Update Phone number), please update your phone number, See: https://github.com/matin/garth/issues/19');
244
+ }
245
+ }
246
+ }
247
+ handleAccountLocked(htmlStr) {
248
+ const accountLockedRegResult = ACCOUNT_LOCKED_RE.exec(htmlStr);
249
+ if (accountLockedRegResult) {
250
+ const msg = accountLockedRegResult[1];
251
+ console.error(msg);
252
+ throw new Error('login failed (AccountLocked), please open connect web page to unlock your account');
253
+ }
254
+ }
255
+ async refreshOauth2Token() {
256
+ try {
257
+ if (!this.OAUTH_CONSUMER) {
258
+ await this.fetchOauthConsumer();
259
+ }
260
+ if (!this.oauth2Token || !this.oauth1Token) {
261
+ throw new Error('Missing required tokens for refresh');
262
+ }
263
+ const oauth1 = {
264
+ oauth: this.getOauthClient(this.OAUTH_CONSUMER),
265
+ token: this.oauth1Token
266
+ };
267
+ await this.exchange(oauth1);
268
+ console.log(`「${this.config.username}」in「${this.url.domain}」 OAuth2 token refreshed successfully`);
269
+ }
270
+ catch (error) {
271
+ console.error('Failed to refresh OAuth2 token:', error);
272
+ throw error;
273
+ }
274
+ }
275
+ async getOauth1Token(ticket) {
276
+ if (!this.OAUTH_CONSUMER) {
277
+ throw new Error('No OAUTH_CONSUMER');
278
+ }
279
+ const params = {
280
+ ticket,
281
+ 'login-url': this.url.GARMIN_SSO_EMBED,
282
+ 'accepts-mfa-tokens': true
283
+ };
284
+ const url = `${this.url.OAUTH_URL}/preauthorized?${qs_1.default.stringify(params)}`;
285
+ const oauth = this.getOauthClient(this.OAUTH_CONSUMER);
286
+ const step4RequestData = {
287
+ url: url,
288
+ method: 'GET'
289
+ };
290
+ const headers = oauth.toHeader(oauth.authorize(step4RequestData));
291
+ // console.log('getOauth1Token - headers:', headers);
292
+ const response = await this.get(url, {
293
+ headers: {
294
+ ...headers,
295
+ 'User-Agent': USER_AGENT_CONNECTMOBILE
296
+ }
297
+ });
298
+ // console.log('getOauth1Token - response:', response);
299
+ const token = qs_1.default.parse(response);
300
+ // console.log('getOauth1Token - token:', token);
301
+ this.oauth1Token = token;
302
+ return { token, oauth };
303
+ }
304
+ getOauthClient(consumer) {
305
+ const oauth = new oauth_1_0a_1.default({
306
+ consumer: consumer,
307
+ signature_method: 'HMAC-SHA1',
308
+ hash_function(base_string, key) {
309
+ return node_crypto_1.default
310
+ .createHmac('sha1', key)
311
+ .update(base_string)
312
+ .digest('base64');
313
+ }
314
+ });
315
+ return oauth;
316
+ }
317
+ //
318
+ async exchange(oauth1) {
319
+ const token = {
320
+ key: oauth1.token.oauth_token,
321
+ secret: oauth1.token.oauth_token_secret
322
+ };
323
+ // console.log('exchange - token:', token);
324
+ const baseUrl = `${this.url.OAUTH_URL}/exchange/user/2.0`;
325
+ const requestData = {
326
+ url: baseUrl,
327
+ method: 'POST',
328
+ data: null
329
+ };
330
+ const step5AuthData = oauth1.oauth.authorize(requestData, token);
331
+ // console.log('login - step5AuthData:', step5AuthData);
332
+ const url = `${baseUrl}?${qs_1.default.stringify(step5AuthData)}`;
333
+ // console.log('exchange - url:', url);
334
+ this.oauth2Token = undefined;
335
+ const response = await this.post(url, null, {
336
+ headers: {
337
+ 'User-Agent': USER_AGENT_CONNECTMOBILE,
338
+ 'Content-Type': 'application/x-www-form-urlencoded'
339
+ }
340
+ });
341
+ // console.log('exchange - response:', response);
342
+ this.oauth2Token = this.setOauth2TokenExpiresAt(response);
343
+ // console.log('exchange - oauth2Token:', this.oauth2Token);
344
+ }
345
+ setOauth2TokenExpiresAt(token) {
346
+ const now = luxon_1.DateTime.now();
347
+ const expiresAt = now.plus({ seconds: token.expires_in });
348
+ const refreshTokenExpiresAt = now.plus({
349
+ seconds: token.refresh_token_expires_in
350
+ });
351
+ return {
352
+ ...token,
353
+ last_update_date: now.toLocal().toString(),
354
+ expires_date: expiresAt.toLocal().toString(),
355
+ expires_at: expiresAt.toSeconds(),
356
+ refresh_token_expires_at: refreshTokenExpiresAt.toSeconds()
357
+ };
358
+ }
359
+ }
360
+ exports.HttpClient = HttpClient;
333
361
  //# sourceMappingURL=HttpClient.js.map