Module: GitFit::Auth::Garmin::StrategyB
- Defined in:
- lib/git_fit/auth/garmin/strategy_b.rb
Overview
rubocop:disable Metrics/ModuleLength
Constant Summary collapse
- 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'
- MOBILE_CLIENT_ID =
'GCM_ANDROID_DARK'- MOBILE_SERVICE =
'https://mobile.integration.garmin.com/gcm/android'- LOGIN_DELAY_MIN =
30.0- LOGIN_DELAY_MAX =
45.0- REDIRECT_STATUSES =
[301, 302, 303, 307, 308].freeze
- AUTH_FLAG =
'-B'
Class Method Summary collapse
- ._extract_ticket_from_url(url) ⇒ Object
- ._find_chrome ⇒ Object
- ._find_playwright_cli ⇒ Object
- ._launch_playwright(chrome_path) ⇒ Object
- ._load_session(session_path) ⇒ Object
- ._mobile_api_login(context, domain, email, password, mfa_code, sso) ⇒ Object
- ._random_delay(label) ⇒ Object
- ._save_session(context, session_path) ⇒ Object
- ._session_file_path(_domain) ⇒ Object
- .call(email:, password:, domain: 'garmin.com', mfa_code: nil) ⇒ Object
- .mfa_required_message(email) ⇒ Object
- .resolve_mfa_code(email, mfa_code) ⇒ Object
- .resume_login(domain, mfa_code, saved, chrome_path) ⇒ Object
- .verify_mfa(context, sso, mfa_method, code) ⇒ Object
Class Method Details
._extract_ticket_from_url(url) ⇒ Object
178 179 180 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 178 def _extract_ticket_from_url(url) url[/[?&]ticket=(ST-[^&\s]+)/, 1] end |
._find_chrome ⇒ Object
232 233 234 235 236 237 238 239 240 241 242 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 232 def _find_chrome candidates = [] env_path = ENV['GIT_FIT_GARMIN_CHROMIUM_PATH'].to_s.strip candidates << env_path unless env_path.empty? candidates.concat(%w[/usr/bin/google-chrome-beta /usr/bin/google-chrome /usr/bin/chromium]) found = candidates.find { |path| File.exist?(path) } return found if found raise GitFit::Sync::AuthError, 'Chrome not found. Set GIT_FIT_GARMIN_CHROMIUM_PATH or use -A strategy' end |
._find_playwright_cli ⇒ Object
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 266 def _find_playwright_cli env_path = ENV['GIT_FIT_PLAYWRIGHT_CLI_PATH'].to_s.strip return env_path unless env_path.empty? %w[ node_modules/.bin/playwright-core ].each do |relative| dir = Dir.pwd loop do candidate = File.join(dir, relative) return candidate if File.exist?(candidate) parent = File.dirname(dir) break if parent == dir dir = parent end end raise GitFit::Sync::AuthError, 'playwright-core CLI not found. npm install playwright-core@1.62.1 in the project root, ' \ 'or set GIT_FIT_PLAYWRIGHT_CLI_PATH, or use -A strategy' end |
._launch_playwright(chrome_path) ⇒ Object
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 244 def _launch_playwright(chrome_path) begin require 'playwright' rescue LoadError raise GitFit::Sync::AuthError, 'playwright-ruby-client gem missing. bundle install, or use -A strategy' end cli = _find_playwright_cli Playwright.create(playwright_cli_executable_path: cli) do |playwright| browser = playwright.chromium.launch(headless: true, executablePath: chrome_path) begin yield browser ensure browser.close end end rescue GitFit::Sync::AuthError raise rescue StandardError => e raise GitFit::Sync::AuthError, "Playwright launch failed: #{e.}" end |
._load_session(session_path) ⇒ Object
211 212 213 214 215 216 217 218 219 220 221 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 211 def _load_session(session_path) return nil unless File.exist?(session_path) data = JSON.parse(File.read(session_path)) age_days = (Time.now.to_f - (data['saved_at'] || 0).to_f) / 86_400.0 { path: session_path, age_days: age_days } rescue StandardError => e warn "failed to load session cookies: #{e.}" File.delete(session_path) if File.exist?(session_path) nil end |
._mobile_api_login(context, domain, email, password, mfa_code, sso) ⇒ Object
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 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 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 71 def _mobile_api_login(context, domain, email, password, mfa_code, sso) req = context.request headers = { 'User-Agent' => MOBILE_UA, 'Accept' => 'application/json, text/plain, */*', 'Content-Type' => 'application/json', 'Origin' => sso, 'Accept-Language' => 'en-US,en;q=0.9', } params = { 'clientId' => MOBILE_CLIENT_ID, 'locale' => 'en-US', 'service' => MOBILE_SERVICE } referer = "#{sso}/mobile/sso/en_US/sign-in?clientId=#{MOBILE_CLIENT_ID}&service=#{MOBILE_SERVICE}" signin_resp = req.get( "#{sso}/mobile/sso/en_US/sign-in", params: { 'clientId' => MOBILE_CLIENT_ID, 'service' => MOBILE_SERVICE }, headers: { 'User-Agent' => MOBILE_UA, 'Accept' => 'text/html,...', 'Accept-Language' => 'en-US,en;q=0.9' }, maxRedirects: 0, ) if REDIRECT_STATUSES.include?(signin_resp.status) location = signin_resp.headers['location'].to_s ticket = _extract_ticket_from_url(location) if ticket warn "session valid — ticket from redirect: #{ticket[0, 20]}..." return [ticket, MOBILE_SERVICE] end warn "302 redirect but no ticket in: #{location[0, 80]}..." end _random_delay('mobile') warn 'posting login credentials...' resp = req.post( "#{sso}/mobile/api/login", params: params, headers: headers.merge('Referer' => referer), data: JSON.generate( 'username' => email, 'password' => password, 'rememberMe' => true, 'captchaToken' => '', ), ) raise GitFit::Sync::AuthError, 'mobile API login 429 (rate limited by Cloudflare)' if resp.status == 429 data = resp.json resp_type = data.dig('responseStatus', 'type') raise GitFit::Sync::AuthError, 'Invalid username or password' if resp_type == 'INVALID_USERNAME_PASSWORD' return [data['serviceTicketId'], MOBILE_SERVICE] if resp_type == 'SUCCESSFUL' raise GitFit::Sync::AuthError, "Unexpected login response: #{resp_type}" unless resp_type == 'MFA_REQUIRED' mfa_method = data.dig('customerMfaInfo', 'mfaLastMethodUsed') || 'email' code = resolve_mfa_code(email, mfa_code) if code.nil? LoginSession.save(domain, { 'strategy' => 'B', 'sso' => sso, 'method' => mfa_method, 'storage_state' => context.storage_state, }) raise MfaRequired, (email) end verify_mfa(context, sso, mfa_method, code) end |
._random_delay(label) ⇒ Object
201 202 203 204 205 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 201 def _random_delay(label) delay = rand(LOGIN_DELAY_MIN..LOGIN_DELAY_MAX) warn "[garmin_auth_pw] #{label}: waiting #{delay.round}s for Cloudflare..." sleep(delay) end |
._save_session(context, session_path) ⇒ Object
223 224 225 226 227 228 229 230 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 223 def _save_session(context, session_path) FileUtils.mkdir_p(File.dirname(session_path)) state = context.storage_state state['saved_at'] = Time.now.to_f File.write(session_path, JSON.generate(state)) rescue StandardError => e warn "failed to save session cookies: #{e.}" end |
._session_file_path(_domain) ⇒ Object
207 208 209 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 207 def _session_file_path(_domain) Auth.file(GitFit::Sync::GarminCom.source_prefix, 'session.json') end |
.call(email:, password:, domain: 'garmin.com', mfa_code: nil) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 27 def call(email:, password:, domain: 'garmin.com', mfa_code: nil) mfa_code = mfa_code.to_s.strip sso = "https://sso.#{domain}" session_path = _session_file_path(domain) chrome_path = _find_chrome if !mfa_code.empty? && (saved = LoginSession.load(domain)) return resume_login(domain, mfa_code, saved, chrome_path) end _launch_playwright(chrome_path) do |browser| session = _load_session(session_path) warn "loaded session cookies (#{session[:age_days].round} days old)" if session opts = { userAgent: MOBILE_UA, viewport: { width: 375, height: 812 } } opts[:storageState] = session[:path] if session context = browser.new_context(**opts) begin ticket, service_url = _mobile_api_login(context, domain, email, password, mfa_code, sso) token = DIExchange.call(domain, ticket, service_url) _save_session(context, session_path) token ensure context.close end end end |
.mfa_required_message(email) ⇒ Object
192 193 194 195 196 197 198 199 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 192 def (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 |
.resolve_mfa_code(email, mfa_code) ⇒ Object
182 183 184 185 186 187 188 189 190 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 182 def resolve_mfa_code(email, mfa_code) code = mfa_code.to_s.strip if code.empty? warn "[garmin_auth_pw] 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, chrome_path) ⇒ Object
56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 56 def resume_login(domain, mfa_code, saved, chrome_path) _launch_playwright(chrome_path) do |browser| context = browser.new_context(storageState: saved['storage_state']) begin ticket, = verify_mfa(context, saved['sso'], saved['method'], mfa_code) token = DIExchange.call(domain, ticket, MOBILE_SERVICE) _save_session(context, _session_file_path(domain)) LoginSession.clear(domain) token ensure context.close end end end |
.verify_mfa(context, sso, mfa_method, code) ⇒ Object
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 |
# File 'lib/git_fit/auth/garmin/strategy_b.rb', line 140 def verify_mfa(context, sso, mfa_method, code) warn 'verifying MFA code...' headers = { 'User-Agent' => MOBILE_UA, 'Accept' => 'application/json, text/plain, */*', 'Content-Type' => 'application/json', 'Origin' => sso, 'Accept-Language' => 'en-US,en;q=0.9', } params = { 'clientId' => MOBILE_CLIENT_ID, 'locale' => 'en-US', 'service' => MOBILE_SERVICE } referer = "#{sso}/mobile/sso/en_US/sign-in?clientId=#{MOBILE_CLIENT_ID}&service=#{MOBILE_SERVICE}" mfa_data = { 'mfaMethod' => mfa_method, 'mfaVerificationCode' => code, 'rememberMyBrowser' => true, 'reconsentList' => [], 'mfaSetup' => false, } resp = context.request.post( "#{sso}/mobile/api/mfa/verifyCode", params: params, headers: headers.merge('Referer' => referer), data: JSON.generate(mfa_data), ) data = resp.json resp_type = data.dig('responseStatus', 'type') return [data['serviceTicketId'], MOBILE_SERVICE] if resp_type == 'SUCCESSFUL' if resp_type == 'MFA_CODE_INVALID' raise GitFit::Sync::AuthError, "MFA code invalid — #{data.dig('responseStatus', 'message') || 'unknown'}" end raise GitFit::Sync::AuthError, "Unexpected MFA response: #{resp_type}" end |