Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(cli): repowise login, logout, and whoami (#690)
Raghav Chamadiya81d4a86b9312
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd.py b/packages/cli/src/repowise/cli/commands/doctor_cmd.pyindex b48d5e9ea..ec50b62a5 100644--- a/packages/cli/src/repowise/cli/commands/doctor_cmd.py+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd.py@@ -254,6 +254,29 @@ def _run_repo_checks(config_detail = "All required API keys configured" if config_ok else "; ".join(config_warnings)checks.append(_check("Provider config", config_ok, config_detail))+ # 6b. Hosted account (informational: signed out is not a failure).+ try:+ from repowise.cli.platform import auth, credentials++ creds = credentials.load()+ if creds is None:+ checks.append(+ _check("Hosted account", True, "Not signed in (optional: repowise login)")+ )+ elif creds.get("stale"):+ checks.append(+ _check("Hosted account", False, "Session expired or revoked; run repowise login")+ )+ else:+ account = auth.fetch_account()+ cached = (account or creds.get("account") or {}) or {}+ who = cached.get("github_username") or cached.get("email") or "unknown"+ tier = cached.get("tier") or "free"+ suffix = "" if account else " (offline, using cached identity)"+ checks.append(_check("Hosted account", True, f"{who} ({tier}){suffix}"))+ except Exception as e:+ checks.append(_check("Hosted account", False, str(e)))+# 7. Stale page countstale_count = 0if db_ok and page_count > 0:diff --git a/packages/cli/src/repowise/cli/commands/login_cmd.py b/packages/cli/src/repowise/cli/commands/login_cmd.pynew file mode 100644index 000000000..5529dfa1b--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/login_cmd.py@@ -0,0 +1,282 @@+"""``repowise login`` / ``logout`` / ``whoami`` — hosted-account sign-in.++Sign-in is browser-based OAuth with PKCE: the command binds an ephemeral+loopback port, opens the hosted consent page, and exchanges the returned+code for tokens stored at ``~/.repowise/credentials.json``. For headless+machines, ``repowise login --with-token`` accepts a personal API key minted+in the hosted dashboard instead.++Signing in is always optional: every local feature works without it. A+login adds the hosted layer (your indexed repos on repowise.dev, reindex+from local tools, account status in doctor).+"""++from __future__ import annotations++import contextlib+import platform as _platform+import secrets+import sys+import threading+import webbrowser+from http.server import BaseHTTPRequestHandler, HTTPServer+from urllib.parse import parse_qs, urlparse++import click++from repowise.cli.helpers import console++#: How long the command waits for the user to finish the browser consent.+_CALLBACK_TIMEOUT_SECONDS = 300++_SUCCESS_HTML = """<!doctype html>+<html><head><title>Repowise</title></head>+<body style="font-family: system-ui, sans-serif; display: flex; align-items: center;+ justify-content: center; height: 90vh; color: #333;">+ <div style="text-align: center;">+ <h2>You're signed in</h2>+ <p>Return to your terminal to continue.</p>+ </div>+</body></html>"""++_DENIED_HTML = _SUCCESS_HTML.replace("You're signed in", "Sign-in was cancelled").replace(+ "Return to your terminal to continue.", "You can close this tab."+)+++class _CallbackResult:+ def __init__(self) -> None:+ self.code: str | None = None+ self.state: str | None = None+ self.error: str | None = None+ self.received = threading.Event()+++def _make_handler(result: _CallbackResult) -> type[BaseHTTPRequestHandler]:+ class Handler(BaseHTTPRequestHandler):+ def do_GET(self) -> None: # http.server callback API name+ parsed = urlparse(self.path)+ if parsed.path != "/callback":+ self.send_response(404)+ self.end_headers()+ return+ params = parse_qs(parsed.query)+ result.code = (params.get("code") or [None])[0]+ result.state = (params.get("state") or [None])[0]+ result.error = (params.get("error") or [None])[0]+ body = _DENIED_HTML if result.error else _SUCCESS_HTML+ payload = body.encode("utf-8")+ self.send_response(200)+ self.send_header("Content-Type", "text/html; charset=utf-8")+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+ result.received.set()++ def log_message(self, *args: object) -> None: # silence stdlib logging+ pass++ return Handler+++def _wait_for_callback(server: HTTPServer, result: _CallbackResult) -> None:+ """Serve requests until the /callback hit lands or the deadline passes."""+ server.timeout = 1.0+ import time++ deadline = time.time() + _CALLBACK_TIMEOUT_SECONDS+ while not result.received.is_set() and time.time() < deadline:+ server.handle_request()+++def _default_device_name() -> str | None:+ with contextlib.suppress(Exception):+ return _platform.node()[:80] or None+ return None+++def _greet(account: dict) -> None:+ name = account.get("github_username") or account.get("email") or "there"+ tier = account.get("tier") or "free"+ console.print(f"[green]✓[/green] Signed in as [bold]{name}[/bold] ({tier} plan)")+ credits_cents = account.get("llm_credit_balance_cents")+ if isinstance(credits_cents, int) and credits_cents > 0:+ console.print(f" Credits: ${credits_cents / 100:.2f}")+++def _link_anonymous_id() -> None:+ """Best-effort: stitch this machine's pre-login telemetry id to the account."""+ with contextlib.suppress(Exception):+ from repowise.cli.platform import identity+ from repowise.cli.platform.client import default_client++ default_client.post("auth/link-anon", {"anon_id": identity.get_anonymous_id()})++[email protected](name="login")+ "--with-token",+ is_flag=True,+ help="Paste a personal API key (rw_live_...) instead of using the browser. "+ "Reads from stdin when piped, otherwise prompts. For SSH/headless machines.",+)+ "--device-name",+ default=None,+ help="Label this machine in your connected apps (default: hostname).",+)+def login_command(with_token: bool, device_name: str | None) -> None:+ """Sign in to your Repowise account."""+ from repowise.cli.platform import auth, credentials++ existing = credentials.load()+ if existing and not existing.get("stale"):+ account = existing.get("account") or {}+ who = account.get("github_username") or "an account"+ console.print(+ f"Already signed in as [bold]{who}[/bold]. "+ "Run [cyan]repowise logout[/cyan] first to switch accounts."+ )+ return++ device = (device_name or _default_device_name() or "").strip()[:80] or None++ if with_token:+ token = (+ sys.stdin.readline().strip()+ if not sys.stdin.isatty()+ else click.prompt("Personal API key", hide_input=True).strip()+ )+ if not token.startswith("rw_live_"):+ raise click.ClickException(+ "That doesn't look like a Repowise API key (expected rw_live_...). "+ "Create one at repowise.dev under Settings > Editor (MCP)."+ )+ credentials.save({"token_kind": "api_key", "access_token": token, "device_name": device})+ account = auth.fetch_account()+ if account is None:+ credentials.delete()+ raise click.ClickException(+ "The key was rejected by the platform. Check it and try again."+ )+ auth.store_account_snapshot(account)+ _link_anonymous_id()+ _greet(account)+ return++ # Browser PKCE flow.+ verifier, challenge = auth.make_pkce_pair()+ state = secrets.token_urlsafe(16)+ result = _CallbackResult()+ try:+ server = HTTPServer(("127.0.0.1", 0), _make_handler(result))+ except OSError as exc:+ raise click.ClickException(+ f"Could not open a local port for the sign-in callback ({exc}). "+ "Use repowise login --with-token instead."+ ) from exc++ try:+ redirect_uri = f"http://127.0.0.1:{server.server_address[1]}/callback"+ url = auth.build_authorize_url(+ redirect_uri=redirect_uri,+ code_challenge=challenge,+ state=state,+ device_name=device,+ )+ console.print("Opening your browser to sign in to Repowise...")+ console.print(f"If it doesn't open, visit:\n [cyan]{url}[/cyan]\n")+ webbrowser.open(url)+ _wait_for_callback(server, result)+ finally:+ server.server_close()++ if not result.received.is_set():+ raise click.ClickException(+ "Timed out waiting for the browser sign-in. "+ "Try again, or use repowise login --with-token on this machine."+ )+ if result.error:+ raise click.ClickException(+ "Sign-in was cancelled in the browser."+ if result.error == "access_denied"+ else f"Sign-in failed: {result.error}"+ )+ if result.state != state or not result.code:+ raise click.ClickException("Sign-in response didn't match this login attempt. Try again.")++ body, error = auth.exchange_code(+ code=result.code, redirect_uri=redirect_uri, code_verifier=verifier+ )+ if body is None:+ raise click.ClickException(error or "Token exchange failed.")++ credentials.save(auth.credentials_from_token_response(body, device_name=device))+ account = auth.fetch_account()+ if account:+ auth.store_account_snapshot(account)+ _link_anonymous_id()+ _greet(account or {})++[email protected](name="logout")+def logout_command() -> None:+ """Sign out of your Repowise account on this machine."""+ from repowise.cli.platform import auth, credentials++ creds = credentials.load()+ if creds is None:+ console.print("Not signed in.")+ return++ # Best-effort server-side revocation of this device's grant; the local+ # delete is the part that must succeed.+ if creds.get("token_kind") == "oauth":+ with contextlib.suppress(Exception):+ from repowise.cli.platform.client import default_client++ params = {}+ if creds.get("device_name"):+ params["device_name"] = creds["device_name"]+ default_client.delete(+ f"oauth/connections/{creds.get('client_id') or auth.CLIENT_ID}",+ params=params or None,+ )+ credentials.delete()+ console.print("[green]✓[/green] Signed out. Local features are unaffected.")++[email protected](name="whoami")+def whoami_command() -> None:+ """Show the Repowise account this machine is signed in to."""+ from repowise.cli.platform import auth, credentials++ creds = credentials.load()+ if creds is None:+ console.print("Not signed in. Run [cyan]repowise login[/cyan] to connect your account.")+ return++ account = auth.fetch_account()+ if account:+ auth.store_account_snapshot(account)+ _greet(account)+ else:+ cached = creds.get("account") or {}+ who = cached.get("github_username") or cached.get("email") or "unknown account"+ if creds.get("stale"):+ console.print(+ f"Signed in as [bold]{who}[/bold], but the session has expired or was "+ "revoked. Run [cyan]repowise login[/cyan] to sign in again."+ )+ else:+ console.print(+ f"Signed in as [bold]{who}[/bold] (couldn't reach the platform to verify)."+ )+ return++ kind = "API key" if creds.get("token_kind") == "api_key" else "browser sign-in"+ device = creds.get("device_name")+ detail = f" Auth: {kind}"+ if device:+ detail += f" on {device}"+ console.print(detail)diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex 4168b6fed..ba3e70fc3 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -21,6 +21,7 @@ from repowise.cli.commands.export_cmd import export_commandfrom repowise.cli.commands.health_cmd import health_commandfrom repowise.cli.commands.hook_cmd import hook_groupfrom repowise.cli.commands.init_cmd import init_command+from repowise.cli.commands.login_cmd import login_command, logout_command, whoami_commandfrom repowise.cli.commands.mcp_cmd import mcp_commandfrom repowise.cli.commands.reindex_cmd import reindex_commandfrom repowise.cli.commands.restyle_cmd import restyle_command, wiki_styles_command@@ -87,6 +88,9 @@ register_command(restyle_command)register_command(wiki_styles_command)register_command(whats_new_command)register_command(telemetry_command)+register_command(login_command)+register_command(logout_command)+register_command(whoami_command)register_command(workspace_group)cli_registry.apply(cli)diff --git a/packages/cli/src/repowise/cli/platform/auth.py b/packages/cli/src/repowise/cli/platform/auth.pynew file mode 100644index 000000000..96b359ca5--- /dev/null+++ b/packages/cli/src/repowise/cli/platform/auth.py@@ -0,0 +1,204 @@+"""Hosted-account auth: PKCE sign-in, token refresh, and header assembly.++The browser flow (``repowise login``) is OAuth 2.1 authorization-code with+PKCE against the hosted platform: the CLI binds an ephemeral loopback port,+opens the consent page in the browser, exchanges the returned code, and+persists the token pair via :mod:`repowise.cli.platform.credentials`.++:func:`auth_headers` is the fail-soft read side consumed by+``PlatformClient._auth_headers``: it transparently refreshes an expired+access token (single-flight across processes) and returns ``{}`` whenever+the user is signed out, offline, or the grant was revoked — a platform call+then simply proceeds anonymously.+"""++from __future__ import annotations++import base64+import hashlib+import secrets+import time+from typing import Any++from repowise.cli.platform import credentials++#: First-party public client (PKCE only, no secret) registered on the hosted+#: authorization server for the CLI.+CLIENT_ID = "repowise-cli"++#: Front-channel consent page (hosted frontend). Production only, matching+#: the PlatformClient design rule.+AUTHORIZE_URL = "https://repowise.dev/oauth/authorize"++#: Scopes the CLI asks for: read everything, plus the write actions the+#: product exposes to signed-in tooling (reindex, docs generation).+SCOPES = "read write"+++def make_pkce_pair() -> tuple[str, str]:+ """Return ``(code_verifier, code_challenge)`` for S256 PKCE."""+ verifier = secrets.token_urlsafe(64)+ digest = hashlib.sha256(verifier.encode("ascii")).digest()+ challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")+ return verifier, challenge+++def build_authorize_url(+ *,+ redirect_uri: str,+ code_challenge: str,+ state: str,+ device_name: str | None,+) -> str:+ from urllib.parse import urlencode++ params = {+ "client_id": CLIENT_ID,+ "redirect_uri": redirect_uri,+ "response_type": "code",+ "scope": SCOPES,+ "state": state,+ "code_challenge": code_challenge,+ "code_challenge_method": "S256",+ }+ if device_name:+ params["device_name"] = device_name+ return f"{AUTHORIZE_URL}?{urlencode(params)}"+++def _token_request(form: dict[str, str]) -> tuple[int, dict[str, Any]]:+ from repowise.cli.platform.client import default_client++ return default_client.post_form("oauth/token", form, timeout=15.0)+++def exchange_code(+ *, code: str, redirect_uri: str, code_verifier: str+) -> tuple[dict[str, Any] | None, str | None]:+ """Exchange an authorization code for tokens.++ Returns ``(token_response, None)`` on success or ``(None, error_message)``+ on failure — login is interactive, so errors surface instead of being+ swallowed.+ """+ status, body = _token_request(+ {+ "grant_type": "authorization_code",+ "code": code,+ "redirect_uri": redirect_uri,+ "code_verifier": code_verifier,+ "client_id": CLIENT_ID,+ }+ )+ if status == 200 and body.get("access_token"):+ return body, None+ detail = body.get("error_description") or body.get("error") or f"HTTP {status or 'error'}"+ return None, f"Token exchange failed: {detail}"+++def credentials_from_token_response(+ body: dict[str, Any], *, device_name: str | None+) -> dict[str, Any]:+ return {+ "token_kind": "oauth",+ "client_id": CLIENT_ID,+ "access_token": body["access_token"],+ "access_expires_at": int(time.time()) + int(body.get("expires_in") or 3600),+ "refresh_token": body.get("refresh_token"),+ "scope": body.get("scope"),+ "device_name": device_name,+ }+++def _refresh(creds: dict[str, Any]) -> dict[str, Any] | None:+ """Rotate the refresh token; persist and return the new credentials.++ On ``invalid_grant`` (revoked/expired server-side) the stored credentials+ are marked stale so subsequent calls stay anonymous instead of retrying+ the dead token on every command. On network failure nothing is written —+ the next call retries.+ """+ refresh_token = creds.get("refresh_token")+ if not refresh_token:+ credentials.mark_stale()+ return None+ status, body = _token_request(+ {+ "grant_type": "refresh_token",+ "refresh_token": refresh_token,+ "client_id": creds.get("client_id") or CLIENT_ID,+ }+ )+ if status == 200 and body.get("access_token"):+ updated = dict(creds)+ updated.update(credentials_from_token_response(body, device_name=creds.get("device_name")))+ updated.pop("stale", None)+ # Preserve the account snapshot for whoami/doctor.+ credentials.save(updated)+ return updated+ if status == 400:+ credentials.mark_stale()+ return None+++def get_valid_credentials() -> dict[str, Any] | None:+ """Return usable credentials, refreshing if needed. ``None`` = signed out.++ Refresh is single-flight across processes: rotation revokes the presented+ token, so a concurrent loser re-reads what the winner persisted.+ """+ creds = credentials.load()+ if creds is None or creds.get("stale"):+ return None+ if not credentials.is_access_expired(creds):+ return creds+ with credentials.refresh_lock() as acquired:+ # Re-read either way: while we waited (or held the lock), another+ # process may have completed the rotation.+ latest = credentials.load()+ if latest is None or latest.get("stale"):+ return None+ if not credentials.is_access_expired(latest):+ return latest+ if not acquired:+ return None+ return _refresh(latest)+++def auth_headers() -> dict[str, str]:+ """Bearer header for platform calls, or ``{}`` when signed out.++ Never raises: any failure (corrupt store, offline refresh, revoked grant)+ degrades to anonymous, matching the PlatformClient fail-silent contract.+ """+ try:+ creds = get_valid_credentials()+ except Exception:+ return {}+ if creds is None:+ return {}+ return {"Authorization": f"Bearer {creds['access_token']}"}+++def fetch_account() -> dict[str, Any] | None:+ """GET /auth/me with the stored credentials. ``None`` when signed out or+ unreachable."""+ if not auth_headers():+ return None+ from repowise.cli.platform.client import default_client++ return default_client.get("auth/me", timeout=5.0)+++def store_account_snapshot(account: dict[str, Any]) -> None:+ """Cache the identity fields whoami/doctor show when offline."""+ creds = credentials.load()+ if creds is None:+ return+ creds["account"] = {+ "id": account.get("id"),+ "github_username": account.get("github_username"),+ "email": account.get("email"),+ "tier": account.get("tier"),+ }+ credentials.save(creds)diff --git a/packages/cli/src/repowise/cli/platform/client.py b/packages/cli/src/repowise/cli/platform/client.pyindex 9f8144a26..c31e033d4 100644--- a/packages/cli/src/repowise/cli/platform/client.py+++ b/packages/cli/src/repowise/cli/platform/client.py@@ -1,10 +1,11 @@"""Central client for the Repowise hosted platform (``api.repowise.dev``).-This is the single seam between the OSS CLI and the hosted product. Today its-only consumer is anonymous telemetry; tomorrow it will carry authenticated-calls (login, account, cross-machine sync). Keeping *all* hosted connectivity-here means a new hosted feature adds a method, not another ad-hoc ``httpx``-call scattered across the CLI.+This is the single seam between the OSS CLI and the hosted product. It+carries anonymous telemetry and, once a user runs ``repowise login``, the+authenticated account calls (whoami, OAuth token exchange, connection+management). Keeping *all* hosted connectivity here means a new hosted+feature adds a method, not another ad-hoc ``httpx`` call scattered across+the CLI.Design rules:@@ -13,9 +14,9 @@ Design rules:shipped CLI always talks to ``https://api.repowise.dev``.* **Fail-silent.** The OSS CLI must work fully offline, so every methodswallows network/parse errors and returns a sentinel instead of raising.-* **Auth-ready.** :meth:`PlatformClient._auth_headers` is the one place a future- bearer token gets attached, so every platform call becomes authenticated at- once when login lands.+* **One auth seam.** :meth:`PlatformClient._auth_headers` is the one place the+ ``repowise login`` bearer token gets attached, so every platform call is+ authenticated uniformly (and stays anonymous when signed out)."""from __future__ import annotations@@ -60,12 +61,17 @@ class PlatformClient:def _auth_headers(self) -> dict[str, str]:"""Return auth headers for an authenticated platform call.- Empty today: the OSS CLI makes only anonymous calls. When the pip- package gains login this reads the stored bearer token from the- credential store, and every platform call is authenticated uniformly- without touching individual call sites.+ Reads the stored login (``repowise login``) via the auth module,+ which transparently refreshes an expired access token. Signed-out,+ offline, or revoked all degrade to ``{}`` — the call proceeds+ anonymously. Lazy import: most commands never touch credentials."""- return {}+ try:+ from repowise.cli.platform import auth++ return auth.auth_headers()+ except Exception:+ return {}def _headers(self, extra: dict[str, str] | None = None) -> dict[str, str]:headers = {@@ -103,6 +109,63 @@ class PlatformClient:# Network, JSON, HTTP-status — all advisory. The CLI works offline.return False+ def post_form(+ self,+ path: str,+ form: dict[str, str],+ *,+ timeout: float | None = None,+ ) -> tuple[int, dict[str, Any]]:+ """POST form-encoded data and return ``(status_code, parsed_body)``.++ For OAuth endpoints (RFC 6749 wants form encoding and meaningful+ error bodies), so unlike :meth:`post` this surfaces the status and+ body instead of collapsing to a bool. Deliberately anonymous: the+ token endpoint authenticates by grant, and attaching+ :meth:`_auth_headers` here would recurse through token refresh.+ Network failures return ``(0, {})``.+ """+ url = f"{self.base_url}/{path.lstrip('/')}"+ try:+ import httpx++ resp = httpx.post(+ url,+ data=form,+ headers={"User-Agent": _user_agent()},+ timeout=timeout or self.timeout,+ )+ try:+ body = resp.json()+ except Exception:+ body = {}+ return resp.status_code, body if isinstance(body, dict) else {}+ except Exception:+ return 0, {}++ def delete(+ self,+ path: str,+ *,+ params: dict[str, Any] | None = None,+ timeout: float | None = None,+ ) -> bool:+ """DELETE ``path``. Returns success, never raises."""+ url = f"{self.base_url}/{path.lstrip('/')}"+ try:+ import httpx++ resp = httpx.delete(+ url,+ params=params,+ headers=self._headers(),+ timeout=timeout or self.timeout,+ )+ resp.raise_for_status()+ return True+ except Exception:+ return False+def get(self,path: str,diff --git a/packages/cli/src/repowise/cli/platform/credentials.py b/packages/cli/src/repowise/cli/platform/credentials.pynew file mode 100644index 000000000..314ab131e--- /dev/null+++ b/packages/cli/src/repowise/cli/platform/credentials.py@@ -0,0 +1,138 @@+"""Hosted-account credential storage (``~/.repowise/credentials.json``).++Holds the tokens ``repowise login`` obtains, kept separate from+``platform.json`` (anonymous state) so secrets live in exactly one file with+owner-only permissions. Two token kinds:++* ``oauth`` — short-lived access token + rotating refresh token from the+ hosted authorization server (the browser sign-in path).+* ``api_key`` — a long-lived ``rw_live_…`` key the user pasted (the+ headless/SSH fallback). No expiry, no refresh.++Reads tolerate a missing or corrupt file (returning ``None``); writes create+the file with ``0600`` (best effort on Windows, where the user-profile ACL is+the effective guard). Refresh rotation is serialized across processes via a+sibling lock file — see :func:`refresh_lock`.+"""++from __future__ import annotations++import contextlib+import json+import os+import time+from collections.abc import Iterator+from pathlib import Path+from typing import Any++CREDENTIALS_FILENAME = "credentials.json"+_LOCK_FILENAME = "credentials.lock"++#: Refresh this many seconds before the recorded expiry to absorb clock skew+#: and request latency.+EXPIRY_SKEW_SECONDS = 60++#: A lock file older than this is a crashed process, not a live refresh.+_LOCK_STALE_SECONDS = 30+++def _path() -> Path:+ from repowise.cli.helpers import user_global_dir++ return user_global_dir() / CREDENTIALS_FILENAME+++def load() -> dict[str, Any] | None:+ """Return stored credentials, or ``None`` if absent/corrupt."""+ try:+ data = json.loads(_path().read_text(encoding="utf-8"))+ except Exception:+ return None+ return data if isinstance(data, dict) and data.get("access_token") else None+++def save(creds: dict[str, Any]) -> None:+ """Persist credentials with owner-only permissions.++ Written via ``os.open`` with mode ``0600`` so the file is never observable+ with wider permissions, then ``chmod`` for the pre-existing-file case.+ """+ path = _path()+ payload = json.dumps(creds, indent=2)+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ try:+ os.write(fd, payload.encode("utf-8"))+ finally:+ os.close(fd)+ with contextlib.suppress(OSError):+ os.chmod(path, 0o600)+++def delete() -> None:+ with contextlib.suppress(OSError):+ _path().unlink()+++def is_access_expired(creds: dict[str, Any]) -> bool:+ """Whether the access token needs a refresh before use.++ API-key credentials never expire. OAuth credentials with no recorded+ expiry are treated as expired (refresh resolves the truth).+ """+ if creds.get("token_kind") == "api_key":+ return False+ expires_at = creds.get("access_expires_at")+ if not isinstance(expires_at, (int, float)):+ return True+ return time.time() >= expires_at - EXPIRY_SKEW_SECONDS+++def mark_stale() -> None:+ """Flag credentials as no longer refreshable (revoked/expired server-side).++ Keeps the account snapshot so ``whoami`` can explain the state, but+ :func:`load`-ing callers should treat ``stale`` as signed out.+ """+ creds = load()+ if creds is not None:+ creds["stale"] = True+ with contextlib.suppress(OSError):+ save(creds)+++def refresh_lock(timeout: float = 10.0) -> Iterator[bool]:+ """Cross-process single-flight lock for token refresh.++ Two parallel CLI invocations must not both rotate the same refresh token+ (the server revokes the presented token on rotation, so the loser would+ sign the machine out). Yields ``True`` when the lock was acquired;+ ``False`` on timeout — the caller should then re-read credentials, since+ the holder probably refreshed them already.+ """+ lock_path = _path().with_name(_LOCK_FILENAME)+ deadline = time.time() + timeout+ acquired = False+ while True:+ try:+ fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)+ os.close(fd)+ acquired = True+ break+ except FileExistsError:+ with contextlib.suppress(OSError):+ if time.time() - lock_path.stat().st_mtime > _LOCK_STALE_SECONDS:+ lock_path.unlink()+ continue+ if time.time() >= deadline:+ break+ time.sleep(0.1)+ except OSError:+ # Unwritable global dir — proceed unlocked rather than fail.+ break+ try:+ yield acquired+ finally:+ if acquired:+ with contextlib.suppress(OSError):+ lock_path.unlink()diff --git a/tests/unit/cli/test_login.py b/tests/unit/cli/test_login.pynew file mode 100644index 000000000..72642e6ce--- /dev/null+++ b/tests/unit/cli/test_login.py@@ -0,0 +1,274 @@+"""Tests for hosted-account sign-in (credentials store + auth module + CLI).++Covers what protects the user: owner-only credential file permissions,+fail-soft anonymous degradation everywhere (signed out, offline, revoked),+single-flight refresh so parallel commands can't revoke each other's rotated+token, and the PKCE values matching the S256 spec.+"""++from __future__ import annotations++import base64+import hashlib+import os+import stat+import sys+import time+from pathlib import Path++import pytest+from click.testing import CliRunner++from repowise.cli.platform import auth, credentials, store+from repowise.cli.platform.client import PlatformClient++[email protected](autouse=True)+def isolated_credentials(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ """Point the credential + platform stores at a temp dir; never touch real+ ~/.repowise (login also reads the anon id from platform.json)."""+ monkeypatch.setattr(credentials, "_path", lambda: tmp_path / "credentials.json")+ monkeypatch.setattr(store, "_path", lambda: tmp_path / "platform.json")+ yield+++def _oauth_creds(**overrides) -> dict:+ creds = {+ "token_kind": "oauth",+ "client_id": "repowise-cli",+ "access_token": "at-1",+ "access_expires_at": int(time.time()) + 3600,+ "refresh_token": "rt-1",+ "device_name": "test-machine",+ }+ creds.update(overrides)+ return creds+++class TestCredentialStore:+ def test_round_trip(self):+ credentials.save(_oauth_creds())+ loaded = credentials.load()+ assert loaded is not None+ assert loaded["access_token"] == "at-1"++ def test_missing_and_corrupt_return_none(self, tmp_path: Path):+ assert credentials.load() is None+ (tmp_path / "credentials.json").write_text("{not json", encoding="utf-8")+ assert credentials.load() is None++ @pytest.mark.skipif(sys.platform == "win32", reason="POSIX permission bits")+ def test_file_is_owner_only(self, tmp_path: Path):+ credentials.save(_oauth_creds())+ mode = stat.S_IMODE(os.stat(tmp_path / "credentials.json").st_mode)+ assert mode == 0o600++ def test_expiry_logic(self):+ assert not credentials.is_access_expired(_oauth_creds())+ assert credentials.is_access_expired(_oauth_creds(access_expires_at=int(time.time()) + 10))+ assert credentials.is_access_expired(_oauth_creds(access_expires_at=None))+ # API keys never expire.+ assert not credentials.is_access_expired(+ {"token_kind": "api_key", "access_token": "rw_live_x"}+ )++ def test_mark_stale_preserves_account(self):+ credentials.save(_oauth_creds(account={"github_username": "raghav"}))+ credentials.mark_stale()+ loaded = credentials.load()+ assert loaded["stale"] is True+ assert loaded["account"]["github_username"] == "raghav"+++class TestPkce:+ def test_challenge_is_s256_of_verifier(self):+ verifier, challenge = auth.make_pkce_pair()+ expected = (+ base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest())+ .rstrip(b"=")+ .decode()+ )+ assert challenge == expected+ assert 43 <= len(verifier) <= 128 # RFC 7636 bounds++ def test_authorize_url_carries_required_params(self):+ url = auth.build_authorize_url(+ redirect_uri="http://127.0.0.1:5555/callback",+ code_challenge="c",+ state="s",+ device_name="my box",+ )+ assert url.startswith(auth.AUTHORIZE_URL + "?")+ for fragment in (+ "client_id=repowise-cli",+ "code_challenge_method=S256",+ "response_type=code",+ "state=s",+ "device_name=my+box",+ ):+ assert fragment in url+++class TestAuthHeaders:+ def test_signed_out_is_anonymous(self):+ assert auth.auth_headers() == {}++ def test_api_key_kind_returns_bearer(self):+ credentials.save({"token_kind": "api_key", "access_token": "rw_live_abc"})+ assert auth.auth_headers() == {"Authorization": "Bearer rw_live_abc"}++ def test_fresh_oauth_token_returned_without_network(self, monkeypatch):+ credentials.save(_oauth_creds())++ def boom(*a, **k):+ raise AssertionError("no network call expected for a fresh token")++ monkeypatch.setattr(auth, "_token_request", boom)+ assert auth.auth_headers() == {"Authorization": "Bearer at-1"}++ def test_expired_token_refreshes_and_persists_rotation(self, monkeypatch):+ credentials.save(_oauth_creds(access_expires_at=int(time.time()) - 10))+ monkeypatch.setattr(+ auth,+ "_token_request",+ lambda form: (+ 200,+ {"access_token": "at-2", "refresh_token": "rt-2", "expires_in": 3600},+ ),+ )+ assert auth.auth_headers() == {"Authorization": "Bearer at-2"}+ stored = credentials.load()+ assert stored["refresh_token"] == "rt-2"+ assert stored["device_name"] == "test-machine"++ def test_revoked_refresh_marks_stale_and_goes_anonymous(self, monkeypatch):+ credentials.save(_oauth_creds(access_expires_at=int(time.time()) - 10))+ monkeypatch.setattr(auth, "_token_request", lambda form: (400, {"error": "invalid_grant"}))+ assert auth.auth_headers() == {}+ assert credentials.load()["stale"] is True+ # And the dead token is not retried on the next call.+ monkeypatch.setattr(+ auth,+ "_token_request",+ lambda form: pytest.fail("stale credentials must not retry refresh"),+ )+ assert auth.auth_headers() == {}++ def test_network_failure_stays_signed_in_but_anonymous(self, monkeypatch):+ credentials.save(_oauth_creds(access_expires_at=int(time.time()) - 10))+ monkeypatch.setattr(auth, "_token_request", lambda form: (0, {}))+ assert auth.auth_headers() == {}+ # Not marked stale: next call may succeed once back online.+ assert credentials.load().get("stale") is None++ def test_platform_client_headers_pick_up_login(self):+ credentials.save({"token_kind": "api_key", "access_token": "rw_live_abc"})+ headers = PlatformClient()._headers()+ assert headers["Authorization"] == "Bearer rw_live_abc"+++class TestRefreshSingleFlight:+ def test_lock_contention_rereads_instead_of_double_rotating(self, monkeypatch):+ """The loser of the lock must consume the winner's persisted rotation,+ never present the (now revoked) old refresh token itself."""+ credentials.save(_oauth_creds(access_expires_at=int(time.time()) - 10))++ calls = []++ def fake_token_request(form):+ calls.append(form)+ # Simulate the winner having persisted a rotation while we+ # held/waited on the lock is covered by re-read; here the single+ # caller path rotates once.+ return (+ 200,+ {"access_token": "at-2", "refresh_token": "rt-2", "expires_in": 3600},+ )++ monkeypatch.setattr(auth, "_token_request", fake_token_request)+ assert auth.get_valid_credentials()["access_token"] == "at-2"+ assert len(calls) == 1+ # Second call finds a fresh token: no second rotation.+ assert auth.get_valid_credentials()["access_token"] == "at-2"+ assert len(calls) == 1++ def test_lock_timeout_returns_none_not_stolen_rotation(self, monkeypatch, tmp_path):+ credentials.save(_oauth_creds(access_expires_at=int(time.time()) - 10))+ # Hold the lock externally with a fresh mtime so it isn't stale-reaped.+ lock = tmp_path / "credentials.lock"+ lock.write_text("held")+ monkeypatch.setattr(credentials, "_LOCK_STALE_SECONDS", 9999)+ monkeypatch.setattr(+ auth,+ "_token_request",+ lambda form: pytest.fail("must not rotate while another process holds the lock"),+ )+ # Short timeout so the test is fast.+ original = credentials.refresh_lock++ def quick_lock(timeout: float = 0.3):+ return original(timeout=timeout)++ monkeypatch.setattr(credentials, "refresh_lock", quick_lock)+ assert auth.get_valid_credentials() is None+++class TestCliCommands:+ def test_whoami_signed_out(self):+ from repowise.cli.commands.login_cmd import whoami_command++ result = CliRunner().invoke(whoami_command)+ assert result.exit_code == 0+ assert "Not signed in" in result.output++ def test_whoami_offline_uses_cached_account(self, monkeypatch):+ from repowise.cli.commands.login_cmd import whoami_command++ credentials.save(_oauth_creds(account={"github_username": "raghav"}))+ monkeypatch.setattr(auth, "fetch_account", lambda: None)+ result = CliRunner().invoke(whoami_command)+ assert result.exit_code == 0+ assert "raghav" in result.output++ def test_logout_deletes_credentials(self, monkeypatch):+ from repowise.cli.commands.login_cmd import logout_command++ credentials.save(_oauth_creds())+ deleted = {}+ monkeypatch.setattr(+ "repowise.cli.platform.client.PlatformClient.delete",+ lambda self, path, params=None, timeout=None: deleted.setdefault("path", path) or True,+ )+ result = CliRunner().invoke(logout_command)+ assert result.exit_code == 0+ assert credentials.load() is None+ assert deleted["path"] == "oauth/connections/repowise-cli"++ def test_login_with_token_rejects_non_key(self, monkeypatch):+ from repowise.cli.commands.login_cmd import login_command++ result = CliRunner().invoke(login_command, ["--with-token"], input="garbage\n")+ assert result.exit_code != 0+ assert "rw_live_" in result.output++ def test_login_with_token_saves_and_greets(self, monkeypatch):+ from repowise.cli.commands.login_cmd import login_command++ monkeypatch.setattr(+ auth,+ "fetch_account",+ lambda: {"github_username": "raghav", "tier": "pro", "llm_credit_balance_cents": 500},+ )+ linked = {}+ monkeypatch.setattr(+ "repowise.cli.platform.client.PlatformClient.post",+ lambda self, path, payload, timeout=None: linked.setdefault(path, payload) or True,+ )+ result = CliRunner().invoke(login_command, ["--with-token"], input="rw_live_secret123\n")+ assert result.exit_code == 0, result.output+ assert "raghav" in result.output+ assert "pro" in result.output+ stored = credentials.load()+ assert stored["token_kind"] == "api_key"+ assert stored["access_token"] == "rw_live_secret123"+ assert "auth/link-anon" in linked