| 1 | """Bluesky search via AT Protocol (requires app password). |
| 2 | |
| 3 | Uses bsky.social for auth and api.bsky.app for post search (the canonical |
| 4 | authenticated AppView). The previous default `public.api.bsky.app` is the |
| 5 | unauthenticated public mirror, which BunnyCDN now blocks for searchPosts |
| 6 | regardless of auth header (verified 2026-05-04). Override the search host |
| 7 | via BSKY_SEARCH_HOST env var if Bluesky migrates infrastructure again. |
| 8 | |
| 9 | Requires BSKY_HANDLE and BSKY_APP_PASSWORD env vars. App passwords are |
| 10 | 19-char xxxx-xxxx-xxxx-xxxx; generate at bsky.app/settings/app-passwords. |
| 11 | The createSession endpoint accepts main-account passwords too, but they're |
| 12 | bad hygiene (no scope, can't revoke individually). |
| 13 | """ |
| 14 | |
| 15 | import hashlib |
| 16 | import math |
| 17 | import os |
| 18 | import re |
| 19 | import threading |
| 20 | import time |
| 21 | from dataclasses import dataclass |
| 22 | from datetime import datetime, timedelta |
| 23 | from typing import Any, Dict, List, Optional |
| 24 | from urllib.parse import urlencode, urlsplit |
| 25 | |
| 26 | from . import auth_safety, http, log, public_host |
| 27 | |
| 28 | BSKY_SESSION_URL = "https://bsky.social/xrpc/com.atproto.server.createSession" |
| 29 | BSKY_REFRESH_URL = "https://bsky.social/xrpc/com.atproto.server.refreshSession" |
| 30 | _DEFAULT_BSKY_SEARCH_HOST = "api.bsky.app" |
| 31 | _BSKY_HOST_RE = re.compile( |
| 32 | r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$" |
| 33 | ) |
| 34 | _BSKY_DISALLOWED_SUFFIXES = (".localhost", ".local", ".internal", ".localdomain", ".home.arpa") |
| 35 | _BSKY_TRUSTED_HOSTS = frozenset({"bsky.app", "bsky.social"}) |
| 36 | _BSKY_TRUSTED_SUFFIXES = (".bsky.app", ".bsky.social") |
| 37 | |
| 38 | |
| 39 | def _is_trusted_bsky_host(host: str) -> bool: |
| 40 | """Return True when ``host`` is a Bluesky domain safe for bsky.social JWTs.""" |
| 41 | normalized = (host or "").strip().lower() |
| 42 | return normalized in _BSKY_TRUSTED_HOSTS or normalized.endswith(_BSKY_TRUSTED_SUFFIXES) |
| 43 | |
| 44 | |
| 45 | def _validate_search_host(raw: Any) -> Optional[str]: |
| 46 | """Validate and normalize a BSKY_SEARCH_HOST override to a bare public FQDN.""" |
| 47 | if not isinstance(raw, str): |
| 48 | return None |
| 49 | text = raw.strip() |
| 50 | if not text: |
| 51 | return None |
| 52 | if any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in text): |
| 53 | return None |
| 54 | # Strip a single pasted https:// origin (reject http:// and other schemes). |
| 55 | if text.lower().startswith("https://"): |
| 56 | text = text[len("https://"):] |
| 57 | if text.endswith("/"): |
| 58 | text = text[:-1] |
| 59 | if not text or not text.isascii(): |
| 60 | return None |
| 61 | if any(ch in text for ch in "/\\@?#:[]%"): |
| 62 | return None |
| 63 | try: |
| 64 | parts = urlsplit(f"https://{text}") |
| 65 | port = parts.port |
| 66 | except ValueError: |
| 67 | return None |
| 68 | if ( |
| 69 | parts.scheme != "https" |
| 70 | or parts.username is not None |
| 71 | or parts.password is not None |
| 72 | or port is not None |
| 73 | or parts.path != "" |
| 74 | or parts.query != "" |
| 75 | or parts.fragment != "" |
| 76 | ): |
| 77 | return None |
| 78 | host = (parts.hostname or "").lower() |
| 79 | if not host or len(host) > 253 or parts.netloc.lower() != host: |
| 80 | return None |
| 81 | if not _BSKY_HOST_RE.fullmatch(host): |
| 82 | return None |
| 83 | if host == "localhost" or host.endswith(_BSKY_DISALLOWED_SUFFIXES): |
| 84 | return None |
| 85 | if public_host._parse_ip_literal(host) is not None or host.rsplit(".", 1)[-1].isdigit(): |
| 86 | return None |
| 87 | if not public_host.is_public_address_syntax(f"https://{host}"): |
| 88 | return None |
| 89 | return host |
| 90 | |
| 91 | |
| 92 | def _bsky_search_redirect_guard(expected_host: str): |
| 93 | """Allow redirects only over HTTPS to the exact validated search host.""" |
| 94 | target_host = expected_host.lower() |
| 95 | |
| 96 | def _guard(newurl: str) -> bool: |
| 97 | if not isinstance(newurl, str) or not newurl or newurl != newurl.strip(): |
| 98 | return False |
| 99 | if any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in newurl): |
| 100 | return False |
| 101 | if not public_host.is_public_address_syntax(newurl): |
| 102 | return False |
| 103 | try: |
| 104 | parts = urlsplit(newurl) |
| 105 | port = parts.port |
| 106 | except ValueError: |
| 107 | return False |
| 108 | return ( |
| 109 | parts.scheme.lower() == "https" |
| 110 | and parts.username is None |
| 111 | and parts.password is None |
| 112 | and "\\" not in parts.netloc |
| 113 | and port in (None, 443) |
| 114 | and (parts.hostname or "").lower() == target_host |
| 115 | ) |
| 116 | |
| 117 | return _guard |
| 118 | |
| 119 | |
| 120 | def _resolve_search_url(config: Optional[Dict[str, Any]] = None) -> str: |
| 121 | """Resolve the Bluesky search URL with BSKY_SEARCH_HOST override. |
| 122 | |
| 123 | Default is api.bsky.app. Override via BSKY_SEARCH_HOST in shell env or |
| 124 | .env file. The project's env.py loads .env into config but not into |
| 125 | os.environ, so check both — same hybrid pattern as last30days.py for |
| 126 | LAST30DAYS_STORE. |
| 127 | |
| 128 | Strictly validates user-supplied host values as bare public FQDNs: |
| 129 | rejects non-HTTPS schemes, embedded paths, queries, fragments, userinfo, |
| 130 | ports, whitespace/control chars, IP literals, and localhost/private hosts. |
| 131 | On invalid input we log a warning and fall back to the default. |
| 132 | """ |
| 133 | config = config or {} |
| 134 | raw = ( |
| 135 | os.environ.get("BSKY_SEARCH_HOST") |
| 136 | or config.get("BSKY_SEARCH_HOST") |
| 137 | or _DEFAULT_BSKY_SEARCH_HOST |
| 138 | ) |
| 139 | host = _validate_search_host(raw) |
| 140 | if not host: |
| 141 | if raw != _DEFAULT_BSKY_SEARCH_HOST: |
| 142 | _log( |
| 143 | f"BSKY_SEARCH_HOST is not a valid public hostname; " |
| 144 | f"falling back to {_DEFAULT_BSKY_SEARCH_HOST}" |
| 145 | ) |
| 146 | host = _DEFAULT_BSKY_SEARCH_HOST |
| 147 | return f"https://{host}/xrpc/app.bsky.feed.searchPosts" |
| 148 | |
| 149 | |
| 150 | # App-password format: xxxx-xxxx-xxxx-xxxx (19 chars, lowercase alphanumeric |
| 151 | # with three hyphens at fixed positions). |
| 152 | _APP_PASSWORD_RE = re.compile(r"^[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$") |
| 153 | |
| 154 | |
| 155 | def _validate_app_password_format(value) -> bool: |
| 156 | """Return True if value matches Bluesky's 19-char app-password format. |
| 157 | |
| 158 | False for non-strings (None, int, list) so callers passing config dict |
| 159 | values directly don't crash. Detect-but-not-gate: the createSession |
| 160 | endpoint also accepts main-account passwords, so failing this check is |
| 161 | a hygiene smell, not a hard error. |
| 162 | """ |
| 163 | if not isinstance(value, str): |
| 164 | return False |
| 165 | return bool(_APP_PASSWORD_RE.fullmatch(value)) |
| 166 | |
| 167 | |
| 168 | DEPTH_CONFIG = { |
| 169 | "quick": 15, |
| 170 | "default": 30, |
| 171 | "deep": 60, |
| 172 | } |
| 173 | |
| 174 | @dataclass |
| 175 | class _SessionEntry: |
| 176 | access_token: str |
| 177 | refresh_token: Optional[str] |
| 178 | created_at: float |
| 179 | |
| 180 | |
| 181 | @dataclass |
| 182 | class _InflightAuth: |
| 183 | event: threading.Event |
| 184 | token: Optional[str] = None |
| 185 | error_msg: Optional[str] = "Bluesky authentication failed (unknown error)" |
| 186 | error_status: Optional[int] = None |
| 187 | did_reauth: bool = False |
| 188 | |
| 189 | |
| 190 | # Module-level session cache and unified singleflight auth slots keyed by |
| 191 | # (handle, sha256(app_password)). _session_lock guards in-memory state only and |
| 192 | # is never held across network I/O or event waits. |
| 193 | _session_lock = threading.Lock() |
| 194 | _session_cache: Dict[tuple[str, str], _SessionEntry] = {} |
| 195 | _inflight_auth: Dict[tuple[str, str], _InflightAuth] = {} |
| 196 | _cache_generation: int = 0 |
| 197 | _TOKEN_MAX_AGE_SECONDS = 5400 # 90 minutes (conservative, tokens last ~2 hours) |
| 198 | |
| 199 | |
| 200 | def _log(msg: str): |
| 201 | log.source_log("Bluesky", msg, tty_only=False) |
| 202 | |
| 203 | |
| 204 | def _wait_for_inflight_auth(inflight: _InflightAuth) -> None: |
| 205 | inflight.event.wait() |
| 206 | |
| 207 | |
| 208 | def _credential_key(handle: str, app_password: str) -> tuple[str, str]: |
| 209 | digest = hashlib.sha256(app_password.encode("utf-8")).hexdigest() |
| 210 | return (handle, digest) |
| 211 | |
| 212 | |
| 213 | def _evict_session( |
| 214 | cred_key: tuple[str, str], |
| 215 | *, |
| 216 | expected_token: Optional[str] = None, |
| 217 | ) -> None: |
| 218 | with _session_lock: |
| 219 | entry = _session_cache.get(cred_key) |
| 220 | if entry is None: |
| 221 | return |
| 222 | if expected_token is None or entry.access_token == expected_token: |
| 223 | _session_cache.pop(cred_key, None) |
| 224 | |
| 225 | |
| 226 | def _execute_create_session_request( |
| 227 | handle: str, |
| 228 | app_password: str, |
| 229 | cred_key: tuple[str, str], |
| 230 | generation: int, |
| 231 | ) -> tuple[Optional[str], Optional[str], Optional[int]]: |
| 232 | try: |
| 233 | response = http.request( |
| 234 | "POST", |
| 235 | BSKY_SESSION_URL, |
| 236 | json_data={"identifier": handle, "password": app_password}, |
| 237 | timeout=15, |
| 238 | ) |
| 239 | token = response.get("accessJwt") if isinstance(response, dict) else None |
| 240 | if token: |
| 241 | with _session_lock: |
| 242 | if _cache_generation == generation: |
| 243 | _session_cache[cred_key] = _SessionEntry( |
| 244 | access_token=token, |
| 245 | refresh_token=response.get("refreshJwt"), |
| 246 | created_at=time.monotonic(), |
| 247 | ) |
| 248 | _log("Session created successfully") |
| 249 | return token, None, None |
| 250 | error_msg = "No accessJwt in session response" |
| 251 | _log(error_msg) |
| 252 | return None, error_msg, None |
| 253 | except http.HTTPError as e: |
| 254 | if e.status_code == 403 and e.body and "cloudflare" in e.body.lower(): |
| 255 | error_msg = "Cloudflare blocked the request (403 Forbidden). This is a network-level block, not an auth issue. Try a different network or VPN." |
| 256 | elif e.status_code == 401: |
| 257 | error_msg = "Invalid credentials (401 Unauthorized). Check BSKY_HANDLE and BSKY_APP_PASSWORD." |
| 258 | else: |
| 259 | safe_err = auth_safety.scrub_secrets(str(e), (app_password,)) |
| 260 | error_msg = f"Session request failed: {safe_err}" |
| 261 | _log(f"Session creation failed: {error_msg}") |
| 262 | return None, error_msg, e.status_code |
| 263 | except Exception as e: |
| 264 | safe_err = auth_safety.scrub_secrets(str(e), (app_password,)) |
| 265 | error_msg = f"Session request failed: {type(e).__name__}: {safe_err}" |
| 266 | _log(f"Session creation failed: {error_msg}") |
| 267 | return None, error_msg, None |
| 268 | |
| 269 | |
| 270 | def _execute_refresh_request( |
| 271 | refresh_jwt: Optional[str], |
| 272 | *, |
| 273 | cred_key: Optional[tuple[str, str]] = None, |
| 274 | generation: Optional[int] = None, |
| 275 | ) -> tuple[Optional[str], Optional[str], Optional[int]]: |
| 276 | clean_refresh, token_err = auth_safety.normalize_header_token(refresh_jwt) |
| 277 | if token_err: |
| 278 | error_msg = f"Bluesky session refresh failed: {token_err}" |
| 279 | _log(f"Session refresh failed: {error_msg}") |
| 280 | return None, error_msg, None |
| 281 | if not clean_refresh: |
| 282 | return None, "No Bluesky refresh token is available", None |
| 283 | |
| 284 | try: |
| 285 | response = http.request( |
| 286 | "POST", |
| 287 | BSKY_REFRESH_URL, |
| 288 | headers={"Authorization": f"Bearer {clean_refresh}"}, |
| 289 | timeout=15, |
| 290 | retries=0, |
| 291 | ) |
| 292 | token = response.get("accessJwt") if isinstance(response, dict) else None |
| 293 | if not token: |
| 294 | return None, "No accessJwt in refresh session response", None |
| 295 | new_refresh = response.get("refreshJwt") or clean_refresh |
| 296 | if cred_key is not None: |
| 297 | with _session_lock: |
| 298 | if generation is None or _cache_generation == generation: |
| 299 | _session_cache[cred_key] = _SessionEntry( |
| 300 | access_token=token, |
| 301 | refresh_token=new_refresh, |
| 302 | created_at=time.monotonic(), |
| 303 | ) |
| 304 | return token, None, None |
| 305 | except http.HTTPError as e: |
| 306 | error_msg = ( |
| 307 | "Bluesky refresh token is invalid (401/400)" |
| 308 | if e.status_code in (400, 401) |
| 309 | else f"Bluesky session refresh failed (HTTP {e.status_code})" |
| 310 | ) |
| 311 | _log(f"Session refresh failed: {error_msg}") |
| 312 | return None, error_msg, e.status_code |
| 313 | except Exception as e: |
| 314 | error_msg = f"Bluesky session refresh failed: {type(e).__name__}" |
| 315 | _log(f"Session refresh failed: {error_msg}") |
| 316 | return None, error_msg, None |
| 317 | |
| 318 | |
| 319 | def _create_session( |
| 320 | handle: str, |
| 321 | app_password: str, |
| 322 | *, |
| 323 | force_new: bool = False, |
| 324 | ) -> tuple[Optional[str], Optional[str], Optional[int]]: |
| 325 | """Create or reuse a cached AT Protocol session for ``(handle, app_password)``. |
| 326 | |
| 327 | Shares a unified per-account singleflight slot with 401 recovery so login |
| 328 | and refresh never run concurrently for the same account and concurrent |
| 329 | callers share both success and failure outcomes. |
| 330 | |
| 331 | Returns: |
| 332 | ``(access_token, error_msg, error_status)`` tuple. |
| 333 | """ |
| 334 | cred_key = _credential_key(handle, app_password) |
| 335 | expired_cached = False |
| 336 | with _session_lock: |
| 337 | generation = _cache_generation |
| 338 | existing = _inflight_auth.get(cred_key) |
| 339 | if existing is not None: |
| 340 | inflight = existing |
| 341 | is_leader = False |
| 342 | else: |
| 343 | entry = _session_cache.get(cred_key) |
| 344 | if not force_new and entry is not None: |
| 345 | if time.monotonic() - entry.created_at < _TOKEN_MAX_AGE_SECONDS: |
| 346 | return entry.access_token, None, None |
| 347 | if entry is not None: |
| 348 | expired_cached = not force_new |
| 349 | _session_cache.pop(cred_key, None) |
| 350 | inflight = _InflightAuth(event=threading.Event()) |
| 351 | _inflight_auth[cred_key] = inflight |
| 352 | is_leader = True |
| 353 | |
| 354 | if not is_leader: |
| 355 | _wait_for_inflight_auth(inflight) |
| 356 | return inflight.token, inflight.error_msg, inflight.error_status |
| 357 | |
| 358 | token: Optional[str] = None |
| 359 | error_msg: Optional[str] = "Bluesky session creation failed (unknown error)" |
| 360 | error_status: Optional[int] = None |
| 361 | try: |
| 362 | if expired_cached: |
| 363 | _log("Session token expired, re-authenticating") |
| 364 | token, error_msg, error_status = _execute_create_session_request( |
| 365 | handle, app_password, cred_key, generation, |
| 366 | ) |
| 367 | return token, error_msg, error_status |
| 368 | except BaseException as exc: |
| 369 | token = None |
| 370 | error_msg = f"Session request failed: {type(exc).__name__}" |
| 371 | error_status = None |
| 372 | raise |
| 373 | finally: |
| 374 | inflight.token = token |
| 375 | inflight.error_msg = error_msg |
| 376 | inflight.error_status = error_status |
| 377 | inflight.did_reauth = True |
| 378 | with _session_lock: |
| 379 | if _inflight_auth.get(cred_key) is inflight: |
| 380 | _inflight_auth.pop(cred_key, None) |
| 381 | inflight.event.set() |
| 382 | |
| 383 | |
| 384 | def _refresh_session( |
| 385 | refresh_jwt: Optional[str], |
| 386 | *, |
| 387 | cred_key: Optional[tuple[str, str]] = None, |
| 388 | failed_token: Optional[str] = None, |
| 389 | ) -> tuple[Optional[str], Optional[str], Optional[int]]: |
| 390 | """Refresh an access token using an AT Protocol refresh JWT. |
| 391 | |
| 392 | Returns: |
| 393 | ``(access_token, error_msg, error_status)`` tuple. When ``cred_key`` is |
| 394 | supplied, coordinates via the unified per-account singleflight slot so |
| 395 | refresh never races a concurrent login or another refresh. |
| 396 | """ |
| 397 | if cred_key is None: |
| 398 | return _execute_refresh_request(refresh_jwt, cred_key=None, generation=None) |
| 399 | |
| 400 | with _session_lock: |
| 401 | generation = _cache_generation |
| 402 | entry = _session_cache.get(cred_key) |
| 403 | if ( |
| 404 | failed_token is not None |
| 405 | and entry is not None |
| 406 | and entry.access_token != failed_token |
| 407 | and time.monotonic() - entry.created_at < _TOKEN_MAX_AGE_SECONDS |
| 408 | ): |
| 409 | return entry.access_token, None, None |
| 410 | existing = _inflight_auth.get(cred_key) |
| 411 | if existing is not None: |
| 412 | inflight = existing |
| 413 | is_leader = False |
| 414 | else: |
| 415 | if refresh_jwt is None and entry is not None: |
| 416 | refresh_jwt = entry.refresh_token |
| 417 | inflight = _InflightAuth(event=threading.Event()) |
| 418 | _inflight_auth[cred_key] = inflight |
| 419 | is_leader = True |
| 420 | |
| 421 | if not is_leader: |
| 422 | _wait_for_inflight_auth(inflight) |
| 423 | return inflight.token, inflight.error_msg, inflight.error_status |
| 424 | |
| 425 | token: Optional[str] = None |
| 426 | error_msg: Optional[str] = "Bluesky session refresh failed (unknown error)" |
| 427 | error_status: Optional[int] = None |
| 428 | try: |
| 429 | token, error_msg, error_status = _execute_refresh_request( |
| 430 | refresh_jwt, cred_key=cred_key, generation=generation, |
| 431 | ) |
| 432 | return token, error_msg, error_status |
| 433 | except BaseException as exc: |
| 434 | token = None |
| 435 | error_msg = f"Bluesky session refresh failed: {type(exc).__name__}" |
| 436 | error_status = None |
| 437 | raise |
| 438 | finally: |
| 439 | inflight.token = token |
| 440 | inflight.error_msg = error_msg |
| 441 | inflight.error_status = error_status |
| 442 | inflight.did_reauth = False |
| 443 | with _session_lock: |
| 444 | if _inflight_auth.get(cred_key) is inflight: |
| 445 | _inflight_auth.pop(cred_key, None) |
| 446 | inflight.event.set() |
| 447 | |
| 448 | |
| 449 | def _recover_session( |
| 450 | handle: str, |
| 451 | app_password: str, |
| 452 | cred_key: tuple[str, str], |
| 453 | failed_token: str, |
| 454 | ) -> tuple[Optional[str], Optional[str], bool]: |
| 455 | """Refresh or re-authenticate once after a 401 via the unified auth slot. |
| 456 | |
| 457 | Returns ``(new_token, error_msg, did_reauth)``. Because login and recovery |
| 458 | share ``_inflight_auth[cred_key]``, a slow refresh can never run |
| 459 | concurrently with or overwrite a newer login for the same account. |
| 460 | """ |
| 461 | with _session_lock: |
| 462 | generation = _cache_generation |
| 463 | entry = _session_cache.get(cred_key) |
| 464 | if ( |
| 465 | entry is not None |
| 466 | and entry.access_token != failed_token |
| 467 | and time.monotonic() - entry.created_at < _TOKEN_MAX_AGE_SECONDS |
| 468 | ): |
| 469 | return entry.access_token, None, False |
| 470 | existing = _inflight_auth.get(cred_key) |
| 471 | if existing is not None: |
| 472 | inflight = existing |
| 473 | is_leader = False |
| 474 | else: |
| 475 | inflight = _InflightAuth(event=threading.Event()) |
| 476 | _inflight_auth[cred_key] = inflight |
| 477 | refresh_jwt = entry.refresh_token if entry is not None else None |
| 478 | is_leader = True |
| 479 | |
| 480 | if not is_leader: |
| 481 | _wait_for_inflight_auth(inflight) |
| 482 | if inflight.token and inflight.token != failed_token: |
| 483 | return inflight.token, None, inflight.did_reauth |
| 484 | with _session_lock: |
| 485 | entry = _session_cache.get(cred_key) |
| 486 | if ( |
| 487 | entry is not None |
| 488 | and entry.access_token != failed_token |
| 489 | and time.monotonic() - entry.created_at < _TOKEN_MAX_AGE_SECONDS |
| 490 | ): |
| 491 | return entry.access_token, None, inflight.did_reauth |
| 492 | if inflight.token is not None: |
| 493 | return inflight.token, None, inflight.did_reauth |
| 494 | return ( |
| 495 | None, |
| 496 | inflight.error_msg or "Bluesky session refresh failed (unknown error)", |
| 497 | inflight.did_reauth, |
| 498 | ) |
| 499 | |
| 500 | token: Optional[str] = None |
| 501 | error_msg: Optional[str] = "Bluesky session refresh failed (unknown error)" |
| 502 | error_status: Optional[int] = None |
| 503 | did_reauth = False |
| 504 | try: |
| 505 | _log("Session expired; refreshing access token and retrying once") |
| 506 | if refresh_jwt: |
| 507 | refreshed_token, refresh_error, refresh_status = _execute_refresh_request( |
| 508 | refresh_jwt, cred_key=cred_key, generation=generation, |
| 509 | ) |
| 510 | if refreshed_token: |
| 511 | token, error_msg, error_status, did_reauth = refreshed_token, None, None, False |
| 512 | return token, error_msg, did_reauth |
| 513 | if refresh_status not in (400, 401): |
| 514 | token, error_msg, error_status, did_reauth = None, refresh_error, refresh_status, False |
| 515 | return token, error_msg, did_reauth |
| 516 | |
| 517 | _log("Refresh token missing or rejected; recreating session once") |
| 518 | did_reauth = True |
| 519 | with _session_lock: |
| 520 | if _cache_generation == generation: |
| 521 | _session_cache.pop(cred_key, None) |
| 522 | new_token, create_error, create_status = _execute_create_session_request( |
| 523 | handle, app_password, cred_key, generation, |
| 524 | ) |
| 525 | if not new_token: |
| 526 | token = None |
| 527 | error_msg = create_error or "Bluesky session creation failed (unknown error)" |
| 528 | error_status = create_status |
| 529 | return token, error_msg, did_reauth |
| 530 | token, error_msg, error_status = new_token, None, None |
| 531 | return token, error_msg, did_reauth |
| 532 | except BaseException as exc: |
| 533 | token = None |
| 534 | error_msg = f"Bluesky session refresh failed: {type(exc).__name__}" |
| 535 | error_status = None |
| 536 | raise |
| 537 | finally: |
| 538 | inflight.token = token |
| 539 | inflight.error_msg = error_msg |
| 540 | inflight.error_status = error_status |
| 541 | inflight.did_reauth = did_reauth |
| 542 | with _session_lock: |
| 543 | if _inflight_auth.get(cred_key) is inflight: |
| 544 | _inflight_auth.pop(cred_key, None) |
| 545 | inflight.event.set() |
| 546 | |
| 547 | |
| 548 | def _reset_session_cache() -> None: |
| 549 | global _cache_generation |
| 550 | with _session_lock: |
| 551 | _session_cache.clear() |
| 552 | _inflight_auth.clear() |
| 553 | _cache_generation += 1 |
| 554 | |
| 555 | |
| 556 | def _extract_core_subject(topic: str) -> str: |
| 557 | """Extract core subject from verbose query for Bluesky search.""" |
| 558 | from .query import SOCIAL_NOISE, extract_core_subject |
| 559 | return extract_core_subject(topic, noise=SOCIAL_NOISE) |
| 560 | |
| 561 | |
| 562 | def _parse_date(item: Dict[str, Any]) -> Optional[str]: |
| 563 | """Parse date from Bluesky post to YYYY-MM-DD. |
| 564 | |
| 565 | AT Protocol uses ISO 8601 format in indexedAt and createdAt fields. |
| 566 | """ |
| 567 | for key in ("indexedAt", "createdAt"): |
| 568 | val = item.get(key) |
| 569 | if val and isinstance(val, str): |
| 570 | try: |
| 571 | dt = datetime.fromisoformat(val.replace("Z", "+00:00")) |
| 572 | return dt.strftime("%Y-%m-%d") |
| 573 | except (ValueError, TypeError): |
| 574 | pass |
| 575 | return None |
| 576 | |
| 577 | |
| 578 | def _exclusive_until_date(to_date: str) -> str: |
| 579 | """Convert the inclusive pipeline end date to an RFC3339 exclusive bound.""" |
| 580 | try: |
| 581 | value = datetime.strptime(to_date, "%Y-%m-%d") + timedelta(days=1) |
| 582 | return value.strftime("%Y-%m-%dT00:00:00Z") |
| 583 | except ValueError: |
| 584 | # Keep the request usable for callers that pass a provider-specific date value. |
| 585 | return to_date |
| 586 | |
| 587 | |
| 588 | def _inclusive_since_date(from_date: str) -> str: |
| 589 | """Convert the inclusive pipeline start date to an RFC3339 lower bound.""" |
| 590 | try: |
| 591 | return datetime.strptime(from_date, "%Y-%m-%d").strftime("%Y-%m-%dT00:00:00Z") |
| 592 | except ValueError: |
| 593 | # Keep the request usable for callers that pass a provider-specific date value. |
| 594 | return from_date |
| 595 | |
| 596 | |
| 597 | def search_bluesky( |
| 598 | topic: str, |
| 599 | from_date: str, |
| 600 | to_date: str, |
| 601 | depth: str = "default", |
| 602 | config: Optional[Dict[str, Any]] = None, |
| 603 | ) -> Dict[str, Any]: |
| 604 | """Search Bluesky via AT Protocol API. |
| 605 | |
| 606 | Args: |
| 607 | topic: Search topic |
| 608 | from_date: Start date (YYYY-MM-DD) |
| 609 | to_date: End date (YYYY-MM-DD) |
| 610 | depth: 'quick', 'default', or 'deep' |
| 611 | config: Config dict with BSKY_HANDLE and BSKY_APP_PASSWORD |
| 612 | |
| 613 | Returns: |
| 614 | Dict with 'posts' list from AT Protocol response. |
| 615 | """ |
| 616 | config = config or {} |
| 617 | handle = config.get("BSKY_HANDLE", "") |
| 618 | app_password = config.get("BSKY_APP_PASSWORD", "") |
| 619 | |
| 620 | if not handle or not app_password: |
| 621 | return {"posts": [], "error": "Bluesky credentials not configured"} |
| 622 | |
| 623 | # One-shot hygiene warning if BSKY_APP_PASSWORD is not in app-password |
| 624 | # form. createSession accepts main-account passwords too — but main |
| 625 | # passwords have no scope (full account access), can't be revoked |
| 626 | # individually, and rotating them breaks every service that holds them. |
| 627 | # We warn but do not gate, matching the project's detect-don't-block |
| 628 | # philosophy elsewhere. |
| 629 | if not _validate_app_password_format(app_password): |
| 630 | _log( |
| 631 | "BSKY_APP_PASSWORD does not look like an app password " |
| 632 | "(expected xxxx-xxxx-xxxx-xxxx, 19 chars). It may be a main " |
| 633 | "account password — those work but are bad hygiene. Generate " |
| 634 | "an app password at https://bsky.app/settings/app-passwords" |
| 635 | ) |
| 636 | |
| 637 | count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"]) |
| 638 | core_topic = _extract_core_subject(topic) |
| 639 | |
| 640 | _log(f"Searching for '{core_topic}' (depth={depth}, limit={count})") |
| 641 | |
| 642 | params = { |
| 643 | "q": core_topic, |
| 644 | "limit": str(min(count, 100)), |
| 645 | "sort": "top", |
| 646 | "since": _inclusive_since_date(from_date), |
| 647 | "until": _exclusive_until_date(to_date), |
| 648 | } |
| 649 | search_base_url = _resolve_search_url(config) |
| 650 | search_host = (urlsplit(search_base_url).hostname or _DEFAULT_BSKY_SEARCH_HOST).lower() |
| 651 | trusted_host = _is_trusted_bsky_host(search_host) |
| 652 | redirect_guard = _bsky_search_redirect_guard(search_host) |
| 653 | url = f"{search_base_url}?{urlencode(params)}" |
| 654 | |
| 655 | def _search_with_token(token: Optional[str]) -> tuple[Optional[Dict[str, Any]], Optional[str]]: |
| 656 | req_kwargs: Dict[str, Any] = { |
| 657 | "timeout": 30, |
| 658 | "redirect_guard": redirect_guard, |
| 659 | } |
| 660 | clean_token: Optional[str] = None |
| 661 | if token is not None: |
| 662 | clean_token, token_err = auth_safety.normalize_header_token(token) |
| 663 | if token_err or not clean_token: |
| 664 | err_msg = token_err or "Invalid token format" |
| 665 | _log(f"Search failed: {err_msg}") |
| 666 | return None, f"Bluesky search failed: {err_msg}" |
| 667 | req_kwargs["headers"] = {"Authorization": f"Bearer {clean_token}"} |
| 668 | if not trusted_host: |
| 669 | req_kwargs["public_only"] = True |
| 670 | try: |
| 671 | response = http.request("GET", url, **req_kwargs) |
| 672 | return response, None |
| 673 | except http.HTTPError as e: |
| 674 | safe_err = auth_safety.scrub_secrets(str(e), (token, clean_token, app_password)) |
| 675 | _log(f"Search failed: {safe_err}") |
| 676 | if e.status_code == 401: |
| 677 | if token is None: |
| 678 | return None, ( |
| 679 | f"Bluesky search host {search_host!r} rejected unauthenticated search (401); " |
| 680 | "bsky.social Bearer tokens are only sent to *.bsky.app / *.bsky.social hosts" |
| 681 | ) |
| 682 | return None, "refresh" |
| 683 | if e.status_code == 403 and e.body and "cloudflare" in e.body.lower(): |
| 684 | return None, "Bluesky search blocked by Cloudflare (403). This is a network-level block - try a different network or VPN." |
| 685 | return None, f"Bluesky search failed: {safe_err}" |
| 686 | except Exception as e: |
| 687 | safe_err = auth_safety.scrub_secrets(str(e), (token, clean_token, app_password)) |
| 688 | _log(f"Search failed: {type(e).__name__}: {safe_err}") |
| 689 | return None, f"Bluesky search failed: {type(e).__name__}: {safe_err}" |
| 690 | |
| 691 | used_token: Optional[str] = None |
| 692 | if not trusted_host: |
| 693 | # Never exfiltrate a live bsky.social session JWT to an arbitrary third-party host. |
| 694 | _log(f"Withholding bsky.social Bearer token from non-Bluesky search host {search_host!r}") |
| 695 | response, error_msg = _search_with_token(None) |
| 696 | else: |
| 697 | token, create_err, _create_status = _create_session(handle, app_password) |
| 698 | if not token: |
| 699 | response, error_msg = None, create_err or "Bluesky session creation failed (unknown error)" |
| 700 | else: |
| 701 | used_token = token |
| 702 | response, error_msg = _search_with_token(token) |
| 703 | |
| 704 | if error_msg == "refresh" and used_token is not None: |
| 705 | cred_key = _credential_key(handle, app_password) |
| 706 | recovered_token, recover_err, did_reauth = _recover_session( |
| 707 | handle, app_password, cred_key, used_token, |
| 708 | ) |
| 709 | if recovered_token: |
| 710 | response, error_msg = _search_with_token(recovered_token) |
| 711 | if error_msg == "refresh": |
| 712 | _evict_session(cred_key, expected_token=recovered_token) |
| 713 | if did_reauth: |
| 714 | error_msg = ( |
| 715 | "Bluesky session remained unauthorized after refresh and re-authentication; " |
| 716 | "check credentials or app password" |
| 717 | ) |
| 718 | else: |
| 719 | error_msg = ( |
| 720 | "Bluesky session remained unauthorized after token refresh; " |
| 721 | "check credentials or app password" |
| 722 | ) |
| 723 | else: |
| 724 | response, error_msg = None, recover_err or "Bluesky session refresh failed (unknown error)" |
| 725 | if error_msg: |
| 726 | return {"posts": [], "error": error_msg} |
| 727 | if response is None: |
| 728 | return {"posts": [], "error": "Bluesky search failed (unknown error)"} |
| 729 | |
| 730 | posts = response.get("posts", []) |
| 731 | _log(f"Found {len(posts)} posts") |
| 732 | return response |
| 733 | |
| 734 | |
| 735 | def parse_bluesky_response(response: Dict[str, Any]) -> List[Dict[str, Any]]: |
| 736 | """Parse AT Protocol response into normalized item dicts. |
| 737 | |
| 738 | Returns: |
| 739 | List of item dicts ready for normalization. |
| 740 | """ |
| 741 | posts = response.get("posts", []) |
| 742 | items = [] |
| 743 | |
| 744 | for i, post in enumerate(posts): |
| 745 | record = post.get("record") or {} |
| 746 | text = record.get("text") or "" |
| 747 | |
| 748 | author = post.get("author") or {} |
| 749 | handle = author.get("handle") or "" |
| 750 | display_name = author.get("displayName") or handle |
| 751 | |
| 752 | # Post URI -> URL |
| 753 | # URI format: at://did:plc:xxx/app.bsky.feed.post/rkey |
| 754 | uri = post.get("uri") or "" |
| 755 | rkey = uri.rsplit("/", 1)[-1] if uri else "" |
| 756 | url = f"https://bsky.app/profile/{handle}/post/{rkey}" if handle and rkey else "" |
| 757 | |
| 758 | likes = post.get("likeCount") or 0 |
| 759 | reposts = post.get("repostCount") or 0 |
| 760 | replies = post.get("replyCount") or 0 |
| 761 | quotes = post.get("quoteCount") or 0 |
| 762 | |
| 763 | date_str = _parse_date(post) or _parse_date(record) |
| 764 | |
| 765 | # Relevance: position-based (AT Protocol sorts by relevance with sort=top) |
| 766 | rank_score = max(0.3, 1.0 - (i * 0.02)) |
| 767 | engagement_boost = min(0.2, math.log1p(likes + reposts) / 40) |
| 768 | relevance = min(1.0, rank_score * 0.7 + engagement_boost + 0.1) |
| 769 | |
| 770 | items.append({ |
| 771 | "handle": handle, |
| 772 | "display_name": display_name, |
| 773 | "text": text, |
| 774 | "url": url, |
| 775 | "date": date_str, |
| 776 | "engagement": { |
| 777 | "likes": likes, |
| 778 | "reposts": reposts, |
| 779 | "replies": replies, |
| 780 | "quotes": quotes, |
| 781 | }, |
| 782 | "relevance": round(relevance, 2), |
| 783 | "why_relevant": f"Bluesky: @{handle}: {text[:60]}" if text else f"Bluesky: {handle}", |
| 784 | }) |
| 785 | |
| 786 | return items |
| 787 |