Module: GitFit::Auth::Garmin::StrategyA

Defined in:
lib/git_fit/auth/garmin/strategy_a.rb

Overview

Strategy A: curl-impersonate shellout (faithful Ruby port of workouts/scripts/garmin_auth.py).

mobile+cffi (primary): single Safari TLS session, /mobile/api/login
portal+cffi (fallback): 5 TLS fingerprints, /portal/api/login

A 30-45s random delay before each GET sign-in is critical for the Cloudflare WAF bypass — keep it. rubocop:disable Metrics/ModuleLength

Constant Summary collapse

PORTAL_CLIENT_ID =
'GarminConnect'
PORTAL_SERVICE =
'https://connect.garmin.com/app'
MOBILE_CLIENT_ID =
'GCM_ANDROID_DARK'
MOBILE_SERVICE =
'https://mobile.integration.garmin.com/gcm/android'
MOBILE_UA =
'Mozilla/5.0 (Linux; Android 13; sdk_gphone64_arm64 Build/TE1A.220922.025; wv) ' \
'AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/132.0.0.0 ' \
'Mobile Safari/537.36'
DESKTOP_UA =
'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'
HTML_ACCEPT =
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
JSON_ACCEPT =
'application/json, text/plain, */*'
LOGIN_DELAY_MIN =
30.0
LOGIN_DELAY_MAX =
45.0
MOBILE_FINGERPRINT =
'safari18_0'
TLS_FINGERPRINTS =
%w[safari18_0 safari17_0 chrome120 edge101 chrome124].freeze
CURL_BINARY =
'curl-impersonate'
AUTH_FLAG =
'-A'

Class Method Summary collapse

Class Method Details

.attempt_portal_fingerprint(sso, domain, imp, email, password, mfa_code) ⇒ Object



166
167
168
169
170
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 166

def attempt_portal_fingerprint(sso, domain, imp, email, password, mfa_code)
  with_session_files do |jar, body|
    attempt_portal_in_session(sso, domain, imp, email, password, mfa_code, jar, body)
  end
end

.attempt_portal_in_session(sso, domain, imp, email, password, mfa_code, jar, body) ⇒ Object



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 172

def attempt_portal_in_session(sso, domain, imp, email, password, mfa_code, jar, body)
  random_delay("portal+cffi/#{imp}")
   = "#{sso}/portal/sso/en-US/sign-in"
  get_params = { clientId: PORTAL_CLIENT_ID, service: PORTAL_SERVICE }
  get_headers = browser_headers.merge('Accept' => HTML_ACCEPT)

  status, = curl_request(
    impersonate: imp,
    jar: jar,
    output: body,
    url: with_query(, get_params),
    headers: get_headers,
  )
  if status == 429
    warn "[garmin_auth] portal+cffi/#{imp} GET 429"
    return nil
  end
  unless status.between?(200, 299)
    warn "[garmin_auth] portal+cffi/#{imp} GET #{status}"
    return nil
  end

  post_headers = browser_headers.merge(
    'Accept' => JSON_ACCEPT,
    'Content-Type' => 'application/json',
    'Origin' => sso,
    'Referer' => "#{}?clientId=#{PORTAL_CLIENT_ID}&service=#{PORTAL_SERVICE}",
  )
   = { clientId: PORTAL_CLIENT_ID, locale: 'en-US', service: PORTAL_SERVICE }
   = JSON.generate(
    username: email,
    password: password,
    rememberMe: true,
    captchaToken: '',
  )

  status, resp_body = curl_request(
    impersonate: imp,
    jar: jar,
    output: body,
    url: with_query("#{sso}/portal/api/login", ),
    headers: post_headers,
    data: ,
  )
  if status == 429
    warn "[garmin_auth] portal+cffi/#{imp} POST 429"
    return nil
  end
  unless status.between?(200, 299)
    warn "[garmin_auth] portal+cffi/#{imp} POST #{status}"
    return nil
  end

  res = JSON.parse(resp_body)
  resp_type = res.dig('responseStatus', 'type')
  if resp_type == 'MFA_REQUIRED'
    method = res.dig('customerMfaInfo', 'mfaLastMethodUsed') || 'email'
    res = handle_mfa(sso, method, , post_headers, mfa_code,
                     impersonate: imp, jar: jar, output: body,
                     email: email, domain: domain, service_url: PORTAL_SERVICE)
    resp_type = res.dig('responseStatus', 'type')
  end

  return [res['serviceTicketId'], PORTAL_SERVICE] if resp_type == 'SUCCESSFUL'
  raise GitFit::Sync::AuthError, 'Invalid username or password' if resp_type == 'INVALID_USERNAME_PASSWORD'

  nil
rescue GitFit::Sync::AuthError
  raise
rescue StandardError => e
  warn "[garmin_auth] portal+cffi/#{imp} error: #{e.message}"
  nil
end

.browser_headersObject



359
360
361
362
363
364
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 359

def browser_headers
  {
    'User-Agent' => DESKTOP_UA,
    'Accept-Language' => 'en-US,en;q=0.9',
  }
end

.call(email:, password:, domain: 'garmin.com', mfa_code: nil) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 44

def call(email:, password:, domain: 'garmin.com', mfa_code: nil)
  check_curl_available!

  code = mfa_code.to_s.strip
  if !code.empty? && (saved = LoginSession.load(domain))
    return (domain, code, saved)
  end

  errors = []
  begin
    return finish((domain, email, password, mfa_code), domain)
  rescue MfaRequired
    raise
  rescue GitFit::Sync::AuthError => e
    errors << "mobile+cffi: #{e.message}"
    warn "[garmin_auth] #{errors.last}"
  rescue StandardError => e
    errors << "mobile+cffi: unexpected error: #{e.message}"
    warn "[garmin_auth] #{errors.last}"
  end

  begin
    return finish((domain, email, password, mfa_code), domain)
  rescue MfaRequired
    raise
  rescue GitFit::Sync::AuthError => e
    errors << "portal+cffi: #{e.message}"
    warn "[garmin_auth] #{errors.last}"
  rescue StandardError => e
    errors << "portal+cffi: unexpected error: #{e.message}"
    warn "[garmin_auth] #{errors.last}"
  end

  raise GitFit::Sync::AuthError, "All strategies exhausted: #{errors.join('; ')}"
end

.check_curl_available!Object



334
335
336
337
338
339
340
341
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 334

def check_curl_available!
  _out, _err, status = Open3.capture3(CURL_BINARY, '--version')
  return if status.success?

  raise GitFit::Sync::AuthError, "#{CURL_BINARY} not found. Install it or use -B strategy"
rescue Errno::ENOENT
  raise GitFit::Sync::AuthError, "#{CURL_BINARY} not found. Install it or use -B strategy"
end

.curl_request(impersonate:, jar:, output:, url:, headers:, data: nil) ⇒ Object



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 343

def curl_request(impersonate:, jar:, output:, url:, headers:, data: nil)
  args = [CURL_BINARY, '--impersonate', impersonate, '-s', '-S', '-L']
  args += ['-c', jar, '-b', jar]
  headers.each { |key, value| args += ['-H', "#{key}: #{value}"] }
  args += ['--data-raw', data] if data
  args += ['-w', "\n%{http_code}", '-o', output, url] # rubocop:disable Style/FormatStringToken
  out, err, status = Open3.capture3(*args)
  unless status.success? && File.exist?(output)
    detail = err.strip.lines.first.to_s
    raise GitFit::Sync::AuthError,
          "#{CURL_BINARY} failed (exit #{status.exitstatus}, impersonate #{impersonate}): #{detail}"
  end
  code = out.strip.split.last.to_i
  [code, File.read(output)]
end

.finish(ticket, service_url, domain) ⇒ Object



378
379
380
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 378

def finish((ticket, service_url), domain)
  DIExchange.call(domain, ticket, service_url)
end

.handle_mfa(sso, method, login_params, post_headers, mfa_code, impersonate:, jar:, output:, email:, domain:, service_url:) ⇒ Object



246
247
248
249
250
251
252
253
254
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 246

def handle_mfa(sso, method, , post_headers, mfa_code,
               impersonate:, jar:, output:, email:, domain:, service_url:)
  code = resolve_mfa_code(mfa_code, email)
  if code.nil?
    (domain, sso, method, , post_headers, impersonate, jar, service_url)
    raise MfaRequired, mfa_required_message(email)
  end
  verify_mfa(sso, method, , post_headers, code, impersonate:, jar:, output:)
end

.mfa_required_message(email) ⇒ Object



325
326
327
328
329
330
331
332
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 325

def mfa_required_message(email)
  "MFA required — check your email (#{email}) for the code.\n" \
    "  This code is valid for a few minutes.\n\n" \
    "  To continue, choose one:\n" \
    "    echo \"<CODE>\" | git fit auth garmin #{AUTH_FLAG}\n" \
    "    git fit auth garmin #{AUTH_FLAG} --mfa-code <CODE>\n\n" \
    "  If the code has expired, request a new one: git fit auth garmin #{AUTH_FLAG}"
end

.mobile_login(domain, email, password, mfa_code) ⇒ Object



86
87
88
89
90
91
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 86

def (domain, email, password, mfa_code)
  sso = "https://sso.#{domain}"
  with_session_files do |jar, body|
    (sso, domain, email, password, mfa_code, jar, body)
  end
end

.mobile_login_session(sso, domain, email, password, mfa_code, jar, body) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 93

def (sso, domain, email, password, mfa_code, jar, body)
  random_delay('mobile+cffi')
   = "#{sso}/mobile/sso/en_US/sign-in"
  get_params = { clientId: MOBILE_CLIENT_ID, service: MOBILE_SERVICE }
  get_headers = {
    'User-Agent' => MOBILE_UA,
    'accept' => HTML_ACCEPT,
    'accept-language' => 'en-US,en;q=0.9',
  }

  status, = curl_request(
    impersonate: MOBILE_FINGERPRINT,
    jar: jar,
    output: body,
    url: with_query(, get_params),
    headers: get_headers,
  )
  raise GitFit::Sync::AuthError, 'mobile+cffi GET 429' if status == 429
  raise GitFit::Sync::AuthError, "mobile+cffi GET #{status}" unless status.between?(200, 299)

  post_headers = get_headers.merge(
    'accept' => JSON_ACCEPT,
    'content-type' => 'application/json',
    'origin' => sso,
    'referer' => "#{}?clientId=#{MOBILE_CLIENT_ID}&service=#{MOBILE_SERVICE}",
  )
   = { clientId: MOBILE_CLIENT_ID, locale: 'en-US', service: MOBILE_SERVICE }
   = JSON.generate(
    username: email,
    password: password,
    rememberMe: true,
    captchaToken: '',
  )

  status, resp_body = curl_request(
    impersonate: MOBILE_FINGERPRINT,
    jar: jar,
    output: body,
    url: with_query("#{sso}/mobile/api/login", ),
    headers: post_headers,
    data: ,
  )
  raise GitFit::Sync::AuthError, 'mobile+cffi POST 429' if status == 429
  raise GitFit::Sync::AuthError, "mobile+cffi POST #{status}" unless status.between?(200, 299)

  res = JSON.parse(resp_body)
  resp_type = res.dig('responseStatus', 'type')
  if resp_type == 'MFA_REQUIRED'
    method = res.dig('customerMfaInfo', 'mfaLastMethodUsed') || 'email'
    res = handle_mfa(sso, method, , post_headers, mfa_code,
                     impersonate: MOBILE_FINGERPRINT, jar: jar, output: body,
                     email: email, domain: domain, service_url: MOBILE_SERVICE)
    resp_type = res.dig('responseStatus', 'type')
  end

  if resp_type == 'SUCCESSFUL'
    [res['serviceTicketId'], MOBILE_SERVICE]
  elsif resp_type == 'INVALID_USERNAME_PASSWORD'
    raise GitFit::Sync::AuthError, 'Invalid username or password'
  else
    raise GitFit::Sync::AuthError, "mobile+cffi: unexpected response type: #{resp_type}"
  end
end

.portal_login(domain, email, password, mfa_code) ⇒ Object



157
158
159
160
161
162
163
164
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 157

def (domain, email, password, mfa_code)
  sso = "https://sso.#{domain}"
  TLS_FINGERPRINTS.each do |imp|
    result = attempt_portal_fingerprint(sso, domain, imp, email, password, mfa_code)
    return result if result
  end
  raise GitFit::Sync::AuthError, 'portal+cffi: all TLS fingerprints exhausted'
end

.random_delay(label) ⇒ Object



80
81
82
83
84
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 80

def random_delay(label)
  delay = rand(LOGIN_DELAY_MIN..LOGIN_DELAY_MAX)
  warn "[garmin_auth] #{label}: waiting #{delay.to_i}s for Cloudflare..."
  sleep(delay)
end

.resolve_mfa_code(mfa_code, email) ⇒ Object



315
316
317
318
319
320
321
322
323
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 315

def resolve_mfa_code(mfa_code, email)
  code = mfa_code.to_s.strip
  if code.empty?
    warn "[garmin_auth] Garmin sent a verification code to #{email}"
    $stderr.write('Enter the 6-digit code: ') if $stdin.tty?
    code = $stdin.gets.to_s.strip
  end
  code.empty? ? nil : code
end

.resume_login(domain, mfa_code, saved) ⇒ Object



304
305
306
307
308
309
310
311
312
313
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 304

def (domain, mfa_code, saved)
  with_session_files do |jar, body|
    File.write(jar, saved['jar'])
    res = verify_mfa(saved['sso'], saved['method'], saved['login_params'],
                     saved['post_headers'], mfa_code,
                     impersonate: saved['impersonate'], jar: jar, output: body)
    LoginSession.clear(domain)
    finish([res['serviceTicketId'], saved['service_url']], domain)
  end
end

.save_login_session(domain, sso, method, login_params, post_headers, impersonate, jar, service_url) ⇒ Object



291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 291

def (domain, sso, method, , post_headers, impersonate, jar, service_url)
  LoginSession.save(domain, {
    'strategy' => 'A',
    'sso' => sso,
    'method' => method,
    'login_params' => ,
    'post_headers' => post_headers,
    'impersonate' => impersonate,
    'jar' => File.read(jar),
    'service_url' => service_url,
  })
end

.verify_mfa(sso, method, login_params, post_headers, code, impersonate:, jar:, output:) ⇒ Object



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 256

def verify_mfa(sso, method, , post_headers, code, impersonate:, jar:, output:)
  mfa_data = {
    'mfaMethod' => method,
    'mfaVerificationCode' => code,
    'rememberMyBrowser' => true,
    'reconsentList' => [],
    'mfaSetup' => false,
  }

  endpoints = [
    ["#{sso}/portal/api/mfa/verifyCode", ],
    ["#{sso}/mobile/api/mfa/verifyCode",
     { clientId: MOBILE_CLIENT_ID, locale: 'en-US', service: MOBILE_SERVICE }],
  ]

  endpoints.each do |ep_url, ep_params|
    status, resp_body = curl_request(
      impersonate: impersonate,
      jar: jar,
      output: output,
      url: with_query(ep_url, ep_params),
      headers: post_headers,
      data: JSON.generate(mfa_data),
    )
    next if status == 429
    next unless status.between?(200, 299)

    res = JSON.parse(resp_body)
    return res if res.dig('responseStatus', 'type') == 'SUCCESSFUL'
  rescue StandardError
    next
  end
  raise GitFit::Sync::AuthError, 'MFA verification failed on all endpoints'
end

.with_query(url, params) ⇒ Object



366
367
368
369
370
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 366

def with_query(url, params)
  return url if params.nil? || params.empty?

  "#{url}?#{URI.encode_www_form(params)}"
end

.with_session_filesObject



372
373
374
375
376
# File 'lib/git_fit/auth/garmin/strategy_a.rb', line 372

def with_session_files
  Dir.mktmpdir('garmin-strategy-a-') do |dir|
    yield File.join(dir, 'cookies.txt'), File.join(dir, 'body.txt')
  end
end