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.

fix(codex): clear user-owned relay pointer on OAuth save

cyh28efd8bb4591
diff --git a/tests/test_codex_config.py b/tests/test_codex_config.py
index 68154175a..a68655000 100644
--- a/tests/test_codex_config.py
+++ b/tests/test_codex_config.py
@@ -317,3 +317,90 @@ def test_apply_oauth_mode_clears_managed_base_url(tmp_path: Path) -> None:
parsed = tomllib.loads((codex_home / "config.toml").read_text(encoding="utf-8"))
assert "model_providers" not in parsed
+
+
+def test_apply_oauth_clears_user_owned_relay_pointer_with_base_url(tmp_path: Path) -> None:
+ """OAuth tokens don't validate against custom relays — clear the pointer.
+
+ Real-world failure mode: user originally set up API-key auth through a
+ relay (``model_provider = "OpenAI"`` → ``[model_providers.OpenAI]``
+ with ``base_url = "https://ai-relay.example.com"``). They switch to
+ OAuth via the UI; we previously preserved the user-owned pointer,
+ which sent OAuth bearer tokens to the relay. The relay returned
+ ``401 INVALID_API_KEY`` (it only accepts API keys), bricking the
+ save. Now: when switching to OAuth, clear the pointer if it targets
+ a section with a custom base_url. The section itself stays for the
+ user to re-point later (or for switching back to api_key mode).
+ """
+ home = tmp_path
+ codex_home = home / ".codex"
+ codex_home.mkdir()
+ seed = (
+ 'model_provider = "OpenAI"\n'
+ 'cli_auth_credentials_store = "file"\n'
+ "\n"
+ "[model_providers.OpenAI]\n"
+ 'name = "OpenAI"\n'
+ 'base_url = "https://ai-relay.example.com"\n'
+ 'wire_api = "responses"\n'
+ )
+ (codex_home / "config.toml").write_text(seed, encoding="utf-8")
+ (codex_home / "auth.json").write_text(
+ json.dumps({"OPENAI_API_KEY": "sk-old", "tokens": {"id_token": "abc"}}),
+ encoding="utf-8",
+ )
+
+ result = codex_config.apply_codex_auth(
+ auth_mode="oauth",
+ api_key=None,
+ base_url=None,
+ home=home,
+ )
+
+ # The pointer is gone — Codex now falls back to the built-in
+ # ``openai`` provider with the default endpoint, where OAuth tokens
+ # actually validate.
+ parsed = tomllib.loads((codex_home / "config.toml").read_text(encoding="utf-8"))
+ assert "model_provider" not in parsed
+ # The user's section is left intact so they can manually re-point
+ # later or re-use it when switching back to api_key mode.
+ assert parsed["model_providers"]["OpenAI"]["base_url"] == "https://ai-relay.example.com"
+ assert parsed["model_providers"]["OpenAI"]["wire_api"] == "responses"
+
+ notices = result["notices"]
+ assert len(notices) == 1
+ assert notices[0]["code"] == "cleared_custom_relay_pointer"
+ assert notices[0]["provider_id"] == "OpenAI"
+ assert notices[0]["base_url"] == "https://ai-relay.example.com"
+
+
+def test_apply_oauth_leaves_user_owned_pointer_when_no_base_url(tmp_path: Path) -> None:
+ """A pointer to a section without ``base_url`` isn't a relay — leave it.
+
+ Some users wire ``model_provider`` at a built-in alias (e.g. one that
+ inherits OpenAI's default endpoint via an inherited ``[provider]``
+ block) for naming reasons. Without a ``base_url`` there is no relay
+ conflict — OAuth tokens go to the default endpoint and validate.
+ """
+ home = tmp_path
+ codex_home = home / ".codex"
+ codex_home.mkdir()
+ seed = (
+ 'model_provider = "CustomLabel"\n'
+ "\n"
+ "[model_providers.CustomLabel]\n"
+ 'name = "Custom"\n'
+ 'wire_api = "responses"\n'
+ )
+ (codex_home / "config.toml").write_text(seed, encoding="utf-8")
+
+ result = codex_config.apply_codex_auth(
+ auth_mode="oauth",
+ api_key=None,
+ base_url=None,
+ home=home,
+ )
+
+ parsed = tomllib.loads((codex_home / "config.toml").read_text(encoding="utf-8"))
+ assert parsed["model_provider"] == "CustomLabel"
+ assert result["notices"] == []
diff --git a/ui/src/components/settings/SettingsCodexProviderPage.tsx b/ui/src/components/settings/SettingsCodexProviderPage.tsx
index 13b57271a..87a790d05 100644
--- a/ui/src/components/settings/SettingsCodexProviderPage.tsx
+++ b/ui/src/components/settings/SettingsCodexProviderPage.tsx
@@ -10,7 +10,7 @@ import { Card, CardContent } from '../ui/card';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { useApi } from '@/context/ApiContext';
-import type { CodexAuthMode, CodexAuthState } from '@/context/ApiContext';
+import type { BackendNotice, CodexAuthMode, CodexAuthState } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
import { BackendOAuthPanel } from './BackendOAuthPanel';
import { BackendTestPanel } from './BackendTestPanel';
@@ -130,6 +130,33 @@ export const SettingsCodexProviderPage: React.FC = () => {
? t('settings.backends.codexApiKeyConfigured', { length: state.api_key_length })
: t('settings.backends.codexApiKeyMissing');
+ // Surface non-fatal config-rewrite warnings from the server as warning
+ // toasts. Today the only emitter is ``cleared_custom_relay_pointer``
+ // (an OAuth switch where the user's ``model_provider`` pointed at a
+ // custom relay whose ``base_url`` won't accept OAuth tokens — we
+ // cleared the pointer so Codex falls back to OpenAI's default
+ // endpoint). Without this banner the user sees a green "saved" toast
+ // and then a 401 on their next message.
+ const surfaceNotices = (notices: BackendNotice[] | undefined) => {
+ if (!notices || notices.length === 0) return;
+ for (const notice of notices) {
+ if (notice.code === 'cleared_custom_relay_pointer') {
+ showToast(
+ t('settings.backends.codexNoticeClearedRelayPointer', {
+ provider: notice.provider_id || 'custom',
+ url: notice.base_url || '',
+ }),
+ 'warning',
+ );
+ } else {
+ showToast(
+ t('settings.backends.codexNoticeGeneric', { code: notice.code }),
+ 'warning',
+ );
+ }
+ }
+ };
+
const onRemoveApiKey = async () => {
// Drop just the API key (V2Config + auth.json's OPENAI_API_KEY),
// leave OAuth tokens intact. Codex's CLI prefers the API key when
@@ -158,6 +185,7 @@ export const SettingsCodexProviderPage: React.FC = () => {
setApiKey('');
setEditingKey(false);
showToast(t('settings.backends.codexApiKeyRemoved'), 'success');
+ surfaceNotices(result.notices);
} catch (err: any) {
showToast(
t('settings.backends.codexApiKeyRemoveFailed', { detail: err?.message || 'unknown' }),
@@ -211,6 +239,7 @@ export const SettingsCodexProviderPage: React.FC = () => {
} else {
showToast(t('settings.backends.codexSaveSuccess'), 'success');
}
+ surfaceNotices(result.notices);
} catch (err: any) {
showToast(err?.message || t('settings.backends.codexSaveFailed'), 'error');
} finally {
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 0a9418d38..29353ad41 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -222,8 +222,20 @@ export type CodexAuthPayload = {
base_url?: string | null;
};
+// Non-fatal warning the server attached to a config-mutation response.
+// Used today for "we cleared a custom relay pointer because OAuth tokens
+// won't validate against your custom base_url"; new codes can be added
+// without touching the type.
+export type BackendNotice = {
+ code: string;
+ provider_id?: string;
+ base_url?: string;
+ detail?: string;
+};
+
export type CodexAuthSaveResult = CodexAuthState & {
restart?: BackendRestartResult;
+ notices?: BackendNotice[];
};
export type ClaudeAuthMode = 'oauth' | 'api_key';
@@ -315,6 +327,7 @@ export type OAuthWebMutationResult = {
ok: boolean;
error?: string;
detail?: string;
+ notices?: BackendNotice[];
};
export type BackendAuthTestResult = {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index f991059ed..c642dc1a2 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -215,6 +215,8 @@
"codexApiKeyRemoveConfirm": "Remove the stored OpenAI API key from auth.json? Codex will fall back to OAuth tokens if present, or sit unconfigured if not.",
"codexApiKeyRemoved": "Stored OpenAI API key removed.",
"codexApiKeyRemoveFailed": "Could not remove API key: {{detail}}",
+ "codexNoticeClearedRelayPointer": "Cleared the custom relay pointer ({{provider}} → {{url}}) because OAuth tokens won't validate against a custom base URL. Codex will now use OpenAI's default endpoint. To switch back, re-add an API key or edit ~/.codex/config.toml manually.",
+ "codexNoticeGeneric": "Config notice: {{code}}",
"opencodeProviderSignIn": "Sign in",
"opencodeProviderOauthSignedIn": "OAuth credentials stored.",
"opencodeProviderOauthPanelTitle": "Sign in to {{name}}",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 3fdf9e6b4..75100f116 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -215,6 +215,8 @@
"codexApiKeyRemoveConfirm": "确定要从 auth.json 移除已保存的 OpenAI API Key 吗?如果有 OAuth 凭据,Codex 会回落到 OAuth;否则会变成未配置状态。",
"codexApiKeyRemoved": "已移除 OpenAI API Key。",
"codexApiKeyRemoveFailed": "移除 API Key 失败:{{detail}}",
+ "codexNoticeClearedRelayPointer": "已清除自定义中继指向({{provider}} → {{url}}):OAuth 凭据无法被自定义 base_url 验证,Codex 将改为使用 OpenAI 官方端点。如需切回,请重新添加 API Key 或手动编辑 ~/.codex/config.toml。",
+ "codexNoticeGeneric": "配置提示:{{code}}",
"opencodeProviderSignIn": "登录",
"opencodeProviderOauthSignedIn": "OAuth 凭据已保存。",
"opencodeProviderOauthPanelTitle": "登录 {{name}}",
diff --git a/vibe/api.py b/vibe/api.py
index 21c6ba072..b4b6d29dc 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -2283,11 +2283,16 @@ def remove_backend_api_key(backend: str) -> dict:
if backend not in {"claude", "codex"}:
return {"ok": False, "error": "unsupported_backend"}
+ notices: list = []
if backend == "codex":
from vibe.codex_config import apply_codex_auth
try:
- apply_codex_auth(auth_mode="oauth", api_key=None, base_url=None)
+ result = apply_codex_auth(auth_mode="oauth", api_key=None, base_url=None)
+ if isinstance(result, dict):
+ raw_notices = result.get("notices")
+ if isinstance(raw_notices, list):
+ notices = raw_notices
except Exception as exc: # noqa: BLE001
logger.error("apply_codex_auth(oauth) during remove-key failed: %s", exc, exc_info=True)
return {"ok": False, "error": "remove_failed", "detail": str(exc)}
@@ -2323,7 +2328,10 @@ def remove_backend_api_key(backend: str) -> dict:
"ok": True,
"message": "Claude relaunches per request; the next message uses the new auth.",
}
- return {"ok": True, "restart": restart}
+ response: dict = {"ok": True, "restart": restart}
+ if notices:
+ response["notices"] = notices
+ return response
def test_backend_auth(backend: str, model: Optional[str] = None) -> dict:
@@ -2550,8 +2558,15 @@ def save_codex_auth(payload: dict) -> dict:
from vibe.codex_config import apply_codex_auth
+ notices: list = []
try:
- apply_codex_auth(auth_mode=auth_mode, api_key=api_key, base_url=effective_base_url)
+ result = apply_codex_auth(
+ auth_mode=auth_mode, api_key=api_key, base_url=effective_base_url
+ )
+ if isinstance(result, dict):
+ raw_notices = result.get("notices")
+ if isinstance(raw_notices, list):
+ notices = raw_notices
except ValueError as exc:
return {"ok": False, "message": str(exc)}
except OSError as exc:
@@ -2571,6 +2586,13 @@ def save_codex_auth(payload: dict) -> dict:
restart_result = restart_backend("codex")
state = get_codex_auth()
state["restart"] = restart_result
+ if notices:
+ # Surface non-fatal config-rewrite notices (e.g. "we cleared a
+ # custom relay pointer because OAuth tokens won't validate
+ # against ai-relay.chainbot.io") so the UI can show a one-time
+ # banner. Without this the user sees a green "saved" toast then
+ # hits a confusing 401 on their next request.
+ state["notices"] = notices
if not restart_result.get("ok", False):
# Config written, restart failed — tell the UI both so the toast
# can say "saved, but you may need to restart Codex manually".
diff --git a/vibe/codex_config.py b/vibe/codex_config.py
index 7023d3a73..804d2b604 100644
--- a/vibe/codex_config.py
+++ b/vibe/codex_config.py
@@ -276,16 +276,21 @@ def apply_codex_auth(
api_key: Optional[str],
base_url: Optional[str],
home: Path | None = None,
-) -> None:
+) -> Dict[str, Any]:
"""Persist the requested auth mode into Codex's on-disk config files.
- ``api_key`` mode: write ``OPENAI_API_KEY`` into ``auth.json``,
- optionally set ``[model_providers.openai].base_url`` if a non-default
- URL was supplied, and pin top-level ``model_provider = "openai"`` so
- Codex actually uses the keyed provider.
+ optionally set ``[model_providers.openai-managed].base_url`` if a
+ non-default URL was supplied, and pin top-level ``model_provider``
+ to the managed entry so Codex actually uses the keyed provider.
- ``oauth`` mode: drop ``OPENAI_API_KEY`` from ``auth.json``, leave any
``tokens`` blob in place, and clear our managed ``base_url`` so the
next launch goes back to OpenAI's default endpoint.
+
+ Returns ``{"notices": [{code, ...}, ...]}`` — non-fatal warnings the
+ caller may want to surface in the UI (e.g. "we cleared a custom
+ relay pointer that won't accept OAuth tokens"). An empty list means
+ the save was a no-op transformation.
"""
if auth_mode not in {"oauth", "api_key"}:
raise ValueError(f"Unsupported codex auth_mode: {auth_mode!r}")
@@ -293,6 +298,7 @@ def apply_codex_auth(
config_path, auth_path = get_codex_config_paths(home)
auth_data = _load_auth(auth_path)
toml_data = _load_toml(config_path)
+ notices: list[Dict[str, Any]] = []
providers = toml_data.setdefault("model_providers", {})
if not isinstance(providers, dict):
@@ -340,11 +346,34 @@ def apply_codex_auth(
# leaving it behind under the legacy reserved name (``openai``)
# makes newer Codex versions refuse to load the config at all.
providers.pop(MANAGED_PROVIDER_ID, None)
- # Revert top-level ``model_provider`` if we own it.
current_mp = toml_data.get("model_provider")
managed_known = {MANAGED_PROVIDER_ID, *LEGACY_MANAGED_PROVIDER_IDS}
if isinstance(current_mp, str) and current_mp in managed_known:
+ # Revert top-level ``model_provider`` if we own it.
toml_data.pop("model_provider", None)
+ elif isinstance(current_mp, str) and current_mp:
+ # User-owned pointer (e.g. a TitleCase ``[model_providers.OpenAI]``
+ # relay block). OAuth tokens are issued by ``auth.openai.com``
+ # and only validated by OpenAI's official Responses endpoint —
+ # a custom relay almost never accepts them and returns
+ # ``401 INVALID_API_KEY``. If the pointed section has a
+ # ``base_url``, clear the pointer so Codex falls back to its
+ # built-in ``openai`` provider with the default endpoint.
+ # The section itself stays untouched, so switching back to
+ # api_key mode can manually re-point at the relay if the user
+ # wants.
+ ptr_section = providers.get(current_mp)
+ if isinstance(ptr_section, dict):
+ ptr_base = ptr_section.get("base_url")
+ if isinstance(ptr_base, str) and ptr_base.strip():
+ toml_data.pop("model_provider", None)
+ notices.append(
+ {
+ "code": "cleared_custom_relay_pointer",
+ "provider_id": current_mp,
+ "base_url": ptr_base.strip(),
+ }
+ )
# Always purge any legacy reserved-name section we may have written
# in older releases. Codex 1.x refuses to load a config that defines
@@ -357,6 +386,7 @@ def apply_codex_auth(
_atomic_write(auth_path, json.dumps(auth_data, indent=2) + "\n", mode=0o600)
_atomic_write(config_path, _dump_toml(toml_data), mode=0o600)
+ return {"notices": notices}
def read_codex_api_key(home: Path | None = None) -> Optional[str]: