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): add Vibe Cloud provider

cyhd7ca4b12ddd1
diff --git a/config/paths.py b/config/paths.py
index 1e3a4272a..721bb7aa5 100644
--- a/config/paths.py
+++ b/config/paths.py
@@ -37,6 +37,10 @@ def get_runtime_ui_pid_path() -> Path:
return get_runtime_dir() / "vibe-ui.pid"
+def get_runtime_remote_access_pid_path() -> Path:
+ return get_runtime_dir() / "remote-access-cloudflared.pid"
+
+
def get_runtime_status_path() -> Path:
return get_runtime_dir() / "status.json"
diff --git a/config/v2_config.py b/config/v2_config.py
index 13f7d2ee0..b1320d393 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -185,6 +185,31 @@ class UiConfig:
open_browser: bool = True
+@dataclass
+class VibeCloudRemoteAccessConfig:
+ enabled: bool = False
+ backend_url: str = "https://vibe.io"
+ public_url: str = ""
+ instance_id: str = ""
+ client_id: str = ""
+ issuer: str = ""
+ authorization_endpoint: str = ""
+ token_endpoint: str = ""
+ jwks_uri: str = ""
+ redirect_uri: str = ""
+ tunnel_token: str = ""
+ instance_secret: str = ""
+ session_secret: str = ""
+ cloudflared_path: str = ""
+ dev_login_hint: str = ""
+
+
+@dataclass
+class RemoteAccessConfig:
+ provider: str = "vibe_cloud"
+ vibe_cloud: VibeCloudRemoteAccessConfig = field(default_factory=VibeCloudRemoteAccessConfig)
+
+
@dataclass
class UpdateConfig:
"""Configuration for automatic update checking and installation."""
@@ -240,6 +265,7 @@ class V2Config:
platform_configs: dict[str, BaseIMConfig] = field(default_factory=dict)
gateway: Optional[GatewayConfig] = None
ui: UiConfig = field(default_factory=UiConfig)
+ remote_access: RemoteAccessConfig = field(default_factory=RemoteAccessConfig)
update: UpdateConfig = field(default_factory=UpdateConfig)
ack_mode: str = "typing"
show_duration: bool = False # Show task duration in result messages
@@ -360,6 +386,22 @@ class V2Config:
raise ValueError("Config 'ui' must be an object")
ui = UiConfig(**_filter_dataclass_fields(UiConfig, ui_payload))
+ remote_access_payload = payload.get("remote_access") or {}
+ if not isinstance(remote_access_payload, dict):
+ raise ValueError("Config 'remote_access' must be an object")
+ remote_access_provider = remote_access_payload.get("provider") or "vibe_cloud"
+ if remote_access_provider != "vibe_cloud":
+ raise ValueError("Config 'remote_access.provider' must be 'vibe_cloud'")
+ vibe_cloud_payload = remote_access_payload.get("vibe_cloud") or {}
+ if not isinstance(vibe_cloud_payload, dict):
+ raise ValueError("Config 'remote_access.vibe_cloud' must be an object")
+ remote_access = RemoteAccessConfig(
+ provider=remote_access_provider,
+ vibe_cloud=VibeCloudRemoteAccessConfig(
+ **_filter_dataclass_fields(VibeCloudRemoteAccessConfig, vibe_cloud_payload)
+ ),
+ )
+
update_payload = payload.get("update") or {}
if not isinstance(update_payload, dict):
raise ValueError("Config 'update' must be an object")
@@ -401,6 +443,7 @@ class V2Config:
agents=agents,
gateway=gateway,
ui=ui,
+ remote_access=remote_access,
update=update,
ack_mode=ack_mode,
show_duration=show_duration,
@@ -444,6 +487,10 @@ class V2Config:
},
"gateway": self.gateway.__dict__ if self.gateway else None,
"ui": self.ui.__dict__,
+ "remote_access": {
+ "provider": self.remote_access.provider,
+ "vibe_cloud": self.remote_access.vibe_cloud.__dict__,
+ },
"update": self.update.__dict__,
"ack_mode": self.ack_mode,
"show_duration": self.show_duration,
diff --git a/pyproject.toml b/pyproject.toml
index 38c8e2b99..eea43a43c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -42,6 +42,7 @@ dependencies = [
"sentry-sdk>=2.0.0",
"python-socks[asyncio]>=2.0.0",
"aiohttp-socks>=0.8.0",
+ "PyJWT[crypto]>=2.9.0",
]
[project.urls]
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 000000000..8b1378917
--- /dev/null
+++ b/tests/__init__.py
@@ -0,0 +1 @@
+
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
new file mode 100644
index 000000000..0c915bac5
--- /dev/null
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -0,0 +1,72 @@
+from __future__ import annotations
+
+import json
+
+from config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Config
+from vibe import remote_access
+
+
+def _config() -> V2Config:
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ platform="slack",
+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ ui=UiConfig(),
+ remote_access=RemoteAccessConfig(),
+ )
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.instance_id = "inst_123"
+ cloud.client_id = "vr_client_123"
+ cloud.public_url = "https://alex.vibe.io"
+ cloud.session_secret = "session-secret"
+ return config
+
+
+def test_session_cookie_roundtrip() -> None:
+ config = _config()
+
+ cookie = remote_access.make_session_cookie(config, "[email protected]", "user-1")
+
+ assert remote_access.validate_session_cookie(config, cookie) is True
+ assert remote_access.validate_session_cookie(config, cookie + "x") is False
+
+
+def test_pair_redeems_key_and_starts_connector(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.enabled = False
+ config.remote_access.vibe_cloud.session_secret = ""
+ config.save()
+
+ def fake_request(url: str, payload: dict, timeout: float = 20.0):
+ assert url == "https://backend.test/api/v1/pairing/redeem"
+ assert payload["pairing_key"] == "vrp_test"
+ return {
+ "instance_id": "inst_123",
+ "client_id": "vr_client_123",
+ "issuer": "https://backend.test",
+ "authorization_endpoint": "https://backend.test/oauth/authorize",
+ "token_endpoint": "https://backend.test/oauth/token",
+ "jwks_uri": "https://backend.test/oauth/jwks.json",
+ "public_url": "https://alex.vibe.io",
+ "redirect_uri": "https://alex.vibe.io/auth/callback",
+ "tunnel_token": "tunnel-token",
+ "instance_secret": "instance-secret",
+ }
+
+ monkeypatch.setattr(remote_access, "_json_request", fake_request)
+ monkeypatch.setattr(remote_access, "start", lambda next_config: {"ok": True, "running": True})
+ monkeypatch.setattr(remote_access, "status", lambda next_config=None: {"ok": True, "running": True, "paired": True})
+
+ result = remote_access.pair("vrp_test", "https://backend.test")
+ saved_payload = json.loads((tmp_path / "config" / "config.json").read_text(encoding="utf-8"))
+
+ assert result["ok"] is True
+ assert saved_payload["remote_access"]["vibe_cloud"]["enabled"] is True
+ assert saved_payload["remote_access"]["vibe_cloud"]["tunnel_token"] == "tunnel-token"
+ assert saved_payload["remote_access"]["vibe_cloud"]["session_secret"]
diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.py
new file mode 100644
index 000000000..16521820a
--- /dev/null
+++ b/tests/test_ui_remote_access_auth.py
@@ -0,0 +1,59 @@
+from __future__ import annotations
+
+from config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Config
+from vibe import remote_access
+from vibe.ui_server import app
+
+
+def _save_config(tmp_path) -> V2Config:
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ platform="slack",
+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ ui=UiConfig(),
+ remote_access=RemoteAccessConfig(),
+ )
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.public_url = "https://alex.vibe.io"
+ cloud.client_id = "vr_client_123"
+ cloud.instance_id = "inst_123"
+ cloud.session_secret = "session-secret"
+ cloud.authorization_endpoint = "https://backend.test/oauth/authorize"
+ cloud.redirect_uri = "https://alex.vibe.io/auth/callback"
+ config.save()
+ return config
+
+
+def test_remote_host_redirects_to_vibe_cloud_login(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+
+ response = app.test_client().get("/dashboard", base_url="https://alex.vibe.io", follow_redirects=False)
+
+ assert response.status_code == 302
+ assert response.headers["Location"].startswith("https://backend.test/oauth/authorize?")
+
+
+def test_localhost_does_not_require_remote_access_cookie(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+
+ response = app.test_client().get("/health", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 200
+
+
+def test_remote_host_allows_valid_remote_session(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ client = app.test_client()
+ client.set_cookie(remote_access.SESSION_COOKIE_NAME, remote_access.make_session_cookie(config, "[email protected]", "user-1"), domain="alex.vibe.io")
+
+ response = client.get("/dashboard", base_url="https://alex.vibe.io", follow_redirects=False)
+
+ assert response.status_code != 302
diff --git a/tests/test_v2_config_platform_registry.py b/tests/test_v2_config_platform_registry.py
index 03aaab4c3..e723abe15 100644
--- a/tests/test_v2_config_platform_registry.py
+++ b/tests/test_v2_config_platform_registry.py
@@ -82,3 +82,16 @@ def test_config_payload_includes_platform_catalog_and_setup_state() -> None:
]
assert payload["setup_state"]["configured_platforms"] == ["slack", "discord", "telegram", "lark", "wechat"]
assert payload["setup_state"]["needs_setup"] is False
+
+
+def test_config_payload_includes_vibe_cloud_remote_access() -> None:
+ config = _base_config()
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.public_url = "https://alex.vibe.io"
+ config.remote_access.vibe_cloud.instance_id = "inst_123"
+
+ payload = api.config_to_payload(config)
+
+ assert payload["remote_access"]["provider"] == "vibe_cloud"
+ assert payload["remote_access"]["vibe_cloud"]["enabled"] is True
+ assert payload["remote_access"]["vibe_cloud"]["public_url"] == "https://alex.vibe.io"
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index e23a30196..d566d242e 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -6,6 +6,7 @@ import { ChannelList } from './components/steps/ChannelList';
import { UserList } from './components/steps/UserList';
import { DoctorPanel } from './components/steps/DoctorPanel';
import { LogsPanel } from './components/steps/LogsPanel';
+import { RemoteAccess } from './components/RemoteAccess';
import { StatusProvider } from './context/StatusContext';
import { ApiProvider, useApi } from './context/ApiContext';
import { ToastProvider } from './context/ToastContext';
@@ -63,6 +64,7 @@ function AppRoutes() {
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/channels" element={<ChannelList isPage />} />
<Route path="/users" element={<UserList />} />
+ <Route path="/remote-access" element={<RemoteAccess />} />
<Route path="/doctor" element={<DoctorPanel isPage />} />
<Route path="/doctor/logs" element={<LogsPanel />} />
<Route path="/" element={<Navigate to="/dashboard" replace />} />
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index d4d0f7dc3..73b95a070 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react';
import { NavLink, Outlet, useLocation } from 'react-router-dom';
-import { LayoutDashboard, MessageSquare, Activity, Users } from 'lucide-react';
+import { LayoutDashboard, MessageSquare, Activity, Users, Globe2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useStatus } from '../context/StatusContext';
import { useApi } from '../context/ApiContext';
@@ -67,6 +67,7 @@ export const AppShell: React.FC = () => {
<NavItem to="/dashboard" icon={LayoutDashboard}>{t('nav.dashboard')}</NavItem>
{hasChannelPlatforms && <NavItem to="/channels" icon={MessageSquare}>{t('nav.channels')}</NavItem>}
<NavItem to="/users" icon={Users}>{t('nav.users')}</NavItem>
+ <NavItem to="/remote-access" icon={Globe2}>{t('nav.remoteAccess')}</NavItem>
<NavItem to="/doctor" icon={Activity}>{t('nav.doctor')}</NavItem>
</nav>
@@ -91,6 +92,7 @@ export const AppShell: React.FC = () => {
<NavLink to="/dashboard" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><LayoutDashboard /></NavLink>
{hasChannelPlatforms && <NavLink to="/channels" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><MessageSquare /></NavLink>}
<NavLink to="/users" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><Users /></NavLink>
+ <NavLink to="/remote-access" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><Globe2 /></NavLink>
<NavLink to="/doctor" className={({isActive}) => clsx("p-2 rounded-lg", isActive ? "text-accent" : "text-muted")}><Activity /></NavLink>
</nav>
</div>
diff --git a/ui/src/components/RemoteAccess.tsx b/ui/src/components/RemoteAccess.tsx
new file mode 100644
index 000000000..18c457fda
--- /dev/null
+++ b/ui/src/components/RemoteAccess.tsx
@@ -0,0 +1,162 @@
+import React, { useEffect, useState } from 'react';
+import { ExternalLink, KeyRound, Link2, Power, RefreshCcw, ShieldCheck } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { useApi } from '../context/ApiContext';
+import { useToast } from '../context/ToastContext';
+
+export const RemoteAccess: React.FC = () => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+ const [loading, setLoading] = useState(true);
+ const [pairing, setPairing] = useState(false);
+ const [status, setStatus] = useState<any>(null);
+ const [backendUrl, setBackendUrl] = useState('https://vibe.io');
+ const [pairingKey, setPairingKey] = useState('');
+
+ const refresh = async () => {
+ setLoading(true);
+ try {
+ const [config, remoteStatus] = await Promise.all([api.getConfig(), api.remoteAccessStatus()]);
+ setStatus(remoteStatus);
+ setBackendUrl(config?.remote_access?.vibe_cloud?.backend_url || 'https://vibe.io');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ useEffect(() => {
+ refresh().catch(() => setLoading(false));
+ }, []);
+
+ const pair = async () => {
+ setPairing(true);
+ try {
+ const result = await api.pairVibeCloudRemoteAccess({
+ backend_url: backendUrl.trim(),
+ pairing_key: pairingKey.trim(),
+ device_name: 'Vibe Remote',
+ });
+ setStatus(result);
+ setPairingKey('');
+ showToast(t('remoteAccess.pairSuccess'), 'success');
+ await refresh();
+ } finally {
+ setPairing(false);
+ }
+ };
+
+ const stop = async () => {
+ const result = await api.stopRemoteAccess();
+ setStatus(result);
+ showToast(t('remoteAccess.stopSuccess'), 'success');
+ };
+
+ const start = async () => {
+ const result = await api.startRemoteAccess();
+ setStatus(result);
+ showToast(t('remoteAccess.startSuccess'), 'success');
+ };
+
+ const publicUrl = status?.public_url;
+ const paired = Boolean(status?.paired);
+ const running = Boolean(status?.running);
+
+ return (
+ <div className="max-w-5xl mx-auto space-y-6">
+ <div className="rounded-3xl border border-slate-200 bg-gradient-to-br from-slate-950 via-slate-900 to-cyan-950 text-white p-8 shadow-xl overflow-hidden relative">
+ <div className="absolute -right-20 -top-24 h-64 w-64 rounded-full bg-cyan-400/20 blur-3xl" />
+ <div className="relative space-y-3">
+ <div className="inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/10 px-3 py-1 text-sm text-cyan-100">
+ <ShieldCheck className="w-4 h-4" />
+ {t('remoteAccess.badge')}
+ </div>
+ <h1 className="text-3xl md:text-4xl font-display font-bold tracking-tight">{t('remoteAccess.title')}</h1>
+ <p className="text-cyan-50/80 max-w-2xl">{t('remoteAccess.subtitle')}</p>
+ </div>
+ </div>
+
+ <div className="grid lg:grid-cols-[1.1fr_0.9fr] gap-6">
+ <section className="rounded-2xl border border-border bg-panel p-6 space-y-5">
+ <div>
+ <h2 className="text-xl font-semibold flex items-center gap-2">
+ <KeyRound className="w-5 h-5 text-accent" />
+ {t('remoteAccess.connectTitle')}
+ </h2>
+ <p className="text-sm text-muted mt-1">{t('remoteAccess.connectDesc')}</p>
+ </div>
+
+ <label className="block space-y-2">
+ <span className="text-sm font-medium">{t('remoteAccess.backendUrl')}</span>
+ <input
+ className="w-full rounded-lg border border-border bg-bg px-3 py-2"
+ value={backendUrl}
+ onChange={(event) => setBackendUrl(event.target.value)}
+ placeholder="https://vibe.io"
+ />
+ </label>
+
+ <label className="block space-y-2">
+ <span className="text-sm font-medium">{t('remoteAccess.pairingKey')}</span>
+ <input
+ className="w-full rounded-lg border border-border bg-bg px-3 py-2 font-mono"
+ value={pairingKey}
+ onChange={(event) => setPairingKey(event.target.value)}
+ placeholder="vrp_xxxxxxxxxxxxxxxxx"
+ />
+ </label>
+
+ <button
+ type="button"
+ className="inline-flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-white font-medium disabled:opacity-50"
+ disabled={pairing || !pairingKey.trim() || !backendUrl.trim()}
+ onClick={pair}
+ >
+ <Link2 className="w-4 h-4" />
+ {pairing ? t('remoteAccess.pairing') : t('remoteAccess.pair')}
+ </button>
+ </section>
+
+ <section className="rounded-2xl border border-border bg-panel p-6 space-y-5">
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <h2 className="text-xl font-semibold">{t('remoteAccess.statusTitle')}</h2>
+ <p className="text-sm text-muted mt-1">{loading ? t('common.loading') : t('remoteAccess.statusDesc')}</p>
+ </div>
+ <button className="rounded-lg border border-border p-2 hover:bg-neutral-50" onClick={refresh} type="button">
+ <RefreshCcw className="w-4 h-4" />
+ </button>
+ </div>
+
+ <div className="grid grid-cols-2 gap-3 text-sm">
+ <div className="rounded-xl bg-neutral-50 p-4 border border-border">
+ <div className="text-muted">{t('remoteAccess.paired')}</div>
+ <div className="font-semibold mt-1">{paired ? t('common.enabled') : t('common.disabled')}</div>
+ </div>
+ <div className="rounded-xl bg-neutral-50 p-4 border border-border">
+ <div className="text-muted">{t('remoteAccess.connector')}</div>
+ <div className="font-semibold mt-1">{running ? t('common.running') : t('common.stopped')}</div>
+ </div>
+ </div>
+
+ {publicUrl && (
+ <a className="flex items-center justify-between rounded-xl border border-border p-4 hover:bg-neutral-50" href={publicUrl} target="_blank" rel="noreferrer">
+ <span className="font-mono text-sm truncate">{publicUrl}</span>
+ <ExternalLink className="w-4 h-4 shrink-0" />
+ </a>
+ )}
+
+ <div className="flex gap-3">
+ <button className="rounded-lg border border-border px-4 py-2 disabled:opacity-50" disabled={!paired || running} onClick={start} type="button">
+ <Power className="w-4 h-4 inline mr-2" />
+ {t('common.start')}
+ </button>
+ <button className="rounded-lg border border-border px-4 py-2 disabled:opacity-50" disabled={!paired || !running} onClick={stop} type="button">
+ {t('common.stop')}
+ </button>
+ </div>
+ </section>
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index d4d04609a..260098763 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -43,6 +43,10 @@ export type ApiContextType = {
getVersion: () => Promise<VersionInfo>;
doUpgrade: () => Promise<UpgradeResult>;
browseDirectory: (path: string, showHidden?: boolean) => Promise<{ ok: boolean; path?: string; parent?: string | null; dirs?: { name: string; path: string }[]; error?: string }>;
+ remoteAccessStatus: () => Promise<any>;
+ pairVibeCloudRemoteAccess: (payload: { backend_url: string; pairing_key: string; device_name?: string }) => Promise<any>;
+ startRemoteAccess: () => Promise<any>;
+ stopRemoteAccess: () => Promise<any>;
};
export type LogEntry = {
@@ -183,6 +187,10 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
getVersion: () => getJson('/version'),
doUpgrade: () => postJson('/upgrade', {}),
browseDirectory: (path, showHidden) => postJson('/browse', { path, show_hidden: showHidden || false }),
+ remoteAccessStatus: () => getJson('/remote-access/status'),
+ pairVibeCloudRemoteAccess: (payload) => postJson('/remote-access/vibe-cloud/pair', payload),
+ startRemoteAccess: () => postJson('/remote-access/start', {}),
+ stopRemoteAccess: () => postJson('/remote-access/stop', {}),
};
return <ApiContext.Provider value={value}>{children}</ApiContext.Provider>;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 63accb253..55bb4e275 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -42,8 +42,27 @@
"dashboard": "Dashboard",
"channels": "Groups",
"users": "Users",
+ "remoteAccess": "Remote Access",
"doctor": "Doctor"
},
+ "remoteAccess": {
+ "badge": "Vibe Cloud provider",
+ "title": "Remote Access",
+ "subtitle": "Expose this local admin UI at your Vibe Cloud hostname. Vibe Cloud handles OAuth; traffic goes directly through Cloudflare Tunnel to this machine.",
+ "connectTitle": "Connect to Vibe Cloud",
+ "connectDesc": "Create an instance in vibe.io, copy the pairing key, then paste it here. Vibe Remote will save the OAuth metadata and start cloudflared.",
+ "backendUrl": "Vibe Cloud URL",
+ "pairingKey": "Pairing key",
+ "pair": "Pair and start",
+ "pairing": "Pairing...",
+ "pairSuccess": "Remote access paired",
+ "startSuccess": "Remote access started",
+ "stopSuccess": "Remote access stopped",
+ "statusTitle": "Runtime status",
+ "statusDesc": "Connector and public URL status.",
+ "paired": "Pairing",
+ "connector": "Connector"
+ },
"appShell": {
"title": "Vibe Remote"
},
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 0db53f6bc..22ec6000d 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -42,8 +42,27 @@
"dashboard": "仪表盘",
"channels": "群组",
"users": "用户",
+ "remoteAccess": "远程访问",
"doctor": "诊断"
},
+ "remoteAccess": {
+ "badge": "Vibe Cloud Provider",
+ "title": "远程访问",
+ "subtitle": "把本地管理后台发布到 Vibe Cloud 分配的访问地址。Vibe Cloud 只负责 OAuth 授权,业务流量通过 Cloudflare Tunnel 直达本机。",
+ "connectTitle": "连接 Vibe Cloud",
+ "connectDesc": "在 vibe.io 创建实例后复制 Pairing Key,粘贴到这里。Vibe Remote 会保存 OAuth 元数据并启动 cloudflared。",
+ "backendUrl": "Vibe Cloud 地址",
+ "pairingKey": "Pairing Key",
+ "pair": "配对并启动",
+ "pairing": "配对中...",
+ "pairSuccess": "远程访问已配对",
+ "startSuccess": "远程访问已启动",
+ "stopSuccess": "远程访问已停止",
+ "statusTitle": "运行状态",
+ "statusDesc": "查看连接器和公网访问地址状态。",
+ "paired": "配对状态",
+ "connector": "连接器"
+ },
"appShell": {
"title": "Vibe Remote"
},
diff --git a/uv.lock b/uv.lock
index 7a714562d..0a43c7d77 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1881,6 +1881,7 @@ dependencies = [
{ name = "flask" },
{ name = "lark-oapi" },
{ name = "markdown-to-mrkdwn" },
+ { name = "pyjwt", extra = ["crypto"] },
{ name = "python-socks", extra = ["asyncio"] },
{ name = "pyyaml" },
{ name = "sentry-sdk" },
@@ -1895,11 +1896,12 @@ requires-dist = [
{ name = "aiohttp-socks", specifier = ">=0.8.0" },
{ name = "anyio", specifier = ">=4.0.0" },
{ name = "apscheduler", specifier = ">=3.10.4" },
- { name = "claude-agent-sdk", specifier = ">=0.1.23" },
+ { name = "claude-agent-sdk", specifier = ">=0.1.66" },
{ name = "discord-py", specifier = ">=2.4.0" },
{ name = "flask", specifier = ">=3.0.0" },
{ name = "lark-oapi", specifier = ">=1.4.0" },
{ name = "markdown-to-mrkdwn", specifier = ">=0.2.0" },
+ { name = "pyjwt", extras = ["crypto"], specifier = ">=2.9.0" },
{ name = "python-socks", extras = ["asyncio"], specifier = ">=2.0.0" },
{ name = "pyyaml", specifier = ">=6.0" },
{ name = "sentry-sdk", specifier = ">=2.0.0" },
diff --git a/vibe/api.py b/vibe/api.py
index 20af50097..a4d6226d4 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -340,6 +340,10 @@ def config_to_payload(config: V2Config) -> dict:
},
"gateway": config.gateway.__dict__ if config.gateway else None,
"ui": config.ui.__dict__,
+ "remote_access": {
+ "provider": config.remote_access.provider,
+ "vibe_cloud": config.remote_access.vibe_cloud.__dict__,
+ },
"update": config.update.__dict__,
"ack_mode": config.ack_mode,
"language": config.language,
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
new file mode 100644
index 000000000..bfb645361
--- /dev/null
+++ b/vibe/remote_access.py
@@ -0,0 +1,384 @@
+"""Vibe Cloud remote-access runtime and auth helpers."""
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import json
+import os
+import platform
+import secrets
+import shutil
+import stat
+import subprocess
+import tarfile
+import tempfile
+import threading
+import time
+import urllib.parse
+import urllib.request
+from pathlib import Path
+from typing import Any
+
+import jwt
+from jwt import PyJWKClient
+
+from config import paths
+from config.v2_config import V2Config
+from vibe import api, runtime
+
+CLOUDFLARED_BASE_URL = "https://github.com/cloudflare/cloudflared/releases/latest/download"
+SESSION_COOKIE_NAME = "__Host-vibe_remote_session"
+SESSION_TTL_SECONDS = 12 * 60 * 60
+_CONNECTOR_LOCK = threading.RLock()
+
+
+def _bin_dir() -> Path:
+ return paths.get_vibe_remote_dir() / "bin"
+
+
+def _managed_cloudflared_path() -> Path:
+ suffix = ".exe" if os.name == "nt" else ""
+ return _bin_dir() / f"cloudflared{suffix}"
+
+
+def _pid_path() -> Path:
+ return paths.get_runtime_remote_access_pid_path()
+
+
+def _state_path() -> Path:
+ return paths.get_runtime_dir() / "remote-access-cloudflared.json"
+
+
+def _asset_name() -> str:
+ system = platform.system().lower()
+ machine = platform.machine().lower()
+ arch = "amd64" if machine in {"x86_64", "amd64"} else "arm64" if machine in {"aarch64", "arm64"} else ""
+ if not arch:
+ raise ValueError(f"Unsupported architecture for cloudflared: {machine}")
+ if system == "linux":
+ return f"cloudflared-linux-{arch}"
+ if system == "darwin":
+ return f"cloudflared-darwin-{arch}.tgz"
+ if system == "windows" and arch == "amd64":
+ return "cloudflared-windows-amd64.exe"
+ raise ValueError(f"Unsupported OS for cloudflared: {system}")
+
+
+def _version(path: str) -> str | None:
+ try:
+ result = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=8, check=False)
+ except Exception:
+ return None
+ output = (result.stdout or result.stderr or "").strip().splitlines()
+ return output[0] if output else None
+
+
+def _make_executable(path: Path) -> None:
+ if os.name == "nt":
+ return
+ mode = path.stat().st_mode
+ path.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
+
+
+def _copy_stream_atomically(source: Any, target: Path) -> None:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ temp_target = target.with_name(f".{target.name}.tmp")
+ temp_target.unlink(missing_ok=True)
+ try:
+ with temp_target.open("wb") as output:
+ shutil.copyfileobj(source, output)
+ os.replace(temp_target, target)
+ except Exception:
+ temp_target.unlink(missing_ok=True)
+ raise
+
+
+def _safe_extract_cloudflared(archive: tarfile.TarFile, target: Path) -> None:
+ for member in archive.getmembers():
+ member_name = Path(member.name)
+ if member_name.name != "cloudflared":
+ continue
+ if member_name.is_absolute() or ".." in member_name.parts or not member.isfile():
+ raise RuntimeError("Downloaded cloudflared archive contained an unsafe entry")
+ source = archive.extractfile(member)
+ if source is None:
+ raise RuntimeError("Downloaded cloudflared archive did not contain a readable binary")
+ _copy_stream_atomically(source, target)
+ return
+ raise RuntimeError("Downloaded cloudflared archive did not contain cloudflared")
+
+
+def install_cloudflared() -> dict[str, Any]:
+ try:
+ paths.ensure_data_dirs()
+ asset = _asset_name()
+ url = f"{CLOUDFLARED_BASE_URL}/{asset}"
+ target = _managed_cloudflared_path()
+ with tempfile.TemporaryDirectory() as tmp:
+ download_path = Path(tmp) / asset
+ urllib.request.urlretrieve(url, download_path)
+ if asset.endswith(".tgz"):
+ with tarfile.open(download_path, "r:gz") as archive:
+ _safe_extract_cloudflared(archive, target)
+ else:
+ with download_path.open("rb") as source:
+ _copy_stream_atomically(source, target)
+ _make_executable(target)
+ return {"ok": True, "path": str(target), "version": _version(str(target)), "source_url": url}
+ except Exception as exc:
+ return {"ok": False, "error": "cloudflared_install_failed", "detail": str(exc)}
+
+
+def _resolve_binary(config: V2Config | None = None) -> str | None:
+ configured = ""
+ if config is not None:
+ configured = getattr(config.remote_access.vibe_cloud, "cloudflared_path", "") or ""
+ if configured:
+ expanded = Path(configured).expanduser()
+ if expanded.exists() and os.access(expanded, os.X_OK):
+ return str(expanded)
+ managed = _managed_cloudflared_path()
+ if managed.exists() and os.access(managed, os.X_OK):
+ return str(managed)
+ return shutil.which("cloudflared")
+
+
+def _read_pid() -> int | None:
+ try:
+ return int(_pid_path().read_text(encoding="utf-8").strip())
+ except Exception:
+ return None
+
+
+def _is_cloudflared_pid(pid: int | None) -> bool:
+ if not pid or not runtime.pid_alive(pid):
+ return False
+ command = runtime.get_process_command(pid) or ""
+ executable = command.strip().split(" ", 1)[0].strip("\"'")
+ return Path(executable).name.lower() in {"cloudflared", "cloudflared.exe"}
+
+
+def _write_state(pid: int, config: V2Config, binary: str) -> None:
+ cloud = config.remote_access.vibe_cloud
+ _state_path().write_text(
+ json.dumps(
+ {
+ "pid": pid,
+ "provider": "vibe_cloud",
+ "binary_path": binary,
+ "public_url": cloud.public_url,
+ "tunnel_token_sha256": hashlib.sha256((cloud.tunnel_token or "").encode("utf-8")).hexdigest(),
+ },
+ indent=2,
+ ),
+ encoding="utf-8",
+ )
+
+
+def status(config: V2Config | None = None) -> dict[str, Any]:
+ try:
+ config = config or V2Config.load()
+ except Exception:
+ config = None
+ pid = _read_pid()
+ running = _is_cloudflared_pid(pid)
+ if pid and not running:
+ _pid_path().unlink(missing_ok=True)
+ _state_path().unlink(missing_ok=True)
+ cloud = getattr(getattr(config, "remote_access", None), "vibe_cloud", None) if config else None
+ binary = _resolve_binary(config)
+ return {
+ "ok": True,
+ "provider": "vibe_cloud",
+ "enabled": bool(getattr(cloud, "enabled", False)),
+ "public_url": getattr(cloud, "public_url", "") if cloud else "",
+ "paired": bool(getattr(cloud, "instance_id", "") and getattr(cloud, "tunnel_token", "")) if cloud else False,
+ "running": running,
+ "pid": pid if running else None,
+ "binary_found": bool(binary),
+ "binary_path": binary,
+ "binary_version": _version(binary) if binary else None,
+ }
+
+
+def stop() -> dict[str, Any]:
+ with _CONNECTOR_LOCK:
+ pid = _read_pid()
+ if pid is not None and not _is_cloudflared_pid(pid):
+ _pid_path().unlink(missing_ok=True)
+ _state_path().unlink(missing_ok=True)
+ return {**status(), "ok": True, "stopped": False, "stale_pid": True}
+ stopped = runtime.stop_process(_pid_path(), timeout=8)
+ if stopped:
+ _state_path().unlink(missing_ok=True)
+ if pid is not None and not stopped and _is_cloudflared_pid(pid):
+ return {**status(), "ok": False, "error": "cloudflared_stop_failed", "stopped": False}
+ return {**status(), "ok": True, "stopped": stopped}
+
+
+def start(config: V2Config | None = None) -> dict[str, Any]:
+ with _CONNECTOR_LOCK:
+ config = config or V2Config.load()
+ cloud = config.remote_access.vibe_cloud
+ if not cloud.enabled:
+ return stop()
+ if not cloud.tunnel_token:
+ stop_result = stop()
+ return {**stop_result, "ok": False, "error": "missing_tunnel_token"}
+ binary = _resolve_binary(config)
+ if not binary:
+ install_result = install_cloudflared()
+ if install_result.get("ok") is False:
+ return {**status(config), **install_result}
+ binary = str(install_result["path"])
+ current = status(config)
+ if current.get("running"):
+ return {**current, "ok": True, "started": False}
+ env = {**os.environ, "TUNNEL_TOKEN": cloud.tunnel_token}
+ try:
+ pid = runtime.spawn_background(
+ [binary, "tunnel", "--no-autoupdate", "run"],
+ _pid_path(),
+ "remote_access_cloudflared_stdout.log",
+ "remote_access_cloudflared_stderr.log",
+ env=env,
+ )
+ _write_state(pid, config, binary)
+ except Exception as exc:
+ return {**status(config), "ok": False, "error": "cloudflared_spawn_failed", "detail": str(exc)}
+ time.sleep(0.2)
+ current = status(config)
+ if not current.get("running"):
+ return {**current, "ok": False, "error": "cloudflared_exited"}
+ return {**current, "ok": True, "started": True, "pid": pid}
+
+
+def reconcile(config: V2Config | None = None) -> dict[str, Any]:
+ config = config or V2Config.load()
+ if config.remote_access.provider == "vibe_cloud" and config.remote_access.vibe_cloud.enabled:
+ return start(config)
+ return stop()
+
+
+def _json_request(url: str, payload: dict[str, Any], timeout: float = 20.0) -> dict[str, Any]:
+ data = json.dumps(payload).encode("utf-8")
+ request = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}, method="POST")
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ return json.loads(response.read().decode("utf-8"))
+
+
+def pair(pairing_key: str, backend_url: str, device_name: str = "Vibe Remote") -> dict[str, Any]:
+ pairing_key = (pairing_key or "").strip()
+ backend_url = (backend_url or "https://vibe.io").strip().rstrip("/")
+ if not pairing_key:
+ return {"ok": False, "error": "missing_pairing_key"}
+ result = _json_request(
+ f"{backend_url}/api/v1/pairing/redeem",
+ {"pairing_key": pairing_key, "device_name": device_name, "local_version": "dev"},
+ )
+ required = ("instance_id", "client_id", "issuer", "authorization_endpoint", "token_endpoint", "jwks_uri", "public_url", "redirect_uri", "tunnel_token", "instance_secret")
+ missing = [field for field in required if not result.get(field)]
+ if missing:
+ return {"ok": False, "error": "invalid_pairing_response", "missing": missing}
+ config = api.load_config()
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.backend_url = backend_url
+ cloud.instance_id = result["instance_id"]
+ cloud.client_id = result["client_id"]
+ cloud.issuer = result["issuer"]
+ cloud.authorization_endpoint = result["authorization_endpoint"]
+ cloud.token_endpoint = result["token_endpoint"]
+ cloud.jwks_uri = result["jwks_uri"]
+ cloud.public_url = result["public_url"]
+ cloud.redirect_uri = result["redirect_uri"]
+ cloud.tunnel_token = result["tunnel_token"]
+ cloud.instance_secret = result["instance_secret"]
+ cloud.session_secret = cloud.session_secret or secrets.token_urlsafe(32)
+ config.save()
+ start_result = start(config)
+ return {**status(config), "ok": start_result.get("ok", False), "pairing": "ok", "start": start_result}
+
+
+def _session_signature(secret: str, payload: str) -> str:
+ return hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
+
+
+def make_session_cookie(config: V2Config, email: str, subject: str) -> str:
+ cloud = config.remote_access.vibe_cloud
+ issued_at = int(time.time())
+ payload = {
+ "email": email,
+ "sub": subject,
+ "instance_id": cloud.instance_id,
+ "iat": issued_at,
+ "exp": issued_at + SESSION_TTL_SECONDS,
+ }
+ payload_text = urllib.parse.quote(json.dumps(payload, separators=(",", ":")), safe="")
+ signature = _session_signature(cloud.session_secret, payload_text)
+ return f"{payload_text}.{signature}"
+
+
+def validate_session_cookie(config: V2Config, cookie_value: str | None) -> bool:
+ if not cookie_value or "." not in cookie_value:
+ return False
+ cloud = config.remote_access.vibe_cloud
+ payload_text, signature = cookie_value.rsplit(".", 1)
+ expected = _session_signature(cloud.session_secret, payload_text)
+ if not hmac.compare_digest(signature, expected):
+ return False
+ try:
+ payload = json.loads(urllib.parse.unquote(payload_text))
+ except Exception:
+ return False
+ return payload.get("instance_id") == cloud.instance_id and int(payload.get("exp", 0)) > int(time.time())
+
+
+def authorization_url(config: V2Config, state: str, nonce: str, code_challenge: str) -> str:
+ cloud = config.remote_access.vibe_cloud
+ params = {
+ "client_id": cloud.client_id,
+ "redirect_uri": cloud.redirect_uri,
+ "response_type": "code",
+ "scope": "openid email",
+ "state": state,
+ "nonce": nonce,
+ "code_challenge": code_challenge,
+ "code_challenge_method": "S256",
+ }
+ if cloud.dev_login_hint:
+ params["login_hint"] = cloud.dev_login_hint
+ return f"{cloud.authorization_endpoint}?{urllib.parse.urlencode(params)}"
+
+
+def exchange_oauth_code(config: V2Config, code: str, code_verifier: str) -> dict[str, Any]:
+ cloud = config.remote_access.vibe_cloud
+ data = urllib.parse.urlencode(
+ {
+ "grant_type": "authorization_code",
+ "client_id": cloud.client_id,
+ "redirect_uri": cloud.redirect_uri,
+ "code": code,
+ "code_verifier": code_verifier,
+ }
+ ).encode("utf-8")
+ request = urllib.request.Request(
+ cloud.token_endpoint,
+ data=data,
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ method="POST",
+ )
+ with urllib.request.urlopen(request, timeout=20) as response:
+ token_payload = json.loads(response.read().decode("utf-8"))
+ id_token = token_payload.get("id_token")
+ if not id_token:
+ raise ValueError("missing_id_token")
+ jwk_client = PyJWKClient(cloud.jwks_uri)
+ signing_key = jwk_client.get_signing_key_from_jwt(id_token)
+ claims = jwt.decode(id_token, signing_key.key, algorithms=["RS256"], audience=cloud.client_id, issuer=cloud.issuer)
+ if claims.get("vibe_instance_id") != cloud.instance_id:
+ raise ValueError("invalid_instance_id")
+ if not claims.get("email_verified"):
+ raise ValueError("email_not_verified")
+ return {"claims": claims, "token": token_payload}
diff --git a/vibe/runtime.py b/vibe/runtime.py
index 398e0a8fb..fcfebf5c3 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -363,12 +363,19 @@ def start_service():
def start_ui(host, port):
command = "from vibe.ui_server import run_ui_server; run_ui_server('{}', {})".format(host, port)
- return spawn_background(
+ pid = spawn_background(
[sys.executable, "-c", command],
paths.get_runtime_ui_pid_path(),
"ui_stdout.log",
"ui_stderr.log",
)
+ try:
+ from vibe import remote_access
+
+ remote_access.reconcile()
+ except Exception:
+ logger.warning("Failed to reconcile remote access after UI start", exc_info=True)
+ return pid
def stop_service():
@@ -377,4 +384,14 @@ def stop_service():
def stop_ui():
+ try:
+ from vibe import remote_access
+
+ result = remote_access.stop()
+ if isinstance(result, dict) and result.get("ok") is False:
+ logger.warning("Failed to stop remote access before UI stop: %s", result.get("error"))
+ return False
+ except Exception:
+ logger.warning("Failed to stop remote access before UI stop", exc_info=True)
+ return False
return stop_process(paths.get_runtime_ui_pid_path())
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 8902b8a58..2d98e1aef 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1,4 +1,6 @@
import asyncio
+import base64
+import hashlib
import hmac
import json
import logging
@@ -10,7 +12,7 @@ import threading
from datetime import datetime
from pathlib import Path
from typing import Any
-from urllib.parse import urlparse
+from urllib.parse import quote, unquote, urlparse
from flask import Flask, request, jsonify, send_file, Response
@@ -37,6 +39,7 @@ TRACEBACK_EXCEPTION_PATTERN = re.compile(
)
CSRF_COOKIE_NAME = "vibe_csrf_token"
CSRF_HEADER_NAME = "X-Vibe-CSRF-Token"
+REMOTE_OAUTH_COOKIE_NAME = "__Host-vibe_remote_oauth"
MUTATING_METHODS = {"POST", "PUT", "PATCH", "DELETE"}
LOG_SOURCES = (
("service", "vibe_remote.log", lambda: paths.get_logs_dir() / "vibe_remote.log"),
@@ -153,6 +156,8 @@ def _current_origin() -> str:
def _is_mutation_guard_exempt() -> bool:
+ if request.path in {"/auth/callback"}:
+ return True
return (
request.path == "/e2e/simulate-interaction"
and os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes")
@@ -178,6 +183,102 @@ def _ensure_csrf_cookie(response: Response) -> Response:
return response
+def _load_remote_access_config() -> V2Config | None:
+ try:
+ return V2Config.load()
+ except Exception:
+ return None
+
+
+def _is_remote_access_request(config: V2Config) -> bool:
+ cloud = config.remote_access.vibe_cloud
+ if not cloud.enabled or not cloud.public_url:
+ return False
+ public_host = urlparse(cloud.public_url).netloc.lower()
+ return bool(public_host and request.host.lower() == public_host)
+
+
+def _remote_auth_exempt_path() -> bool:
+ path = request.path
+ return (
+ path == "/health"
+ or path == "/auth/callback"
+ or path.startswith("/assets/")
+ or path == "/favicon.ico"
+ )
+
+
+def _oauth_cookie_signature(secret: str, payload: str) -> str:
+ return hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
+
+
+def _make_oauth_cookie(secret: str, payload: dict[str, Any]) -> str:
+ payload_text = quote(json.dumps(payload, separators=(",", ":")), safe="")
+ signature = _oauth_cookie_signature(secret, payload_text)
+ return f"{payload_text}.{signature}"
+
+
+def _read_oauth_cookie(secret: str, value: str | None) -> dict[str, Any] | None:
+ if not value or "." not in value:
+ return None
+ payload_text, signature = value.rsplit(".", 1)
+ if not hmac.compare_digest(signature, _oauth_cookie_signature(secret, payload_text)):
+ return None
+ try:
+ payload = json.loads(unquote(payload_text))
+ except Exception:
+ return None
+ if int(payload.get("exp", 0)) <= int(datetime.now().timestamp()):
+ return None
+ return payload if isinstance(payload, dict) else None
+
+
+def _redirect_to_vibe_cloud_login(config: V2Config):
+ from vibe import remote_access
+
+ cloud = config.remote_access.vibe_cloud
+ code_verifier = secrets.token_urlsafe(48)
+ digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
+ code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
+ state = secrets.token_urlsafe(24)
+ nonce = secrets.token_urlsafe(24)
+ oauth_cookie = _make_oauth_cookie(
+ cloud.session_secret,
+ {
+ "state": state,
+ "nonce": nonce,
+ "code_verifier": code_verifier,
+ "next": request.full_path if request.query_string else request.path,
+ "exp": int(datetime.now().timestamp()) + 300,
+ },
+ )
+ response = Response(status=302)
+ response.headers["Location"] = remote_access.authorization_url(config, state, nonce, code_challenge)
+ response.set_cookie(
+ REMOTE_OAUTH_COOKIE_NAME,
+ oauth_cookie,
+ httponly=True,
+ secure=True,
+ samesite="Lax",
+ path="/",
+ )
+ return response
+
+
+def enforce_remote_access_cookie():
+ config = _load_remote_access_config()
+ if config is None or not _is_remote_access_request(config) or _remote_auth_exempt_path():
+ return None
+ from vibe import remote_access
+
+ if remote_access.validate_session_cookie(config, request.cookies.get(remote_access.SESSION_COOKIE_NAME)):
+ return None
+ if request.method == "GET":
+ return _redirect_to_vibe_cloud_login(config)
+ return jsonify({"ok": False, "error": "remote_access_login_required"}), 401
+
+
@app.before_request
def protect_mutating_ui_requests():
if request.method not in MUTATING_METHODS:
@@ -432,12 +533,84 @@ def control():
@app.route("/config", methods=["POST"])
def config_post():
from vibe import api
+ from vibe import remote_access
payload = request.json or {}
config = api.save_config(payload)
+ if "remote_access" in payload:
+ result = remote_access.reconcile(config)
+ if result.get("ok") is False:
+ return jsonify({"ok": False, "error": result.get("error", "remote_access_reconcile_failed"), "remote_access": result, "config": api.config_to_payload(config)}), 500
return jsonify(api.config_to_payload(config))
[email protected]("/remote-access/status", methods=["GET"])
+def remote_access_status():
+ from vibe import remote_access
+
+ return jsonify(remote_access.status())
+
+
[email protected]("/remote-access/vibe-cloud/pair", methods=["POST"])
+def remote_access_vibe_cloud_pair():
+ from vibe import remote_access
+
+ payload = request.json or {}
+ result = remote_access.pair(
+ payload.get("pairing_key", ""),
+ payload.get("backend_url", "https://vibe.io"),
+ payload.get("device_name", "Vibe Remote"),
+ )
+ return jsonify(result), 200 if result.get("ok") else 400
+
+
[email protected]("/remote-access/start", methods=["POST"])
+def remote_access_start():
+ from vibe import remote_access
+
+ result = remote_access.start()
+ return jsonify(result), 200 if result.get("ok") else 400
+
+
[email protected]("/remote-access/stop", methods=["POST"])
+def remote_access_stop():
+ from vibe import remote_access
+
+ result = remote_access.stop()
+ return jsonify(result), 200 if result.get("ok") else 400
+
+
[email protected]("/auth/callback", methods=["GET"])
+def remote_access_auth_callback():
+ from vibe import remote_access
+
+ config = _load_remote_access_config()
+ if config is None or not _is_remote_access_request(config):
+ return jsonify({"error": "remote_access_not_enabled"}), 400
+ cloud = config.remote_access.vibe_cloud
+ oauth_state = _read_oauth_cookie(cloud.session_secret, request.cookies.get(REMOTE_OAUTH_COOKIE_NAME))
+ if not oauth_state or oauth_state.get("state") != request.args.get("state"):
+ return jsonify({"error": "invalid_oauth_state"}), 400
+ try:
+ result = remote_access.exchange_oauth_code(config, request.args.get("code", ""), oauth_state["code_verifier"])
+ claims = result["claims"]
+ except Exception as exc:
+ return jsonify({"error": "oauth_exchange_failed", "detail": str(exc)}), 400
+ response = Response(status=302)
+ response.headers["Location"] = str(oauth_state.get("next") or "/")
+ response.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, str(claims.get("email", "")), str(claims.get("sub", ""))),
+ httponly=True,
+ secure=True,
+ samesite="Lax",
+ path="/",
+ max_age=remote_access.SESSION_TTL_SECONDS,
+ )
+ response.delete_cookie(REMOTE_OAUTH_COOKIE_NAME, path="/", secure=True, samesite="Lax")
+ return response
+
+
@app.route("/ui/reload", methods=["POST"])
def ui_reload():
from vibe import runtime