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): show Cloudflare network path (#1158)

Call White5b1f1488b0b6
diff --git a/docs/plans/tunnel-quality-and-route-recovery.md b/docs/plans/tunnel-quality-and-route-recovery.md
index 86c181a4f..1a893c329 100644
--- a/docs/plans/tunnel-quality-and-route-recovery.md
+++ b/docs/plans/tunnel-quality-and-route-recovery.md
@@ -188,6 +188,83 @@ rolling deployment.
| RA-TQ-023 | Status cleanup preserves rollback after a promoted process exits | supervisor lifecycle test |
| RA-TQ-024 | Pinned transport rejects comparison evidence from another protocol | protocol-evidence contract test |
+### Local network-path diagnostics
+
+The local `GET /api/remote-access/status` response adds a `network_path`
+object while a managed Connector is running. This object never enters the
+avibe.bot runtime-status payload. It combines three bounded, independently
+verified observations:
+
+- cloudflared's loopback-only `/diag/tunnel` endpoint supplies the Anycast edge
+ IP addresses for the active Connector's live connections;
+- a fresh scrape of the active Connector's existing `edge_locations` metric
+ supplies node identifiers such as `sin09`; persisted locations are not reused
+ when that live scrape fails; and
+- a remote request's `CF-Ray` suffix supplies the browser ingress colo. Avibe
+ ignores `CF-Ray` unless the request matches the paired public hostname. This
+ header is diagnostic-only input and never participates in access control or
+ route recovery.
+
+Colo codes are enriched from Cloudflare's public status component catalog. The
+catalog is cached locally for seven days and refreshed in a background thread;
+status reads never wait on that external request. Unknown codes remain visible
+as raw codes instead of being assigned a guessed location.
+
+Representative local-only shape:
+
+```json
+{
+ "network_path": {
+ "schema_version": 1,
+ "provider": "Cloudflare",
+ "asn": 13335,
+ "sampled_at": "2026-08-04T04:00:00Z",
+ "locations_pending": false,
+ "client_access": "remote",
+ "client_ingress": {
+ "colo": "SIN",
+ "location": "Singapore, Singapore",
+ "country": "Singapore"
+ },
+ "connector": {
+ "locations": [
+ {
+ "id": "sin09",
+ "colo": "SIN",
+ "location": "Singapore, Singapore",
+ "country": "Singapore"
+ }
+ ],
+ "edge_ips": ["198.41.192.47"]
+ },
+ "route": { "assessment": "same_metro" }
+ }
+}
+```
+
+The route assessment is deliberately conservative:
+
+- `same_metro`: every observed Connector colo matches the browser ingress colo;
+- `same_country`: every observed Connector colo resolves to the browser
+ ingress country, but at least one metro differs;
+- `cross_country`: at least one known active Connector colo is in another
+ country, so a cross-country path is possible; and
+- `unknown`: the browser ingress, Connector colos, or location mapping is not
+ complete enough to decide.
+
+This is a geographic diagnostic, not a traceroute. Cloudflare Anycast does not
+expose the selected facility, internal router, transit carrier, or backbone
+hops through the Tunnel APIs, and multiple live Connector edges mean Avibe
+cannot identify which connection served one browser request. The UI therefore
+says `potential cross-country route` rather than claiming a definite detour.
+Geography alone never triggers route optimization; the measured request path
+and availability gates remain authoritative.
+
+| ID | Scenario | Required evidence |
+| --- | --- | --- |
+| RA-TQ-025 | Local status shows bounded active edge nodes, locations, network owner, and Anycast IPs without uploading them | parser, status, and privacy-boundary tests |
+| RA-TQ-026 | Only paired-public-host `CF-Ray` metadata participates in a conservative geographic route assessment | request-boundary and assessment tests |
+
## Product Decisions
1. Tunnel RTT is a first-class health signal, but not a standalone truth.
@@ -200,7 +277,8 @@ rolling deployment.
4. The local runtime owns detection and recovery. avibe.bot displays the latest
state but does not remotely command connector lifecycle changes.
5. Cloud reporting sends one bounded aggregate, not raw Prometheus samples,
- edge IPs, connector IDs, request URLs, or time-series telemetry.
+ edge IPs, connector IDs, request URLs, or time-series telemetry. Raw edge
+ details remain local-only diagnostics.
6. Normal operation uses one connector. A second connector exists only during
evaluation and drain.
7. V1 does not expose threshold tuning. It provides one manual "Optimize route"
@@ -594,7 +672,10 @@ After a successful promotion, show one non-blocking message such as
navigation state across the expected SSE reconnect; do not redirect or reload
the application shell.
-Avoid exposing connector IDs, edge IPs, tunnel tokens, or internal log paths.
+Keep raw infrastructure out of the primary status. The owner-visible local
+Remote Access page may expose active Cloudflare node IDs and Anycast edge IPs
+behind technical details; remote callers remain session-authenticated. Never
+expose tunnel tokens, internal log paths, or the user's client IP.
## avibe.bot Runtime-Status Contract
@@ -743,7 +824,10 @@ properties.
- Bind metrics endpoints to `127.0.0.1` only.
- Never report edge IP addresses, connector IDs, tunnel token fingerprints,
- request paths, host network addresses, or public probe response bodies.
+ request paths, host network addresses, or public probe response bodies to
+ avibe.bot. The local status API may return the active Cloudflare edge IPs and
+ node IDs for owner-visible diagnostics only; remote requests remain subject
+ to the existing session authentication boundary.
- Do not enable debug cloudflared logging; it can include request headers.
- Keep the existing instance-secret authentication for runtime status.
- The control plane stores only the latest bounded aggregate.
diff --git a/tests/scenarios/tunnel_quality/catalog.yaml b/tests/scenarios/tunnel_quality/catalog.yaml
index 0e896dc11..6083a5fda 100644
--- a/tests/scenarios/tunnel_quality/catalog.yaml
+++ b/tests/scenarios/tunnel_quality/catalog.yaml
@@ -5,6 +5,7 @@ capability:
canonical_tests:
- tests/test_tunnel_quality.py
- tests/test_tunnel_recovery.py
+ - tests/test_cloudflare_network.py
status_legend:
covered: automated scenario or contract coverage exists
partial: focused coverage exists but a live network dependency remains
@@ -155,3 +156,15 @@ scenarios:
kind: contract
layer: scenario
test: tests/test_tunnel_recovery.py::test_ra_tq_024_pinned_protocol_rejects_stale_tail_evidence
+ - id: RA-TQ-025
+ name: Local status exposes bounded live Cloudflare network-path diagnostics without uploading them
+ status: covered
+ kind: network_policy
+ layer: contract
+ test: tests/test_cloudflare_network.py::test_ra_tq_025_network_path_combines_nodes_ips_and_location
+ - id: RA-TQ-026
+ name: Only paired-public-host CF-Ray metadata participates in conservative route assessment
+ status: covered
+ kind: network_policy
+ layer: contract
+ test: tests/test_ui_remote_access_auth.py::test_ra_tq_026_remote_status_uses_cf_ray_on_paired_public_host
diff --git a/tests/test_cloudflare_network.py b/tests/test_cloudflare_network.py
new file mode 100644
index 000000000..5742a9f23
--- /dev/null
+++ b/tests/test_cloudflare_network.py
@@ -0,0 +1,99 @@
+from __future__ import annotations
+
+from vibe import cloudflare_network
+
+
+def _catalog():
+ return {
+ "SIN": {"colo": "SIN", "location": "Singapore, Singapore", "country": "Singapore"},
+ "NRT": {"colo": "NRT", "location": "Tokyo, Japan", "country": "Japan"},
+ "KIX": {"colo": "KIX", "location": "Osaka, Japan", "country": "Japan"},
+ }
+
+
+def test_ra_tq_025_parses_official_cloudflare_location_components() -> None:
+ catalog = cloudflare_network.parse_location_components(
+ {
+ "components": [
+ {"name": "Singapore, Singapore - (SIN)"},
+ {"name": "Adelaide, SA, Australia - (ADL)"},
+ {"name": "Cloudflare Sites and Services"},
+ {"name": "invalid - (too-long)"},
+ ]
+ }
+ )
+
+ assert catalog == {
+ "SIN": {"colo": "SIN", "location": "Singapore, Singapore", "country": "Singapore"},
+ "ADL": {"colo": "ADL", "location": "Adelaide, SA, Australia", "country": "Australia"},
+ }
+
+
+def test_ra_tq_025_parses_cloudflare_node_and_ray_codes() -> None:
+ assert cloudflare_network.colo_from_edge_location("sin09") == "SIN"
+ assert cloudflare_network.colo_from_edge_location("sin") is None
+ assert cloudflare_network.parse_cf_ray_colo("9f1234567890abcd-SIN") == "SIN"
+ assert cloudflare_network.parse_cf_ray_colo("test-ray") is None
+
+
+def test_ra_tq_025_tunnel_diag_keeps_only_bounded_public_edge_ips() -> None:
+ payload = {
+ "connections": [
+ {"edgeAddress": "198.41.192.47"},
+ {"edgeAddress": "198.41.192.47"},
+ {"edgeAddress": "127.0.0.1"},
+ {"edgeAddress": "2606:4700::1"},
+ {"edgeAddress": "not-an-ip"},
+ ]
+ }
+
+ assert cloudflare_network.parse_tunnel_diag(payload) == ["198.41.192.47", "2606:4700::1"]
+
+
+def test_ra_tq_026_route_assessment_is_conservative() -> None:
+ catalog = _catalog()
+
+ assert cloudflare_network.assess_route("SIN", ["SIN", "SIN"], catalog) == "same_metro"
+ assert cloudflare_network.assess_route("NRT", ["NRT", "KIX"], catalog) == "same_country"
+ assert cloudflare_network.assess_route("SIN", ["SIN", "NRT"], catalog) == "cross_country"
+ assert cloudflare_network.assess_route("SIN", ["NRT", "LAX"], catalog) == "cross_country"
+ assert cloudflare_network.assess_route(None, ["SIN"], catalog) == "unknown"
+ assert cloudflare_network.assess_route("SIN", ["SIN", "LAX"], catalog) == "unknown"
+
+
+def test_ra_tq_025_network_path_combines_nodes_ips_and_location(monkeypatch) -> None:
+ monkeypatch.setattr(cloudflare_network, "location_catalog", lambda: (_catalog(), False))
+ monkeypatch.setattr(
+ cloudflare_network,
+ "tunnel_edge_ips",
+ lambda metrics_url: ["198.41.192.47", "198.41.200.53"],
+ )
+
+ snapshot = cloudflare_network.network_path_snapshot(
+ ["sin09", "sin12"],
+ "http://127.0.0.1:60553",
+ client_colo="SIN",
+ client_access="remote",
+ )
+
+ assert snapshot["provider"] == "Cloudflare"
+ assert snapshot["asn"] == 13335
+ assert snapshot["client_ingress"]["location"] == "Singapore, Singapore"
+ assert snapshot["client_access"] == "remote"
+ assert snapshot["connector"]["locations"][0]["id"] == "sin09"
+ assert snapshot["connector"]["edge_ips"] == ["198.41.192.47", "198.41.200.53"]
+ assert snapshot["route"]["assessment"] == "same_metro"
+
+
+def test_ra_tq_025_diag_rejects_non_loopback_metrics_url(monkeypatch) -> None:
+ called = False
+
+ def unexpected_get(*args, **kwargs):
+ nonlocal called
+ called = True
+ raise AssertionError("request should not be made")
+
+ monkeypatch.setattr(cloudflare_network.requests, "get", unexpected_get)
+
+ assert cloudflare_network.tunnel_edge_ips("http://203.0.113.10:9090") == []
+ assert called is False
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
index 0a2734d6a..b6523ec10 100644
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -4,6 +4,7 @@ import ipaddress
import json
import threading
import time
+from types import SimpleNamespace
import pytest
from cryptography.hazmat.primitives.asymmetric import rsa
@@ -783,6 +784,10 @@ def test_ra_tq_007_runtime_status_payload_includes_tunnel_quality(monkeypatch, t
"ok": True,
"running": True,
"binary_found": True,
+ "network_path": {
+ "schema_version": 1,
+ "connector": {"edge_ips": ["198.41.192.47"]},
+ },
"tunnel_quality": {
"schema_version": 1,
"state": "healthy",
@@ -801,6 +806,8 @@ def test_ra_tq_007_runtime_status_payload_includes_tunnel_quality(monkeypatch, t
assert payload["expected_origin_service"] == "http://127.0.0.1:5123"
assert payload["observed_origin_service"] == "http://100.97.103.112:5123"
assert payload["tunnel_quality"]["grade"] == "good"
+ assert "network_path" not in payload
+ assert "198.41.192.47" not in json.dumps(payload)
def test_ra_tq_014_runtime_status_payload_includes_v2_request_path(monkeypatch, tmp_path) -> None:
@@ -1353,6 +1360,93 @@ def test_status_preserves_pid_file_when_process_command_is_unknown(monkeypatch,
assert remote_access._state_path().exists()
+def test_ra_tq_025_status_computes_network_path_only_for_local_api(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ pid = 123
+ remote_access._pid_path().parent.mkdir(parents=True, exist_ok=True)
+ remote_access._pid_path().write_text(str(pid), encoding="utf-8")
+ runtime.write_json(
+ remote_access._state_path(),
+ {
+ "pid": pid,
+ "active": {"pid": pid, "metrics_url": "http://127.0.0.1:29001"},
+ },
+ )
+ runtime.write_json(
+ remote_access._quality_state_path(),
+ {"schema_version": 2, "edge_locations": ["sin09", "sin12"]},
+ )
+ monkeypatch.setattr(runtime, "pid_alive", lambda candidate: candidate == pid)
+ monkeypatch.setattr(runtime, "get_process_command", lambda candidate: "cloudflared tunnel run")
+ monkeypatch.setattr(remote_access, "_resolve_binary", lambda cfg: "/usr/local/bin/cloudflared")
+ monkeypatch.setattr(
+ remote_access.tunnel_quality,
+ "scrape_metrics",
+ lambda metrics_url: SimpleNamespace(edge_locations=("sin09", "sin12")),
+ )
+ calls = []
+ monkeypatch.setattr(
+ remote_access.cloudflare_network,
+ "network_path_snapshot",
+ lambda locations, metrics_url, *, client_colo=None, client_access="local": calls.append(
+ (locations, metrics_url, client_colo, client_access)
+ )
+ or {"schema_version": 1},
+ )
+
+ internal_status = remote_access.status(config)
+ local_status = remote_access.status(
+ config,
+ client_colo="SIN",
+ client_access="remote",
+ include_network_path=True,
+ )
+
+ assert "network_path" not in internal_status
+ assert local_status["network_path"] == {"schema_version": 1}
+ assert calls == [(["sin09", "sin12"], "http://127.0.0.1:29001", "SIN", "remote")]
+
+
+def test_ra_tq_025_status_rejects_edge_locations_when_live_scrape_fails(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ pid = 123
+ remote_access._pid_path().parent.mkdir(parents=True, exist_ok=True)
+ remote_access._pid_path().write_text(str(pid), encoding="utf-8")
+ runtime.write_json(
+ remote_access._state_path(),
+ {
+ "pid": pid,
+ "active": {"pid": pid, "metrics_url": "http://127.0.0.1:29001"},
+ },
+ )
+ runtime.write_json(
+ remote_access._quality_state_path(),
+ {"schema_version": 2, "edge_locations": ["nrt01"]},
+ )
+ monkeypatch.setattr(runtime, "pid_alive", lambda candidate: candidate == pid)
+ monkeypatch.setattr(runtime, "get_process_command", lambda candidate: "cloudflared tunnel run")
+ monkeypatch.setattr(remote_access, "_resolve_binary", lambda cfg: "/usr/local/bin/cloudflared")
+
+ def unavailable_metrics(_metrics_url):
+ raise OSError("metrics unavailable")
+
+ monkeypatch.setattr(remote_access.tunnel_quality, "scrape_metrics", unavailable_metrics)
+ observed_locations = []
+ monkeypatch.setattr(
+ remote_access.cloudflare_network,
+ "network_path_snapshot",
+ lambda locations, metrics_url, **kwargs: observed_locations.append(locations)
+ or {"schema_version": 1},
+ )
+
+ result = remote_access.status(config, include_network_path=True)
+
+ assert result["network_path"] == {"schema_version": 1}
+ assert observed_locations == [[]]
+
+
def test_start_refuses_duplicate_connector_when_process_command_is_unknown(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
pid = 123
diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.py
index 37b98ca5e..521fbed1a 100644
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@ -828,6 +828,66 @@ def test_trusted_proxy_forwarded_host_routes_remote_access(monkeypatch, tmp_path
assert response.headers["Location"].startswith(config.remote_access.vibe_cloud.authorization_endpoint)
+def test_ra_tq_026_remote_status_uses_cf_ray_on_paired_public_host(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ observed = []
+
+ def status(
+ loaded_config=None,
+ *,
+ client_colo=None,
+ client_access="local",
+ include_network_path=False,
+ ):
+ observed.append((loaded_config, client_colo, client_access, include_network_path))
+ return {"ok": True, "client_colo": client_colo}
+
+ monkeypatch.setattr(remote_access, "status", status)
+ with app.test_request_context(
+ "/api/remote-access/status",
+ base_url="https://alex.avibe.bot",
+ headers={"CF-Ray": "9f1234567890abcd-SIN"},
+ ):
+ response = ui_server.remote_access_status()
+
+ assert response.status_code == 200
+ assert observed[0][0].remote_access.vibe_cloud.public_url == config.remote_access.vibe_cloud.public_url
+ assert observed[0][1] == "SIN"
+ assert observed[0][2] == "remote"
+ assert observed[0][3] is True
+
+
+def test_ra_tq_026_remote_status_ignores_spoofed_cf_ray(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ observed = []
+
+ def status(
+ loaded_config=None,
+ *,
+ client_colo=None,
+ client_access="local",
+ include_network_path=False,
+ ):
+ observed.append((loaded_config, client_colo, client_access, include_network_path))
+ return {"ok": True, "client_colo": client_colo}
+
+ monkeypatch.setattr(remote_access, "status", status)
+ with app.test_request_context(
+ "/api/remote-access/status",
+ base_url="http://127.0.0.1:5123",
+ headers={"CF-Ray": "9f1234567890abcd-NRT"},
+ ):
+ response = ui_server.remote_access_status()
+
+ assert response.status_code == 200
+ assert observed[0][1] is None
+ assert observed[0][2] == "local"
+ assert observed[0][3] is True
+ assert config.remote_access.vibe_cloud.public_url == "https://alex.avibe.bot"
+
+
def test_trusted_proxy_missing_forwarded_host_fails_closed(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")
diff --git a/ui/src/components/RemoteAccess.tsx b/ui/src/components/RemoteAccess.tsx
index eee7af259..8fb93715a 100644
--- a/ui/src/components/RemoteAccess.tsx
+++ b/ui/src/components/RemoteAccess.tsx
@@ -1,7 +1,19 @@
import React, { useCallback, useEffect, useState } from 'react';
-import { CheckCircle2, Cloud, ExternalLink, Link2, RefreshCcw, Route } from 'lucide-react';
+import {
+ ArrowRight,
+ CheckCircle2,
+ ChevronDown,
+ Cloud,
+ ExternalLink,
+ Link2,
+ MapPin,
+ Network,
+ RefreshCcw,
+ Route,
+ Server,
+} from 'lucide-react';
import { Trans, useTranslation } from 'react-i18next';
-import { type RemoteAccessStatus, useApi } from '../context/ApiContext';
+import { type CloudflareEdgeLocation, type RemoteAccessStatus, useApi } from '../context/ApiContext';
import { useToast } from '../context/ToastContext';
import { getTunnelQualityDisplayState, getTunnelRequestPathDisplayState } from '../lib/tunnelQuality';
import { CompactField } from './settings/SettingsPrimitives';
@@ -17,6 +29,10 @@ const formatLatency = (milliseconds: number) => (
: `${Math.round(milliseconds)} ms`
);
+const formatEdgeLocation = (location: CloudflareEdgeLocation) => (
+ location.location ? `${location.location} (${location.colo})` : location.colo
+);
+
export const RemoteAccess: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
@@ -134,6 +150,7 @@ export const RemoteAccess: React.FC = () => {
const message = t('remoteAccess.startSuccess');
setActionMessage({ type: 'success', text: message });
showToast(message, 'success');
+ await refresh(true).catch(() => undefined);
} catch (error) {
const message = error instanceof Error ? error.message : t('errors.remote_access_unknown');
setActionMessage({ type: 'error', text: message });
@@ -149,6 +166,7 @@ export const RemoteAccess: React.FC = () => {
const message = t('remoteAccess.optimizeStarted');
setActionMessage({ type: 'success', text: message });
showToast(message, 'success');
+ await refresh(true).catch(() => undefined);
} catch (error) {
const message = error instanceof Error ? error.message : t('errors.remote_access_unknown');
setActionMessage({ type: 'error', text: message });
@@ -195,6 +213,42 @@ export const RemoteAccess: React.FC = () => {
const protocolDisplay = configuredProtocol === 'auto' && effectiveProtocol !== 'unknown'
? t('remoteAccess.protocolAutomatic', { protocol: protocolLabel })
: protocolLabel;
+ const networkPath = status?.network_path;
+ const connectorLocations = networkPath?.connector.locations || [];
+ const connectorMetros = connectorLocations.filter((location, index) => (
+ connectorLocations.findIndex((candidate) => candidate.colo === location.colo) === index
+ ));
+ const primaryConnectorLocation = connectorMetros[0];
+ const connectorLocationSummary = primaryConnectorLocation
+ ? connectorMetros.length > 1
+ ? t('remoteAccess.networkAdditionalLocations', {
+ location: formatEdgeLocation(primaryConnectorLocation),
+ count: connectorMetros.length - 1,
+ })
+ : formatEdgeLocation(primaryConnectorLocation)
+ : t('remoteAccess.networkLocationUnavailable');
+ const clientLocationSummary = networkPath?.client_ingress
+ ? formatEdgeLocation(networkPath.client_ingress)
+ : networkPath?.client_access === 'remote'
+ ? t('remoteAccess.networkIngressUnavailable')
+ : t('remoteAccess.networkLocalBrowser');
+ const routeAssessment = networkPath?.route.assessment || 'unknown';
+ const routeVariant = routeAssessment === 'same_metro'
+ ? 'success'
+ : routeAssessment === 'same_country'
+ ? 'info'
+ : routeAssessment === 'cross_country'
+ ? 'warning'
+ : 'secondary';
+ const routeLabel = t(`remoteAccess.networkRoute${
+ routeAssessment === 'same_metro'
+ ? 'SameMetro'
+ : routeAssessment === 'same_country'
+ ? 'SameCountry'
+ : routeAssessment === 'cross_country'
+ ? 'CrossCountry'
+ : 'Unknown'
+ }`);
return (
<section
@@ -308,6 +362,73 @@ export const RemoteAccess: React.FC = () => {
</div>
</div>
+ {running && networkPath && (
+ <div className="border-b border-border px-5 py-4">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="flex min-w-0 items-center gap-2">
+ <Network className="size-4 shrink-0 text-cyan" />
+ <h3 className="text-[13px] font-semibold text-foreground">{t('remoteAccess.networkPath')}</h3>
+ </div>
+ <Badge variant={routeVariant}>{routeLabel}</Badge>
+ </div>
+
+ <div className="mt-3 grid border-y border-border/70 md:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)_auto_minmax(0,1fr)] md:items-stretch">
+ <div className="min-w-0 py-3 md:pr-4">
+ <div className="flex items-center gap-1.5 text-[11px] text-muted">
+ <MapPin className="size-3.5 shrink-0" />
+ {t('remoteAccess.networkBrowserIngress')}
+ </div>
+ <div className="mt-1 break-words text-[12px] font-medium text-foreground">{clientLocationSummary}</div>
+ </div>
+ <ArrowRight className="my-auto hidden size-4 text-muted md:block" />
+ <div className="min-w-0 border-t border-border/70 py-3 md:border-l-0 md:border-t-0 md:px-4">
+ <div className="flex items-center gap-1.5 text-[11px] text-muted">
+ <Cloud className="size-3.5 shrink-0" />
+ {t('remoteAccess.networkProvider')}
+ </div>
+ <div className="mt-1 text-[12px] font-medium text-foreground">
+ {networkPath.provider} <span className="font-mono text-[11px] text-muted">AS{networkPath.asn}</span>
+ </div>
+ </div>
+ <ArrowRight className="my-auto hidden size-4 text-muted md:block" />
+ <div className="min-w-0 border-t border-border/70 py-3 md:border-l-0 md:border-t-0 md:pl-4">
+ <div className="flex items-center gap-1.5 text-[11px] text-muted">
+ <Server className="size-3.5 shrink-0" />
+ {t('remoteAccess.networkConnectorEdges')}
+ </div>
+ <div className="mt-1 break-words text-[12px] font-medium text-foreground">{connectorLocationSummary}</div>
+ </div>
+ </div>
+
+ <details className="group mt-2 text-[11px]">
+ <summary className="flex w-fit cursor-pointer list-none items-center gap-1 py-1 text-muted hover:text-foreground">
+ <ChevronDown className="size-3.5 transition-transform group-open:rotate-180" />
+ {t('remoteAccess.networkTechnicalDetails')}
+ </summary>
+ <div className="mt-1 grid gap-3 border-t border-border/60 pt-3 sm:grid-cols-2">
+ <div className="min-w-0">
+ <div className="font-medium text-muted">{t('remoteAccess.networkEdgeNodes')}</div>
+ <div className="mt-1 space-y-1 font-mono text-foreground/85">
+ {connectorLocations.length > 0 ? connectorLocations.map((location) => (
+ <div key={location.id} className="break-all">
+ {location.id} · {formatEdgeLocation(location)}
+ </div>
+ )) : <div>{t('remoteAccess.networkLocationUnavailable')}</div>}
+ </div>
+ </div>
+ <div className="min-w-0">
+ <div className="font-medium text-muted">{t('remoteAccess.networkAnycastIps')}</div>
+ <div className="mt-1 space-y-1 font-mono text-foreground/85">
+ {networkPath.connector.edge_ips.length > 0 ? networkPath.connector.edge_ips.map((address) => (
+ <div key={address} className="break-all">{address}</div>
+ )) : <div>{t('remoteAccess.networkIpUnavailable')}</div>}
+ </div>
+ </div>
+ </div>
+ </details>
+ </div>
+ )}
+
{showPairingForm ? (
<div className="grid gap-3 px-5 py-4 md:grid-cols-[1fr_auto] md:items-end">
<label className="space-y-1.5">
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 683d0232f..017e375dd 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -407,6 +407,29 @@ export type TunnelQualitySnapshot = {
};
};
+export type CloudflareEdgeLocation = {
+ colo: string;
+ location?: string;
+ country?: string;
+};
+
+export type TunnelNetworkPath = {
+ schema_version: 1;
+ provider: 'Cloudflare';
+ asn: 13335;
+ sampled_at: string;
+ locations_pending: boolean;
+ client_access: 'local' | 'remote';
+ client_ingress: CloudflareEdgeLocation | null;
+ connector: {
+ locations: Array<CloudflareEdgeLocation & { id: string }>;
+ edge_ips: string[];
+ };
+ route: {
+ assessment: 'same_metro' | 'same_country' | 'cross_country' | 'unknown';
+ };
+};
+
export type RemoteAccessStatus = {
ok: boolean;
enabled: boolean;
@@ -416,6 +439,7 @@ export type RemoteAccessStatus = {
pid_state?: string;
transport_protocol?: 'auto' | 'quic' | 'http2';
tunnel_quality?: TunnelQualitySnapshot;
+ network_path?: TunnelNetworkPath;
error?: string;
optimization_started?: boolean;
};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 817ead38d..e3a0c54f3 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1132,6 +1132,22 @@
"requestPath": "Requests · P95 {{p95}} · P99 {{p99}} · {{slow}}% > 1 s",
"requestPathUnavailable": "Requests unavailable · {{success}}/{{count}} succeeded",
"requestPathMeasuring": "Measuring requests · {{count}} samples",
+ "networkPath": "Network path",
+ "networkBrowserIngress": "This browser",
+ "networkProvider": "Network",
+ "networkConnectorEdges": "Tunnel edges",
+ "networkLocalBrowser": "Local browser",
+ "networkIngressUnavailable": "Ingress location unavailable",
+ "networkLocationUnavailable": "Location unavailable",
+ "networkAdditionalLocations": "{{location}} +{{count}} more",
+ "networkRouteSameMetro": "No geographic detour detected",
+ "networkRouteSameCountry": "Within-country route",
+ "networkRouteCrossCountry": "Potential cross-country route",
+ "networkRouteUnknown": "Route assessment unavailable",
+ "networkTechnicalDetails": "Technical details",
+ "networkEdgeNodes": "Cloudflare edge nodes",
+ "networkAnycastIps": "Cloudflare Anycast IPs",
+ "networkIpUnavailable": "Edge IP unavailable",
"optimizeRoute": "Optimize route",
"optimizingRoute": "Optimizing...",
"optimizeStarted": "A second Connector is evaluating a better route"
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 62395d9b6..2778fd770 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1132,6 +1132,22 @@
"requestPath": "远程请求 · P95 {{p95}} · P99 {{p99}} · {{slow}}% 超过 1 秒",
"requestPathUnavailable": "远程请求不可用 · {{success}}/{{count}} 成功",
"requestPathMeasuring": "正在测量远程请求 · {{count}} 个样本",
+ "networkPath": "网络路径",
+ "networkBrowserIngress": "当前浏览器",
+ "networkProvider": "网络",
+ "networkConnectorEdges": "Tunnel 边缘节点",
+ "networkLocalBrowser": "本地浏览器",
+ "networkIngressUnavailable": "入口位置暂不可用",
+ "networkLocationUnavailable": "位置暂不可用",
+ "networkAdditionalLocations": "{{location}},另有 {{count}} 个",
+ "networkRouteSameMetro": "未发现地理绕路",
+ "networkRouteSameCountry": "境内路径",
+ "networkRouteCrossCountry": "可能存在跨国路径",
+ "networkRouteUnknown": "暂无法判断是否绕路",
+ "networkTechnicalDetails": "技术详情",
+ "networkEdgeNodes": "Cloudflare 边缘节点",
+ "networkAnycastIps": "Cloudflare Anycast IP",
+ "networkIpUnavailable": "暂未获取边缘 IP",
"optimizeRoute": "优化线路",
"optimizingRoute": "优化中...",
"optimizeStarted": "第二条 Connector 正在评估更优线路"
diff --git a/vibe/cloudflare_network.py b/vibe/cloudflare_network.py
new file mode 100644
index 000000000..fb3022830
--- /dev/null
+++ b/vibe/cloudflare_network.py
@@ -0,0 +1,315 @@
+"""Local-only Cloudflare Tunnel network path diagnostics."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+import ipaddress
+import logging
+import re
+import threading
+import time
+import urllib.parse
+from pathlib import Path
+from typing import Any
+
+import requests
+
+from config import paths
+from vibe import runtime
+
+
+logger = logging.getLogger(__name__)
+
+CLOUDFLARE_ASN = 13335
+CLOUDFLARE_STATUS_COMPONENTS_URL = "https://www.cloudflarestatus.com/api/v2/components.json"
+LOCATION_CATALOG_TTL_SECONDS = 7 * 24 * 60 * 60
+LOCATION_CATALOG_RETRY_SECONDS = 10 * 60
+DIAG_CACHE_TTL_SECONDS = 15
+DIAG_TIMEOUT_SECONDS = 0.5
+MAX_EDGE_CONNECTIONS = 8
+
+_COMPONENT_LOCATION_RE = re.compile(r"^(.{1,160}) - \(([A-Z0-9]{3})\)$")
+_EDGE_LOCATION_RE = re.compile(r"^([A-Za-z]{3})[0-9]+$")
+_CF_RAY_RE = re.compile(r"^[0-9A-Fa-f]{8,32}-([A-Za-z0-9]{3})$")
+
+_CATALOG_LOCK = threading.Lock()
+_CATALOG: dict[str, dict[str, str]] | None = None
+_CATALOG_LOADED_PATH: Path | None = None
+_CATALOG_UPDATED_AT = 0.0
+_CATALOG_LAST_ATTEMPT = 0.0
+_CATALOG_REFRESH_THREAD: threading.Thread | None = None
+
+_DIAG_LOCK = threading.Lock()
+_DIAG_CACHE: dict[str, tuple[float, list[str]]] = {}
+
+
+def _utc_timestamp(now: float | None = None) -> str:
+ value = datetime.fromtimestamp(now if now is not None else time.time(), tz=timezone.utc)
+ return value.isoformat(timespec="seconds").replace("+00:00", "Z")
+
+
+def _catalog_cache_path() -> Path:
+ return paths.get_runtime_dir() / "cloudflare-location-catalog.json"
+
+
+def parse_location_components(payload: Any) -> dict[str, dict[str, str]]:
+ """Parse the bounded Cloudflare status location catalog."""
+
+ if not isinstance(payload, dict) or not isinstance(payload.get("components"), list):
+ return {}
+ catalog: dict[str, dict[str, str]] = {}
+ for component in payload["components"][:1000]:
+ if not isinstance(component, dict):
+ continue
+ name = component.get("name")
+ if not isinstance(name, str):
+ continue
+ match = _COMPONENT_LOCATION_RE.fullmatch(name.strip())
+ if match is None:
+ continue
+ location, colo = match.groups()
+ country = location.rsplit(",", 1)[-1].strip()
+ if not country or len(country) > 80:
+ continue
+ catalog[colo] = {
+ "colo": colo,
+ "location": location.strip(),
+ "country": country,
+ }
+ return catalog
+
+
+def parse_cf_ray_colo(value: str | None) -> str | None:
+ if not isinstance(value, str):
+ return None
+ match = _CF_RAY_RE.fullmatch(value.strip())
+ return match.group(1).upper() if match is not None else None
+
+
+def colo_from_edge_location(value: str | None) -> str | None:
+ if not isinstance(value, str):
+ return None
+ match = _EDGE_LOCATION_RE.fullmatch(value.strip())
+ return match.group(1).upper() if match is not None else None
+
+
+def _read_cached_catalog(path: Path) -> tuple[dict[str, dict[str, str]], float]:
+ payload = runtime.read_json(path)
+ if not isinstance(payload, dict):
+ return {}, 0.0
+ catalog = payload.get("locations")
+ updated_at = payload.get("updated_at_epoch")
+ if not isinstance(catalog, dict) or not isinstance(updated_at, (int, float)):
+ return {}, 0.0
+ validated = parse_location_components(
+ {
+ "components": [
+ {"name": f"{value.get('location', '')} - ({key})"}
+ for key, value in list(catalog.items())[:1000]
+ if isinstance(key, str) and isinstance(value, dict)
+ ]
+ }
+ )
+ return validated, float(updated_at)
+
+
+def _refresh_location_catalog(path: Path) -> None:
+ global _CATALOG, _CATALOG_UPDATED_AT, _CATALOG_REFRESH_THREAD
+ try:
+ response = requests.get(CLOUDFLARE_STATUS_COMPONENTS_URL, timeout=5.0)
+ response.raise_for_status()
+ catalog = parse_location_components(response.json())
+ if not catalog:
+ return
+ path.parent.mkdir(parents=True, exist_ok=True)
+ runtime.write_json(
+ path,
+ {
+ "schema_version": 1,
+ "updated_at": _utc_timestamp(),
+ "updated_at_epoch": time.time(),
+ "locations": catalog,
+ },
+ )
+ with _CATALOG_LOCK:
+ if _CATALOG_LOADED_PATH == path:
+ _CATALOG = catalog
+ _CATALOG_UPDATED_AT = time.time()
+ except Exception:
+ logger.debug("Could not refresh Cloudflare location catalog", exc_info=True)
+ finally:
+ with _CATALOG_LOCK:
+ if _CATALOG_REFRESH_THREAD is threading.current_thread():
+ _CATALOG_REFRESH_THREAD = None
+
+
+def location_catalog(*, now: float | None = None) -> tuple[dict[str, dict[str, str]], bool]:
+ """Return cached locations immediately and refresh stale data in the background."""
+
+ global _CATALOG, _CATALOG_LOADED_PATH, _CATALOG_UPDATED_AT
+ global _CATALOG_LAST_ATTEMPT, _CATALOG_REFRESH_THREAD
+
+ current_time = time.time() if now is None else now
+ path = _catalog_cache_path()
+ with _CATALOG_LOCK:
+ if _CATALOG_LOADED_PATH != path:
+ _CATALOG, _CATALOG_UPDATED_AT = _read_cached_catalog(path)
+ _CATALOG_LOADED_PATH = path
+ _CATALOG_LAST_ATTEMPT = 0.0
+ _CATALOG_REFRESH_THREAD = None
+
+ stale = not _CATALOG or current_time - _CATALOG_UPDATED_AT >= LOCATION_CATALOG_TTL_SECONDS
+ retry_ready = current_time - _CATALOG_LAST_ATTEMPT >= LOCATION_CATALOG_RETRY_SECONDS
+ if stale and retry_ready and _CATALOG_REFRESH_THREAD is None:
+ _CATALOG_LAST_ATTEMPT = current_time
+ thread = threading.Thread(
+ target=_refresh_location_catalog,
+ args=(path,),
+ name="vibe-cloudflare-location-catalog",
+ daemon=True,
+ )
+ _CATALOG_REFRESH_THREAD = thread
+ thread.start()
+ return dict(_CATALOG or {}), stale
+
+
+def _local_metrics_base_url(metrics_url: str) -> str | None:
+ try:
+ parsed = urllib.parse.urlsplit(metrics_url)
+ except ValueError:
+ return None
+ if (
+ parsed.scheme != "http"
+ or parsed.username
+ or parsed.password
+ or parsed.path not in {"", "/"}
+ or parsed.query
+ or parsed.fragment
+ ):
+ return None
+ try:
+ host = ipaddress.ip_address(parsed.hostname or "")
+ port = parsed.port
+ except ValueError:
+ return None
+ if not host.is_loopback or port is None:
+ return None
+ display_host = f"[{host}]" if host.version == 6 else str(host)
+ return f"http://{display_host}:{port}"
+
+
+def parse_tunnel_diag(payload: Any) -> list[str]:
+ if not isinstance(payload, dict) or not isinstance(payload.get("connections"), list):
+ return []
+ addresses: list[str] = []
+ for connection in payload["connections"][:MAX_EDGE_CONNECTIONS]:
+ if not isinstance(connection, dict):
+ continue
+ value = connection.get("edgeAddress")
+ try:
+ address = ipaddress.ip_address(value)
+ except (TypeError, ValueError):
+ continue
+ normalized = str(address)
+ if not address.is_global or normalized in addresses:
+ continue
+ addresses.append(normalized)
+ return addresses
+
+
+def tunnel_edge_ips(metrics_url: str | None, *, now: float | None = None) -> list[str]:
+ if not isinstance(metrics_url, str):
+ return []
+ base_url = _local_metrics_base_url(metrics_url)
+ if base_url is None:
+ return []
+ current_time = time.monotonic() if now is None else now
+ with _DIAG_LOCK:
+ expired = [
+ key
+ for key, (sampled_at, _) in _DIAG_CACHE.items()
+ if current_time - sampled_at >= DIAG_CACHE_TTL_SECONDS
+ ]
+ for key in expired:
+ _DIAG_CACHE.pop(key, None)
+ cached = _DIAG_CACHE.get(base_url)
+ if cached is not None and current_time - cached[0] < DIAG_CACHE_TTL_SECONDS:
+ return list(cached[1])
+ try:
+ response = requests.get(f"{base_url}/diag/tunnel", timeout=DIAG_TIMEOUT_SECONDS)
+ response.raise_for_status()
+ addresses = parse_tunnel_diag(response.json())
+ except Exception:
+ addresses = []
+ with _DIAG_LOCK:
+ _DIAG_CACHE[base_url] = (current_time, addresses)
+ return list(addresses)
+
+
+def _location_payload(colo: str, catalog: dict[str, dict[str, str]]) -> dict[str, str]:
+ location = catalog.get(colo)
+ if location is None:
+ return {"colo": colo}
+ return dict(location)
+
+
+def assess_route(
+ client_colo: str | None,
+ connector_colos: list[str],
+ catalog: dict[str, dict[str, str]],
+) -> str:
+ if client_colo is None or not connector_colos:
+ return "unknown"
+ if all(colo == client_colo for colo in connector_colos):
+ return "same_metro"
+ client_country = (catalog.get(client_colo) or {}).get("country")
+ connector_countries = [(catalog.get(colo) or {}).get("country") for colo in connector_colos]
+ if not client_country:
+ return "unknown"
+ known_connector_countries = [country for country in connector_countries if country]
+ if any(country != client_country for country in known_connector_countries):
+ return "cross_country"
+ if len(known_connector_countries) != len(connector_countries):
+ return "unknown"
+ return "same_country"
+
+
+def network_path_snapshot(
+ edge_locations: list[str],
+ metrics_url: str | None,
+ *,
+ client_colo: str | None = None,
+ client_access: str = "local",
+) -> dict[str, Any]:
+ catalog, locations_pending = location_catalog()
+ connector_locations: list[dict[str, str]] = []
+ connector_colos: list[str] = []
+ seen_ids: set[str] = set()
+ for raw_location in edge_locations[:MAX_EDGE_CONNECTIONS]:
+ if not isinstance(raw_location, str):
+ continue
+ edge_id = raw_location.strip().lower()
+ colo = colo_from_edge_location(edge_id)
+ if colo is None or edge_id in seen_ids:
+ continue
+ seen_ids.add(edge_id)
+ connector_colos.append(colo)
+ connector_locations.append({"id": edge_id, **_location_payload(colo, catalog)})
+
+ normalized_client = client_colo.upper() if isinstance(client_colo, str) else None
+ return {
+ "schema_version": 1,
+ "provider": "Cloudflare",
+ "asn": CLOUDFLARE_ASN,
+ "sampled_at": _utc_timestamp(),
+ "locations_pending": locations_pending,
+ "client_access": "remote" if client_access == "remote" else "local",
+ "client_ingress": _location_payload(normalized_client, catalog) if normalized_client else None,
+ "connector": {
+ "locations": connector_locations,
+ "edge_ips": tunnel_edge_ips(metrics_url),
+ },
+ "route": {
+ "assessment": assess_route(normalized_client, connector_colos, catalog),
+ },
+ }
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index ecfbcd725..f488528f4 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -37,7 +37,7 @@ from jwt import PyJWKClient
from config import paths
from config.v2_config import V2Config
-from vibe import api, runtime
+from vibe import api, cloudflare_network, runtime
from vibe import tunnel_quality
logger = logging.getLogger(__name__)
@@ -550,7 +550,25 @@ def tunnel_quality_snapshot() -> dict[str, Any] | None:
return None
-def status(config: V2Config | None = None) -> dict[str, Any]:
+def _live_network_edge_locations(active: dict[str, Any], pid: int | None) -> list[str]:
+ metrics_url = active.get("metrics_url")
+ if active.get("pid") != pid or not isinstance(metrics_url, str) or not metrics_url:
+ return []
+ try:
+ sample = tunnel_quality.scrape_metrics(metrics_url)
+ except Exception:
+ logger.debug("Could not obtain live Tunnel edge locations", exc_info=True)
+ return []
+ return list(sample.edge_locations)
+
+
+def status(
+ config: V2Config | None = None,
+ *,
+ client_colo: str | None = None,
+ client_access: str = "local",
+ include_network_path: bool = False,
+) -> dict[str, Any]:
try:
config = config or V2Config.load()
except Exception:
@@ -586,6 +604,14 @@ def status(config: V2Config | None = None) -> dict[str, Any]:
quality = tunnel_quality_snapshot()
if quality is not None:
result["tunnel_quality"] = quality
+ if running and include_network_path:
+ active = _state_connector("active") or {}
+ result["network_path"] = cloudflare_network.network_path_snapshot(
+ _live_network_edge_locations(active, pid),
+ active.get("metrics_url") if isinstance(active.get("metrics_url"), str) else None,
+ client_colo=client_colo,
+ client_access=client_access,
+ )
return result
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 10a3992cf..4f7e490cb 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4712,7 +4712,27 @@ async def config_post():
def remote_access_status():
from vibe import remote_access
- return jsonify(remote_access.status())
+ config = _load_remote_access_config()
+ client_colo = None
+ remote_request = bool(
+ config is not None
+ and _is_remote_access_request(config)
+ )
+ if remote_request:
+ from vibe import cloudflare_network
+
+ # CF-Ray is diagnostic-only input. It never participates in access
+ # control or route recovery, so a locally spoofed value can at most
+ # change the caller's own displayed ingress location.
+ client_colo = cloudflare_network.parse_cf_ray_colo(request.headers.get("CF-Ray"))
+ return jsonify(
+ remote_access.status(
+ config,
+ client_colo=client_colo,
+ client_access="remote" if remote_request else "local",
+ include_network_path=True,
+ )
+ )
@app.route("/api/remote-access/vibe-cloud/pair", methods=["POST"])