bambu_cloud.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. """
  2. Bambu Lab Cloud API Service
  3. Handles authentication and profile management with Bambu Lab's cloud services.
  4. """
  5. import logging
  6. from datetime import datetime, timedelta, timezone
  7. import httpx
  8. logger = logging.getLogger(__name__)
  9. BAMBU_API_BASE = "https://api.bambulab.com"
  10. BAMBU_API_BASE_CN = "https://api.bambulab.cn"
  11. # Client identity sent to Bambu Lab's cloud services. We identify honestly as
  12. # Bambuddy — the URL in parens makes the source unambiguous so Bambu can
  13. # distinguish our traffic from impersonators. This is the opposite of what the
  14. # OrcaSlicer fork was called out for in the May 2026 Bambu Lab blog post
  15. # ("Setting the record straight on cloud access and community"): we do not
  16. # introduce ourselves as official Bambu Studio.
  17. _USER_AGENT = "Bambuddy/1.0 (+https://github.com/maziggy/bambuddy)"
  18. # Cloudflare protection on Bambu Lab's edge intermittently returns interstitials /
  19. # challenges instead of the JSON the API normally produces (issue #1575). The
  20. # parse error that results is opaque — these helpers detect the CF markers so
  21. # we can surface an actionable message instead of "Invalid response from Bambu Cloud".
  22. _CF_INTERSTITIAL_USER_MESSAGE = (
  23. "Bambu Cloud is temporarily blocking automated requests from your network. "
  24. "This is a Cloudflare protection on Bambu Lab's side, not a Bambuddy issue. "
  25. "Please wait a few minutes and try again. If it persists, signing in to "
  26. "bambulab.com once from a browser on the same network usually clears the "
  27. "challenge."
  28. )
  29. def _detect_cloudflare_challenge(response) -> str | None:
  30. """Return a user-actionable message when the response is a Cloudflare
  31. challenge / mitigation page instead of the JSON the API normally returns.
  32. Triggers on any of:
  33. - body contains "Just a moment..." (CF interactive challenge title)
  34. - body contains "challenges.cloudflare.com" (CF turnstile widget src)
  35. - HTTP 403 with a "cf-mitigated" response header (CF blocked)
  36. - HTTP 503 with a "cf-ray" response header (CF Under Attack mode)
  37. Returns None when the response doesn't look like a CF challenge — callers
  38. fall through to their existing error path.
  39. """
  40. try:
  41. body = response.text or ""
  42. except Exception:
  43. body = ""
  44. if "Just a moment..." in body or "challenges.cloudflare.com" in body:
  45. return _CF_INTERSTITIAL_USER_MESSAGE
  46. try:
  47. status = int(getattr(response, "status_code", 0) or 0)
  48. except (TypeError, ValueError):
  49. status = 0
  50. headers = getattr(response, "headers", {}) or {}
  51. if status == 403 and "cf-mitigated" in headers:
  52. return _CF_INTERSTITIAL_USER_MESSAGE
  53. if status == 503 and "cf-ray" in headers:
  54. return _CF_INTERSTITIAL_USER_MESSAGE
  55. return None
  56. # The `/v1/iot-service/api/slicer/setting` endpoint subtree — the plural GET
  57. # for the list, the singular GET/DELETE for a specific preset by setting_id, and
  58. # the POST for create — requires a `version` query parameter in the XX.YY.ZZ.WW
  59. # format Bambu Studio releases use. Without it the API returns HTTP 400
  60. # "field 'version' is not set"; non-matching formats like "bambuddy-1.0" return
  61. # HTTP 422 "Invalid input parameters". However, Bambu's server accepts ANY value
  62. # within that format — it doesn't validate against a release manifest. We
  63. # therefore use a neutral "1.0.0.0" placeholder that does not impersonate any
  64. # real Bambu Studio release. Our client identity is in the User-Agent header.
  65. _SLICER_API_VERSION = "1.0.0.0"
  66. class BambuCloudError(Exception):
  67. """Base exception for Bambu Cloud errors.
  68. ``status_code`` carries the upstream HTTP status when the failure came from
  69. a response rather than from the transport, so callers can tell an expected
  70. "this preset isn't in the catalog" 400 apart from an expired token or a
  71. cloud outage. It stays ``None`` for connection-level failures.
  72. """
  73. def __init__(self, message: str, *, status_code: int | None = None):
  74. super().__init__(message)
  75. self.status_code = status_code
  76. class BambuCloudAuthError(BambuCloudError):
  77. """Authentication related errors."""
  78. pass
  79. _shared_http_client: httpx.AsyncClient | None = None
  80. def set_shared_http_client(client: httpx.AsyncClient | None) -> None:
  81. """Register an app-scoped ``httpx.AsyncClient`` so per-request
  82. ``BambuCloudService`` instances can reuse its connection pool.
  83. Pass ``None`` during shutdown to unregister. The service only holds a
  84. reference (never closes a client it does not own), so region + token
  85. state still stays per-request — this only shares the transport pool.
  86. """
  87. global _shared_http_client
  88. _shared_http_client = client
  89. class BambuCloudService:
  90. """Service for interacting with Bambu Lab Cloud API."""
  91. def __init__(self, region: str = "global", client: httpx.AsyncClient | None = None):
  92. self.base_url = BAMBU_API_BASE if region == "global" else BAMBU_API_BASE_CN
  93. self.access_token: str | None = None
  94. self.refresh_token: str | None = None
  95. self.token_expiry: datetime | None = None
  96. # Prefer an explicitly-injected client (tests), else fall back to the
  97. # app-scoped shared client (production), and finally create our own so
  98. # scripts / tests that skip the lifespan still get a working service.
  99. if client is not None:
  100. self._client = client
  101. self._owns_client = False
  102. elif _shared_http_client is not None:
  103. self._client = _shared_http_client
  104. self._owns_client = False
  105. else:
  106. self._client = httpx.AsyncClient(timeout=30.0)
  107. self._owns_client = True
  108. @property
  109. def is_authenticated(self) -> bool:
  110. """Check if we have a valid token."""
  111. if not self.access_token:
  112. return False
  113. return not (self.token_expiry and datetime.now(timezone.utc) > self.token_expiry)
  114. def _get_headers(self) -> dict:
  115. """Get headers for authenticated requests."""
  116. headers = {
  117. "Content-Type": "application/json",
  118. "User-Agent": _USER_AGENT,
  119. }
  120. if self.access_token:
  121. headers["Authorization"] = f"Bearer {self.access_token}"
  122. return headers
  123. async def login_request(self, email: str, password: str) -> dict:
  124. """
  125. Initiate login - this will trigger either email verification or TOTP prompt.
  126. Returns dict with login status, verification type, and tfaKey if needed.
  127. """
  128. try:
  129. response = await self._client.post(
  130. f"{self.base_url}/v1/user-service/user/login",
  131. headers={"Content-Type": "application/json"},
  132. json={
  133. "account": email,
  134. "password": password,
  135. },
  136. )
  137. try:
  138. data = response.json()
  139. except Exception as json_err:
  140. logger.error("Failed to parse login response: %s, body: %s", json_err, response.text[:500])
  141. cf_message = _detect_cloudflare_challenge(response)
  142. return {
  143. "success": False,
  144. "needs_verification": False,
  145. "message": cf_message or "Invalid response from Bambu Cloud",
  146. }
  147. logger.debug(
  148. f"Login response: status={response.status_code}, loginType={data.get('loginType')}, hasTfaKey={'tfaKey' in data}"
  149. )
  150. if response.status_code == 200:
  151. login_type = data.get("loginType")
  152. tfa_key = data.get("tfaKey")
  153. # TOTP authentication required
  154. if login_type == "tfa" or (tfa_key and login_type != "verifyCode"):
  155. return {
  156. "success": False,
  157. "needs_verification": True,
  158. "verification_type": "totp",
  159. "tfa_key": tfa_key,
  160. "message": "Enter the code from your authenticator app",
  161. }
  162. # Email verification required
  163. if login_type == "verifyCode":
  164. return {
  165. "success": False,
  166. "needs_verification": True,
  167. "verification_type": "email",
  168. "tfa_key": None,
  169. "message": "Verification code sent to email",
  170. }
  171. # Direct login success (rare, usually needs 2FA)
  172. if "accessToken" in data:
  173. self._set_tokens(data)
  174. return {"success": True, "needs_verification": False, "message": "Login successful"}
  175. # Handle specific error codes
  176. error_msg = data.get("message") or data.get("error") or "Login failed"
  177. return {"success": False, "needs_verification": False, "message": error_msg}
  178. except Exception as e:
  179. logger.error("Login request failed: %s", e)
  180. raise BambuCloudAuthError(f"Login request failed: {e}")
  181. async def verify_code(self, email: str, code: str) -> dict:
  182. """
  183. Complete login with email verification code.
  184. """
  185. try:
  186. response = await self._client.post(
  187. f"{self.base_url}/v1/user-service/user/login",
  188. headers={"Content-Type": "application/json"},
  189. json={
  190. "account": email,
  191. "code": code,
  192. },
  193. )
  194. try:
  195. data = response.json()
  196. except Exception as json_err:
  197. logger.error("Failed to parse email-verify response: %s, body: %s", json_err, response.text[:500])
  198. cf_message = _detect_cloudflare_challenge(response)
  199. return {"success": False, "message": cf_message or "Invalid response from Bambu Cloud"}
  200. logger.debug("Email verify response: status=%s, hasToken=%s", response.status_code, "accessToken" in data)
  201. if response.status_code == 200 and "accessToken" in data:
  202. self._set_tokens(data)
  203. return {"success": True, "message": "Login successful"}
  204. return {"success": False, "message": data.get("message", "Verification failed")}
  205. except Exception as e:
  206. logger.error("Email verification failed: %s", e)
  207. raise BambuCloudAuthError(f"Verification failed: {e}")
  208. async def verify_totp(self, tfa_key: str, code: str) -> dict:
  209. """
  210. Complete login with TOTP code from authenticator app.
  211. Args:
  212. tfa_key: The tfaKey returned from initial login request
  213. code: 6-digit TOTP code from authenticator app
  214. """
  215. try:
  216. # TFA endpoint is on bambulab.com, NOT api.bambulab.com.
  217. # We previously sent a Chrome User-Agent plus Origin/Referer headers
  218. # under the assumption Cloudflare would block bot-identified
  219. # requests. Verified 2026-05-12 via curl that the endpoint accepts
  220. # honest "Bambuddy/X.Y.Z" identification cleanly (HTTP 400 with the
  221. # expected application-level "Login failed" JSON, no Cloudflare
  222. # interstitial). Browser-impersonation removed to stay clearly on
  223. # the right side of Bambu Lab's "no falsified client identity" line.
  224. tfa_url = "https://bambulab.com/api/sign-in/tfa"
  225. if "bambulab.cn" in self.base_url:
  226. tfa_url = "https://bambulab.cn/api/sign-in/tfa"
  227. response = await self._client.post(
  228. tfa_url,
  229. headers={
  230. "Content-Type": "application/json",
  231. "User-Agent": _USER_AGENT,
  232. "Accept": "application/json",
  233. },
  234. json={
  235. "tfaKey": tfa_key,
  236. "tfaCode": code,
  237. },
  238. )
  239. logger.debug(
  240. f"TOTP verify response: status={response.status_code}, body={response.text[:200] if response.text else '(empty)'}"
  241. )
  242. # Handle empty response
  243. if not response.text or not response.text.strip():
  244. logger.warning("TOTP verification returned empty response (status %s)", response.status_code)
  245. return {"success": False, "message": "Bambu Cloud returned empty response. Please try again."}
  246. try:
  247. data = response.json()
  248. except Exception as json_err:
  249. logger.error("Failed to parse TOTP response: %s, body: %s", json_err, response.text[:500])
  250. cf_message = _detect_cloudflare_challenge(response)
  251. return {"success": False, "message": cf_message or "Invalid response from Bambu Cloud"}
  252. # Token might be in accessToken, token field, or cookies
  253. access_token = data.get("accessToken") or data.get("token")
  254. # Also check cookies for token
  255. if not access_token:
  256. for cookie in response.cookies:
  257. if "token" in cookie.lower():
  258. access_token = response.cookies.get(cookie)
  259. break
  260. if response.status_code == 200 and access_token:
  261. self.access_token = access_token
  262. self.refresh_token = data.get("refreshToken")
  263. from datetime import datetime, timedelta, timezone
  264. self.token_expiry = datetime.now(timezone.utc) + timedelta(days=30)
  265. return {"success": True, "message": "Login successful"}
  266. # Provide helpful error message
  267. error_msg = data.get("message", "")
  268. if "expired" in error_msg.lower():
  269. return {"success": False, "message": "TOTP session expired. Please try logging in again."}
  270. if not error_msg:
  271. error_msg = f"TOTP verification failed (status {response.status_code})"
  272. return {"success": False, "message": error_msg}
  273. except Exception as e:
  274. logger.error("TOTP verification failed: %s", e)
  275. # Return error instead of raising - don't trigger 401/500
  276. return {"success": False, "message": f"TOTP verification error: {e}"}
  277. def _set_tokens(self, data: dict):
  278. """Set tokens from login response."""
  279. self.access_token = data.get("accessToken")
  280. self.refresh_token = data.get("refreshToken")
  281. # Token typically valid for ~3 months, but we'll refresh more often
  282. self.token_expiry = datetime.now(timezone.utc) + timedelta(days=30)
  283. def set_token(self, access_token: str):
  284. """Set access token directly (for stored tokens)."""
  285. self.access_token = access_token
  286. self.token_expiry = datetime.now(timezone.utc) + timedelta(days=30)
  287. def logout(self):
  288. """Clear authentication state."""
  289. self.access_token = None
  290. self.refresh_token = None
  291. self.token_expiry = None
  292. async def get_user_profile(self) -> dict:
  293. """Get user profile information."""
  294. if not self.is_authenticated:
  295. raise BambuCloudAuthError("Not authenticated")
  296. try:
  297. response = await self._client.get(
  298. f"{self.base_url}/v1/design-user-service/my/preference", headers=self._get_headers()
  299. )
  300. if response.status_code == 200:
  301. return response.json()
  302. raise BambuCloudError(f"Failed to get profile: {response.status_code}")
  303. except httpx.RequestError as e:
  304. raise BambuCloudError(f"Request failed: {e}")
  305. async def get_slicer_settings(self, version: str = _SLICER_API_VERSION) -> dict:
  306. """
  307. Get all slicer settings (filament, printer, process presets).
  308. Args:
  309. version: Slicer version string. Bambu's API requires the XX.YY.ZZ.WW
  310. format but does not validate against a release manifest — we
  311. default to the neutral _SLICER_API_VERSION placeholder so we
  312. never claim to be a specific Bambu Studio build. Callers should
  313. normally use the default.
  314. """
  315. if not self.is_authenticated:
  316. raise BambuCloudAuthError("Not authenticated")
  317. try:
  318. response = await self._client.get(
  319. f"{self.base_url}/v1/iot-service/api/slicer/setting",
  320. headers=self._get_headers(),
  321. params={"version": version},
  322. )
  323. data = response.json()
  324. if response.status_code == 200:
  325. return data
  326. raise BambuCloudError(f"Failed to get settings: {response.status_code}")
  327. except httpx.RequestError as e:
  328. raise BambuCloudError(f"Request failed: {e}")
  329. async def get_setting_detail(self, setting_id: str) -> dict:
  330. """Get detailed information for a specific setting/preset."""
  331. if not self.is_authenticated:
  332. raise BambuCloudAuthError("Not authenticated")
  333. try:
  334. response = await self._client.get(
  335. f"{self.base_url}/v1/iot-service/api/slicer/setting/{setting_id}",
  336. headers=self._get_headers(),
  337. params={"version": _SLICER_API_VERSION},
  338. )
  339. if response.status_code == 200:
  340. return response.json()
  341. # Include body so a future contract change is self-diagnostic from logs.
  342. body = (response.text or "")[:200]
  343. raise BambuCloudError(
  344. f"Failed to get setting detail: {response.status_code} {body}",
  345. status_code=response.status_code,
  346. )
  347. except httpx.RequestError as e:
  348. raise BambuCloudError(f"Request failed: {e}")
  349. async def create_setting(
  350. self, preset_type: str, name: str, base_id: str, setting: dict, version: str = "2.0.0.0"
  351. ) -> dict:
  352. """
  353. Create a new slicer preset/setting.
  354. Args:
  355. preset_type: Type of preset - "filament", "print", or "printer"
  356. name: Display name for the preset
  357. base_id: Base preset ID to inherit from (e.g., "GFSA00")
  358. setting: Dict of setting key-value pairs (only modified values from base)
  359. version: Version string for the preset (default: "2.0.0.0")
  360. Returns:
  361. Created preset data including the new setting_id
  362. """
  363. if not self.is_authenticated:
  364. raise BambuCloudAuthError("Not authenticated")
  365. try:
  366. # Add timestamp if not present
  367. import time
  368. if "updated_time" not in setting:
  369. setting["updated_time"] = str(int(time.time()))
  370. payload = {
  371. "type": preset_type,
  372. "name": name,
  373. "version": version,
  374. "base_id": base_id,
  375. "setting": setting,
  376. }
  377. response = await self._client.post(
  378. f"{self.base_url}/v1/iot-service/api/slicer/setting", headers=self._get_headers(), json=payload
  379. )
  380. data = response.json()
  381. if response.status_code in (200, 201):
  382. return data
  383. error_msg = data.get("message") or data.get("error") or f"HTTP {response.status_code}"
  384. raise BambuCloudError(f"Failed to create setting: {error_msg}")
  385. except httpx.RequestError as e:
  386. raise BambuCloudError(f"Request failed: {e}")
  387. async def update_setting(self, setting_id: str, name: str | None = None, setting: dict | None = None) -> dict:
  388. """
  389. Update an existing slicer preset/setting.
  390. Note: Bambu Cloud API doesn't support true updates. Instead, we:
  391. 1. Fetch the current setting metadata (type, base_id, version)
  392. 2. Use the provided settings as the new complete settings (NOT merged)
  393. 3. Delete the old setting first (to avoid name conflicts)
  394. 4. Create a new setting via POST
  395. Args:
  396. setting_id: ID of the preset to update
  397. name: New display name (optional)
  398. setting: Dict of setting key-value pairs - this REPLACES the old settings entirely
  399. Returns:
  400. Updated preset data with new setting_id
  401. """
  402. if not self.is_authenticated:
  403. raise BambuCloudAuthError("Not authenticated")
  404. try:
  405. # Fetch current setting to get metadata (type, base_id, version)
  406. current = await self.get_setting_detail(setting_id)
  407. preset_type = current.get("type", "filament")
  408. # Use provided settings directly (complete replacement, not merge)
  409. # This allows the frontend to edit the full settings JSON
  410. if setting is not None:
  411. updated_setting = setting.copy()
  412. else:
  413. updated_setting = current.get("setting", {}).copy()
  414. # Extract name from settings_id field in the JSON, or use provided name, or fall back to current
  415. # The settings_id field contains the name in quotes, e.g., '"My Preset Name"'
  416. settings_id_key = {
  417. "filament": "filament_settings_id",
  418. "print": "print_settings_id",
  419. "printer": "printer_settings_id",
  420. }.get(preset_type, "filament_settings_id")
  421. settings_id_value = updated_setting.get(settings_id_key, "")
  422. if settings_id_value:
  423. # Remove surrounding quotes if present (e.g., '"foo"' -> 'foo')
  424. updated_name = settings_id_value.strip('"')
  425. elif name is not None:
  426. updated_name = name
  427. else:
  428. updated_name = current.get("name", "Untitled")
  429. # Update the timestamp
  430. import time
  431. updated_setting["updated_time"] = str(int(time.time()))
  432. # Ensure settings_id field matches the name
  433. updated_setting[settings_id_key] = f'"{updated_name}"'
  434. # Delete the old setting FIRST to avoid name conflicts
  435. await self.delete_setting(setting_id)
  436. # Create new setting via POST
  437. payload = {
  438. "type": preset_type,
  439. "name": updated_name,
  440. "version": current.get("version", "2.0.0.0"),
  441. "base_id": current.get("base_id", ""),
  442. "setting": updated_setting,
  443. }
  444. response = await self._client.post(
  445. f"{self.base_url}/v1/iot-service/api/slicer/setting", headers=self._get_headers(), json=payload
  446. )
  447. data = response.json()
  448. if response.status_code == 200:
  449. return data
  450. error_msg = data.get("message") or data.get("error") or f"HTTP {response.status_code}"
  451. raise BambuCloudError(f"Failed to update setting: {error_msg}")
  452. except httpx.RequestError as e:
  453. raise BambuCloudError(f"Request failed: {e}")
  454. async def delete_setting(self, setting_id: str) -> dict:
  455. """
  456. Delete a slicer preset/setting.
  457. Args:
  458. setting_id: ID of the preset to delete
  459. Returns:
  460. Deletion confirmation
  461. """
  462. if not self.is_authenticated:
  463. raise BambuCloudAuthError("Not authenticated")
  464. try:
  465. response = await self._client.delete(
  466. f"{self.base_url}/v1/iot-service/api/slicer/setting/{setting_id}",
  467. headers=self._get_headers(),
  468. params={"version": _SLICER_API_VERSION},
  469. )
  470. if response.status_code in (200, 204):
  471. return {"success": True, "message": "Setting deleted"}
  472. data = response.json() if response.content else {}
  473. error_msg = data.get("message") or data.get("error") or f"HTTP {response.status_code}"
  474. raise BambuCloudError(f"Failed to delete setting: {error_msg}")
  475. except httpx.RequestError as e:
  476. raise BambuCloudError(f"Request failed: {e}")
  477. async def get_devices(self) -> dict:
  478. """Get list of bound devices."""
  479. if not self.is_authenticated:
  480. raise BambuCloudAuthError("Not authenticated")
  481. try:
  482. response = await self._client.get(
  483. f"{self.base_url}/v1/iot-service/api/user/bind", headers=self._get_headers()
  484. )
  485. if response.status_code == 200:
  486. return response.json()
  487. raise BambuCloudError(f"Failed to get devices: {response.status_code}")
  488. except httpx.RequestError as e:
  489. raise BambuCloudError(f"Request failed: {e}")
  490. async def get_firmware_version(self, device_id: str) -> dict:
  491. """
  492. Get firmware version info for a device.
  493. Returns dict with:
  494. - current_version: Installed firmware version
  495. - latest_version: Latest available firmware version
  496. - update_available: Boolean indicating if update is available
  497. - release_notes: Release notes for latest version
  498. """
  499. if not self.is_authenticated:
  500. raise BambuCloudAuthError("Not authenticated")
  501. try:
  502. response = await self._client.get(
  503. f"{self.base_url}/v1/iot-service/api/user/device/version",
  504. headers=self._get_headers(),
  505. params={"device_id": device_id},
  506. )
  507. if response.status_code == 200:
  508. data = response.json()
  509. # API wraps response in 'data' field
  510. return data.get("data", data)
  511. raise BambuCloudError(f"Failed to get firmware version: {response.status_code}")
  512. except httpx.RequestError as e:
  513. raise BambuCloudError(f"Request failed: {e}")
  514. async def close(self):
  515. """Close the HTTP client we own. No-op when sharing an app-scoped client."""
  516. if self._owns_client:
  517. await self._client.aclose()
  518. # Previously this module exposed a process-wide ``_cloud_service`` singleton
  519. # via ``get_cloud_service()`` / ``reset_cloud_service()``. That pattern leaked
  520. # region and token state across users (a China-region login would pin the
  521. # singleton to api.bambulab.cn until the next explicit reset), so the singleton
  522. # has been removed. Callers should construct a per-request
  523. # ``BambuCloudService(region=...)`` from the stored region and ``await
  524. # cloud.close()`` it when done. See ``routes.cloud.build_authenticated_cloud``
  525. # for the standard pattern.