Synchronously refresh an expired token via the platform OAuth endpoint.
(tokens: dict[str, Any])
| 142 | |
| 143 | |
| 144 | def _refresh_token(tokens: dict[str, Any]) -> dict[str, Any]: |
| 145 | """Synchronously refresh an expired token via the platform OAuth endpoint.""" |
| 146 | data = oauth_refresh_request( |
| 147 | TOKEN_URL, |
| 148 | { |
| 149 | "grant_type": "refresh_token", |
| 150 | "refresh_token": tokens["refreshToken"], |
| 151 | "client_id": CLIENT_ID, |
| 152 | }, |
| 153 | json_body=True, |
| 154 | timeout=30, |
| 155 | provider_label="auth", |
| 156 | ) |
| 157 | # The refresh endpoint normally returns access_token; a malformed or |
| 158 | # error-shaped response would otherwise blow up with a raw KeyError. |
| 159 | # Never interpolate ``data`` here — it carries the freshly minted |
| 160 | # access / refresh tokens. Report only the missing field name. |
| 161 | access_token = data.get("access_token") |
| 162 | if not access_token: |
| 163 | raise litellm.AuthenticationError( |
| 164 | message=( |
| 165 | "Claude Code token refresh response missing field: access_token. " |
| 166 | "Run 'claude /login' and retry." |
| 167 | ), |
| 168 | model="auth", |
| 169 | llm_provider="auth", |
| 170 | ) |
| 171 | |
| 172 | new_tokens = { |
| 173 | "accessToken": access_token, |
| 174 | "refreshToken": data.get("refresh_token") or tokens["refreshToken"], |
| 175 | "expiresAt": int(time.time() + (data.get("expires_in") or 3600)), |
| 176 | "scopes": (data.get("scope") or "").split(), |
| 177 | "updatedAt": int(time.time() * 1000), |
| 178 | } |
| 179 | |
| 180 | # Persist atomically. The store handles read-only mounts internally; |
| 181 | # the cache replace keeps the in-process token current for the rest |
| 182 | # of the container session even when the on-disk write fails. |
| 183 | write_json_atomic(CREDENTIALS_PATH, new_tokens) |
| 184 | _credentials_cache.replace(new_tokens) |
| 185 | return new_tokens |
| 186 | |
| 187 | |
| 188 | def get_access_token(force_refresh: bool = False) -> str: |
no test coverage detected