Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(remote-access): accept active custom hostnames

Maxvint17dfb95775cd
diff --git a/docs/plans/custom-hostname-heartbeat.md b/docs/plans/custom-hostname-heartbeat.md
new file mode 100644
index 000000000..bcfcf9006
--- /dev/null
+++ b/docs/plans/custom-hostname-heartbeat.md
@@ -0,0 +1,39 @@
+# Custom Hostname Heartbeat Plan
+
+## Background
+
+Avibe Cloud can route both the managed instance hostname and active custom
+hostnames through the same Cloudflare tunnel. The local UI currently recognizes
+only the managed `public_url` host and always uses the paired OAuth
+`redirect_uri`, so custom-host traffic is rejected or redirected away from the
+originating hostname.
+
+## Goal
+
+- Consume the heartbeat response's `active_hostnames` snapshot without breaking
+ compatibility with older backends.
+- Authorize each exact active hostname through the existing remote-access
+ authentication and origin checks.
+- Keep OAuth authorization, code exchange, and the final browser navigation on
+ the hostname that started the flow.
+
+## Solution
+
+1. Normalize successful heartbeat snapshots, replace a process-local cache under
+ a lock, and atomically persist the snapshot with its instance id and receive
+ timestamp under Avibe's state directory.
+2. Resolve allowed remote hosts as the valid `public_url` hostname plus the
+ current instance's cached snapshot. Reuse that exact-match decision for HTTP,
+ CSRF origin calculation, and authenticated WebSocket paths.
+3. Select `https://{request_host}/auth/callback` only for an allowed host. Store
+ it in both OAuth handshake representations and pass that same value to the
+ token exchange after callback validation.
+4. Cover normalization, legacy responses, replacement/removal, persisted
+ startup behavior, host rejection, redirect selection, and exchange binding.
+
+## Validation
+
+- Focused tests in `tests/test_remote_access_vibe_cloud.py` and
+ `tests/test_ui_remote_access_auth.py`.
+- Full runs of both affected test modules.
+- Ruff checks for changed Python files.
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index 495113e70..f3ed032e0 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -54,6 +54,8 @@ _STATUS_REPORT_LOCK = threading.Lock()
_STATUS_REPORT_THREADS: set[threading.Thread] = set()
_STATUS_REPORT_PENDING: tuple[V2Config | None, str, str | None] | None = None
_STATUS_REPORT_ATEXIT_REGISTERED = False
+_ACTIVE_HOSTNAMES_LOCK = threading.Lock()
+_ACTIVE_HOSTNAMES_CACHE: tuple[Path, str, frozenset[str], float | None] | None = None
STATUS_HEARTBEAT_SECONDS = 5 * 60
RESOURCE_ACL_SYNC_INTERVAL_SECONDS = 30
QUALITY_REPORT_SECONDS = 60
@@ -141,6 +143,10 @@ def _state_path() -> Path:
return paths.get_runtime_dir() / "remote-access-cloudflared.json"
+def _active_hostnames_state_path() -> Path:
+ return paths.get_state_dir() / "remote-access-active-hostnames.json"
+
+
def _quality_state_path() -> Path:
return paths.get_runtime_dir() / "remote-access-tunnel-quality.json"
@@ -399,6 +405,80 @@ def _read_state() -> dict[str, Any] | None:
return payload if isinstance(payload, dict) else None
+def _normalize_active_hostnames(value: Any) -> tuple[str, ...]:
+ if not isinstance(value, list):
+ return ()
+ normalized: list[str] = []
+ seen: set[str] = set()
+ for item in value:
+ if not isinstance(item, str):
+ continue
+ hostname = item.strip().lower().rstrip(".")
+ if not hostname or "/" in hostname or ":" in hostname or hostname in seen:
+ continue
+ seen.add(hostname)
+ normalized.append(hostname)
+ return tuple(normalized)
+
+
+def _replace_active_hostnames(config: V2Config, value: Any) -> frozenset[str]:
+ global _ACTIVE_HOSTNAMES_CACHE
+
+ instance_id = str(config.remote_access.vibe_cloud.instance_id or "").strip()
+ hostnames = _normalize_active_hostnames(value)
+ source_updated_at = time.time()
+ state_path = _active_hostnames_state_path()
+ payload = {
+ "schema_version": 1,
+ "instance_id": instance_id,
+ "active_hostnames": list(hostnames),
+ "source_updated_at": source_updated_at,
+ }
+ with _ACTIVE_HOSTNAMES_LOCK:
+ _ACTIVE_HOSTNAMES_CACHE = (state_path, instance_id, frozenset(hostnames), source_updated_at)
+ try:
+ state_path.parent.mkdir(parents=True, exist_ok=True)
+ runtime.write_json(state_path, payload)
+ except OSError as exc:
+ logger.warning("failed to persist remote access hostname snapshot: %s", exc)
+ return frozenset(hostnames)
+
+
+def active_hostnames(config: V2Config) -> frozenset[str]:
+ """Return the latest control-plane hostname snapshot for this instance."""
+
+ global _ACTIVE_HOSTNAMES_CACHE
+
+ instance_id = str(config.remote_access.vibe_cloud.instance_id or "").strip()
+ if not instance_id:
+ return frozenset()
+ state_path = _active_hostnames_state_path()
+ with _ACTIVE_HOSTNAMES_LOCK:
+ cached = _ACTIVE_HOSTNAMES_CACHE
+ if cached is not None and cached[0] == state_path and cached[1] == instance_id:
+ return cached[2]
+
+ payload = runtime.read_json(state_path)
+ if not isinstance(payload, dict) or payload.get("schema_version") != 1:
+ return frozenset()
+ if str(payload.get("instance_id") or "").strip() != instance_id:
+ return frozenset()
+ hostnames = frozenset(_normalize_active_hostnames(payload.get("active_hostnames")))
+ try:
+ source_updated_at = float(payload["source_updated_at"])
+ except (KeyError, TypeError, ValueError):
+ source_updated_at = None
+ _ACTIVE_HOSTNAMES_CACHE = (state_path, instance_id, hostnames, source_updated_at)
+ return hostnames
+
+
+def _clear_active_hostnames_cache() -> None:
+ global _ACTIVE_HOSTNAMES_CACHE
+
+ with _ACTIVE_HOSTNAMES_LOCK:
+ _ACTIVE_HOSTNAMES_CACHE = None
+
+
def _state_connector(name: str) -> dict[str, Any] | None:
state = _read_state()
if not state:
@@ -555,6 +635,8 @@ def report_runtime_status(config: V2Config | None = None, event: str = "heartbea
cloud = config.remote_access.vibe_cloud
if not (cloud.instance_id and cloud.instance_secret and cloud.backend_url):
return {"ok": False, "error": "remote_status_not_configured"}
+ if urllib.parse.urlsplit(cloud.backend_url).scheme.lower() != "https":
+ return {"ok": False, "error": "remote_status_backend_url_invalid"}
payload = {
"instance_secret": cloud.instance_secret,
**runtime_status_payload(config, event=event, last_error=last_error),
@@ -564,6 +646,7 @@ def report_runtime_status(config: V2Config | None = None, event: str = "heartbea
payload,
timeout=5.0,
)
+ _replace_active_hostnames(config, result.get("active_hostnames"))
return {"ok": True, **result}
except Exception as exc:
return {"ok": False, "error": "remote_status_report_failed", "detail": str(exc)}
@@ -2566,11 +2649,17 @@ def session_needs_membership_refresh(payload: Mapping[str, Any], now: int | None
return claims_issued_at <= 0 or current - claims_issued_at >= SESSION_ORGANIZATION_REFRESH_SECONDS
-def authorization_url(config: V2Config, state: str, nonce: str, code_challenge: str) -> str:
+def authorization_url(
+ config: V2Config,
+ state: str,
+ nonce: str,
+ code_challenge: str,
+ redirect_uri: str | None = None,
+) -> str:
cloud = config.remote_access.vibe_cloud
params = {
"client_id": cloud.client_id,
- "redirect_uri": cloud.redirect_uri,
+ "redirect_uri": redirect_uri or cloud.redirect_uri,
"response_type": "code",
"scope": "openid email",
"state": state,
@@ -2583,14 +2672,19 @@ def authorization_url(config: V2Config, state: str, nonce: str, code_challenge:
return f"{cloud.authorization_endpoint}?{urllib.parse.urlencode(params)}"
-def exchange_oauth_code(config: V2Config, code: str, code_verifier: str) -> dict[str, Any]:
+def exchange_oauth_code(
+ config: V2Config,
+ code: str,
+ code_verifier: str,
+ redirect_uri: str | None = None,
+) -> dict[str, Any]:
cloud = config.remote_access.vibe_cloud
response = requests.post(
cloud.token_endpoint,
data={
"grant_type": "authorization_code",
"client_id": cloud.client_id,
- "redirect_uri": cloud.redirect_uri,
+ "redirect_uri": redirect_uri or cloud.redirect_uri,
"code": code,
"code_verifier": code_verifier,
},
@@ -2695,7 +2789,13 @@ def _warn_oauth_store_at_capacity() -> None:
def store_oauth_handshake(
- rid: str, *, nonce: str, code_verifier: str, next_target: str, device_hash: str | None = None
+ rid: str,
+ *,
+ nonce: str,
+ code_verifier: str,
+ next_target: str,
+ device_hash: str | None = None,
+ redirect_uri: str | None = None,
) -> None:
"""Persist a login handshake in memory, keyed by the signed state's random id.
@@ -2710,6 +2810,7 @@ def store_oauth_handshake(
"code_verifier": code_verifier,
"next": next_target,
"device_hash": device_hash,
+ "redirect_uri": redirect_uri,
"exp": now + OAUTH_HANDSHAKE_TTL_SECONDS,
}
with _OAUTH_STORE_LOCK:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 3d42f403f..6ab6acf41 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -320,9 +320,9 @@ def _current_origin() -> str:
return trusted_forwarded_origin
if config is not None and _is_remote_access_request(config):
- public_origin = _remote_access_public_origin(config)
- if public_origin:
- return public_origin
+ remote_origin = _remote_access_request_origin(config)
+ if remote_origin:
+ return remote_origin
if trusted_forwarded_origin is None:
return f"{scheme}://{netloc}"
@@ -1283,10 +1283,21 @@ def _normalized_host(value: str | None) -> str:
def _is_remote_access_request(config: V2Config) -> bool:
+ return _remote_access_host_allowed(config, _effective_normalized_host())
+
+
+def _remote_access_allowed_hosts(config: V2Config) -> frozenset[str]:
public_host = _remote_access_public_host(config)
if not public_host:
- return False
- return _normalized_host(_effective_request_host()) == public_host
+ return frozenset()
+ from vibe import remote_access
+
+ return frozenset({public_host, *remote_access.active_hostnames(config)})
+
+
+def _remote_access_host_allowed(config: V2Config, host: str | None) -> bool:
+ normalized = _normalized_host(host)
+ return bool(normalized and normalized in _remote_access_allowed_hosts(config))
def _remote_access_public_host(config: V2Config) -> str | None:
@@ -1309,6 +1320,22 @@ def _remote_access_public_origin(config: V2Config) -> str | None:
return f"{parsed.scheme}://{parsed.netloc.lower().rstrip('.')}"
+def _remote_access_request_origin(config: V2Config) -> str | None:
+ host = _effective_normalized_host()
+ if not _remote_access_host_allowed(config, host):
+ return None
+ if host == _remote_access_public_host(config):
+ return _remote_access_public_origin(config)
+ return f"https://{host}"
+
+
+def _remote_access_oauth_redirect_uri(config: V2Config) -> str:
+ host = _effective_normalized_host()
+ if _remote_access_host_allowed(config, host):
+ return f"https://{host}/auth/callback"
+ return config.remote_access.vibe_cloud.redirect_uri
+
+
def _origin_identity(value: str) -> tuple[str, str, int | None] | None:
parsed = urlparse(value)
if not parsed.scheme or not parsed.hostname or parsed.username or parsed.password:
@@ -1323,10 +1350,17 @@ def _same_origin(left: str, right: str) -> bool:
def _remote_access_public_origin_matches(origin: str, config: V2Config) -> bool:
- trusted_origin = _remote_access_public_origin(config)
- if not trusted_origin:
+ identity = _origin_identity(origin)
+ if identity is None:
return False
- return _same_origin(origin, trusted_origin)
+ scheme, host, _ = identity
+ if scheme != "https" or not _remote_access_host_allowed(config, host):
+ return False
+ if host == _remote_access_public_host(config):
+ trusted_origin = _remote_access_public_origin(config)
+ else:
+ trusted_origin = f"https://{host}"
+ return bool(trusted_origin and _same_origin(origin, trusted_origin))
def _remote_access_public_url_invalid(config: V2Config) -> bool:
@@ -1596,6 +1630,7 @@ def _redirect_to_vibe_cloud_login(config: V2Config):
rid=rid,
)
nonce = secrets.token_urlsafe(24)
+ redirect_uri = _remote_access_oauth_redirect_uri(config)
# Stable per-browser binding id: reuse the existing device cookie so it stays
# consistent across the iOS authorize excursion (it is NOT regenerated per flow,
# unlike the handshake state), generating one only on first use.
@@ -1611,6 +1646,7 @@ def _redirect_to_vibe_cloud_login(config: V2Config):
code_verifier=code_verifier,
next_target=next_target,
device_hash=_oauth_device_hash(cloud.session_secret, device_id),
+ redirect_uri=redirect_uri,
)
oauth_cookie = _make_oauth_cookie(
cloud.session_secret,
@@ -1619,11 +1655,18 @@ def _redirect_to_vibe_cloud_login(config: V2Config):
"nonce": nonce,
"code_verifier": code_verifier,
"next": next_target,
+ "redirect_uri": redirect_uri,
"exp": int(datetime.now().timestamp()) + REMOTE_OAUTH_HANDSHAKE_TTL_SECONDS,
},
)
response = Response(status=302)
- response.headers["Location"] = remote_access.authorization_url(config, state, nonce, code_challenge)
+ response.headers["Location"] = remote_access.authorization_url(
+ config,
+ state,
+ nonce,
+ code_challenge,
+ redirect_uri=redirect_uri,
+ )
response.set_cookie(
REMOTE_OAUTH_COOKIE_NAME,
oauth_cookie,
@@ -2529,7 +2572,7 @@ def _show_runtime_websocket_authorized(websocket: Any) -> bool:
return _websocket_is_local_request(websocket)
if _websocket_is_local_request(websocket, config):
return True
- if _websocket_normalized_host(websocket) != _remote_access_public_host(config):
+ if not _remote_access_host_allowed(config, _websocket_normalized_host(websocket)):
return False
return _remote_access_websocket_session_payload(websocket, config) is not None
@@ -2562,7 +2605,7 @@ def _show_runtime_hmr_origin_allowed(websocket: Any) -> bool:
def _remote_access_websocket_session_payload(websocket: Any, config: V2Config | None) -> dict[str, Any] | None:
if config is None or _websocket_is_local_request(websocket, config):
return None
- if _websocket_normalized_host(websocket) != _remote_access_public_host(config):
+ if not _remote_access_host_allowed(config, _websocket_normalized_host(websocket)):
return None
from vibe import remote_access
@@ -4229,6 +4272,7 @@ def remote_access_auth_callback():
code_verifier = cookie_state["code_verifier"]
handshake_nonce = cookie_state.get("nonce")
next_target = cookie_state.get("next")
+ redirect_uri = str(cookie_state.get("redirect_uri") or cloud.redirect_uri)
elif store_record is not None and _oauth_store_record_device_bound(cloud.session_secret, store_record):
# Store-fallback for the iOS standalone PWA case, where the handshake cookie's
# state desyncs (authorize ran in a separate in-app-browser context). Gated on
@@ -4240,6 +4284,7 @@ def remote_access_auth_callback():
code_verifier = store_record["code_verifier"]
handshake_nonce = store_record.get("nonce")
next_target = store_record.get("next")
+ redirect_uri = str(store_record.get("redirect_uri") or cloud.redirect_uri)
else:
# Neither the cookie nor the server-side store yielded the handshake.
# Rate-limited: this branch is unauthenticated-reachable.
@@ -4259,7 +4304,12 @@ def remote_access_auth_callback():
next_target = url_state.get("next") if url_state else "/"
return _oauth_callback_error_response("invalid_oauth_state", next_target=next_target)
try:
- result = remote_access.exchange_oauth_code(config, _oauth_callback_arg("code") or "", code_verifier)
+ result = remote_access.exchange_oauth_code(
+ config,
+ _oauth_callback_arg("code") or "",
+ code_verifier,
+ redirect_uri=redirect_uri,
+ )
claims = result["claims"]
session_claims = result.get("session_claims")
if not isinstance(session_claims, dict):