Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(llm): add first-party OpenAI Codex OAuth provider (#690)

TyrionH-is-codingc3d1dd0b15e4
diff --git a/README.md b/README.md
index 154f621b7..d65cb2b30 100644
--- a/README.md
+++ b/README.md
@@ -619,6 +619,8 @@ Settings is the operational control plane, with a live status strip (Backend, LL
Most sections use a draft-and-apply flow, so you can test a provider before committing it. Four themes ship in the box — Default, Cream, Dark, and Glass. Project-root `.env` files are intentionally ignored; runtime configuration lives under `data/user/settings/*.json` unless `DEEPTUTOR_HOME` or `deeptutor start --home` points the app elsewhere.
+**OpenAI Codex OAuth (experimental).** Picking **OpenAI Codex** under Models → LLM replaces the API-key fields with a browser sign-in that runs against your own ChatGPT plan, so no `OPENAI_API_KEY` is needed. Tokens live only in `<user-root>/private/openai-codex/` and DeepTutor never reads or modifies your `~/.codex` CLI login. The model list comes from that account's live catalog; signing in publishes the profile but only becomes the active model when no LLM is configured yet, so it never repoints a deployment behind your back. Because a token authorizes one person's plan, the profile is not shareable through user grants — each account signs in for itself, and the browser has to reach the machine running the backend (on a remote server run `deeptutor provider login openai-codex` there instead). Quota errors and catalog failures are reported as-is and never fall back to a paid provider. This compatibility path is experimental: the upstream interface may change.
+
</details>
<details>
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..42e3d0439
--- /dev/null
+++ b/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,38 @@
+# Third-party notices
+
+## CSSwitch
+
+- Project: [SuperJJ007/CSSwitch](https://github.com/SuperJJ007/CSSwitch)
+- Source commit: `4e0af6ba7909dca22f1257b168172ecbe4af4836`
+- License: MIT
+- Copyright: Copyright (c) 2026 shanjunjie
+- Adapted concepts: PKCE loopback login, auth generations, atomic credential updates, model-catalog cache invalidation, and redacted operation states.
+
+DeepTutor's Codex OAuth support draws on the design concepts listed above and
+implements them independently against DeepTutor's own settings directory, model
+catalog, and provider lifecycle. The MIT license text from that source commit
+follows:
+
+```text
+MIT License
+
+Copyright (c) 2026 shanjunjie
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+```
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index 26f5ddc1b..25f3a2bb4 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -21,6 +21,7 @@ logger = logging.getLogger(__name__)
from deeptutor.multi_user.context import get_current_user
from deeptutor.multi_user.model_access import allowed_llm_options
+from deeptutor.services.codex_auth import CodexAuthError, get_codex_oauth_service
from deeptutor.services.config import (
get_config_test_runner,
get_model_catalog_service,
@@ -331,7 +332,17 @@ def _require_settings_admin() -> None:
)
-def _provider_choices() -> dict[str, list[dict[str, str]]]:
+def _codex_http_exception(error: CodexAuthError) -> HTTPException:
+ return HTTPException(
+ status_code=error.http_status,
+ detail={
+ "code": error.code,
+ "message": error.public_message,
+ },
+ )
+
+
+def _provider_choices() -> dict[str, list[dict[str, Any]]]:
"""Build dropdown options for provider selection, keyed by service type."""
from deeptutor.services.config.provider_runtime import (
EMBEDDING_PROVIDERS,
@@ -354,6 +365,7 @@ def _provider_choices() -> dict[str, list[dict[str, str]]]:
else s.label
),
"base_url": s.default_api_base,
+ "auth_mode": s.auth_mode,
}
for s in PROVIDERS
],
@@ -508,6 +520,51 @@ async def get_settings():
}
[email protected]("/providers/openai-codex/oauth/start")
+async def start_openai_codex_oauth() -> dict[str, Any]:
+ _require_settings_admin()
+ try:
+ return await get_codex_oauth_service().start_login()
+ except CodexAuthError as exc:
+ raise _codex_http_exception(exc) from None
+
+
[email protected]("/providers/openai-codex/oauth/status")
+async def get_openai_codex_oauth_status() -> dict[str, Any]:
+ _require_settings_admin()
+ try:
+ return get_codex_oauth_service().public_status()
+ except CodexAuthError as exc:
+ raise _codex_http_exception(exc) from None
+
+
[email protected]("/providers/openai-codex/oauth/cancel")
+async def cancel_openai_codex_oauth() -> dict[str, Any]:
+ _require_settings_admin()
+ try:
+ return await get_codex_oauth_service().cancel_login()
+ except CodexAuthError as exc:
+ raise _codex_http_exception(exc) from None
+
+
[email protected]("/providers/openai-codex/oauth/logout")
+async def logout_openai_codex_oauth() -> dict[str, Any]:
+ _require_settings_admin()
+ try:
+ return await get_codex_oauth_service().logout()
+ except CodexAuthError as exc:
+ raise _codex_http_exception(exc) from None
+
+
[email protected]("/providers/openai-codex/models/refresh")
+async def refresh_openai_codex_models() -> dict[str, Any]:
+ _require_settings_admin()
+ try:
+ return await get_codex_oauth_service().refresh_models()
+ except CodexAuthError as exc:
+ raise _codex_http_exception(exc) from None
+
+
@router.get("/catalog")
async def get_catalog():
_require_settings_admin()
diff --git a/deeptutor/core/agentic/client.py b/deeptutor/core/agentic/client.py
index 7d5a85117..79d6e2de8 100644
--- a/deeptutor/core/agentic/client.py
+++ b/deeptutor/core/agentic/client.py
@@ -95,10 +95,11 @@ def _build_anthropic_adapter(config: LLMClientConfig, spec: Any) -> Any:
def _build_codex_adapter(config: LLMClientConfig, spec: Any) -> Any:
+ from deeptutor.services.codex_auth.constants import CODEX_DEFAULT_MODEL_ID
from deeptutor.services.llm.provider_core import OpenAICodexProvider
oauth_provider = OpenAICodexProvider(
- default_model=config.model or "openai-codex/gpt-5.1-codex",
+ default_model=config.model or CODEX_DEFAULT_MODEL_ID,
)
return _ProviderOpenAIAdapter(oauth_provider)
diff --git a/deeptutor/multi_user/model_access.py b/deeptutor/multi_user/model_access.py
index 83508d0c4..eaf06a902 100644
--- a/deeptutor/multi_user/model_access.py
+++ b/deeptutor/multi_user/model_access.py
@@ -39,6 +39,16 @@ def _model_by_id(profile: dict[str, Any], model_id: str) -> dict[str, Any] | Non
return None
+def is_owner_bound(profile: dict[str, Any]) -> bool:
+ """Whether a profile is tied to the identity of the operator who set it up.
+
+ OAuth providers such as Codex authenticate one individual's plan rather than
+ a billable team key, so those profiles are never lent to other accounts
+ through grants — each user signs in for themselves or goes without.
+ """
+ return bool(profile.get("owner_bound"))
+
+
def redacted_model_access(user_id: str | None = None) -> dict[str, list[dict[str, Any]]]:
user = get_current_user()
if user_id is None:
@@ -49,6 +59,11 @@ def redacted_model_access(user_id: str | None = None) -> dict[str, list[dict[str
for item in grant.get("models", {}).get("llm", []) or []:
profile_id = str(item.get("profile_id") or item.get("id") or "")
profile = _profile_by_id(catalog, "llm", profile_id)
+ if profile is not None and is_owner_bound(profile):
+ # A grant may predate the profile becoming owner-bound. Drop it here,
+ # the one place every caller resolves grants through, so the option
+ # list, the capability gate, and selection validation all agree.
+ continue
if not profile:
result["llm"].append(
{
diff --git a/deeptutor/multi_user/router.py b/deeptutor/multi_user/router.py
index 6a47a6f77..e832d1c9e 100644
--- a/deeptutor/multi_user/router.py
+++ b/deeptutor/multi_user/router.py
@@ -17,6 +17,7 @@ from .audit import log_admin_action
from .grants import load_grant, save_grant
from .identity import get_user_by_id, list_user_info
from .knowledge_access import admin_kb_base_dir
+from .model_access import is_owner_bound
from .paths import get_admin_path_service
router = APIRouter()
@@ -42,6 +43,10 @@ def _admin_catalog_summary() -> dict[str, list[dict[str, Any]]]:
if service not in out:
continue
for profile in state.get("profiles", []) or []:
+ if is_owner_bound(profile):
+ # Bound to one person's OAuth identity, so it is not assignable.
+ # Listing it here would offer admins a grant the server drops.
+ continue
profile_id = str(profile.get("id") or "")
models = []
for model in profile.get("models", []) or []:
diff --git a/deeptutor/services/codex_auth/__init__.py b/deeptutor/services/codex_auth/__init__.py
new file mode 100644
index 000000000..b88672c9e
--- /dev/null
+++ b/deeptutor/services/codex_auth/__init__.py
@@ -0,0 +1,24 @@
+"""Independent OpenAI Codex OAuth support for DeepTutor."""
+
+from .contracts import (
+ CatalogSnapshot,
+ CodexAuthError,
+ CodexCredentials,
+ CodexModel,
+ CodexToken,
+ TokenClaims,
+ decode_codex_jwt,
+)
+from .service import CodexOAuthService, get_codex_oauth_service
+
+__all__ = [
+ "CatalogSnapshot",
+ "CodexAuthError",
+ "CodexCredentials",
+ "CodexModel",
+ "CodexOAuthService",
+ "CodexToken",
+ "TokenClaims",
+ "decode_codex_jwt",
+ "get_codex_oauth_service",
+]
diff --git a/deeptutor/services/codex_auth/catalog.py b/deeptutor/services/codex_auth/catalog.py
new file mode 100644
index 000000000..100995877
--- /dev/null
+++ b/deeptutor/services/codex_auth/catalog.py
@@ -0,0 +1,258 @@
+"""Account-scoped live model catalog for Codex OAuth."""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Mapping
+from dataclasses import replace
+import hashlib
+import time
+from typing import Any
+
+import httpx
+
+from .constants import (
+ CODEX_CLIENT_VERSION,
+ CODEX_FRESH_CACHE_SECONDS,
+ CODEX_MAX_CATALOG_BYTES,
+ CODEX_MAX_MODELS,
+ CODEX_MODELS_URL,
+ CODEX_STALE_CACHE_SECONDS,
+)
+from .contracts import CatalogSnapshot, CodexAuthError, CodexCredentials, CodexModel
+from .storage import CodexCredentialStore
+
+
+def parse_models_response(payload: Mapping[str, Any]) -> tuple[CodexModel, ...]:
+ raw_models = payload.get("models")
+ if not isinstance(raw_models, list):
+ raise CodexAuthError(
+ "catalog_invalid",
+ "Codex returned an invalid model catalog.",
+ 502,
+ )
+ if len(raw_models) > CODEX_MAX_MODELS:
+ raise CodexAuthError(
+ "catalog_too_large",
+ "The Codex model catalog exceeded DeepTutor's safety limit.",
+ 502,
+ )
+
+ models: list[CodexModel] = []
+ for raw_model in raw_models:
+ if not isinstance(raw_model, dict):
+ raise CodexAuthError(
+ "catalog_invalid",
+ "Codex returned an invalid model catalog.",
+ 502,
+ )
+ if raw_model.get("visibility") != "list":
+ continue
+ slug = raw_model.get("slug")
+ display_name = raw_model.get("display_name")
+ if not isinstance(slug, str) or not slug:
+ raise CodexAuthError(
+ "catalog_invalid",
+ "Codex returned an invalid model catalog.",
+ 502,
+ )
+ if not isinstance(display_name, str) or not display_name:
+ display_name = slug
+ priority = raw_model.get("priority", 0)
+ if isinstance(priority, bool) or not isinstance(priority, int):
+ priority = 0
+
+ models.append(
+ CodexModel(
+ slug=slug,
+ display_name=display_name,
+ priority=priority,
+ visibility="list",
+ default_reasoning_level=_optional_string(raw_model.get("default_reasoning_level")),
+ supported_reasoning_levels=_reasoning_levels(
+ raw_model.get("supported_reasoning_levels")
+ ),
+ supports_reasoning_summary=_summary_support(raw_model),
+ supports_parallel_tool_calls=(
+ raw_model.get("supports_parallel_tool_calls") is True
+ ),
+ use_responses_lite=raw_model.get("use_responses_lite") is True,
+ )
+ )
+
+ return tuple(sorted(models, key=lambda model: (model.priority, model.slug)))
+
+
+def _optional_string(value: object) -> str | None:
+ return value if isinstance(value, str) and value else None
+
+
+def _reasoning_levels(value: object) -> tuple[str, ...]:
+ if not isinstance(value, list):
+ return ()
+ efforts: list[str] = []
+ for item in value:
+ effort: object
+ if isinstance(item, dict):
+ effort = item.get("effort")
+ else:
+ effort = item
+ if isinstance(effort, str) and effort and effort not in efforts:
+ efforts.append(effort)
+ return tuple(efforts)
+
+
+def _summary_support(raw_model: Mapping[str, Any]) -> bool:
+ current = raw_model.get("supports_reasoning_summary_parameter")
+ if isinstance(current, bool):
+ return current
+ return raw_model.get("supports_reasoning_summaries") is True
+
+
+class CodexModelCatalog:
+ def __init__(
+ self,
+ store: CodexCredentialStore,
+ *,
+ http: httpx.AsyncClient,
+ clock: Callable[[], float] = time.time,
+ ) -> None:
+ self._store = store
+ self._http = http
+ self._clock = clock
+
+ async def get(
+ self,
+ credentials: CodexCredentials,
+ force: bool,
+ ) -> CatalogSnapshot:
+ now = int(self._clock())
+ account_hash = hashlib.sha256(credentials.account_id.encode("utf-8")).hexdigest()
+ cache = self._matching_cache(credentials, account_hash)
+ if cache is not None and not force and self._age(cache, now) <= CODEX_FRESH_CACHE_SECONDS:
+ return replace(cache, source="fresh-cache")
+
+ headers = {
+ "Authorization": f"Bearer {credentials.access_token}",
+ "Accept": "application/json",
+ "chatgpt-account-id": credentials.account_id,
+ }
+ if cache is not None and cache.etag:
+ headers["If-None-Match"] = cache.etag
+
+ try:
+ response = await self._http.get(
+ CODEX_MODELS_URL,
+ params={"client_version": CODEX_CLIENT_VERSION},
+ headers=headers,
+ )
+ except httpx.RequestError as exc:
+ return self._stale_or_raise(cache, now, exc)
+
+ if response.status_code == 401:
+ await self.invalidate()
+ raise CodexAuthError(
+ "catalog_unauthorized",
+ "Codex authentication is no longer authorized.",
+ 401,
+ )
+ if response.status_code == 403:
+ await self.invalidate()
+ raise CodexAuthError(
+ "catalog_forbidden",
+ "This Codex account cannot access the model catalog.",
+ 403,
+ )
+ if response.status_code == 304:
+ if cache is None:
+ raise CodexAuthError(
+ "catalog_invalid",
+ "Codex returned an invalid model catalog response.",
+ 502,
+ )
+ snapshot = replace(cache, source="revalidated-cache", fetched_at=now)
+ self._store.save_catalog_cache(snapshot.to_dict())
+ return snapshot
+
+ try:
+ response.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ return self._stale_or_raise(cache, now, exc)
+
+ content_length = response.headers.get("content-length")
+ if (
+ content_length is not None
+ and content_length.isdigit()
+ and int(content_length) > CODEX_MAX_CATALOG_BYTES
+ ) or len(response.content) > CODEX_MAX_CATALOG_BYTES:
+ raise CodexAuthError(
+ "catalog_too_large",
+ "The Codex model catalog exceeded DeepTutor's safety limit.",
+ 502,
+ )
+ try:
+ payload = response.json()
+ except ValueError as exc:
+ raise CodexAuthError(
+ "catalog_invalid",
+ "Codex returned an invalid model catalog.",
+ 502,
+ ) from exc
+ if not isinstance(payload, dict):
+ raise CodexAuthError(
+ "catalog_invalid",
+ "Codex returned an invalid model catalog.",
+ 502,
+ )
+
+ snapshot = CatalogSnapshot(
+ models=parse_models_response(payload),
+ source="live",
+ fetched_at=now,
+ etag=response.headers.get("etag"),
+ generation=credentials.generation,
+ account_hash=account_hash,
+ )
+ self._store.save_catalog_cache(snapshot.to_dict())
+ return snapshot
+
+ async def invalidate(self) -> None:
+ self._store.clear_catalog_cache()
+
+ def _matching_cache(
+ self,
+ credentials: CodexCredentials,
+ account_hash: str,
+ ) -> CatalogSnapshot | None:
+ try:
+ payload = self._store.load_catalog_cache()
+ if payload is None:
+ return None
+ snapshot = CatalogSnapshot.from_dict(payload)
+ except CodexAuthError as exc:
+ if exc.code != "catalog_corrupt":
+ raise
+ self._store.clear_catalog_cache()
+ return None
+ if snapshot.generation != credentials.generation:
+ return None
+ if snapshot.account_hash != account_hash:
+ return None
+ return snapshot
+
+ @staticmethod
+ def _age(snapshot: CatalogSnapshot, now: int) -> int:
+ return max(0, now - snapshot.fetched_at)
+
+ def _stale_or_raise(
+ self,
+ cache: CatalogSnapshot | None,
+ now: int,
+ cause: Exception,
+ ) -> CatalogSnapshot:
+ if cache is not None and self._age(cache, now) <= CODEX_STALE_CACHE_SECONDS:
+ return replace(cache, source="stale-cache")
+ raise CodexAuthError(
+ "catalog_unavailable",
+ "The Codex model catalog is temporarily unavailable.",
+ 503,
+ ) from cause
diff --git a/deeptutor/services/codex_auth/constants.py b/deeptutor/services/codex_auth/constants.py
new file mode 100644
index 000000000..e55017769
--- /dev/null
+++ b/deeptutor/services/codex_auth/constants.py
@@ -0,0 +1,23 @@
+"""Audited OpenAI Codex compatibility constants."""
+
+CODEX_UPSTREAM_COMMIT = "81da9deb065d7adb283816b19b40f89bcc484276"
+CODEX_CLIENT_VERSION = "0.145.0"
+CODEX_OAUTH_ISSUER = "https://auth.openai.com"
+CODEX_OAUTH_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"
+CODEX_OAUTH_SCOPE = "openid profile email offline_access api.connectors.read api.connectors.invoke"
+CODEX_OAUTH_ORIGINATOR = "codex_cli_rs"
+CODEX_CALLBACK_PORTS = (1455, 1457)
+CODEX_CALLBACK_PATH = "/auth/callback"
+CODEX_LOGIN_TIMEOUT_SECONDS = 300
+CODEX_TOKEN_URL = f"{CODEX_OAUTH_ISSUER}/oauth/token"
+CODEX_REVOKE_URL = f"{CODEX_OAUTH_ISSUER}/oauth/revoke"
+CODEX_MODELS_URL = "https://chatgpt.com/backend-api/codex/models"
+CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses"
+CODEX_FRESH_CACHE_SECONDS = 300
+CODEX_STALE_CACHE_SECONDS = 86_400
+CODEX_MAX_MODELS = 512
+CODEX_MAX_CATALOG_BYTES = 8 * 1024 * 1024
+# Fallback only, used when a caller does not name a model. The real list always
+# comes from the signed-in account's live catalog.
+CODEX_DEFAULT_MODEL = "gpt-5.6-sol"
+CODEX_DEFAULT_MODEL_ID = f"openai-codex/{CODEX_DEFAULT_MODEL}"
diff --git a/deeptutor/services/codex_auth/contracts.py b/deeptutor/services/codex_auth/contracts.py
new file mode 100644
index 000000000..b2d62872e
--- /dev/null
+++ b/deeptutor/services/codex_auth/contracts.py
@@ -0,0 +1,239 @@
+"""Data contracts shared by the independent Codex OAuth components."""
+
+from __future__ import annotations
+
+import base64
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+import json
+from typing import Any, Literal
+
+CatalogSource = Literal["live", "fresh-cache", "revalidated-cache", "stale-cache"]
+
+
+class CodexAuthError(RuntimeError):
+ """An OAuth error whose string form is safe to expose to a user."""
+
+ def __init__(self, code: str, public_message: str, http_status: int = 400) -> None:
+ super().__init__(public_message)
+ self.code = code
+ self.public_message = public_message
+ self.http_status = http_status
+
+ def __str__(self) -> str:
+ return self.public_message
+
+
+@dataclass(frozen=True)
+class TokenClaims:
+ expires_at: int | None
+ account_id: str | None
+
+
+@dataclass(frozen=True)
+class CodexCredentials:
+ schema_version: int
+ access_token: str = field(repr=False)
+ refresh_token: str = field(repr=False)
+ id_token: str = field(repr=False)
+ account_id: str
+ expires_at: int
+ generation: int
+
+ def public_token(self) -> CodexToken:
+ return CodexToken(
+ access_token=self.access_token,
+ account_id=self.account_id,
+ expires_at=self.expires_at,
+ generation=self.generation,
+ )
+
+ def to_dict(self) -> dict[str, object]:
+ return {
+ "schema_version": self.schema_version,
+ "access_token": self.access_token,
+ "refresh_token": self.refresh_token,
+ "id_token": self.id_token,
+ "account_id": self.account_id,
+ "expires_at": self.expires_at,
+ "generation": self.generation,
+ }
+
+ @classmethod
+ def from_dict(cls, payload: Mapping[str, Any]) -> CodexCredentials:
+ try:
+ schema_version = payload["schema_version"]
+ access_token = payload["access_token"]
+ refresh_token = payload["refresh_token"]
+ id_token = payload["id_token"]
+ account_id = payload["account_id"]
+ expires_at = payload["expires_at"]
+ generation = payload["generation"]
+ if (
+ isinstance(schema_version, bool)
+ or schema_version != 1
+ or not all(
+ isinstance(value, str) and bool(value)
+ for value in (
+ access_token,
+ refresh_token,
+ id_token,
+ account_id,
+ )
+ )
+ or isinstance(expires_at, bool)
+ or not isinstance(expires_at, int)
+ or expires_at <= 0
+ or isinstance(generation, bool)
+ or not isinstance(generation, int)
+ or generation < 0
+ ):
+ raise ValueError
+ return cls(
+ schema_version=schema_version,
+ access_token=access_token,
+ refresh_token=refresh_token,
+ id_token=id_token,
+ account_id=account_id,
+ expires_at=expires_at,
+ generation=generation,
+ )
+ except (KeyError, TypeError, ValueError) as exc:
+ raise CodexAuthError(
+ "credential_corrupt",
+ "Stored Codex credentials are invalid.",
+ 500,
+ ) from exc
+
+
+@dataclass(frozen=True)
+class CodexToken:
+ access_token: str = field(repr=False)
+ account_id: str
+ expires_at: int
+ generation: int
+
+
+@dataclass(frozen=True)
+class CodexModel:
+ slug: str
+ display_name: str
+ priority: int
+ visibility: str
+ default_reasoning_level: str | None
+ supported_reasoning_levels: tuple[str, ...]
+ supports_reasoning_summary: bool
+ supports_parallel_tool_calls: bool
+ use_responses_lite: bool
+
+ def to_dict(self) -> dict[str, object]:
+ return {
+ "slug": self.slug,
+ "display_name": self.display_name,
+ "priority": self.priority,
+ "visibility": self.visibility,
+ "default_reasoning_level": self.default_reasoning_level,
+ "supported_reasoning_levels": list(self.supported_reasoning_levels),
+ "supports_reasoning_summary": self.supports_reasoning_summary,
+ "supports_parallel_tool_calls": self.supports_parallel_tool_calls,
+ "use_responses_lite": self.use_responses_lite,
+ }
+
+ @classmethod
+ def from_dict(cls, payload: Mapping[str, Any]) -> CodexModel:
+ try:
+ reasoning_levels = payload["supported_reasoning_levels"]
+ if not isinstance(reasoning_levels, list):
+ raise TypeError
+ return cls(
+ slug=str(payload["slug"]),
+ display_name=str(payload["display_name"]),
+ priority=int(payload["priority"]),
+ visibility=str(payload["visibility"]),
+ default_reasoning_level=(
+ str(payload["default_reasoning_level"])
+ if payload.get("default_reasoning_level") is not None
+ else None
+ ),
+ supported_reasoning_levels=tuple(str(item) for item in reasoning_levels),
+ supports_reasoning_summary=bool(payload["supports_reasoning_summary"]),
+ supports_parallel_tool_calls=bool(payload["supports_parallel_tool_calls"]),
+ use_responses_lite=bool(payload["use_responses_lite"]),
+ )
+ except (KeyError, TypeError, ValueError) as exc:
+ raise CodexAuthError(
+ "catalog_corrupt",
+ "Stored Codex model data is invalid.",
+ 500,
+ ) from exc
+
+
+@dataclass(frozen=True)
+class CatalogSnapshot:
+ models: tuple[CodexModel, ...]
+ source: CatalogSource
+ fetched_at: int
+ etag: str | None
+ generation: int
+ account_hash: str
+
+ def to_dict(self) -> dict[str, object]:
+ return {
+ "models": [model.to_dict() for model in self.models],
+ "source": self.source,
+ "fetched_at": self.fetched_at,
+ "etag": self.etag,
+ "generation": self.generation,
+ "account_hash": self.account_hash,
+ }
+
+ @classmethod
+ def from_dict(cls, payload: Mapping[str, Any]) -> CatalogSnapshot:
+ try:
+ models = payload["models"]
+ source = payload["source"]
+ if not isinstance(models, list):
+ raise TypeError
+ if source not in {"live", "fresh-cache", "revalidated-cache", "stale-cache"}:
+ raise ValueError
+ return cls(
+ models=tuple(CodexModel.from_dict(item) for item in models),
+ source=source,
+ fetched_at=int(payload["fetched_at"]),
+ etag=str(payload["etag"]) if payload.get("etag") is not None else None,
+ generation=int(payload["generation"]),
+ account_hash=str(payload["account_hash"]),
+ )
+ except (KeyError, TypeError, ValueError) as exc:
+ raise CodexAuthError(
+ "catalog_corrupt",
+ "Stored Codex model data is invalid.",
+ 500,
+ ) from exc
+
+
+def decode_codex_jwt(token: str) -> TokenClaims:
+ """Decode the minimal unverified claims needed after a trusted TLS exchange."""
+
+ try:
+ payload_part = token.split(".")[1]
+ padding = "=" * (-len(payload_part) % 4)
+ raw = base64.urlsafe_b64decode(payload_part + padding)
+ payload = json.loads(raw)
+ if not isinstance(payload, dict):
+ raise TypeError
+ except (IndexError, TypeError, ValueError, json.JSONDecodeError) as exc:
+ raise CodexAuthError("invalid_token", "Codex returned an invalid token.", 401) from exc
+
+ expires_at = payload.get("exp")
+ if isinstance(expires_at, bool) or not isinstance(expires_at, int):
+ expires_at = None
+
+ account_id: str | None = None
+ auth_claim = payload.get("https://api.openai.com/auth")
+ if isinstance(auth_claim, dict):
+ raw_account_id = auth_claim.get("chatgpt_account_id")
+ if isinstance(raw_account_id, str) and raw_account_id:
+ account_id = raw_account_id
+
+ return TokenClaims(expires_at=expires_at, account_id=account_id)
diff --git a/deeptutor/services/codex_auth/oauth.py b/deeptutor/services/codex_auth/oauth.py
new file mode 100644
index 000000000..75e222c96
--- /dev/null
+++ b/deeptutor/services/codex_auth/oauth.py
@@ -0,0 +1,285 @@
+"""PKCE, loopback callback, and HTTP operations for Codex OAuth."""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+from collections.abc import Iterable
+from dataclasses import dataclass
+import hashlib
+import secrets
+from typing import Any
+from urllib.parse import parse_qs, urlencode, urlsplit
+
+import httpx
+
+from .constants import (
+ CODEX_CALLBACK_PATH,
+ CODEX_OAUTH_CLIENT_ID,
+ CODEX_OAUTH_ISSUER,
+ CODEX_OAUTH_ORIGINATOR,
+ CODEX_OAUTH_SCOPE,
+ CODEX_REVOKE_URL,
+ CODEX_TOKEN_URL,
+)
+from .contracts import CodexAuthError, CodexCredentials
+
+
+@dataclass(frozen=True)
+class PkceCodes:
+ verifier: str
+ challenge: str
+
+
+@dataclass(frozen=True)
+class OAuthCallbackResult:
+ code: str | None
+ state: str | None
+ error: str | None
+
+
+def generate_pkce() -> PkceCodes:
+ verifier = secrets.token_urlsafe(64)
+ digest = hashlib.sha256(verifier.encode("ascii")).digest()
+ challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
+ return PkceCodes(verifier=verifier, challenge=challenge)
+
+
+def build_authorize_url(*, redirect_uri: str, state: str, pkce: PkceCodes) -> str:
+ query = urlencode(
+ {
+ "response_type": "code",
+ "client_id": CODEX_OAUTH_CLIENT_ID,
+ "redirect_uri": redirect_uri,
+ "scope": CODEX_OAUTH_SCOPE,
+ "code_challenge": pkce.challenge,
+ "code_challenge_method": "S256",
+ "state": state,
+ "originator": CODEX_OAUTH_ORIGINATOR,
+ "id_token_add_organizations": "true",
+ "codex_cli_simplified_flow": "true",
+ }
+ )
+ return f"{CODEX_OAUTH_ISSUER}/oauth/authorize?{query}"
+
+
+class LoopbackCallback:
+ """A one-shot OAuth callback listener bound only to loopback addresses.
+
+ The redirect URI has to stay ``http://localhost:<port>`` because that is what
+ the upstream OAuth client accepts, and ``localhost`` resolves to either stack
+ depending on the host. Both loopback addresses are therefore bound, with a
+ plain IPv4 bind as the fallback on hosts without IPv6.
+ """
+
+ hosts = ("127.0.0.1", "::1")
+
+ def __init__(
+ self,
+ server: asyncio.AbstractServer,
+ result: asyncio.Future[OAuthCallbackResult],
+ port: int,
+ ) -> None:
+ self._server = server
+ self._result = result
+ self._cancelled = False
+ self.port = port
+
+ @classmethod
+ async def start(cls, ports: Iterable[int]) -> LoopbackCallback:
+ loop = asyncio.get_running_loop()
+ result: asyncio.Future[OAuthCallbackResult] = loop.create_future()
+
+ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ status = "404 Not Found"
+ body = (
+ "<!doctype html><title>DeepTutor Codex</title>"
+ "<p>This callback path is not available.</p>"
+ )
+ callback_result: OAuthCallbackResult | None = None
+ try:
+ request = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=2)
+ request_line = request.split(b"\r\n", 1)[0].decode("ascii")
+ method, target, _version = request_line.split(" ", 2)
+ parsed = urlsplit(target)
+ if method == "GET" and parsed.path == CODEX_CALLBACK_PATH:
+ query = parse_qs(parsed.query)
+ callback_result = OAuthCallbackResult(
+ code=_first(query.get("code")),
+ state=_first(query.get("state")),
+ error=_first(query.get("error")),
+ )
+ status = "200 OK"
+ body = (
+ "<!doctype html><title>DeepTutor Codex</title>"
+ "<p>Authentication received. You can return to DeepTutor.</p>"
+ )
+ except (ValueError, UnicodeDecodeError, asyncio.IncompleteReadError, TimeoutError):
+ status = "400 Bad Request"
+ body = (
+ "<!doctype html><title>DeepTutor Codex</title>"
+ "<p>The authentication callback was invalid.</p>"
+ )
+
+ encoded = body.encode("utf-8")
+ writer.write(
+ (
+ f"HTTP/1.1 {status}\r\n"
+ "Content-Type: text/html; charset=utf-8\r\n"
+ f"Content-Length: {len(encoded)}\r\n"
+ "Cache-Control: no-store\r\n"
+ "Connection: close\r\n\r\n"
+ ).encode("ascii")
+ + encoded
+ )
+ try:
+ await writer.drain()
+ finally:
+ writer.close()
+ await writer.wait_closed()
+
+ if callback_result is not None and not result.done():
+ result.set_result(callback_result)
+
+ async def bind(hosts: list[str], port: int) -> asyncio.AbstractServer | None:
+ try:
+ server = await asyncio.start_server(handle, hosts, port)
+ except OSError:
+ return None
+ if len({int(sock.getsockname()[1]) for sock in server.sockets}) == 1:
+ return server
+ # An ephemeral port can land differently on each stack, and the
+ # redirect URI can only name one of them. Fall back to a single bind.
+ server.close()
+ await server.wait_closed()
+ return None
+
+ server: asyncio.AbstractServer | None = None
+ for port in ports:
+ server = await bind(list(cls.hosts), port) or await bind([cls.hosts[0]], port)
+ if server is not None:
+ break
+ if server is None or not server.sockets:
+ raise CodexAuthError(
+ "callback_unavailable",
+ "DeepTutor could not start the local Codex sign-in callback.",
+ 503,
+ )
+ bound_port = int(server.sockets[0].getsockname()[1])
+ return cls(server=server, result=result, port=bound_port)
+
+ async def _close(self) -> None:
+ self._server.close()
+ await self._server.wait_closed()
+
+ async def wait(self, timeout: float) -> OAuthCallbackResult:
+ try:
+ callback = await asyncio.wait_for(asyncio.shield(self._result), timeout=timeout)
+ except TimeoutError as exc:
+ await self._close()
+ raise CodexAuthError(
+ "login_timeout",
+ "Codex sign-in timed out.",
+ 408,
+ ) from exc
+ except asyncio.CancelledError as exc:
+ await self._close()
+ if self._cancelled:
+ raise CodexAuthError(
+ "login_cancelled",
+ "Codex sign-in was cancelled.",
+ 409,
+ ) from exc
+ raise
+ await self._close()
+ return callback
+
+ async def cancel(self) -> None:
+ self._cancelled = True
+ if not self._result.done():
+ self._result.cancel()
+ await self._close()
+
+
+def _first(values: list[str] | None) -> str | None:
+ if not values:
+ return None
+ return values[0]
+
+
+class CodexOAuthClient:
+ """HTTP client for the audited Codex OAuth token endpoints."""
+
+ def __init__(self, http: httpx.AsyncClient) -> None:
+ self._http = http
+
+ async def exchange_code(
+ self,
+ code: str,
+ redirect_uri: str,
+ verifier: str,
+ ) -> dict[str, Any]:
+ return await self._token_request(
+ data={
+ "client_id": CODEX_OAUTH_CLIENT_ID,
+ "grant_type": "authorization_code",
+ "code": code,
+ "redirect_uri": redirect_uri,
+ "code_verifier": verifier,
+ },
+ error_code="token_exchange_failed",
+ public_message="Codex sign-in could not be completed.",
+ )
+
+ async def refresh(self, refresh_token: str) -> dict[str, Any]:
+ return await self._token_request(
+ json_payload={
+ "client_id": CODEX_OAUTH_CLIENT_ID,
+ "grant_type": "refresh_token",
+ "refresh_token": refresh_token,
+ },
+ error_code="token_refresh_failed",
+ public_message="Codex authentication could not be refreshed.",
+ )
+
+ async def revoke(self, credentials: CodexCredentials) -> None:
+ token = credentials.refresh_token or credentials.access_token
+ hint = "refresh_token" if credentials.refresh_token else "access_token"
+ try:
+ response = await self._http.post(
+ CODEX_REVOKE_URL,
+ data={
+ "client_id": CODEX_OAUTH_CLIENT_ID,
+ "token": token,
+ "token_type_hint": hint,
+ },
+ )
+ response.raise_for_status()
+ except httpx.HTTPError as exc:
+ raise CodexAuthError(
+ "token_revoke_failed",
+ "Codex authentication could not be revoked remotely.",
+ 502,
+ ) from exc
+
+ async def _token_request(
+ self,
+ *,
+ data: dict[str, str] | None = None,
+ json_payload: dict[str, str] | None = None,
+ error_code: str,
+ public_message: str,
+ ) -> dict[str, Any]:
+ try:
+ response = await self._http.post(
+ CODEX_TOKEN_URL,
+ data=data,
+ json=json_payload,
+ )
+ response.raise_for_status()
+ payload = response.json()
+ if not isinstance(payload, dict):
+ raise ValueError
+ return payload
+ except (httpx.HTTPError, ValueError) as exc:
+ raise CodexAuthError(error_code, public_message, 502) from exc
diff --git a/deeptutor/services/codex_auth/service.py b/deeptutor/services/codex_auth/service.py
new file mode 100644
index 000000000..00b158021
--- /dev/null
+++ b/deeptutor/services/codex_auth/service.py
@@ -0,0 +1,660 @@
+"""Codex OAuth orchestration and managed model-catalog integration."""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator, Awaitable, Callable
+from contextlib import asynccontextmanager
+from dataclasses import dataclass
+import hashlib
+from pathlib import Path
+import secrets
+import time
+from typing import Any
+
+import httpx
+
+from deeptutor.services.config.model_catalog import (
+ ModelCatalogService,
+ get_model_catalog_service,
+)
+from deeptutor.services.path_service import get_path_service
+
+from .catalog import CodexModelCatalog
+from .constants import (
+ CODEX_CALLBACK_PATH,
+ CODEX_CALLBACK_PORTS,
+ CODEX_LOGIN_TIMEOUT_SECONDS,
+)
+from .contracts import (
+ CatalogSnapshot,
+ CodexAuthError,
+ CodexCredentials,
+ CodexModel,
+ CodexToken,
+ decode_codex_jwt,
+)
+from .oauth import (
+ CodexOAuthClient,
+ LoopbackCallback,
+ OAuthCallbackResult,
+ PkceCodes,
+ build_authorize_url,
+ generate_pkce,
+)
+from .storage import CodexCredentialStore
+
+MANAGED_BY = "openai_codex_oauth"
+CODEX_PROFILE_ID = "llm-profile-openai-codex-managed"
+
+
+@dataclass(frozen=True)
+class CatalogSyncResult:
+ catalog: dict[str, Any]
+ activated: bool
+
+
+@dataclass
+class _LoginOperation:
+ operation_id: str
+ state_secret: str
+ pkce: PkceCodes
+ callback: Any
+ redirect_uri: str
+ authorize_url: str
+ deadline: float
+ expected_generation: int
+ operation_state: str = "waiting"
+ error_code: str | None = None
+ activated: bool = False
+ task: asyncio.Task[None] | None = None
+
+
+def codex_model_id(slug: str) -> str:
+ digest = hashlib.sha256(slug.encode("utf-8")).hexdigest()[:16]
+ return f"llm-model-openai-codex-{digest}"
+
+
+def _managed_model(model: CodexModel) -> dict[str, Any]:
+ return {
+ "id": codex_model_id(model.slug),
+ "name": model.display_name,
+ "model": model.slug,
+ "managed_by": MANAGED_BY,
+ "codex_priority": model.priority,
+ "codex_default_reasoning_level": model.default_reasoning_level,
+ "codex_supported_reasoning_levels": list(model.supported_reasoning_levels),
+ "codex_supports_reasoning_summary": model.supports_reasoning_summary,
+ "codex_supports_parallel_tool_calls": model.supports_parallel_tool_calls,
+ "codex_use_responses_lite": model.use_responses_lite,
+ }
+
+
+def _managed_profile(snapshot: CatalogSnapshot) -> dict[str, Any]:
+ return {
+ "id": CODEX_PROFILE_ID,
+ "name": "OpenAI Codex",
+ "binding": "openai_codex",
+ "base_url": "https://chatgpt.com/backend-api",
+ "api_key": "",
+ "api_version": "",
+ "extra_headers": {},
+ "managed_by": MANAGED_BY,
+ "read_only": True,
+ # A Codex token authorizes exactly one person's ChatGPT plan, so this
+ # profile stays with the operator who signed in and is never shared with
+ # other users through grants (see deeptutor/multi_user/model_access.py).
+ "owner_bound": True,
+ "models": [_managed_model(model) for model in snapshot.models],
+ }
+
+
+def sync_codex_catalog(
+ catalog_service: ModelCatalogService,
+ snapshot: CatalogSnapshot,
+) -> CatalogSyncResult:
+ """Publish the managed Codex profile into the shared model catalog.
+
+ Choosing the active model stays the operator's call. The only automatic
+ activation happens when the deployment has no active LLM at all, so a fresh
+ install is usable right after sign-in without ever silently replacing a
+ model somebody already picked.
+ """
+ profile = _managed_profile(snapshot)
+ activated = False
+
+ def mutate(catalog: dict[str, Any]) -> None:
+ nonlocal activated
+ llm = catalog["services"]["llm"]
+ profiles = llm.setdefault("profiles", [])
+ managed_indexes = [
+ index
+ for index, existing in enumerate(profiles)
+ if existing.get("managed_by") == MANAGED_BY
+ ]
+ if managed_indexes:
+ first_index = managed_indexes[0]
+ profiles[:] = [
+ existing for existing in profiles if existing.get("managed_by") != MANAGED_BY
+ ]
+ profiles.insert(min(first_index, len(profiles)), profile)
+ else:
+ profiles.append(profile)
+
+ if not profile["models"]:
+ return
+ current_profile_id = llm.get("active_profile_id")
+ if not current_profile_id:
+ llm["active_profile_id"] = CODEX_PROFILE_ID
+ llm["active_model_id"] = profile["models"][0]["id"]
+ activated = True
+ elif current_profile_id == CODEX_PROFILE_ID:
+ valid_model_ids = {model["id"] for model in profile["models"]}
+ if llm.get("active_model_id") not in valid_model_ids:
+ llm["active_model_id"] = profile["models"][0]["id"]
+
+ return CatalogSyncResult(catalog=catalog_service.update(mutate), activated=activated)
+
+
+def remove_codex_catalog(catalog_service: ModelCatalogService) -> dict[str, Any]:
+ """Drop the managed Codex profile and never leave a dangling selection."""
+
+ def mutate(catalog: dict[str, Any]) -> None:
+ llm = catalog["services"]["llm"]
+ current_is_managed = llm.get("active_profile_id") == CODEX_PROFILE_ID
+ llm["profiles"] = [
+ profile
+ for profile in llm.get("profiles", [])
+ if profile.get("managed_by") != MANAGED_BY
+ ]
+ if current_is_managed:
+ llm["active_profile_id"] = None
+ llm["active_model_id"] = None
+
+ return catalog_service.update(mutate)
+
+
+class CodexOAuthService:
+ """Coordinate independent Codex login, refresh, catalog sync, and logout."""
+
+ _TERMINAL_STATES = {"completed", "cancelled", "expired", "failed"}
+
+ def __init__(
+ self,
+ store: CodexCredentialStore,
+ catalog: CodexModelCatalog,
+ model_catalog: ModelCatalogService,
+ *,
+ oauth_client: CodexOAuthClient | None = None,
+ callback_factory: Callable[[], Awaitable[Any]] | None = None,
+ clock: Callable[[], float] = time.time,
+ ) -> None:
+ self._store = store
+ self._catalog = catalog
+ self._model_catalog = model_catalog
+ self._owned_http: httpx.AsyncClient | None = None
+ if oauth_client is None:
+ self._owned_http = httpx.AsyncClient(timeout=30)
+ oauth_client = CodexOAuthClient(self._owned_http)
+ self._oauth = oauth_client
+ self._callback_factory = callback_factory or self._start_default_callback
+ self._clock = clock
+ self._operation: _LoginOperation | None = None
+ self._last_snapshot: CatalogSnapshot | None = None
+ self._operation_lock = asyncio.Lock()
+ self._refresh_lock = asyncio.Lock()
+ self._catalog_sync_lock = asyncio.Lock()
+ self._inference_lock = asyncio.Lock()
+ self._active_inferences = 0
+ self._logging_out = False
+
+ @staticmethod
+ async def _start_default_callback() -> LoopbackCallback:
+ return await LoopbackCallback.start(CODEX_CALLBACK_PORTS)
+
+ async def start_login(self) -> dict[str, Any]:
+ async with self._operation_lock:
+ if self._operation_is_active():
+ return self._login_start_payload(self._operation)
+
+ callback = await self._callback_factory()
+ pkce = generate_pkce()
+ state_secret = secrets.token_urlsafe(32)
+ redirect_uri = f"http://localhost:{callback.port}{CODEX_CALLBACK_PATH}"
+ operation = _LoginOperation(
+ operation_id=secrets.token_urlsafe(24),
+ state_secret=state_secret,
+ pkce=pkce,
+ callback=callback,
+ redirect_uri=redirect_uri,
+ authorize_url=build_authorize_url(
+ redirect_uri=redirect_uri,
+ state=state_secret,
+ pkce=pkce,
+ ),
+ deadline=self._clock() + CODEX_LOGIN_TIMEOUT_SECONDS,
+ expected_generation=self._store.current_generation(),
+ )
+ self._operation = operation
+ operation.task = asyncio.create_task(self._run_login(operation))
+ return self._login_start_payload(operation)
+
+ def _login_start_payload(self, operation: _LoginOperation | None) -> dict[str, Any]:
+ if operation is None:
+ raise CodexAuthError(
+ "login_not_started",
+ "Codex sign-in has not been started.",
+ 409,
+ )
+ return {
+ "operation_id": operation.operation_id,
+ "authorize_url": operation.authorize_url,
+ "expires_in": max(0, int(operation.deadline - self._clock())),
+ }
+
+ def _operation_is_active(self) -> bool:
+ operation = self._operation
+ return bool(
+ operation is not None
+ and operation.operation_state not in self._TERMINAL_STATES
+ and (operation.task is None or not operation.task.done())
+ )
+
+ async def _run_login(self, operation: _LoginOperation) -> None:
+ try:
+ callback = await operation.callback.wait(
+ timeout=max(0, operation.deadline - self._clock())
+ )
+ self._validate_callback(callback, operation.state_secret)
+ operation.operation_state = "exchanging"
+ payload = await self._oauth.exchange_code(
+ callback.code,
+ operation.redirect_uri,
+ operation.pkce.verifier,
+ )
+ credentials = self._credentials_from_payload(
+ payload,
+ expected_generation=operation.expected_generation,
+ )
+ committed = self._store.commit_credentials(
+ credentials,
+ expected_generation=operation.expected_generation,
+ )
+ operation.operation_state = "fetching_models"
+ await self._catalog.invalidate()
+ snapshot = await self._catalog.get(committed, force=True)
+ async with self._catalog_sync_lock:
+ sync_result = sync_codex_catalog(self._model_catalog, snapshot)
+ self._last_snapshot = snapshot
+ operation.activated = sync_result.activated
+ operation.operation_state = "completed"
+ except CodexAuthError as exc:
+ operation.error_code = exc.code
+ if exc.code == "login_cancelled":
+ operation.operation_state = "cancelled"
+ elif exc.code == "login_timeout":
+ operation.operation_state = "expired"
+ else:
+ operation.operation_state = "failed"
+ except asyncio.CancelledError:
+ operation.error_code = "login_cancelled"
+ operation.operation_state = "cancelled"
+ except Exception:
+ operation.error_code = "login_failed"
+ operation.operation_state = "failed"
+
+ @staticmethod
+ def _validate_callback(
+ callback: OAuthCallbackResult,
+ expected_state: str,
+ ) -> None:
+ if callback.error is not None:
+ code = (
+ "authorization_denied"
+ if callback.error == "access_denied"
+ else "oauth_callback_failed"
+ )
+ raise CodexAuthError(code, "Codex sign-in was not authorized.", 401)
+ if callback.state is None or not secrets.compare_digest(
+ callback.state,
+ expected_state,
+ ):
+ raise CodexAuthError(
+ "state_mismatch",
+ "Codex sign-in returned an invalid state.",
+ 400,
+ )
+ if not callback.code:
+ raise CodexAuthError(
+ "authorization_code_missing",
+ "Codex sign-in did not return an authorization code.",
+ 400,
+ )
+
+ async def cancel_login(self) -> dict[str, Any]:
+ async with self._operation_lock:
+ operation = self._operation
+ if not self._operation_is_active() or operation is None:
+ return self.public_status()
+ await operation.callback.cancel()
+ await asyncio.sleep(0)
+ if operation.task is not None and not operation.task.done():
+ operation.task.cancel()
+ task = operation.task
+ if task is not None:
+ await asyncio.gather(task, return_exceptions=True)
+ return self.public_status()
+
+ async def refresh_models(self) -> dict[str, Any]:
+ async with self._catalog_sync_lock:
+ token = await self.get_token()
+ credentials = self._store.load_credentials()
+ if credentials is None or credentials.generation != token.generation:
+ raise CodexAuthError(
+ "authentication_changed",
+ "Codex authentication changed before models could be refreshed.",
+ 409,
+ )
+ snapshot = await self._catalog.get(credentials, force=True)
+ sync_codex_catalog(self._model_catalog, snapshot)
+ self._last_snapshot = snapshot
+ return self.public_status()
+
+ async def get_token(self) -> CodexToken:
+ async with self._refresh_lock:
+ credentials = self._store.load_credentials()
+ if credentials is None:
+ raise CodexAuthError(
+ "authentication_required",
+ "Sign in to Codex before using this model.",
+ 401,
+ )
+ if credentials.expires_at - int(self._clock()) > 300:
+ return credentials.public_token()
+ refreshed = await self._refresh_credentials(credentials)
+ return refreshed.public_token()
+
+ async def _refresh_credentials(
+ self,
+ credentials: CodexCredentials,
+ ) -> CodexCredentials:
+ payload = await self._oauth.refresh(credentials.refresh_token)
+ refreshed = self._credentials_from_payload(
+ payload,
+ expected_generation=credentials.generation,
+ fallback=credentials,
+ )
+ if refreshed.account_id != credentials.account_id:
+ raise CodexAuthError(
+ "account_changed",
+ "Codex authentication returned a different account.",
+ 409,
+ )
+ committed = self._store.commit_credentials(
+ refreshed,
+ expected_generation=credentials.generation,
+ )
+ await self._catalog.invalidate()
+ return committed
+
+ async def recover_after_unauthorized(self, generation: int) -> None:
+ async with self._refresh_lock:
+ credentials = self._store.load_credentials()
+ if credentials is None:
+ raise CodexAuthError(
+ "authentication_required",
+ "Sign in to Codex before using this model.",
+ 401,
+ )
+ if credentials.generation != generation:
+ return
+ await self._refresh_credentials(credentials)
+
+ @asynccontextmanager
+ async def inference_guard(self) -> AsyncIterator[None]:
+ async with self._inference_lock:
+ if self._logging_out:
+ raise CodexAuthError(
+ "logout_in_progress",
+ "Codex sign-out is in progress.",
+ 409,
+ )
+ self._active_inferences += 1
+ try:
+ yield
+ finally:
+ async with self._inference_lock:
+ self._active_inferences -= 1
+
+ async def logout(self) -> dict[str, Any]:
+ async with self._inference_lock:
+ if self._active_inferences:
+ raise CodexAuthError(
+ "inference_in_progress",
+ "Stop active Codex generation before signing out.",
+ 409,
+ )
+ self._logging_out = True
+ try:
+ await self.cancel_login()
+ async with self._catalog_sync_lock:
+ credentials = self._store.load_credentials()
+ if credentials is not None:
+ try:
+ await self._oauth.revoke(credentials)
+ except Exception:
+ pass
+ self._store.clear_credentials(expected_generation=credentials.generation)
+ else:
+ self._store.clear_credentials(
+ expected_generation=self._store.current_generation()
+ )
+ remove_codex_catalog(self._model_catalog)
+ try:
+ await self._catalog.invalidate()
+ except Exception:
+ pass
+ self._last_snapshot = None
+ self._operation = None
+ return self.public_status()
+ finally:
+ async with self._inference_lock:
+ self._logging_out = False
+
+ def public_status(self) -> dict[str, Any]:
+ operation = self._operation
+ credentials: CodexCredentials | None = None
+ storage_error: str | None = None
+ try:
+ credentials = self._store.load_credentials()
+ except CodexAuthError as exc:
+ storage_error = exc.code
+
+ active_operation = self._operation_is_active()
+ if active_operation:
+ connection = "authorizing"
+ elif credentials is not None:
+ connection = "connected"
+ elif operation is not None and operation.operation_state == "failed":
+ connection = "error"
+ else:
+ connection = "disconnected"
+
+ snapshot = self._status_snapshot(credentials)
+ return {
+ "connection": connection,
+ "operation_id": operation.operation_id if operation is not None else None,
+ "operation_state": (operation.operation_state if operation is not None else None),
+ "model_count": len(snapshot.models) if snapshot is not None else 0,
+ "catalog_source": snapshot.source if snapshot is not None else None,
+ "catalog_fetched_at": (snapshot.fetched_at if snapshot is not None else None),
+ "active_model": self._active_codex_model(),
+ "activated": (operation.activated if operation is not None else False),
+ "error_code": (
+ storage_error or (operation.error_code if operation is not None else None)
+ ),
+ }
+
+ def _status_snapshot(
+ self,
+ credentials: CodexCredentials | None,
+ ) -> CatalogSnapshot | None:
+ if credentials is None:
+ return None
+ snapshot = self._last_snapshot
+ if snapshot is not None and snapshot.generation == credentials.generation:
+ return snapshot
+ try:
+ payload = self._store.load_catalog_cache()
+ if payload is None:
+ return None
+ cached = CatalogSnapshot.from_dict(payload)
+ except CodexAuthError:
+ return None
+ if cached.generation != credentials.generation:
+ return None
+ return cached
+
+ def _active_codex_model(self) -> str | None:
+ """Report the active model only while Codex itself is the active profile.
+
+ Reporting the deployment-wide active model here would tell the operator
+ "Codex is active: deepseek-chat" whenever another provider is selected.
+ """
+ catalog = self._model_catalog.load()
+ llm = catalog.get("services", {}).get("llm", {})
+ if llm.get("active_profile_id") != CODEX_PROFILE_ID:
+ return None
+ model = self._model_catalog.get_active_model(catalog, "llm")
+ if model is None:
+ return None
+ value = model.get("model")
+ return value if isinstance(value, str) and value else None
+
+ def _credentials_from_payload(
+ self,
+ payload: dict[str, Any],
+ *,
+ expected_generation: int,
+ fallback: CodexCredentials | None = None,
+ ) -> CodexCredentials:
+ access_token = self._required_token(
+ payload.get("access_token"),
+ fallback.access_token if fallback is not None else None,
+ )
+ refresh_token = self._required_token(
+ payload.get("refresh_token"),
+ fallback.refresh_token if fallback is not None else None,
+ )
+ id_token = self._required_token(
+ payload.get("id_token"),
+ fallback.id_token if fallback is not None else None,
+ )
+
+ account_id = self._first_nonempty_string(
+ payload.get("account_id"),
+ payload.get("chatgpt_account_id"),
+ )
+ expires_at = self._positive_int(payload.get("expires_at"))
+ for token in (id_token, access_token):
+ if account_id is not None and expires_at is not None:
+ break
+ try:
+ claims = decode_codex_jwt(token)
+ except CodexAuthError:
+ continue
+ account_id = account_id or claims.account_id
+ expires_at = expires_at or claims.expires_at
+
+ if account_id is None and fallback is not None:
+ account_id = fallback.account_id
+ if expires_at is None:
+ expires_in = self._positive_int(payload.get("expires_in"))
+ if expires_in is not None:
+ expires_at = int(self._clock()) + expires_in
+ if expires_at is None and fallback is not None:
+ expires_at = fallback.expires_at
+ if account_id is None or expires_at is None:
+ raise CodexAuthError(
+ "token_response_invalid",
+ "Codex returned incomplete authentication data.",
+ 502,
+ )
+
+ return CodexCredentials(
+ schema_version=1,
+ access_token=access_token,
+ refresh_token=refresh_token,
+ id_token=id_token,
+ account_id=account_id,
+ expires_at=expires_at,
+ generation=expected_generation,
+ )
+
+ @staticmethod
+ def _required_token(value: object, fallback: str | None) -> str:
+ if isinstance(value, str) and value:
+ return value
+ if fallback:
+ return fallback
+ raise CodexAuthError(
+ "token_response_invalid",
+ "Codex returned incomplete authentication data.",
+ 502,
+ )
+
+ @staticmethod
+ def _first_nonempty_string(*values: object) -> str | None:
+ for value in values:
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+ @staticmethod
+ def _positive_int(value: object) -> int | None:
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
+ return None
+ return value
+
+
+_SERVICE_INSTANCES: dict[str, CodexOAuthService] = {}
+
+
+def _codex_user_root() -> Path:
+ """Anchor the credential store to the caller's own root.
+
+ A Codex token is issued against one person's ChatGPT plan. Resolving other
+ users to the administrator's root would run a whole deployment on a single
+ subscription, so every account signs in for itself or does not use Codex.
+ """
+ return get_path_service().get_user_root().resolve()
+
+
+def get_codex_oauth_service() -> CodexOAuthService:
+ user_root = _codex_user_root()
+ key = str(user_root)
+ service = _SERVICE_INSTANCES.get(key)
+ if service is None:
+ store = CodexCredentialStore(user_root)
+ http = httpx.AsyncClient(timeout=30)
+ catalog = CodexModelCatalog(store, http=http)
+ service = CodexOAuthService(
+ store,
+ catalog,
+ get_model_catalog_service(),
+ oauth_client=CodexOAuthClient(http),
+ )
+ _SERVICE_INSTANCES[key] = service
+ return service
+
+
+__all__ = [
+ "CODEX_PROFILE_ID",
+ "MANAGED_BY",
+ "CatalogSyncResult",
+ "CodexOAuthService",
+ "codex_model_id",
+ "get_codex_oauth_service",
+ "remove_codex_catalog",
+ "sync_codex_catalog",
+]
diff --git a/deeptutor/services/codex_auth/storage.py b/deeptutor/services/codex_auth/storage.py
new file mode 100644
index 000000000..5fa6f98a4
--- /dev/null
+++ b/deeptutor/services/codex_auth/storage.py
@@ -0,0 +1,246 @@
+"""Private, generation-safe storage for DeepTutor Codex credentials."""
+
+from __future__ import annotations
+
+from collections.abc import Iterator, Mapping
+from contextlib import contextmanager
+from dataclasses import replace
+import json
+import os
+from pathlib import Path
+import stat
+import tempfile
+import threading
+from typing import Any, BinaryIO
+
+from .contracts import CodexAuthError, CodexCredentials
+
+_SCHEMA_VERSION = 1
+
+
+def _is_reparse_point(path: Path) -> bool:
+ try:
+ attributes = getattr(os.lstat(path), "st_file_attributes", 0)
+ except FileNotFoundError:
+ return False
+ return bool(attributes & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0))
+
+
+def _unsafe_path() -> CodexAuthError:
+ return CodexAuthError(
+ "unsafe_storage_path",
+ "Codex authentication storage uses an unsafe filesystem path.",
+ 500,
+ )
+
+
+def _assert_safe_directory(path: Path) -> None:
+ if path.is_symlink() or _is_reparse_point(path):
+ raise _unsafe_path()
+ if path.exists() and not path.is_dir():
+ raise _unsafe_path()
+
+
+def _assert_safe_regular_path(path: Path) -> None:
+ _assert_safe_directory(path.parent)
+ if path.is_symlink() or _is_reparse_point(path):
+ raise _unsafe_path()
+ if path.exists() and not path.is_file():
+ raise _unsafe_path()
+
+
+@contextmanager
+def _locked_file(path: Path) -> Iterator[BinaryIO]:
+ _assert_safe_regular_path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("a+b") as handle:
+ os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
+ handle.seek(0, os.SEEK_END)
+ if handle.tell() == 0:
+ handle.write(b"\0")
+ handle.flush()
+ handle.seek(0)
+ if os.name == "nt":
+ import msvcrt
+
+ msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
+ try:
+ yield handle
+ finally:
+ handle.seek(0)
+ if os.name == "nt":
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
+ else:
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
+
+
+def _atomic_write_json(path: Path, payload: Mapping[str, Any]) -> None:
+ _assert_safe_regular_path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, temp_name = tempfile.mkstemp(
+ prefix=f".{path.name}.",
+ suffix=".tmp",
+ dir=path.parent,
+ )
+ temp_path = Path(temp_name)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
+ json.dump(payload, handle, ensure_ascii=False, indent=2)
+ handle.write("\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.chmod(temp_path, stat.S_IRUSR | stat.S_IWUSR)
+ os.replace(temp_path, path)
+ finally:
+ temp_path.unlink(missing_ok=True)
+
+
+class CodexCredentialStore:
+ """Store credentials only below DeepTutor's explicitly supplied user root."""
+
+ def __init__(self, user_root: Path) -> None:
+ self.root = Path(user_root) / "private" / "openai-codex"
+ self.credentials_path = self.root / "credentials.v1.json"
+ self.state_path = self.root / "state.v1.json"
+ self.catalog_cache_path = self.root / "models-cache.v1.json"
+ self.lock_path = self.root / "auth.lock"
+ self._thread_lock = threading.Lock()
+
+ def _ensure_root(self) -> None:
+ private_root = self.root.parent
+ private_root.mkdir(parents=True, exist_ok=True)
+ _assert_safe_directory(private_root)
+ self.root.mkdir(exist_ok=True)
+ _assert_safe_directory(self.root)
+ os.chmod(private_root, stat.S_IRWXU)
+ os.chmod(self.root, stat.S_IRWXU)
+
+ @contextmanager
+ def _locked(self) -> Iterator[None]:
+ with self._thread_lock:
+ self._ensure_root()
+ with _locked_file(self.lock_path):
+ yield
+
+ @staticmethod
+ def _read_json(path: Path, *, code: str, message: str) -> dict[str, Any] | None:
+ _assert_safe_regular_path(path)
+ if not path.exists():
+ return None
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise CodexAuthError(code, message, 500) from exc
+ if not isinstance(payload, dict):
+ raise CodexAuthError(code, message, 500)
+ return payload
+
+ def _read_state_unlocked(self) -> dict[str, Any]:
+ state = self._read_json(
+ self.state_path,
+ code="state_corrupt",
+ message="Stored Codex authentication state is invalid.",
+ )
+ if state is None:
+ return {"schema_version": _SCHEMA_VERSION, "generation": 0}
+ generation = state.get("generation")
+ if isinstance(generation, bool) or not isinstance(generation, int) or generation < 0:
+ raise CodexAuthError(
+ "state_corrupt",
+ "Stored Codex authentication state is invalid.",
+ 500,
+ )
+ return state
+
+ @staticmethod
+ def _generation_changed() -> CodexAuthError:
+ return CodexAuthError(
+ "generation_changed",
+ "Codex authentication changed while this operation was running.",
+ 409,
+ )
+
+ def current_generation(self) -> int:
+ with self._locked():
+ return int(self._read_state_unlocked()["generation"])
+
+ def load_credentials(self) -> CodexCredentials | None:
+ with self._locked():
+ state_generation = int(self._read_state_unlocked()["generation"])
+ payload = self._read_json(
+ self.credentials_path,
+ code="credential_corrupt",
+ message="Stored Codex credentials are invalid.",
+ )
+ if payload is None:
+ return None
+ credentials = CodexCredentials.from_dict(payload)
+ if credentials.generation != state_generation:
+ return None
+ return credentials
+
+ def commit_credentials(
+ self,
+ credentials: CodexCredentials,
+ expected_generation: int,
+ ) -> CodexCredentials:
+ with self._locked():
+ state = self._read_state_unlocked()
+ current_generation = int(state["generation"])
+ if current_generation != expected_generation:
+ raise self._generation_changed()
+ next_generation = current_generation + 1
+ committed = replace(
+ credentials,
+ schema_version=_SCHEMA_VERSION,
+ generation=next_generation,
+ )
+ next_state = {
+ **state,
+ "schema_version": _SCHEMA_VERSION,
+ "generation": next_generation,
+ }
+ _atomic_write_json(self.state_path, next_state)
+ _atomic_write_json(self.credentials_path, committed.to_dict())
+ return committed
+
+ def clear_credentials(self, expected_generation: int | None = None) -> int:
+ with self._locked():
+ state = self._read_state_unlocked()
+ current_generation = int(state["generation"])
+ if expected_generation is not None and current_generation != expected_generation:
+ raise self._generation_changed()
+ next_generation = current_generation + 1
+ _atomic_write_json(
+ self.state_path,
+ {
+ **state,
+ "schema_version": _SCHEMA_VERSION,
+ "generation": next_generation,
+ },
+ )
+ for path in (self.credentials_path, self.catalog_cache_path):
+ _assert_safe_regular_path(path)
+ path.unlink(missing_ok=True)
+ return next_generation
+
+ def load_catalog_cache(self) -> dict[str, Any] | None:
+ with self._locked():
+ return self._read_json(
+ self.catalog_cache_path,
+ code="catalog_corrupt",
+ message="Stored Codex model data is invalid.",
+ )
+
+ def save_catalog_cache(self, payload: Mapping[str, Any]) -> None:
+ with self._locked():
+ _atomic_write_json(self.catalog_cache_path, payload)
+
+ def clear_catalog_cache(self) -> None:
+ with self._locked():
+ _assert_safe_regular_path(self.catalog_cache_path)
+ self.catalog_cache_path.unlink(missing_ok=True)
diff --git a/deeptutor/services/config/model_catalog.py b/deeptutor/services/config/model_catalog.py
index cdaa2ec87..8ad7fd957 100644
--- a/deeptutor/services/config/model_catalog.py
+++ b/deeptutor/services/config/model_catalog.py
@@ -1,8 +1,12 @@
from __future__ import annotations
+from collections.abc import Callable
from copy import deepcopy
import json
+import os
from pathlib import Path
+import tempfile
+import threading
from typing import Any
from uuid import uuid4
@@ -51,6 +55,7 @@ class ModelCatalogService:
def __init__(self, path: Path | None = None):
self.path = path or CATALOG_PATH
+ self._lock = threading.RLock()
@classmethod
def get_instance(cls, path: Path | None = None) -> "ModelCatalogService":
@@ -88,12 +93,32 @@ class ModelCatalogService:
return loaded if isinstance(loaded, dict) else {}
def save(self, catalog: dict[str, Any]) -> dict[str, Any]:
- normalized = deepcopy(catalog)
- self._normalize(normalized)
- self.path.parent.mkdir(parents=True, exist_ok=True)
- with open(self.path, "w", encoding="utf-8") as handle:
- json.dump(normalized, handle, indent=2, ensure_ascii=False)
- return normalized
+ with self._lock:
+ normalized = deepcopy(catalog)
+ self._normalize(normalized)
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ fd, temp_name = tempfile.mkstemp(
+ prefix=f".{self.path.name}.",
+ suffix=".tmp",
+ dir=self.path.parent,
+ )
+ temp_path = Path(temp_name)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
+ json.dump(normalized, handle, indent=2, ensure_ascii=False)
+ handle.write("\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(temp_path, self.path)
+ finally:
+ temp_path.unlink(missing_ok=True)
+ return normalized
+
+ def update(self, mutator: Callable[[dict[str, Any]], None]) -> dict[str, Any]:
+ with self._lock:
+ catalog = self.load()
+ mutator(catalog)
+ return self.save(catalog)
def apply(self, catalog: dict[str, Any] | None = None) -> dict[str, Any]:
current = self.save(catalog or self.load())
diff --git a/deeptutor/services/llm/provider_core/openai_codex_provider.py b/deeptutor/services/llm/provider_core/openai_codex_provider.py
index a7ea1917c..95a15d68d 100644
--- a/deeptutor/services/llm/provider_core/openai_codex_provider.py
+++ b/deeptutor/services/llm/provider_core/openai_codex_provider.py
@@ -1,8 +1,7 @@
-"""OpenAI Codex Responses provider backed by oauth-cli-kit."""
+"""OpenAI Codex Responses provider backed by DeepTutor's private OAuth service."""
from __future__ import annotations
-import asyncio
from collections.abc import Awaitable, Callable
import hashlib
import json
@@ -11,6 +10,9 @@ from typing import Any
import httpx
from loguru import logger
+from deeptutor.services.codex_auth import CodexAuthError, get_codex_oauth_service
+from deeptutor.services.codex_auth.constants import CODEX_DEFAULT_MODEL_ID, CODEX_RESPONSES_URL
+from deeptutor.services.codex_auth.contracts import CodexToken
from deeptutor.services.llm.openai_http_client import disable_ssl_verify_enabled
from deeptutor.services.llm.provider_core.base import LLMProvider, LLMResponse, ToolCallRequest
from deeptutor.services.llm.provider_core.openai_responses import (
@@ -19,25 +21,24 @@ from deeptutor.services.llm.provider_core.openai_responses import (
convert_tools,
)
-DEFAULT_CODEX_URL = "https://chatgpt.com/backend-api/codex/responses"
DEFAULT_ORIGINATOR = "DeepTutor"
+class CodexHTTPError(RuntimeError):
+ def __init__(self, status_code: int, safe_message: str) -> None:
+ super().__init__(safe_message)
+ self.status_code = status_code
+
+
class OpenAICodexProvider(LLMProvider):
"""Use OpenAI Codex OAuth tokens to call the Responses API."""
- def __init__(self, default_model: str = "openai-codex/gpt-5.1-codex"):
+ def __init__(self, default_model: str = CODEX_DEFAULT_MODEL_ID):
super().__init__(api_key=None, api_base=None)
self.default_model = default_model
- async def _load_token(self) -> Any:
- try:
- from oauth_cli_kit import get_token as get_codex_token
- except ImportError as exc: # pragma: no cover - optional dependency
- raise RuntimeError(
- "oauth_cli_kit is not installed. Install CLI deps or switch provider."
- ) from exc
- return await asyncio.to_thread(get_codex_token)
+ async def _load_token(self) -> CodexToken:
+ return await get_codex_oauth_service().get_token()
async def _call_codex(
self,
@@ -51,9 +52,6 @@ class OpenAICodexProvider(LLMProvider):
model_name = model or self.default_model
system_prompt, input_items = convert_messages(messages)
- token = await self._load_token()
- headers = _build_headers(getattr(token, "account_id", None), getattr(token, "access", None))
-
body: dict[str, Any] = {
"model": _strip_model_prefix(model_name),
"store": False,
@@ -71,29 +69,68 @@ class OpenAICodexProvider(LLMProvider):
if tools:
body["tools"] = convert_tools(tools)
- try:
+ service = get_codex_oauth_service()
+ async with service.inference_guard():
try:
- content, tool_calls, finish_reason = await _request_codex(
- DEFAULT_CODEX_URL,
- headers,
- body,
- verify=not disable_ssl_verify_enabled(),
- on_content_delta=on_content_delta,
- )
- except Exception as exc:
- if "CERTIFICATE_VERIFY_FAILED" not in str(exc):
+ token = await self._load_token()
+ headers = _build_headers(token.account_id, token.access_token)
+ try:
+ content, tool_calls, finish_reason = await _request_codex(
+ CODEX_RESPONSES_URL,
+ headers,
+ body,
+ verify=not disable_ssl_verify_enabled(),
+ on_content_delta=on_content_delta,
+ )
+ except CodexHTTPError as exc:
+ if exc.status_code == 401:
+ try:
+ await service.recover_after_unauthorized(token.generation)
+ except CodexAuthError:
+ # Only promise a retry when the session really was
+ # renewed; a dead refresh token needs a new sign-in.
+ logger.warning("Codex token renewal after HTTP 401 failed")
+ raise CodexHTTPError(
+ exc.status_code,
+ "Codex login expired and could not be renewed. Sign in again.",
+ ) from None
raise
- logger.warning("SSL verification failed for Codex API; retrying with verify=False")
- content, tool_calls, finish_reason = await _request_codex(
- DEFAULT_CODEX_URL,
- headers,
- body,
- verify=False,
- on_content_delta=on_content_delta,
+ except Exception as exc:
+ if "CERTIFICATE_VERIFY_FAILED" not in str(exc):
+ raise
+ logger.warning(
+ "SSL verification failed for Codex API; retrying with verify=False"
+ )
+ content, tool_calls, finish_reason = await _request_codex(
+ CODEX_RESPONSES_URL,
+ headers,
+ body,
+ verify=False,
+ on_content_delta=on_content_delta,
+ )
+ return LLMResponse(
+ content=content,
+ tool_calls=tool_calls,
+ finish_reason=finish_reason,
+ )
+ except CodexHTTPError as exc:
+ return LLMResponse(
+ content=f"Error calling Codex: {exc}",
+ finish_reason="error",
+ )
+ except CodexAuthError as exc:
+ return LLMResponse(
+ content=f"Error calling Codex: {exc.public_message}",
+ finish_reason="error",
+ )
+ except Exception:
+ # The user-facing text stays generic so upstream payloads never
+ # leak, but an operator still needs the real cause in the log.
+ logger.exception("Codex request failed")
+ return LLMResponse(
+ content="Error calling Codex: Codex request failed. Please try again.",
+ finish_reason="error",
)
- return LLMResponse(content=content, tool_calls=tool_calls, finish_reason=finish_reason)
- except Exception as exc:
- return LLMResponse(content=f"Error calling Codex: {exc}", finish_reason="error")
async def chat(
self,
@@ -142,7 +179,7 @@ def _strip_model_prefix(model: str) -> str:
return model
-def _build_headers(account_id: Any, token: Any) -> dict[str, str]:
+def _build_headers(account_id: str, token: str) -> dict[str, str]:
if not token:
raise RuntimeError(
"OpenAI Codex is not logged in. Run `deeptutor provider login openai-codex`."
@@ -170,9 +207,17 @@ async def _request_codex(
async with httpx.AsyncClient(timeout=60.0, verify=verify) as client:
async with client.stream("POST", url, headers=headers, json=body) as response:
if response.status_code != 200:
- text = await response.aread()
- raise RuntimeError(
- _friendly_error(response.status_code, text.decode("utf-8", "ignore"))
+ raw = await response.aread()
+ # Kept out of the reply the learner sees, but an operator cannot
+ # diagnose an upstream rejection without the body.
+ logger.debug(
+ "Codex API returned HTTP {}: {}",
+ response.status_code,
+ raw.decode("utf-8", "ignore")[:500],
+ )
+ raise CodexHTTPError(
+ response.status_code,
+ _friendly_error(response.status_code),
)
return await consume_sse(response, on_content_delta)
@@ -182,7 +227,11 @@ def _prompt_cache_key(messages: list[dict[str, Any]]) -> str:
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
-def _friendly_error(status_code: int, raw: str) -> str:
+def _friendly_error(status_code: int) -> str:
+ if status_code == 401:
+ return "Codex login expired. The session was refreshed; retry this request."
+ if status_code == 403:
+ return "This Codex account is not allowed to make the requested call."
if status_code == 429:
- return "ChatGPT usage quota exceeded or rate limit triggered. Please try again later."
- return f"HTTP {status_code}: {raw}"
+ return "Codex usage quota exceeded or rate limit triggered. Please try again later."
+ return f"Codex returned HTTP {status_code}."
diff --git a/deeptutor/services/provider_registry.py b/deeptutor/services/provider_registry.py
index 36d910f1d..bb8b96b69 100644
--- a/deeptutor/services/provider_registry.py
+++ b/deeptutor/services/provider_registry.py
@@ -65,6 +65,10 @@ class ProviderSpec:
return "local"
return "standard"
+ @property
+ def auth_mode(self) -> str:
+ return "oauth" if self.is_oauth else "api_key"
+
@property
def label(self) -> str:
return self.display_name or self.name.title()
diff --git a/deeptutor_cli/README.md b/deeptutor_cli/README.md
index c5c3ffbb6..a8964ec11 100644
--- a/deeptutor_cli/README.md
+++ b/deeptutor_cli/README.md
@@ -228,6 +228,10 @@ deeptutor provider login openai-codex # 执行 OpenAI Codex OAuth 登录
deeptutor provider login github-copilot # 校验现有 GitHub Copilot 认证是否可用
```
+`openai-codex` 会打开系统浏览器,使用 DeepTutor 自己的独立 OAuth 流程登录。它不需要 `OPENAI_API_KEY`,也不会读取或同步本机 `~/.codex`;凭据保存在 `<user-root>/private/openai-codex/`,与 Web 设置页共用。授权回调监听本机回环地址,因此须在运行后端的机器上完成登录。
+
+Codex 令牌授权的是**你本人**的 ChatGPT 套餐,因此凭据只归当前登录用户,不会通过模型授权共享给部署内的其他用户——每位用户各自登录。登录成功后,模型列表来自该账号的动态目录;仅当此前尚未配置任何 LLM 时,Codex 才会被自动设为活动模型,否则不改动你已选的模型。目录刷新失败、上游 `429` 或其他错误都会如实报告,不会回退到付费 API Provider。这条 Codex backend 兼容路径目前属于实验性能力。
+
---
## 典型工作流
diff --git a/deeptutor_cli/provider_cmd.py b/deeptutor_cli/provider_cmd.py
index e7ec91000..32f73fa36 100644
--- a/deeptutor_cli/provider_cmd.py
+++ b/deeptutor_cli/provider_cmd.py
@@ -2,8 +2,13 @@
from __future__ import annotations
+import asyncio
+import webbrowser
+
import typer
+from deeptutor.services.codex_auth import CodexAuthError, get_codex_oauth_service
+
from .common import maybe_run
@@ -18,7 +23,7 @@ def register(app: typer.Typer) -> None:
"""Authenticate or validate provider access."""
key = provider.strip().lower().replace("-", "_")
if key == "openai_codex":
- _login_openai_codex()
+ maybe_run(_login_openai_codex())
return
if key == "github_copilot":
maybe_run(_login_github_copilot())
@@ -28,30 +33,44 @@ def register(app: typer.Typer) -> None:
)
-def _login_openai_codex() -> None:
+async def _login_openai_codex() -> None:
+ service = get_codex_oauth_service()
try:
- from oauth_cli_kit import get_token, login_oauth_interactive
- except ImportError:
+ started = await service.start_login()
+ authorize_url = str(started["authorize_url"])
typer.echo(
- "oauth_cli_kit is not installed. Install CLI deps from a local checkout: "
- "python -m pip install -e ./packaging/deeptutor-cli"
+ "Opening the OpenAI Codex sign-in in your browser; "
+ "credentials are written only to DeepTutor's private directory."
)
- raise typer.Exit(code=1)
+ if not webbrowser.open(authorize_url):
+ typer.echo(f"The browser did not open automatically. Visit: {authorize_url}")
- token = None
- try:
- token = get_token()
- except Exception:
- token = None
- if not (token and getattr(token, "access", None)):
- token = login_oauth_interactive(
- print_fn=typer.echo,
- prompt_fn=typer.prompt,
- )
- if not (token and getattr(token, "access", None)):
- typer.echo("OpenAI Codex OAuth authentication failed.")
+ while True:
+ status = service.public_status()
+ operation_state = status.get("operation_state")
+ if operation_state == "completed":
+ typer.echo(
+ f"OpenAI Codex sign-in succeeded. Models available: "
+ f"{status.get('model_count', 0)}."
+ )
+ active_model = status.get("active_model")
+ if active_model:
+ typer.echo(f"Codex is the active model: {active_model}")
+ else:
+ typer.echo("Select a Codex model in Settings to start using it.")
+ return
+ if operation_state in {"failed", "expired", "cancelled"}:
+ error_code = status.get("error_code") or operation_state
+ typer.echo(f"OpenAI Codex sign-in did not complete: {error_code}")
+ raise typer.Exit(code=1)
+ await asyncio.sleep(0.5)
+ except asyncio.CancelledError:
+ await service.cancel_login()
+ typer.echo("Cancelled the OpenAI Codex sign-in.")
+ raise typer.Exit(code=130) from None
+ except CodexAuthError as exc:
+ typer.echo(f"OpenAI Codex sign-in failed: {exc.public_message}")
raise typer.Exit(code=1)
- typer.echo("OpenAI Codex OAuth authentication succeeded.")
async def _login_github_copilot() -> None:
diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.py
index 877252cfe..ad55f5f46 100644
--- a/tests/api/test_settings_router.py
+++ b/tests/api/test_settings_router.py
@@ -1,11 +1,14 @@
from __future__ import annotations
from copy import deepcopy
+import json
+from types import SimpleNamespace
from typing import Any
import pytest
from deeptutor.api.routers import settings as settings_router
+from deeptutor.services.codex_auth.contracts import CodexAuthError
from deeptutor.services.config.provider_runtime import (
ResolvedEmbeddingConfig,
ResolvedLLMConfig,
@@ -44,6 +47,45 @@ class _FakeCatalogService:
}
+class _FakeCodexOAuthService:
+ def __init__(self) -> None:
+ self.calls: list[str] = []
+
+ async def start_login(self) -> dict[str, Any]:
+ self.calls.append("start")
+ return {
+ "operation_id": "operation-1",
+ "authorize_url": "https://auth.openai.com/oauth/authorize?state=opaque",
+ "expires_in": 300,
+ }
+
+ def public_status(self) -> dict[str, Any]:
+ self.calls.append("status")
+ return {
+ "connection": "connected",
+ "operation_id": None,
+ "operation_state": None,
+ "model_count": 1,
+ "catalog_source": "live",
+ "catalog_fetched_at": 1_000,
+ "active_model": "gpt-5.6-sol",
+ "activated": False,
+ "error_code": None,
+ }
+
+ async def cancel_login(self) -> dict[str, Any]:
+ self.calls.append("cancel")
+ return self.public_status()
+
+ async def logout(self) -> dict[str, Any]:
+ self.calls.append("logout")
+ return self.public_status()
+
+ async def refresh_models(self) -> dict[str, Any]:
+ self.calls.append("refresh")
+ return self.public_status()
+
+
def _build_catalog(
*,
llm_model: str,
@@ -725,6 +767,120 @@ async def test_update_ui_settings_preserves_theme_and_language_when_code_block_u
assert persisted["code_block_theme"] == "dracula"
+def test_codex_provider_choice_is_advertised_as_oauth() -> None:
+ llm = {item["value"]: item for item in settings_router._provider_choices()["llm"]}
+
+ assert llm["openai_codex"] == {
+ "value": "openai_codex",
+ "label": "OpenAI Codex",
+ "base_url": "https://chatgpt.com/backend-api",
+ "auth_mode": "oauth",
+ }
+ # API-key providers keep the same shape, so the frontend never special-cases
+ # a missing field.
+ assert llm["openai"]["auth_mode"] == "api_key"
+
+
+async def test_codex_oauth_status_is_admin_only(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from fastapi import HTTPException
+
+ monkeypatch.setattr(
+ settings_router,
+ "get_current_user",
+ lambda: SimpleNamespace(is_admin=False),
+ )
+ monkeypatch.setattr(
+ settings_router,
+ "get_codex_oauth_service",
+ lambda: (_ for _ in ()).throw(AssertionError("service must not be accessed")),
+ raising=False,
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ await settings_router.get_openai_codex_oauth_status()
+
+ assert exc_info.value.status_code == 403
+
+
+async def test_codex_oauth_routes_return_only_public_service_payloads(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ fake = _FakeCodexOAuthService()
+ monkeypatch.setattr(
+ settings_router,
+ "get_current_user",
+ lambda: SimpleNamespace(is_admin=True),
+ )
+ monkeypatch.setattr(
+ settings_router,
+ "get_codex_oauth_service",
+ lambda: fake,
+ raising=False,
+ )
+
+ started = await settings_router.start_openai_codex_oauth()
+ status_payload = await settings_router.get_openai_codex_oauth_status()
+ cancelled = await settings_router.cancel_openai_codex_oauth()
+ refreshed = await settings_router.refresh_openai_codex_models()
+ logged_out = await settings_router.logout_openai_codex_oauth()
+
+ assert set(started) == {"operation_id", "authorize_url", "expires_in"}
+ assert (
+ "token"
+ not in json.dumps([started, status_payload, cancelled, refreshed, logged_out]).lower()
+ )
+ assert fake.calls == [
+ "start",
+ "status",
+ "cancel",
+ "status",
+ "refresh",
+ "status",
+ "logout",
+ "status",
+ ]
+
+
+async def test_codex_oauth_error_maps_to_sanitized_http_detail(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from fastapi import HTTPException
+
+ class FailingService:
+ async def start_login(self) -> dict[str, Any]:
+ raise CodexAuthError(
+ "token_exchange_failed",
+ "Codex sign-in could not be completed.",
+ 502,
+ )
+
+ monkeypatch.setattr(
+ settings_router,
+ "get_current_user",
+ lambda: SimpleNamespace(is_admin=True),
+ )
+ monkeypatch.setattr(
+ settings_router,
+ "get_codex_oauth_service",
+ lambda: FailingService(),
+ raising=False,
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ await settings_router.start_openai_codex_oauth()
+
+ assert exc_info.value.status_code == 502
+ assert exc_info.value.detail == {
+ "code": "token_exchange_failed",
+ "message": "Codex sign-in could not be completed.",
+ }
+
+
@pytest.mark.asyncio
async def test_update_ui_settings_persists_explicit_theme_and_language_defaults(
monkeypatch: pytest.MonkeyPatch, tmp_path
diff --git a/tests/cli/test_provider_cli.py b/tests/cli/test_provider_cli.py
index 9b8ecf5f0..90ba4641d 100644
--- a/tests/cli/test_provider_cli.py
+++ b/tests/cli/test_provider_cli.py
@@ -1,6 +1,11 @@
from pathlib import Path
import unittest
+from typer.testing import CliRunner
+
+from deeptutor_cli import provider_cmd
+from deeptutor_cli.main import app
+
ROOT = Path(__file__).resolve().parents[2]
PROVIDER_CMD = (ROOT / "deeptutor_cli" / "provider_cmd.py").read_text(encoding="utf-8")
CLI_README = (ROOT / "deeptutor_cli" / "README.md").read_text(encoding="utf-8")
@@ -31,5 +36,65 @@ class ProviderCliDocsContractTest(unittest.TestCase):
self.assertNotIn("OAuth login (`openai-codex`, `github-copilot`)", ROOT_README)
+class _FakeCliCodexService:
+ def __init__(self) -> None:
+ self.cancelled = False
+
+ async def start_login(self) -> dict[str, object]:
+ return {
+ "operation_id": "operation-1",
+ "authorize_url": "https://auth.openai.com/oauth/authorize?state=opaque",
+ "expires_in": 300,
+ }
+
+ def public_status(self) -> dict[str, object]:
+ return {
+ "connection": "connected",
+ "operation_state": "completed",
+ "active_model": "gpt-5.6-sol",
+ "model_count": 7,
+ "error_code": None,
+ }
+
+ async def cancel_login(self) -> dict[str, object]:
+ self.cancelled = True
+ return self.public_status()
+
+
+def test_openai_codex_cli_does_not_import_codex_cli_credentials() -> None:
+ assert "oauth_cli_kit" not in PROVIDER_CMD
+ assert "get_codex_oauth_service" in PROVIDER_CMD
+ assert "~/.codex" not in PROVIDER_CMD
+ assert "Path.home" not in PROVIDER_CMD
+
+
+def test_cli_opens_authorize_url_and_waits_for_completion(monkeypatch) -> None:
+ service = _FakeCliCodexService()
+ urls: list[str] = []
+ monkeypatch.setattr(
+ provider_cmd,
+ "get_codex_oauth_service",
+ lambda: service,
+ raising=False,
+ )
+ monkeypatch.setattr(
+ provider_cmd.webbrowser,
+ "open",
+ lambda url: urls.append(url) or True,
+ raising=False,
+ )
+
+ result = CliRunner().invoke(
+ app,
+ ["provider", "login", "openai-codex"],
+ )
+
+ assert urls == ["https://auth.openai.com/oauth/authorize?state=opaque"]
+ assert result.exit_code == 0
+ # The CLI speaks English like every other command in this app.
+ assert "private directory" in result.stdout
+ assert "gpt-5.6-sol" in result.stdout
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/multi_user/test_owner_bound_models.py b/tests/multi_user/test_owner_bound_models.py
new file mode 100644
index 000000000..0c2b1ca37
--- /dev/null
+++ b/tests/multi_user/test_owner_bound_models.py
@@ -0,0 +1,91 @@
+"""Owner-bound profiles are never lent to other accounts through grants.
+
+Codex authenticates one person's ChatGPT plan rather than a billable team key,
+so granting that profile to other users would run a whole deployment on a single
+subscription. Administrators still use their own sign-in: they resolve models
+straight from the catalog and never pass through the grant view tested here.
+"""
+
+from types import SimpleNamespace
+
+import pytest
+
+from deeptutor.multi_user import model_access
+from deeptutor.multi_user.context import reset_current_user, set_current_user
+from deeptutor.multi_user.models import CurrentUser, UserScope
+
+CODEX_PROFILE = "llm-profile-openai-codex-managed"
+
+
+def make_user(tmp_path):
+ return CurrentUser(
+ id="u_alice",
+ username="alice",
+ role="user",
+ scope=UserScope(kind="user", user_id="u_alice", root=tmp_path / "u_alice"),
+ )
+
+
+def _catalog(*, owner_bound: bool) -> dict:
+ profile: dict = {
+ "id": CODEX_PROFILE,
+ "name": "OpenAI Codex",
+ "models": [{"id": "m-sol", "name": "GPT-5.6-Sol", "model": "gpt-5.6-sol"}],
+ }
+ if owner_bound:
+ profile["owner_bound"] = True
+ return {"services": {"llm": {"profiles": [profile]}}}
+
+
+def _grant(_user_id=None) -> dict:
+ return {"models": {"llm": [{"profile_id": CODEX_PROFILE, "model_ids": ["m-sol"]}]}}
+
+
+def test_owner_bound_profile_is_withheld_from_granted_users(tmp_path, monkeypatch):
+ monkeypatch.setattr(model_access, "admin_catalog", lambda: _catalog(owner_bound=True))
+ monkeypatch.setattr(model_access, "load_grant", _grant)
+ token = set_current_user(make_user(tmp_path))
+ try:
+ assert model_access.redacted_model_access()["llm"] == []
+ assert model_access.allowed_llm_options()["options"] == []
+ assert model_access.has_capability_access("llm") is False
+ with pytest.raises(PermissionError):
+ model_access.apply_allowed_llm_selection(
+ {"profile_id": CODEX_PROFILE, "model_id": "m-sol"}
+ )
+ finally:
+ reset_current_user(token)
+
+
+def test_owner_bound_profile_is_not_offered_as_assignable(tmp_path, monkeypatch):
+ """Admins must not be shown a grant the server would silently discard."""
+ from deeptutor.multi_user import router as multi_user_router
+
+ monkeypatch.setattr(
+ multi_user_router,
+ "ModelCatalogService",
+ lambda path=None: SimpleNamespace(load=lambda: _catalog(owner_bound=True)),
+ )
+ monkeypatch.setattr(
+ multi_user_router,
+ "get_admin_path_service",
+ lambda: SimpleNamespace(get_settings_file=lambda _name: tmp_path / "catalog.json"),
+ )
+
+ assert multi_user_router._admin_catalog_summary() == {"llm": []}
+
+
+def test_ordinary_shared_profiles_stay_grantable(tmp_path, monkeypatch):
+ """The filter has to stay narrow: an API-key profile is still shareable."""
+ monkeypatch.setattr(model_access, "admin_catalog", lambda: _catalog(owner_bound=False))
+ monkeypatch.setattr(model_access, "load_grant", _grant)
+ token = set_current_user(make_user(tmp_path))
+ try:
+ granted = model_access.redacted_model_access()["llm"]
+ assert [item["model_id"] for item in granted] == ["m-sol"]
+ assert model_access.has_capability_access("llm") is True
+ assert model_access.apply_allowed_llm_selection(
+ {"profile_id": CODEX_PROFILE, "model_id": "m-sol"}
+ ) == {"profile_id": CODEX_PROFILE, "model_id": "m-sol"}
+ finally:
+ reset_current_user(token)
diff --git a/tests/services/codex_auth/fixtures/models-response.json b/tests/services/codex_auth/fixtures/models-response.json
new file mode 100644
index 000000000..8a933e3c7
--- /dev/null
+++ b/tests/services/codex_auth/fixtures/models-response.json
@@ -0,0 +1,31 @@
+{
+ "models": [
+ {
+ "slug": "gpt-5.6-sol",
+ "display_name": "GPT-5.6-Sol",
+ "visibility": "list",
+ "priority": 1,
+ "default_reasoning_level": "medium",
+ "supported_reasoning_levels": [
+ {
+ "effort": "medium",
+ "description": "Balanced"
+ },
+ {
+ "effort": "high",
+ "description": "Deeper"
+ }
+ ],
+ "supports_reasoning_summary_parameter": true,
+ "supports_parallel_tool_calls": true,
+ "use_responses_lite": false
+ },
+ {
+ "slug": "internal-hidden",
+ "display_name": "Hidden",
+ "visibility": "hide",
+ "priority": 0,
+ "supported_reasoning_levels": []
+ }
+ ]
+}
diff --git a/tests/services/codex_auth/test_catalog.py b/tests/services/codex_auth/test_catalog.py
new file mode 100644
index 000000000..e308b6066
--- /dev/null
+++ b/tests/services/codex_auth/test_catalog.py
@@ -0,0 +1,250 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+import httpx
+import pytest
+
+from deeptutor.services.codex_auth.catalog import CodexModelCatalog, parse_models_response
+from deeptutor.services.codex_auth.constants import (
+ CODEX_CLIENT_VERSION,
+ CODEX_MAX_CATALOG_BYTES,
+ CODEX_MAX_MODELS,
+)
+from deeptutor.services.codex_auth.contracts import CodexAuthError, CodexCredentials
+from deeptutor.services.codex_auth.storage import CodexCredentialStore
+
+FIXTURE_PATH = Path(__file__).parent / "fixtures" / "models-response.json"
+
+
+def _fixture() -> dict[str, Any]:
+ return json.loads(FIXTURE_PATH.read_text(encoding="utf-8"))
+
+
+def _credentials(
+ *,
+ account_id: str = "account-123",
+ generation: int = 1,
+) -> CodexCredentials:
+ return CodexCredentials(
+ schema_version=1,
+ access_token="access-secret",
+ refresh_token="refresh-secret",
+ id_token="id-secret",
+ account_id=account_id,
+ expires_at=2_000_000_000,
+ generation=generation,
+ )
+
+
+class ResponseQueue:
+ def __init__(self, *responses: httpx.Response | Exception) -> None:
+ self.responses = list(responses)
+ self.requests: list[httpx.Request] = []
+
+ def __call__(self, request: httpx.Request) -> httpx.Response:
+ self.requests.append(request)
+ response = self.responses.pop(0)
+ if isinstance(response, Exception):
+ raise response
+ return response
+
+
+def _catalog(
+ tmp_path: Path,
+ queue: ResponseQueue,
+ clock: list[int],
+) -> tuple[CodexModelCatalog, httpx.AsyncClient]:
+ http = httpx.AsyncClient(transport=httpx.MockTransport(queue))
+ catalog = CodexModelCatalog(
+ CodexCredentialStore(tmp_path),
+ http=http,
+ clock=lambda: clock[0],
+ )
+ return catalog, http
+
+
+def test_parse_catalog_keeps_only_picker_visible_raw_models() -> None:
+ models = parse_models_response(_fixture())
+
+ assert [model.slug for model in models] == ["gpt-5.6-sol"]
+ assert models[0].display_name == "GPT-5.6-Sol"
+ assert models[0].supported_reasoning_levels == ("medium", "high")
+ assert models[0].supports_reasoning_summary is True
+
+
+def test_parse_catalog_supports_legacy_summary_field_and_sorts() -> None:
+ payload = {
+ "models": [
+ {
+ "slug": "z-last",
+ "display_name": "Z",
+ "visibility": "list",
+ "priority": 2,
+ "supported_reasoning_levels": [],
+ "supports_reasoning_summaries": True,
+ },
+ {
+ "slug": "a-first",
+ "display_name": "A",
+ "visibility": "list",
+ "priority": 1,
+ "supported_reasoning_levels": [],
+ },
+ ]
+ }
+
+ models = parse_models_response(payload)
+
+ assert [model.slug for model in models] == ["a-first", "z-last"]
+ assert models[1].supports_reasoning_summary is True
+
+
+def test_parse_catalog_rejects_more_than_model_limit() -> None:
+ models = [
+ {
+ "slug": f"model-{index}",
+ "display_name": f"Model {index}",
+ "visibility": "list",
+ "priority": index,
+ "supported_reasoning_levels": [],
+ }
+ for index in range(CODEX_MAX_MODELS + 1)
+ ]
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ parse_models_response({"models": models})
+
+ assert exc_info.value.code == "catalog_too_large"
+
+
+async def test_live_catalog_uses_account_headers_and_client_version(tmp_path: Path) -> None:
+ queue = ResponseQueue(httpx.Response(200, json=_fixture(), headers={"ETag": '"catalog-v1"'}))
+ clock = [1_000]
+ catalog, http = _catalog(tmp_path, queue, clock)
+ try:
+ snapshot = await catalog.get(_credentials(), force=True)
+ finally:
+ await http.aclose()
+
+ request = queue.requests[0]
+ assert request.url.params["client_version"] == CODEX_CLIENT_VERSION
+ assert request.headers["chatgpt-account-id"] == "account-123"
+ assert request.headers["authorization"] == "Bearer access-secret"
+ assert snapshot.source == "live"
+ assert snapshot.etag == '"catalog-v1"'
+
+
+async def test_fresh_cache_skips_network_and_etag_304_revalidates(tmp_path: Path) -> None:
+ queue = ResponseQueue(
+ httpx.Response(200, json=_fixture(), headers={"ETag": '"catalog-v1"'}),
+ httpx.Response(304),
+ )
+ clock = [1_000]
+ catalog, http = _catalog(tmp_path, queue, clock)
+ try:
+ live = await catalog.get(_credentials(), force=True)
+ clock[0] = 1_100
+ fresh = await catalog.get(_credentials(), force=False)
+ assert len(queue.requests) == 1
+ clock[0] = 1_301
+ revalidated = await catalog.get(_credentials(), force=False)
+ finally:
+ await http.aclose()
+
+ assert live.source == "live"
+ assert fresh.source == "fresh-cache"
+ assert revalidated.source == "revalidated-cache"
+ assert revalidated.fetched_at == 1_301
+ assert queue.requests[1].headers["if-none-match"] == '"catalog-v1"'
+
+
+async def test_network_failure_uses_only_matching_stale_cache(tmp_path: Path) -> None:
+ queue = ResponseQueue(
+ httpx.Response(200, json=_fixture()),
+ httpx.ConnectError("offline"),
+ httpx.ConnectError("offline"),
+ )
+ clock = [1_000]
+ catalog, http = _catalog(tmp_path, queue, clock)
+ try:
+ await catalog.get(_credentials(), force=True)
+ clock[0] = 1_301
+ stale = await catalog.get(_credentials(), force=False)
+ with pytest.raises(CodexAuthError) as wrong_generation:
+ await catalog.get(_credentials(generation=2), force=True)
+ finally:
+ await http.aclose()
+
+ assert stale.source == "stale-cache"
+ assert wrong_generation.value.code == "catalog_unavailable"
+
+
+async def test_cache_is_partitioned_by_account(tmp_path: Path) -> None:
+ queue = ResponseQueue(
+ httpx.Response(200, json=_fixture()),
+ httpx.ConnectError("offline"),
+ )
+ clock = [1_000]
+ catalog, http = _catalog(tmp_path, queue, clock)
+ try:
+ await catalog.get(_credentials(account_id="account-a"), force=True)
+ clock[0] = 1_301
+ with pytest.raises(CodexAuthError) as exc_info:
+ await catalog.get(
+ _credentials(account_id="account-b"),
+ force=True,
+ )
+ finally:
+ await http.aclose()
+
+ assert exc_info.value.code == "catalog_unavailable"
+
+
+ ("status_code", "error_code"),
+ [(401, "catalog_unauthorized"), (403, "catalog_forbidden")],
+)
+async def test_auth_errors_never_use_stale_cache(
+ tmp_path: Path,
+ status_code: int,
+ error_code: str,
+) -> None:
+ queue = ResponseQueue(
+ httpx.Response(200, json=_fixture()),
+ httpx.Response(status_code, text="private error"),
+ )
+ clock = [1_000]
+ catalog, http = _catalog(tmp_path, queue, clock)
+ try:
+ await catalog.get(_credentials(), force=True)
+ clock[0] = 1_301
+ with pytest.raises(CodexAuthError) as exc_info:
+ await catalog.get(_credentials(), force=True)
+ finally:
+ await http.aclose()
+
+ assert exc_info.value.code == error_code
+ assert "private error" not in str(exc_info.value)
+ assert CodexCredentialStore(tmp_path).load_catalog_cache() is None
+
+
+async def test_catalog_rejects_response_larger_than_eight_mib(tmp_path: Path) -> None:
+ queue = ResponseQueue(httpx.Response(200, content=b" " * (CODEX_MAX_CATALOG_BYTES + 1)))
+ clock = [1_000]
+ catalog, http = _catalog(tmp_path, queue, clock)
+ try:
+ with pytest.raises(CodexAuthError) as exc_info:
+ await catalog.get(_credentials(), force=True)
+ finally:
+ await http.aclose()
+
+ assert exc_info.value.code == "catalog_too_large"
diff --git a/tests/services/codex_auth/test_contracts.py b/tests/services/codex_auth/test_contracts.py
new file mode 100644
index 000000000..0624043b2
--- /dev/null
+++ b/tests/services/codex_auth/test_contracts.py
@@ -0,0 +1,163 @@
+from __future__ import annotations
+
+import base64
+import json
+
+import pytest
+
+from deeptutor.services.codex_auth.constants import (
+ CODEX_CALLBACK_PORTS,
+ CODEX_CLIENT_VERSION,
+ CODEX_DEFAULT_MODEL,
+ CODEX_MODELS_URL,
+ CODEX_OAUTH_CLIENT_ID,
+)
+from deeptutor.services.codex_auth.contracts import (
+ CatalogSnapshot,
+ CodexAuthError,
+ CodexCredentials,
+ CodexModel,
+ TokenClaims,
+ decode_codex_jwt,
+)
+
+
+def _jwt_for_test(payload: dict[str, object]) -> str:
+ def encode(value: dict[str, object]) -> str:
+ raw = json.dumps(value, separators=(",", ":")).encode("utf-8")
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
+
+ return f"{encode({'alg': 'none'})}.{encode(payload)}."
+
+
+def _model() -> CodexModel:
+ return CodexModel(
+ slug="gpt-5.6-sol",
+ display_name="GPT-5.6-Sol",
+ priority=10,
+ visibility="list",
+ default_reasoning_level="medium",
+ supported_reasoning_levels=("low", "medium", "high"),
+ supports_reasoning_summary=True,
+ supports_parallel_tool_calls=True,
+ use_responses_lite=False,
+ )
+
+
+def test_codex_upstream_contract_is_pinned() -> None:
+ assert CODEX_OAUTH_CLIENT_ID == "app_EMoamEEZ73f0CkXaXp7hrann"
+ assert CODEX_CALLBACK_PORTS == (1455, 1457)
+ assert CODEX_CLIENT_VERSION == "0.145.0"
+ assert CODEX_MODELS_URL.endswith("/backend-api/codex/models")
+ assert CODEX_DEFAULT_MODEL == "gpt-5.6-sol"
+
+
+def test_decode_token_claims_drops_email() -> None:
+ token = _jwt_for_test(
+ {
+ "exp": 2_000_000_000,
+ "email": "[email protected]",
+ "https://api.openai.com/auth": {
+ "chatgpt_account_id": "account-123",
+ "chatgpt_plan_type": "plus",
+ },
+ }
+ )
+
+ claims = decode_codex_jwt(token)
+
+ assert claims == TokenClaims(expires_at=2_000_000_000, account_id="account-123")
+ assert "email" not in repr(claims).lower()
+ assert "example.test" not in repr(claims)
+
+
+def test_decode_token_claims_ignores_wrong_field_types() -> None:
+ token = _jwt_for_test(
+ {
+ "exp": "not-an-integer",
+ "https://api.openai.com/auth": {"chatgpt_account_id": 42},
+ }
+ )
+
+ assert decode_codex_jwt(token) == TokenClaims(expires_at=None, account_id=None)
+
+
+def test_decode_token_claims_rejects_malformed_payload_without_echoing_token() -> None:
+ token = "header.not-base64.secret"
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ decode_codex_jwt(token)
+
+ error = exc_info.value
+ assert error.code == "invalid_token"
+ assert error.http_status == 401
+ assert str(error) == error.public_message
+ assert token not in str(error)
+
+
+def test_credentials_round_trip_and_public_token() -> None:
+ credentials = CodexCredentials(
+ schema_version=1,
+ access_token="access-secret",
+ refresh_token="refresh-secret",
+ id_token="id-secret",
+ account_id="account-123",
+ expires_at=2_000_000_000,
+ generation=7,
+ )
+
+ restored = CodexCredentials.from_dict(credentials.to_dict())
+
+ assert restored == credentials
+ assert restored.public_token().access_token == "access-secret"
+ assert not hasattr(restored.public_token(), "refresh_token")
+
+
+ ("field", "value"),
+ [
+ ("access_token", None),
+ ("refresh_token", ""),
+ ("id_token", 123),
+ ("account_id", None),
+ ("expires_at", True),
+ ("generation", True),
+ ("schema_version", 2),
+ ],
+)
+def test_credentials_reject_corrupt_field_types(
+ field: str,
+ value: object,
+) -> None:
+ payload = CodexCredentials(
+ schema_version=1,
+ access_token="access-secret",
+ refresh_token="refresh-secret",
+ id_token="id-secret",
+ account_id="account-123",
+ expires_at=2_000_000_000,
+ generation=7,
+ ).to_dict()
+ payload[field] = value
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ CodexCredentials.from_dict(payload)
+
+ assert exc_info.value.code == "credential_corrupt"
+
+
+def test_catalog_snapshot_round_trip_preserves_tuples() -> None:
+ snapshot = CatalogSnapshot(
+ models=(_model(),),
+ source="live",
+ fetched_at=2_000_000_000,
+ etag='"catalog-v1"',
+ generation=7,
+ account_hash="account-hash",
+ )
+
+ restored = CatalogSnapshot.from_dict(snapshot.to_dict())
+
+ assert restored == snapshot
+ assert isinstance(restored.models, tuple)
+ assert isinstance(restored.models[0].supported_reasoning_levels, tuple)
diff --git a/tests/services/codex_auth/test_oauth.py b/tests/services/codex_auth/test_oauth.py
new file mode 100644
index 000000000..4f8e936f3
--- /dev/null
+++ b/tests/services/codex_auth/test_oauth.py
@@ -0,0 +1,209 @@
+from __future__ import annotations
+
+import asyncio
+import json
+from urllib.parse import parse_qs, urlsplit
+
+import httpx
+import pytest
+
+from deeptutor.services.codex_auth.constants import (
+ CODEX_OAUTH_CLIENT_ID,
+ CODEX_OAUTH_SCOPE,
+)
+from deeptutor.services.codex_auth.contracts import CodexAuthError, CodexCredentials
+from deeptutor.services.codex_auth.oauth import (
+ CodexOAuthClient,
+ LoopbackCallback,
+ PkceCodes,
+ build_authorize_url,
+ generate_pkce,
+)
+
+
+async def _send_get(port: int, target: str) -> str:
+ reader, writer = await asyncio.open_connection("127.0.0.1", port)
+ writer.write(
+ f"GET {target} HTTP/1.1\r\nHost: localhost:{port}\r\nConnection: close\r\n\r\n".encode()
+ )
+ await writer.drain()
+ response = (await reader.read()).decode("utf-8", errors="replace")
+ writer.close()
+ await writer.wait_closed()
+ return response
+
+
+def _credentials() -> CodexCredentials:
+ return CodexCredentials(
+ schema_version=1,
+ access_token="access-secret",
+ refresh_token="refresh-secret",
+ id_token="id-secret",
+ account_id="account-123",
+ expires_at=2_000_000_000,
+ generation=1,
+ )
+
+
+def test_authorize_url_matches_audited_codex_contract() -> None:
+ pkce = PkceCodes(verifier="v" * 64, challenge="challenge")
+ url = build_authorize_url(
+ redirect_uri="http://localhost:1455/auth/callback",
+ state="state-123",
+ pkce=pkce,
+ )
+ query = parse_qs(urlsplit(url).query)
+
+ assert query["client_id"] == [CODEX_OAUTH_CLIENT_ID]
+ assert query["scope"] == [CODEX_OAUTH_SCOPE]
+ assert query["code_challenge_method"] == ["S256"]
+ assert query["state"] == ["state-123"]
+ assert query["id_token_add_organizations"] == ["true"]
+ assert query["codex_cli_simplified_flow"] == ["true"]
+ assert query["originator"] == ["codex_cli_rs"]
+
+
+def test_generated_pkce_is_url_safe_and_self_consistent() -> None:
+ first = generate_pkce()
+ second = generate_pkce()
+
+ assert 43 <= len(first.verifier) <= 128
+ assert "=" not in first.verifier
+ assert "=" not in first.challenge
+ assert first != second
+
+
+async def test_loopback_accepts_callback_without_echoing_secrets() -> None:
+ callback = await LoopbackCallback.start(ports=(0,))
+
+ response = await _send_get(
+ callback.port,
+ "/auth/callback?code=secret-code&state=expected",
+ )
+ result = await callback.wait(timeout=1)
+
+ assert result.code == "secret-code"
+ assert result.state == "expected"
+ assert result.error is None
+ assert "200 OK" in response
+ assert "secret-code" not in response
+ assert "expected" not in response
+
+
+async def test_loopback_ignores_wrong_path_then_accepts_oauth_error() -> None:
+ callback = await LoopbackCallback.start(ports=(0,))
+
+ response = await _send_get(callback.port, "/wrong?code=do-not-accept")
+ assert "404 Not Found" in response
+ result_task = asyncio.create_task(callback.wait(timeout=1))
+ await asyncio.sleep(0)
+ assert not result_task.done()
+
+ await _send_get(
+ callback.port,
+ "/auth/callback?error=access_denied&state=expected",
+ )
+ result = await result_task
+ assert result.code is None
+ assert result.error == "access_denied"
+ assert result.state == "expected"
+
+
+async def test_loopback_falls_back_when_first_port_is_occupied() -> None:
+ occupied = await asyncio.start_server(lambda _reader, _writer: None, "127.0.0.1", 0)
+ occupied_port = int(occupied.sockets[0].getsockname()[1])
+ callback = await LoopbackCallback.start(ports=(occupied_port, 0))
+ try:
+ assert callback.hosts[0] == "127.0.0.1"
+ assert all(host in {"127.0.0.1", "::1"} for host in callback.hosts)
+ assert callback.port != occupied_port
+ finally:
+ await callback.cancel()
+ occupied.close()
+ await occupied.wait_closed()
+
+
+async def test_loopback_timeout_and_cancel_are_public_errors() -> None:
+ timed_out = await LoopbackCallback.start(ports=(0,))
+ with pytest.raises(CodexAuthError) as timeout_error:
+ await timed_out.wait(timeout=0.01)
+ assert timeout_error.value.code == "login_timeout"
+
+ cancelled = await LoopbackCallback.start(ports=(0,))
+ waiter = asyncio.create_task(cancelled.wait(timeout=1))
+ await asyncio.sleep(0)
+ await cancelled.cancel()
+ with pytest.raises(CodexAuthError) as cancel_error:
+ await waiter
+ assert cancel_error.value.code == "login_cancelled"
+
+
+async def test_oauth_http_requests_match_exchange_refresh_and_revoke_contracts() -> None:
+ requests: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ requests.append(request)
+ if request.url.path.endswith("/revoke"):
+ return httpx.Response(200)
+ return httpx.Response(
+ 200,
+ json={
+ "access_token": "new-access",
+ "refresh_token": "new-refresh",
+ "id_token": "new-id",
+ "expires_in": 3600,
+ },
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
+ client = CodexOAuthClient(http)
+ exchanged = await client.exchange_code(
+ code="authorization-code",
+ redirect_uri="http://localhost:1455/auth/callback",
+ verifier="verifier",
+ )
+ refreshed = await client.refresh("refresh-secret")
+ await client.revoke(_credentials())
+
+ exchange_body = parse_qs(requests[0].content.decode())
+ assert requests[0].headers["content-type"].startswith("application/x-www-form-urlencoded")
+ assert exchange_body == {
+ "client_id": [CODEX_OAUTH_CLIENT_ID],
+ "grant_type": ["authorization_code"],
+ "code": ["authorization-code"],
+ "redirect_uri": ["http://localhost:1455/auth/callback"],
+ "code_verifier": ["verifier"],
+ }
+ assert json.loads(requests[1].content) == {
+ "client_id": CODEX_OAUTH_CLIENT_ID,
+ "grant_type": "refresh_token",
+ "refresh_token": "refresh-secret",
+ }
+ revoke_body = parse_qs(requests[2].content.decode())
+ assert revoke_body == {
+ "client_id": [CODEX_OAUTH_CLIENT_ID],
+ "token": ["refresh-secret"],
+ "token_type_hint": ["refresh_token"],
+ }
+ assert exchanged["access_token"] == "new-access"
+ assert refreshed["refresh_token"] == "new-refresh"
+
+
+async def test_oauth_http_failure_does_not_echo_upstream_body() -> None:
+ def handler(_request: httpx.Request) -> httpx.Response:
+ return httpx.Response(400, text="private-upstream-detail")
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
+ client = CodexOAuthClient(http)
+ with pytest.raises(CodexAuthError) as exc_info:
+ await client.refresh("refresh-secret")
+
+ assert exc_info.value.code == "token_refresh_failed"
+ assert "private-upstream-detail" not in str(exc_info.value)
+ assert "refresh-secret" not in str(exc_info.value)
diff --git a/tests/services/codex_auth/test_service.py b/tests/services/codex_auth/test_service.py
new file mode 100644
index 000000000..35f6526e5
--- /dev/null
+++ b/tests/services/codex_auth/test_service.py
@@ -0,0 +1,713 @@
+from __future__ import annotations
+
+import asyncio
+from copy import deepcopy
+import json
+from pathlib import Path
+from typing import Any
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+
+from deeptutor.services.codex_auth import service as service_module
+from deeptutor.services.codex_auth.contracts import (
+ CatalogSnapshot,
+ CodexAuthError,
+ CodexCredentials,
+ CodexModel,
+)
+from deeptutor.services.codex_auth.oauth import OAuthCallbackResult
+from deeptutor.services.codex_auth.service import (
+ CODEX_PROFILE_ID,
+ MANAGED_BY,
+ CodexOAuthService,
+ codex_model_id,
+ remove_codex_catalog,
+ sync_codex_catalog,
+)
+from deeptutor.services.codex_auth.storage import CodexCredentialStore
+from deeptutor.services.config.model_catalog import ModelCatalogService
+
+
+def test_each_user_gets_their_own_codex_credential_root(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """A Codex token authorizes one person's ChatGPT plan, so it is never pooled.
+
+ Resolving other accounts to the administrator's root would run an entire
+ deployment on a single subscription.
+ """
+ roots = {"admin": tmp_path / "admin-user", "learner": tmp_path / "regular-user"}
+ signed_in = {"who": "admin"}
+ monkeypatch.setattr(
+ service_module,
+ "get_path_service",
+ lambda: type("Paths", (), {"get_user_root": lambda self: roots[signed_in["who"]]})(),
+ )
+
+ assert service_module._codex_user_root() == roots["admin"]
+ signed_in["who"] = "learner"
+ assert service_module._codex_user_root() == roots["learner"]
+ assert not hasattr(service_module, "get_admin_path_service")
+
+
+def _model(
+ slug: str,
+ *,
+ display_name: str | None = None,
+ priority: int = 1,
+) -> CodexModel:
+ return CodexModel(
+ slug=slug,
+ display_name=display_name or slug,
+ priority=priority,
+ visibility="list",
+ default_reasoning_level="medium",
+ supported_reasoning_levels=("medium", "high"),
+ supports_reasoning_summary=True,
+ supports_parallel_tool_calls=True,
+ use_responses_lite=False,
+ )
+
+
+def _snapshot(
+ source: str,
+ *models: CodexModel,
+) -> CatalogSnapshot:
+ return CatalogSnapshot(
+ models=models,
+ source=source, # type: ignore[arg-type]
+ fetched_at=1_000,
+ etag='"v1"',
+ generation=1,
+ account_hash="account-hash",
+ )
+
+
+def _seeded_service(tmp_path: Path) -> tuple[ModelCatalogService, dict]:
+ service = ModelCatalogService(tmp_path / "model_catalog.json")
+ original = service.load()
+ llm = original["services"]["llm"]
+ llm["profiles"] = [
+ {
+ "id": "llm-profile-existing",
+ "name": "Existing",
+ "binding": "siliconflow",
+ "base_url": "https://api.siliconflow.cn/v1",
+ "api_key": "existing-key",
+ "models": [
+ {
+ "id": "llm-model-existing",
+ "name": "DeepSeek V3",
+ "model": "deepseek-ai/DeepSeek-V3",
+ },
+ {
+ "id": "llm-model-backup",
+ "name": "Backup",
+ "model": "backup-model",
+ },
+ ],
+ }
+ ]
+ llm["active_profile_id"] = "llm-profile-existing"
+ llm["active_model_id"] = "llm-model-existing"
+ saved = service.save(original)
+ return service, saved
+
+
+def _selection(catalog: dict) -> dict[str, str | None]:
+ llm = catalog["services"]["llm"]
+ return {
+ "profile_id": llm.get("active_profile_id"),
+ "model_id": llm.get("active_model_id"),
+ }
+
+
+def _managed_profile(catalog: dict) -> dict:
+ return next(
+ profile
+ for profile in catalog["services"]["llm"]["profiles"]
+ if profile.get("managed_by") == MANAGED_BY
+ )
+
+
+def test_sync_publishes_a_read_only_owner_bound_codex_profile(tmp_path: Path) -> None:
+ service, _original = _seeded_service(tmp_path)
+
+ result = sync_codex_catalog(
+ service,
+ _snapshot("live", _model("gpt-5.6-sol"), _model("gpt-5.6-terra", priority=2)),
+ )
+
+ profile = _managed_profile(result.catalog)
+ assert profile["id"] == CODEX_PROFILE_ID
+ assert profile["binding"] == "openai_codex"
+ assert profile["api_key"] == ""
+ assert profile["read_only"] is True
+ # Owner-bound stops grants from lending this ChatGPT plan to other accounts.
+ assert profile["owner_bound"] is True
+ assert [model["model"] for model in profile["models"]] == [
+ "gpt-5.6-sol",
+ "gpt-5.6-terra",
+ ]
+
+
+def test_signing_in_never_replaces_a_model_the_operator_already_chose(
+ tmp_path: Path,
+) -> None:
+ """Connecting a provider must not silently repoint everyone's chats."""
+ service, original = _seeded_service(tmp_path)
+
+ result = sync_codex_catalog(service, _snapshot("live", _model("gpt-5.6-sol")))
+
+ assert result.activated is False
+ assert _selection(result.catalog) == _selection(original)
+
+
+def test_signing_in_activates_codex_only_when_no_model_is_configured(
+ tmp_path: Path,
+) -> None:
+ service = ModelCatalogService(tmp_path / "model_catalog.json")
+
+ result = sync_codex_catalog(service, _snapshot("live", _model("gpt-5.6-sol")))
+
+ assert result.activated is True
+ assert _selection(result.catalog) == {
+ "profile_id": CODEX_PROFILE_ID,
+ "model_id": codex_model_id("gpt-5.6-sol"),
+ }
+
+
+def test_refresh_replaces_only_managed_models(tmp_path: Path) -> None:
+ service, _original = _seeded_service(tmp_path)
+ first = sync_codex_catalog(
+ service,
+ _snapshot("live", _model("gpt-5.6-sol"), _model("old-model")),
+ )
+ existing_profile = deepcopy(
+ next(
+ profile
+ for profile in first.catalog["services"]["llm"]["profiles"]
+ if profile["id"] == "llm-profile-existing"
+ )
+ )
+
+ refreshed = sync_codex_catalog(service, _snapshot("live", _model("new-model")))
+
+ assert [model["model"] for model in _managed_profile(refreshed.catalog)["models"]] == [
+ "new-model"
+ ]
+ assert (
+ next(
+ profile
+ for profile in refreshed.catalog["services"]["llm"]["profiles"]
+ if profile["id"] == "llm-profile-existing"
+ )
+ == existing_profile
+ )
+
+
+def test_refresh_repoints_a_selection_whose_model_left_the_account(tmp_path: Path) -> None:
+ service = ModelCatalogService(tmp_path / "model_catalog.json")
+ sync_codex_catalog(service, _snapshot("live", _model("retired-model")))
+
+ refreshed = sync_codex_catalog(service, _snapshot("live", _model("current-model")))
+
+ assert _selection(refreshed.catalog) == {
+ "profile_id": CODEX_PROFILE_ID,
+ "model_id": codex_model_id("current-model"),
+ }
+
+
+def test_logout_removes_the_managed_profile_and_clears_its_selection(
+ tmp_path: Path,
+) -> None:
+ service = ModelCatalogService(tmp_path / "model_catalog.json")
+ sync_codex_catalog(service, _snapshot("live", _model("gpt-5.6-sol")))
+
+ removed = remove_codex_catalog(service)
+
+ assert removed["services"]["llm"]["profiles"] == []
+ assert _selection(removed) == {"profile_id": None, "model_id": None}
+
+
+def test_logout_leaves_another_providers_selection_untouched(tmp_path: Path) -> None:
+ service, original = _seeded_service(tmp_path)
+ sync_codex_catalog(service, _snapshot("live", _model("gpt-5.6-sol")))
+
+ removed = remove_codex_catalog(service)
+
+ assert _selection(removed) == _selection(original)
+ assert not any(
+ profile.get("managed_by") == MANAGED_BY
+ for profile in removed["services"]["llm"]["profiles"]
+ )
+
+
+def test_catalog_sync_does_not_touch_neighboring_history_file(tmp_path: Path) -> None:
+ history = tmp_path / "chat-history.json"
+ history.write_text('{"model":"old"}', encoding="utf-8")
+ service, _original = _seeded_service(tmp_path)
+
+ sync_codex_catalog(service, _snapshot("live", _model("gpt-5.6-sol")))
+
+ assert history.read_text(encoding="utf-8") == '{"model":"old"}'
+
+
+class FakeCallback:
+ port = 1455
+
+ def __init__(self, error: CodexAuthError | None = None) -> None:
+ self._result: asyncio.Future[OAuthCallbackResult] = (
+ asyncio.get_running_loop().create_future()
+ )
+ self.error = error
+
+ async def wait(self, timeout: float) -> OAuthCallbackResult:
+ if self.error is not None:
+ raise self.error
+ return await asyncio.wait_for(asyncio.shield(self._result), timeout)
+
+ async def cancel(self) -> None:
+ if not self._result.done():
+ self._result.set_exception(
+ CodexAuthError("login_cancelled", "Codex sign-in was cancelled.", 409)
+ )
+
+ def complete(self, authorize_url: str, *, code: str = "authorization-code") -> None:
+ state = parse_qs(urlsplit(authorize_url).query)["state"][0]
+ self._result.set_result(OAuthCallbackResult(code=code, state=state, error=None))
+
+ def complete_with_state(self, state: str) -> None:
+ self._result.set_result(
+ OAuthCallbackResult(code="authorization-code", state=state, error=None)
+ )
+
+
+class FakeOAuthClient:
+ def __init__(self) -> None:
+ self.exchange_payload: dict[str, Any] = {
+ "access_token": "new-access",
+ "refresh_token": "new-refresh",
+ "id_token": "new-id",
+ "account_id": "account-123",
+ "expires_in": 3_600,
+ }
+ self.refresh_payload: dict[str, Any] = {
+ "access_token": "refreshed-access",
+ "refresh_token": "refreshed-refresh",
+ "id_token": "refreshed-id",
+ "account_id": "account-123",
+ "expires_in": 3_600,
+ }
+ self.exchange_error: CodexAuthError | None = None
+ self.revoke_error: CodexAuthError | None = None
+ self.refresh_started: asyncio.Event | None = None
+ self.refresh_release: asyncio.Event | None = None
+ self.refresh_calls = 0
+
+ async def exchange_code(
+ self,
+ code: str,
+ redirect_uri: str,
+ verifier: str,
+ ) -> dict[str, Any]:
+ del code, redirect_uri, verifier
+ if self.exchange_error is not None:
+ raise self.exchange_error
+ return dict(self.exchange_payload)
+
+ async def refresh(self, refresh_token: str) -> dict[str, Any]:
+ del refresh_token
+ self.refresh_calls += 1
+ if self.refresh_started is not None:
+ self.refresh_started.set()
+ if self.refresh_release is not None:
+ await self.refresh_release.wait()
+ return dict(self.refresh_payload)
+
+ async def revoke(self, credentials: CodexCredentials) -> None:
+ del credentials
+ if self.revoke_error is not None:
+ raise self.revoke_error
+
+
+class FakeCatalog:
+ def __init__(
+ self,
+ snapshot: CatalogSnapshot,
+ error: CodexAuthError | None = None,
+ ) -> None:
+ self.snapshot = snapshot
+ self.error = error
+ self.calls: list[tuple[int, bool]] = []
+ self.invalidated = False
+ self.get_started: asyncio.Event | None = None
+ self.get_release: asyncio.Event | None = None
+
+ async def get(
+ self,
+ credentials: CodexCredentials,
+ force: bool,
+ ) -> CatalogSnapshot:
+ self.calls.append((credentials.generation, force))
+ if self.get_started is not None:
+ self.get_started.set()
+ if self.get_release is not None:
+ await self.get_release.wait()
+ if self.error is not None:
+ raise self.error
+ return self.snapshot
+
+ async def invalidate(self) -> None:
+ self.invalidated = True
+
+
+def _stored_credentials(
+ token: str = "old",
+ *,
+ expires_at: int = 10_000,
+) -> CodexCredentials:
+ return CodexCredentials(
+ schema_version=1,
+ access_token=f"{token}-access",
+ refresh_token=f"{token}-refresh",
+ id_token=f"{token}-id",
+ account_id="account-123",
+ expires_at=expires_at,
+ generation=0,
+ )
+
+
+async def _oauth_service(
+ tmp_path: Path,
+ *,
+ callback_error: CodexAuthError | None = None,
+ catalog_error: CodexAuthError | None = None,
+ clock: list[int] | None = None,
+) -> tuple[
+ CodexOAuthService,
+ FakeCallback,
+ FakeOAuthClient,
+ FakeCatalog,
+ CodexCredentialStore,
+ ModelCatalogService,
+]:
+ callback = FakeCallback(callback_error)
+ oauth = FakeOAuthClient()
+ snapshot = _snapshot("live", _model("gpt-5.6-sol"))
+ catalog = FakeCatalog(snapshot, catalog_error)
+ store = CodexCredentialStore(tmp_path)
+ model_catalog, _original = _seeded_service(tmp_path)
+
+ async def callback_factory() -> FakeCallback:
+ return callback
+
+ service = CodexOAuthService(
+ store,
+ catalog,
+ model_catalog,
+ oauth_client=oauth,
+ callback_factory=callback_factory,
+ clock=(lambda: (clock or [1_000])[0]),
+ )
+ return service, callback, oauth, catalog, store, model_catalog
+
+
+async def _wait_until_terminal(service: CodexOAuthService) -> dict[str, Any]:
+ for _ in range(100):
+ status = service.public_status()
+ if status["operation_state"] in {
+ "completed",
+ "cancelled",
+ "expired",
+ "failed",
+ }:
+ return status
+ await asyncio.sleep(0)
+ raise AssertionError("Codex login operation did not finish")
+
+
+async def test_successful_live_login_keeps_the_existing_model_selection(
+ tmp_path: Path,
+) -> None:
+ service, callback, _oauth, _catalog, _store, model_catalog = await _oauth_service(tmp_path)
+ original_selection = _selection(model_catalog.load())
+
+ started = await service.start_login()
+ duplicate = await service.start_login()
+ callback.complete(started["authorize_url"])
+ status = await _wait_until_terminal(service)
+
+ assert duplicate == started
+ assert status["connection"] == "connected"
+ assert status["operation_state"] == "completed"
+ assert status["catalog_source"] == "live"
+ # Codex is published but not activated, so it reports no active model of its
+ # own and the deployment keeps running on whatever was already selected.
+ assert status["active_model"] is None
+ assert status["activated"] is False
+ assert _selection(model_catalog.load()) == original_selection
+ assert set(started) == {"operation_id", "authorize_url", "expires_in"}
+
+
+async def test_catalog_failure_keeps_auth_but_not_selection(tmp_path: Path) -> None:
+ service, callback, _oauth, _catalog, store, model_catalog = await _oauth_service(
+ tmp_path,
+ catalog_error=CodexAuthError(
+ "catalog_unavailable",
+ "The Codex model catalog is unavailable.",
+ 503,
+ ),
+ )
+ original_selection = _selection(model_catalog.load())
+
+ started = await service.start_login()
+ callback.complete(started["authorize_url"])
+ status = await _wait_until_terminal(service)
+
+ assert status["connection"] == "connected"
+ assert status["operation_state"] == "failed"
+ assert status["error_code"] == "catalog_unavailable"
+ assert _selection(model_catalog.load()) == original_selection
+ assert store.load_credentials() is not None
+
+
[email protected]("failure", ["state", "timeout", "exchange"])
+async def test_login_failures_do_not_overwrite_old_credentials(
+ tmp_path: Path,
+ failure: str,
+) -> None:
+ callback_error = (
+ CodexAuthError("login_timeout", "Codex sign-in timed out.", 408)
+ if failure == "timeout"
+ else None
+ )
+ service, callback, oauth, _catalog, store, _models = await _oauth_service(
+ tmp_path,
+ callback_error=callback_error,
+ )
+ old = store.commit_credentials(_stored_credentials(), expected_generation=0)
+ if failure == "exchange":
+ oauth.exchange_error = CodexAuthError(
+ "token_exchange_failed",
+ "Codex sign-in could not be completed.",
+ 502,
+ )
+
+ started = await service.start_login()
+ if failure == "state":
+ callback.complete_with_state("wrong-state")
+ elif failure == "exchange":
+ callback.complete(started["authorize_url"])
+ status = await _wait_until_terminal(service)
+
+ loaded = store.load_credentials()
+ assert loaded is not None
+ assert loaded.access_token == old.access_token
+ assert status["operation_state"] == ("expired" if failure == "timeout" else "failed")
+
+
+async def test_cancel_login_preserves_existing_credentials(tmp_path: Path) -> None:
+ service, _callback, _oauth, _catalog, store, _models = await _oauth_service(tmp_path)
+ old = store.commit_credentials(_stored_credentials(), expected_generation=0)
+
+ await service.start_login()
+ status = await service.cancel_login()
+
+ loaded = store.load_credentials()
+ assert loaded is not None
+ assert loaded.access_token == old.access_token
+ assert status["operation_state"] == "cancelled"
+
+
+async def test_get_token_refreshes_inside_five_minute_window(tmp_path: Path) -> None:
+ clock = [1_000]
+ service, _callback, oauth, _catalog, store, _models = await _oauth_service(
+ tmp_path,
+ clock=clock,
+ )
+ store.commit_credentials(
+ _stored_credentials(expires_at=1_200),
+ expected_generation=0,
+ )
+
+ token = await service.get_token()
+
+ assert oauth.refresh_calls == 1
+ assert token.access_token == "refreshed-access"
+ assert token.generation == 2
+
+
+async def test_refresh_rejects_changed_account_without_overwriting(tmp_path: Path) -> None:
+ clock = [1_000]
+ service, _callback, oauth, _catalog, store, _models = await _oauth_service(
+ tmp_path,
+ clock=clock,
+ )
+ original = store.commit_credentials(
+ _stored_credentials(expires_at=1_200),
+ expected_generation=0,
+ )
+ oauth.refresh_payload["account_id"] = "different-account"
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ await service.get_token()
+
+ assert exc_info.value.code == "account_changed"
+ loaded = store.load_credentials()
+ assert loaded is not None
+ assert loaded.access_token == original.access_token
+
+
+async def test_late_refresh_cannot_resurrect_logged_out_credentials(tmp_path: Path) -> None:
+ clock = [1_000]
+ service, _callback, oauth, _catalog, store, _models = await _oauth_service(
+ tmp_path,
+ clock=clock,
+ )
+ committed = store.commit_credentials(
+ _stored_credentials(expires_at=1_200),
+ expected_generation=0,
+ )
+ oauth.refresh_started = asyncio.Event()
+ oauth.refresh_release = asyncio.Event()
+
+ refresh_task = asyncio.create_task(service.get_token())
+ await oauth.refresh_started.wait()
+ store.clear_credentials(expected_generation=committed.generation)
+ oauth.refresh_release.set()
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ await refresh_task
+ assert exc_info.value.code == "generation_changed"
+ assert store.load_credentials() is None
+
+
+async def test_logout_rejected_while_inference_is_active(tmp_path: Path) -> None:
+ service, _callback, _oauth, _catalog, store, _models = await _oauth_service(tmp_path)
+ store.commit_credentials(_stored_credentials(), expected_generation=0)
+
+ async with service.inference_guard():
+ with pytest.raises(CodexAuthError) as exc_info:
+ await service.logout()
+
+ assert exc_info.value.code == "inference_in_progress"
+ assert store.load_credentials() is not None
+
+
+async def test_logout_cannot_be_undone_by_inflight_model_refresh(
+ tmp_path: Path,
+) -> None:
+ service, _callback, _oauth, catalog, store, model_catalog = await _oauth_service(tmp_path)
+ store.commit_credentials(_stored_credentials(), expected_generation=0)
+ catalog.get_started = asyncio.Event()
+ catalog.get_release = asyncio.Event()
+
+ refresh_task = asyncio.create_task(service.refresh_models())
+ await catalog.get_started.wait()
+ logout_task = asyncio.create_task(service.logout())
+ await asyncio.sleep(0)
+ catalog.get_release.set()
+ await asyncio.gather(refresh_task, logout_task)
+
+ assert store.load_credentials() is None
+ assert not any(
+ profile.get("managed_by") == MANAGED_BY
+ for profile in model_catalog.load()["services"]["llm"]["profiles"]
+ )
+
+
+async def test_revoke_failure_does_not_block_local_logout_and_restore(
+ tmp_path: Path,
+) -> None:
+ service, _callback, oauth, _catalog, store, model_catalog = await _oauth_service(tmp_path)
+ committed = store.commit_credentials(_stored_credentials(), expected_generation=0)
+ original = model_catalog.load()
+ sync_codex_catalog(model_catalog, _snapshot("live", _model("gpt-5.6-sol")))
+ oauth.revoke_error = CodexAuthError(
+ "token_revoke_failed",
+ "Codex authentication could not be revoked remotely.",
+ 502,
+ )
+
+ status = await service.logout()
+
+ assert status["connection"] == "disconnected"
+ assert store.current_generation() == committed.generation + 1
+ assert store.load_credentials() is None
+ assert _selection(model_catalog.load()) == _selection(original)
+
+
+async def test_restarted_service_restores_connection_without_operation_or_secrets(
+ tmp_path: Path,
+) -> None:
+ service, _callback, oauth, catalog, store, model_catalog = await _oauth_service(tmp_path)
+ del service
+ committed = store.commit_credentials(
+ CodexCredentials(
+ schema_version=1,
+ access_token="top-secret-access",
+ refresh_token="top-secret-refresh",
+ id_token="top-secret-id",
+ account_id="full-account-secret",
+ expires_at=10_000,
+ generation=0,
+ ),
+ expected_generation=0,
+ )
+ store.save_catalog_cache(
+ CatalogSnapshot(
+ models=(_model("gpt-5.6-sol"),),
+ source="live",
+ fetched_at=1_000,
+ etag=None,
+ generation=committed.generation,
+ account_hash="hash-only",
+ ).to_dict()
+ )
+ restarted = CodexOAuthService(
+ store,
+ catalog,
+ model_catalog,
+ oauth_client=oauth,
+ callback_factory=lambda: None, # type: ignore[arg-type,return-value]
+ clock=lambda: 1_000,
+ )
+
+ status = restarted.public_status()
+ serialized = json.dumps(status)
+
+ assert status["connection"] == "connected"
+ assert status["operation_id"] is None
+ assert status["operation_state"] is None
+ assert "top-secret" not in serialized
+ assert "full-account-secret" not in serialized
+
+
+async def test_recover_after_unauthorized_forces_refresh_for_next_request(
+ tmp_path: Path,
+) -> None:
+ service, _callback, oauth, _catalog, store, _models = await _oauth_service(tmp_path)
+ committed = store.commit_credentials(
+ _stored_credentials(expires_at=10_000),
+ expected_generation=0,
+ )
+
+ await service.recover_after_unauthorized(committed.generation)
+
+ assert oauth.refresh_calls == 1
+ assert store.load_credentials().access_token == "refreshed-access" # type: ignore[union-attr]
diff --git a/tests/services/codex_auth/test_storage.py b/tests/services/codex_auth/test_storage.py
new file mode 100644
index 000000000..94bff2c81
--- /dev/null
+++ b/tests/services/codex_auth/test_storage.py
@@ -0,0 +1,178 @@
+from __future__ import annotations
+
+from concurrent.futures import ThreadPoolExecutor
+import os
+from pathlib import Path
+import stat
+
+import pytest
+
+from deeptutor.services.codex_auth.contracts import CodexAuthError, CodexCredentials
+from deeptutor.services.codex_auth.storage import CodexCredentialStore
+
+
+def _credentials(token: str) -> CodexCredentials:
+ return CodexCredentials(
+ schema_version=1,
+ access_token=f"access-{token}",
+ refresh_token=f"refresh-{token}",
+ id_token=f"id-{token}",
+ account_id="account-123",
+ expires_at=2_000_000_000,
+ generation=0,
+ )
+
+
+def test_store_is_scoped_below_deeptutor_user_root(tmp_path: Path) -> None:
+ store = CodexCredentialStore(tmp_path)
+
+ assert store.root == tmp_path / "private" / "openai-codex"
+ assert ".codex" not in str(store.root)
+
+
+def test_store_uses_versioned_files_and_leaves_no_temporary_files(tmp_path: Path) -> None:
+ store = CodexCredentialStore(tmp_path)
+ committed = store.commit_credentials(_credentials("one"), expected_generation=0)
+ store.save_catalog_cache({"models": []})
+
+ assert committed.generation == 1
+ assert {path.name for path in store.root.iterdir()} == {
+ "auth.lock",
+ "credentials.v1.json",
+ "models-cache.v1.json",
+ "state.v1.json",
+ }
+ assert not list(store.root.glob(".*.tmp"))
+ assert not list(store.root.glob(".credentials.v1.json.*"))
+
+
+def test_refresh_generation_cannot_overwrite_new_login(tmp_path: Path) -> None:
+ store = CodexCredentialStore(tmp_path)
+ first = store.commit_credentials(_credentials("old"), expected_generation=0)
+ second = store.commit_credentials(_credentials("new"), expected_generation=first.generation)
+
+ with pytest.raises(CodexAuthError, match="changed"):
+ store.commit_credentials(
+ _credentials("late-refresh"),
+ expected_generation=first.generation,
+ )
+
+ loaded = store.load_credentials()
+ assert loaded is not None
+ assert loaded.access_token == second.access_token
+
+
+def test_clear_increments_generation_and_prevents_credential_resurrection(tmp_path: Path) -> None:
+ store = CodexCredentialStore(tmp_path)
+ committed = store.commit_credentials(_credentials("old"), expected_generation=0)
+ store.save_catalog_cache({"models": [{"slug": "old"}]})
+
+ generation = store.clear_credentials(expected_generation=committed.generation)
+
+ assert generation == 2
+ assert store.current_generation() == 2
+ assert store.load_credentials() is None
+ assert store.load_catalog_cache() is None
+ with pytest.raises(CodexAuthError, match="changed"):
+ store.commit_credentials(_credentials("late"), expected_generation=1)
+
+
+def test_two_threads_cannot_commit_the_same_generation(tmp_path: Path) -> None:
+ store = CodexCredentialStore(tmp_path)
+ first = store.commit_credentials(_credentials("first"), expected_generation=0)
+
+ def commit(token: str) -> str:
+ try:
+ store.commit_credentials(_credentials(token), expected_generation=first.generation)
+ except CodexAuthError as exc:
+ return exc.code
+ return "committed"
+
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ results = list(executor.map(commit, ("a", "b")))
+
+ assert sorted(results) == ["committed", "generation_changed"]
+ assert store.current_generation() == 2
+
+
+def test_store_never_calls_path_home(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ def fail_home(cls: type[Path]) -> Path:
+ raise AssertionError("Path.home must not be used")
+
+ monkeypatch.setattr(Path, "home", classmethod(fail_home))
+ store = CodexCredentialStore(tmp_path)
+ store.commit_credentials(_credentials("token"), expected_generation=0)
+ store.clear_credentials(expected_generation=1)
+
+
+def test_corrupt_credentials_raise_public_error(tmp_path: Path) -> None:
+ store = CodexCredentialStore(tmp_path)
+ store.root.mkdir(parents=True)
+ store.credentials_path.write_text("{broken", encoding="utf-8")
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ store.load_credentials()
+
+ assert exc_info.value.code == "credential_corrupt"
+ assert "{broken" not in str(exc_info.value)
+
+
+def test_catalog_cache_round_trip(tmp_path: Path) -> None:
+ store = CodexCredentialStore(tmp_path)
+
+ store.save_catalog_cache({"etag": '"v1"', "models": [{"slug": "gpt-5.6-sol"}]})
+
+ assert store.current_generation() == 0
+ assert store.load_catalog_cache() == {
+ "etag": '"v1"',
+ "models": [{"slug": "gpt-5.6-sol"}],
+ }
+
+
+def test_existing_symlink_target_is_rejected(tmp_path: Path) -> None:
+ store = CodexCredentialStore(tmp_path)
+ store.root.mkdir(parents=True)
+ outside = tmp_path / "outside.json"
+ outside.write_text("{}", encoding="utf-8")
+ try:
+ store.credentials_path.symlink_to(outside)
+ except OSError:
+ pytest.skip("Creating symlinks is unavailable on this platform")
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ store.load_credentials()
+
+ assert exc_info.value.code == "unsafe_storage_path"
+
+
+def test_windows_reparse_point_is_rejected(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ from deeptutor.services.codex_auth import storage
+
+ store = CodexCredentialStore(tmp_path)
+ store.root.mkdir(parents=True)
+ store.credentials_path.write_text("{}", encoding="utf-8")
+ monkeypatch.setattr(
+ storage,
+ "_is_reparse_point",
+ lambda path: path == store.credentials_path,
+ )
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ store.load_credentials()
+
+ assert exc_info.value.code == "unsafe_storage_path"
+
+
+ os.name == "nt", reason="POSIX permission bits are not authoritative on Windows"
+)
+def test_private_files_are_owner_only_on_supported_platforms(tmp_path: Path) -> None:
+ store = CodexCredentialStore(tmp_path)
+ store.commit_credentials(_credentials("token"), expected_generation=0)
+
+ mode = stat.S_IMODE(store.credentials_path.stat().st_mode)
+
+ assert mode & (stat.S_IRWXG | stat.S_IRWXO) == 0
diff --git a/tests/services/llm/test_codex_disable_ssl_verify.py b/tests/services/llm/test_codex_disable_ssl_verify.py
index 4ab792ba1..91a062ff1 100644
--- a/tests/services/llm/test_codex_disable_ssl_verify.py
+++ b/tests/services/llm/test_codex_disable_ssl_verify.py
@@ -8,6 +8,7 @@ fallback.
from __future__ import annotations
+from contextlib import asynccontextmanager
from typing import Any
import pytest
@@ -25,12 +26,27 @@ def _clean_ssl_env(monkeypatch: pytest.MonkeyPatch) -> None:
def _stub_token_loader(monkeypatch: pytest.MonkeyPatch) -> None:
class _Token:
- access = "test-token"
+ access_token = "test-token"
account_id = "test-account"
+ generation = 1
async def _fake_load_token(self: Any) -> _Token:
return _Token()
+ class _Service:
+ @asynccontextmanager
+ async def inference_guard(self):
+ yield
+
+ async def recover_after_unauthorized(self, generation: int) -> None:
+ del generation
+
+ monkeypatch.setattr(
+ openai_codex_provider,
+ "get_codex_oauth_service",
+ lambda: _Service(),
+ raising=False,
+ )
monkeypatch.setattr(openai_codex_provider.OpenAICodexProvider, "_load_token", _fake_load_token)
diff --git a/tests/services/llm/test_openai_codex_oauth_provider.py b/tests/services/llm/test_openai_codex_oauth_provider.py
new file mode 100644
index 000000000..a1d86a710
--- /dev/null
+++ b/tests/services/llm/test_openai_codex_oauth_provider.py
@@ -0,0 +1,205 @@
+from __future__ import annotations
+
+from contextlib import asynccontextmanager
+from typing import Any, AsyncIterator
+
+import pytest
+
+from deeptutor.services.codex_auth.constants import CODEX_RESPONSES_URL
+from deeptutor.services.codex_auth.contracts import CodexAuthError, CodexToken
+from deeptutor.services.llm.provider_core import openai_codex_provider as module
+from deeptutor.services.llm.provider_core.openai_codex_provider import (
+ CodexHTTPError,
+ OpenAICodexProvider,
+)
+
+
+class FakeCodexService:
+ def __init__(self) -> None:
+ self.token = CodexToken(
+ access_token="test-access-token",
+ account_id="account-123",
+ expires_at=2_000_000_000,
+ generation=7,
+ )
+ self.token_calls = 0
+ self.guard_entries = 0
+ self.recovered_generation: int | None = None
+
+ async def get_token(self) -> CodexToken:
+ self.token_calls += 1
+ return self.token
+
+ async def recover_after_unauthorized(self, generation: int) -> None:
+ self.recovered_generation = generation
+
+ @asynccontextmanager
+ async def inference_guard(self) -> AsyncIterator[None]:
+ self.guard_entries += 1
+ yield
+
+
+async def test_provider_uses_deeptutor_token_service_and_raw_sol_id(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ service = FakeCodexService()
+ requests: list[tuple[str, dict[str, str], dict[str, Any]]] = []
+
+ async def request(
+ url: str,
+ headers: dict[str, str],
+ body: dict[str, Any],
+ **_kwargs: Any,
+ ) -> tuple[str, list[Any], str]:
+ requests.append((url, headers, body))
+ return "ok", [], "stop"
+
+ monkeypatch.setattr(module, "get_codex_oauth_service", lambda: service)
+ monkeypatch.setattr(module, "_request_codex", request)
+
+ result = await OpenAICodexProvider().chat(
+ [{"role": "user", "content": "hello"}],
+ model="openai-codex/gpt-5.6-sol",
+ reasoning_effort="medium",
+ tools=[
+ {
+ "type": "function",
+ "function": {
+ "name": "lookup",
+ "description": "Look something up",
+ "parameters": {"type": "object"},
+ },
+ }
+ ],
+ )
+
+ url, headers, body = requests[0]
+ assert result.finish_reason == "stop"
+ assert service.token_calls == 1
+ assert service.guard_entries == 1
+ assert url == CODEX_RESPONSES_URL
+ assert headers["Authorization"] == "Bearer test-access-token"
+ assert headers["chatgpt-account-id"] == "account-123"
+ assert body["model"] == "gpt-5.6-sol"
+ assert body["reasoning"] == {"effort": "medium"}
+ assert body["tools"][0]["name"] == "lookup"
+
+
+async def test_401_refreshes_for_next_request_without_replay(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ service = FakeCodexService()
+ request_count = 0
+
+ async def rejected_request(*_args: Any, **_kwargs: Any) -> tuple[str, list[Any], str]:
+ nonlocal request_count
+ request_count += 1
+ raise CodexHTTPError(401, module._friendly_error(401))
+
+ monkeypatch.setattr(module, "get_codex_oauth_service", lambda: service)
+ monkeypatch.setattr(module, "_request_codex", rejected_request)
+
+ result = await OpenAICodexProvider().chat(
+ [{"role": "user", "content": "hello"}],
+ model="gpt-5.6-sol",
+ )
+
+ assert request_count == 1
+ assert service.recovered_generation == service.token.generation
+ assert result.finish_reason == "error"
+ assert "retry" in result.content.lower()
+
+
+async def test_401_with_dead_refresh_token_does_not_promise_a_retry(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Telling the user "already refreshed, retry" would loop them forever."""
+ service = FakeCodexService()
+
+ async def failed_recovery(generation: int) -> None:
+ raise CodexAuthError(
+ "authentication_required",
+ "Sign in to Codex before using this model.",
+ 401,
+ )
+
+ async def rejected_request(*_args: Any, **_kwargs: Any) -> tuple[str, list[Any], str]:
+ raise CodexHTTPError(401, module._friendly_error(401))
+
+ service.recover_after_unauthorized = failed_recovery # type: ignore[method-assign]
+ monkeypatch.setattr(module, "get_codex_oauth_service", lambda: service)
+ monkeypatch.setattr(module, "_request_codex", rejected_request)
+
+ result = await OpenAICodexProvider().chat(
+ [{"role": "user", "content": "hello"}],
+ model="gpt-5.6-sol",
+ )
+
+ assert result.finish_reason == "error"
+ assert "retry" not in result.content.lower()
+ assert "sign in again" in result.content.lower()
+
+
+async def test_429_never_reads_openai_api_key_or_falls_back(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ service = FakeCodexService()
+ destinations: list[str] = []
+ monkeypatch.setenv("OPENAI_API_KEY", "must-not-be-used")
+
+ async def rate_limited(
+ url: str,
+ *_args: Any,
+ **_kwargs: Any,
+ ) -> tuple[str, list[Any], str]:
+ destinations.append(url)
+ raise CodexHTTPError(429, "Codex usage quota exceeded.")
+
+ monkeypatch.setattr(module, "get_codex_oauth_service", lambda: service)
+ monkeypatch.setattr(module, "_request_codex", rate_limited)
+
+ result = await OpenAICodexProvider().chat(
+ [{"role": "user", "content": "hello"}],
+ model="gpt-5.6-sol",
+ )
+
+ assert "Codex usage quota" in result.content
+ assert destinations == [CODEX_RESPONSES_URL]
+ assert service.token_calls == 1
+
+
+async def test_provider_does_not_expose_network_error_details(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ service = FakeCodexService()
+
+ async def network_failure(
+ *_args: Any,
+ **_kwargs: Any,
+ ) -> tuple[str, list[Any], str]:
+ raise RuntimeError("private proxy host and token")
+
+ monkeypatch.setattr(module, "get_codex_oauth_service", lambda: service)
+ monkeypatch.setattr(module, "_request_codex", network_failure)
+
+ result = await OpenAICodexProvider().chat(
+ [{"role": "user", "content": "hello"}],
+ )
+
+ assert result.finish_reason == "error"
+ assert "private proxy" not in result.content
+ assert "token" not in result.content.lower()
+
+
+def test_provider_source_no_longer_imports_oauth_cli_kit() -> None:
+ source = module.__loader__.get_source(module.__name__) # type: ignore[union-attr]
+
+ assert source is not None
+ assert "oauth_cli_kit" not in source
+ assert "get_codex_oauth_service" in source
+ assert OpenAICodexProvider().get_default_model() == "openai-codex/gpt-5.6-sol"
diff --git a/tests/services/test_model_catalog.py b/tests/services/test_model_catalog.py
index 1cb986b33..c62101cd4 100644
--- a/tests/services/test_model_catalog.py
+++ b/tests/services/test_model_catalog.py
@@ -1,3 +1,4 @@
+from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
@@ -158,3 +159,31 @@ def test_load_persists_normalized_active_ids(tmp_path: Path):
assert llm["active_model_id"] == "llm-model-a"
assert saved["services"]["embedding"]["profiles"] == []
assert saved["services"]["search"]["profiles"] == []
+
+
+def test_update_serializes_concurrent_catalog_mutations(tmp_path: Path):
+ service = ModelCatalogService(path=tmp_path / "model_catalog.json")
+ initial = service.load()
+ initial["mutation_count"] = 0
+ service.save(initial)
+
+ def increment(_index: int) -> None:
+ def mutate(catalog: dict) -> None:
+ catalog["mutation_count"] = int(catalog.get("mutation_count", 0)) + 1
+
+ service.update(mutate)
+
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ list(executor.map(increment, range(40)))
+
+ assert service.load()["mutation_count"] == 40
+
+
+def test_atomic_save_leaves_no_temporary_file(tmp_path: Path):
+ catalog_path = tmp_path / "model_catalog.json"
+ service = ModelCatalogService(path=catalog_path)
+
+ service.save({"version": 1, "services": {}})
+
+ assert catalog_path.exists()
+ assert not list(tmp_path.glob(".model_catalog.json.*"))
diff --git a/tests/services/test_provider_registry.py b/tests/services/test_provider_registry.py
index 03cc770cf..b3d886602 100644
--- a/tests/services/test_provider_registry.py
+++ b/tests/services/test_provider_registry.py
@@ -41,3 +41,19 @@ def test_edenai_provider_aliases_and_base_detection() -> None:
def test_openai_codex_is_not_detected_from_api_base() -> None:
assert find_gateway(api_base="https://codex.example.com/v1") is None
+
+
+def test_openai_codex_provider_is_oauth_backed() -> None:
+ spec = find_by_name("openai_codex")
+
+ assert spec is not None
+ assert spec.auth_mode == "oauth"
+ assert spec.env_key == ""
+
+
+def test_github_copilot_is_oauth_backed() -> None:
+ spec = find_by_name("github_copilot")
+
+ assert spec is not None
+ assert spec.auth_mode == "oauth"
+ assert spec.env_key == ""
diff --git a/web/components/settings/CodexOAuthCard.tsx b/web/components/settings/CodexOAuthCard.tsx
new file mode 100644
index 000000000..b46bb7dd9
--- /dev/null
+++ b/web/components/settings/CodexOAuthCard.tsx
@@ -0,0 +1,246 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { ExternalLink, RefreshCw, ShieldCheck, Unplug } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import Button from "@/components/ui/Button";
+import {
+ cancelCodexLogin,
+ CodexOAuthApiError,
+ codexErrorMessageKey,
+ codexStatusMessageKey,
+ getCodexStatus,
+ logoutCodex,
+ refreshCodexModels,
+ shouldPollCodexStatus,
+ startCodexLogin,
+ type CodexOAuthStatus,
+} from "@/lib/codex-oauth";
+
+import { useSettings } from "./SettingsContext";
+
+export function CodexOAuthCard() {
+ const { t } = useTranslation();
+ const { reloadSettings, hasUnsavedChanges, setToast } = useSettings();
+ const [status, setStatus] = useState<CodexOAuthStatus | null>(null);
+ const [pending, setPending] = useState(false);
+ const [errorKey, setErrorKey] = useState<string | null>(null);
+ const [pollTick, setPollTick] = useState(0);
+ const reloadedOperation = useRef<string | null>(null);
+
+ const loadStatus = useCallback(async () => {
+ try {
+ const next = await getCodexStatus();
+ setStatus(next);
+ setErrorKey(null);
+ return next;
+ } catch (error) {
+ setErrorKey(
+ codexErrorMessageKey(
+ error instanceof CodexOAuthApiError ? error.code : null,
+ ),
+ );
+ return null;
+ }
+ }, []);
+
+ useEffect(() => {
+ void loadStatus();
+ }, [loadStatus]);
+
+ useEffect(() => {
+ if (!status || !shouldPollCodexStatus(status)) return;
+ // pollTick, not the status object, is what schedules the next poll: a failed
+ // request leaves `status` identical, and keying the timer off it alone would
+ // strand the card on "waiting" forever after one dropped response.
+ const timer = window.setTimeout(() => {
+ void loadStatus();
+ setPollTick((tick) => tick + 1);
+ }, 1_000);
+ return () => window.clearTimeout(timer);
+ }, [loadStatus, status, pollTick]);
+
+ // Reloading replaces the whole catalog draft, so this must never run behind
+ // the operator's back while they have unsaved edits open on another provider.
+ const syncCatalog = useCallback(async () => {
+ if (hasUnsavedChanges) {
+ setToast(t("codex.oauth.reloadDeferred"));
+ return;
+ }
+ await reloadSettings();
+ }, [hasUnsavedChanges, reloadSettings, setToast, t]);
+
+ useEffect(() => {
+ if (
+ status?.operation_state !== "completed" ||
+ !status.operation_id ||
+ reloadedOperation.current === status.operation_id
+ ) {
+ return;
+ }
+ reloadedOperation.current = status.operation_id;
+ void syncCatalog();
+ }, [syncCatalog, status]);
+
+ const signIn = async () => {
+ const authWindow = window.open("about:blank", "_blank", "popup");
+ if (authWindow) authWindow.opener = null;
+ setPending(true);
+ setErrorKey(null);
+ try {
+ const started = await startCodexLogin();
+ if (authWindow) {
+ authWindow.location.replace(started.authorize_url);
+ } else {
+ window.location.assign(started.authorize_url);
+ }
+ setStatus(await getCodexStatus());
+ } catch (error) {
+ authWindow?.close();
+ setErrorKey(
+ codexErrorMessageKey(
+ error instanceof CodexOAuthApiError ? error.code : null,
+ ),
+ );
+ } finally {
+ setPending(false);
+ }
+ };
+
+ const cancel = async () => {
+ setPending(true);
+ try {
+ setStatus(await cancelCodexLogin());
+ } catch (error) {
+ setErrorKey(
+ codexErrorMessageKey(
+ error instanceof CodexOAuthApiError ? error.code : null,
+ ),
+ );
+ } finally {
+ setPending(false);
+ }
+ };
+
+ const refresh = async () => {
+ setPending(true);
+ try {
+ setStatus(await refreshCodexModels());
+ await syncCatalog();
+ setErrorKey(null);
+ } catch (error) {
+ setErrorKey(
+ codexErrorMessageKey(
+ error instanceof CodexOAuthApiError ? error.code : null,
+ ),
+ );
+ } finally {
+ setPending(false);
+ }
+ };
+
+ const logout = async () => {
+ setPending(true);
+ try {
+ setStatus(await logoutCodex());
+ await syncCatalog();
+ setErrorKey(null);
+ } catch (error) {
+ setErrorKey(
+ codexErrorMessageKey(
+ error instanceof CodexOAuthApiError ? error.code : null,
+ ),
+ );
+ } finally {
+ setPending(false);
+ }
+ };
+
+ const polling = Boolean(status && shouldPollCodexStatus(status));
+ const connected = status?.connection === "connected";
+ const messageKey = errorKey || (status ? codexStatusMessageKey(status) : null);
+
+ return (
+ <section className="rounded-xl border border-[var(--border)] bg-[var(--muted)]/30 p-4">
+ <div className="flex items-start gap-3">
+ <ShieldCheck className="mt-0.5 h-5 w-5 text-[var(--primary)]" />
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium">{t("codex.oauth.title")}</p>
+ <p className="mt-1 text-xs text-[var(--muted-foreground)]">
+ {t("codex.oauth.isolated")}
+ </p>
+ <p className="mt-1 text-xs text-[var(--muted-foreground)]">
+ {t("codex.oauth.ownerBound")}
+ </p>
+ {!connected && (
+ <p className="mt-1 text-xs text-[var(--muted-foreground)]">
+ {t("codex.oauth.localOnly")}
+ </p>
+ )}
+ <p className="mt-1 text-xs text-amber-600 dark:text-amber-400">
+ {t("codex.oauth.experimental")}
+ </p>
+ {messageKey && (
+ <p className="mt-3 text-sm text-[var(--foreground)]">
+ {t(messageKey)}
+ </p>
+ )}
+ {connected && status?.model_count !== undefined && (
+ <p className="mt-1 text-xs text-[var(--muted-foreground)]">
+ {t("codex.oauth.modelCount", { count: status.model_count })}
+ </p>
+ )}
+ <div className="mt-4 flex flex-wrap gap-2">
+ {!connected && !polling && (
+ <Button
+ type="button"
+ size="sm"
+ loading={pending}
+ onClick={() => void signIn()}
+ icon={<ExternalLink className="h-4 w-4" />}
+ >
+ {t("codex.oauth.signIn")}
+ </Button>
+ )}
+ {polling && (
+ <Button
+ type="button"
+ size="sm"
+ variant="secondary"
+ disabled={pending}
+ onClick={() => void cancel()}
+ >
+ {t("codex.oauth.cancel")}
+ </Button>
+ )}
+ {connected && (
+ <>
+ <Button
+ type="button"
+ size="sm"
+ variant="secondary"
+ loading={pending}
+ onClick={() => void refresh()}
+ icon={<RefreshCw className="h-4 w-4" />}
+ >
+ {t("codex.oauth.refresh")}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="danger"
+ disabled={pending}
+ onClick={() => void logout()}
+ icon={<Unplug className="h-4 w-4" />}
+ >
+ {t("codex.oauth.logout")}
+ </Button>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/web/components/settings/ServiceConfigEditor.tsx b/web/components/settings/ServiceConfigEditor.tsx
index 1fddb2aa7..edff6d90a 100644
--- a/web/components/settings/ServiceConfigEditor.tsx
+++ b/web/components/settings/ServiceConfigEditor.tsx
@@ -16,6 +16,8 @@ import {
import { useTranslation } from "react-i18next";
import ProviderIcon from "@/components/common/ProviderIcon";
+import { CodexOAuthCard } from "./CodexOAuthCard";
+import { isCodexOAuthProfile, isManagedCodexProfile } from "./codex-profile";
import {
type CatalogModel,
type CatalogProfile,
@@ -77,6 +79,20 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
const activeProfile = getActiveProfile(draft, service);
const activeModel = getActiveModel(draft, service);
+ const activeProviderValue =
+ service === "search"
+ ? activeProfile?.provider || ""
+ : activeProfile?.binding || "";
+ const activeProviderOption = (providers[service] || []).find(
+ (option) => option.value === activeProviderValue,
+ );
+ const isManagedCodex = isManagedCodexProfile(activeProfile);
+ const isCodexOAuth = isCodexOAuthProfile(
+ service,
+ activeProviderValue,
+ activeProviderOption,
+ activeProfile,
+ );
const [showApiKey, setShowApiKey] = useState(false);
const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
@@ -202,7 +218,9 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
const isActive =
profile.id === draft.services[service].active_profile_id;
const profileDetail = activeProfileDetail(profile, service, t);
- const isEditing = editingProfileId === profile.id;
+ const isManagedProfile = isManagedCodexProfile(profile);
+ const isEditing =
+ editingProfileId === profile.id && !isManagedProfile;
return (
<div
key={profile.id}
@@ -218,7 +236,9 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
}
});
}}
- onDoubleClick={() => startProfileRename(profile)}
+ onDoubleClick={() => {
+ if (!isManagedProfile) startProfileRename(profile);
+ }}
onKeyDown={(e) => {
if (isEditing) return;
if (e.key === "Enter" || e.key === " ") {
@@ -232,7 +252,11 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
});
}
}}
- title={isEditing ? undefined : t("Double-click to rename")}
+ title={
+ isEditing || isManagedProfile
+ ? undefined
+ : t("Double-click to rename")
+ }
className={`group relative cursor-pointer rounded-lg px-3 py-2 text-left transition-colors ${
isActive
? "bg-[var(--muted)]/70 text-[var(--foreground)]"
@@ -278,18 +302,20 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
>
{profile.name}
</div>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- startProfileRename(profile);
- }}
- className="-mr-1 shrink-0 rounded-md p-1 text-[var(--muted-foreground)]/60 transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
- aria-label={t("Rename profile")}
- title={t("Rename profile")}
- >
- <Pencil className="h-3 w-3" />
- </button>
+ {!isManagedProfile && (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ startProfileRename(profile);
+ }}
+ className="-mr-1 shrink-0 rounded-md p-1 text-[var(--muted-foreground)]/60 transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ aria-label={t("Rename profile")}
+ title={t("Rename profile")}
+ >
+ <Pencil className="h-3 w-3" />
+ </button>
+ )}
</div>
)}
<div className="mt-0.5 truncate text-[11px] leading-tight text-[var(--muted-foreground)]/70">
@@ -302,10 +328,10 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
<div className="mt-2 border-t border-[var(--border)]/40 pt-2">
<button
onClick={() => removeActiveProfile(service)}
- disabled={!activeProfile}
+ disabled={!activeProfile || isManagedCodex}
className="flex w-full items-center gap-1.5 rounded-lg px-3 py-1.5 text-left text-[11px] text-[var(--muted-foreground)]/60 transition-colors hover:bg-red-500/5 hover:text-red-500 disabled:opacity-30"
title={
- activeProfile
+ activeProfile && !isManagedCodex
? t("Permanently remove the currently selected profile.")
: undefined
}
@@ -354,24 +380,26 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
<div className="text-[13px] font-medium text-[var(--foreground)]">
{t("Models")}
</div>
- <div className="flex items-center gap-2">
- <button
- type="button"
- onClick={() => addModel(service)}
- className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
- >
- <Plus className="h-3 w-3" />
- {t("Model")}
- </button>
- <button
- onClick={() => removeActiveModel(service)}
- disabled={!activeModel}
- className="inline-flex items-center gap-1 text-[11px] text-[var(--muted-foreground)]/40 transition-colors hover:text-red-500 disabled:opacity-30"
- >
- <Trash2 className="h-3 w-3" />
- {t("Delete")}
- </button>
- </div>
+ {!isCodexOAuth && (
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => addModel(service)}
+ className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
+ >
+ <Plus className="h-3 w-3" />
+ {t("Model")}
+ </button>
+ <button
+ onClick={() => removeActiveModel(service)}
+ disabled={!activeModel}
+ className="inline-flex items-center gap-1 text-[11px] text-[var(--muted-foreground)]/40 transition-colors hover:text-red-500 disabled:opacity-30"
+ >
+ <Trash2 className="h-3 w-3" />
+ {t("Delete")}
+ </button>
+ </div>
+ )}
</div>
{activeProfile.models.length > 0 && (
<div className="mb-4 flex flex-wrap items-center gap-1.5">
@@ -391,7 +419,7 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
: "";
return (
<div key={model.id} className="min-w-0">
- {editingModelId === model.id ? (
+ {editingModelId === model.id && !isCodexOAuth ? (
<input
autoFocus
className="h-8 w-60 rounded-lg border border-[var(--border)] bg-[var(--background)] px-2.5 text-[12.5px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
@@ -420,8 +448,14 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
model.id;
})
}
- onDoubleClick={() => startModelRename(model)}
- title={t("Double-click to rename")}
+ onDoubleClick={() => {
+ if (!isCodexOAuth) startModelRename(model);
+ }}
+ title={
+ isCodexOAuth
+ ? undefined
+ : t("Double-click to rename")
+ }
className={`inline-flex h-8 items-center gap-1.5 rounded-lg px-2.5 text-[12.5px] transition-colors ${
isActive
? "bg-[var(--muted)] text-[var(--foreground)]"
@@ -450,7 +484,7 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
})}
</div>
)}
- {activeModel && (
+ {activeModel && !isCodexOAuth && (
<div className="grid gap-4 sm:grid-cols-2">
<div>
<div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
@@ -945,11 +979,21 @@ function ProfileFields({
const providerValue =
service === "search" ? profile.provider || "" : profile.binding || "";
+ const providerOption = (providers[service] || []).find(
+ (option) => option.value === providerValue,
+ );
+ const isManagedCodex = isManagedCodexProfile(profile);
+ const isCodexOAuth = isCodexOAuthProfile(
+ service,
+ providerValue,
+ providerOption,
+ profile,
+ );
- // Only the search service hides fields by provider. LLM/embedding always
- // expose Base URL and API Key, so default both to shown for them.
const fields =
- service === "search"
+ isCodexOAuth
+ ? { apiKey: false, baseUrl: false, baseUrlRequired: false }
+ : service === "search"
? searchProviderFields(profile.provider)
: { apiKey: true, baseUrl: true, baseUrlRequired: false };
const searxngMissingBaseUrl =
@@ -972,6 +1016,7 @@ function ProfileFields({
<select
className={`${selectClass} ${providerValue ? "pl-9" : ""}`}
value={providerValue}
+ disabled={isManagedCodex}
onChange={(e) => {
const val = e.target.value;
const field = service === "search" ? "provider" : "binding";
@@ -1050,6 +1095,11 @@ function ProfileFields({
</p>
)}
</div>
+ {isCodexOAuth && (
+ <div className="sm:col-span-2">
+ <CodexOAuthCard />
+ </div>
+ )}
{fields.baseUrl && (
<div className="sm:col-span-2">
<div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
@@ -1116,76 +1166,82 @@ function ProfileFields({
</div>
</div>
)}
- <div className="sm:col-span-2 rounded-xl border border-[var(--border)]/60 bg-[var(--muted)]/20">
- <button
- type="button"
- onClick={() => setExtraOpen((value) => !value)}
- className="flex w-full items-center justify-between gap-3 px-3.5 py-3 text-left"
- aria-expanded={extraOpen}
- >
- <span>
- <span className="block text-[12px] font-medium text-[var(--foreground)]">
- {t("Extra (optional)")}
- </span>
- <span className="mt-0.5 block text-[11px] text-[var(--muted-foreground)]">
- {service === "search"
- ? t("API version and proxy")
- : t("API version and extra request headers")}
+ {!isCodexOAuth && (
+ <div className="sm:col-span-2 rounded-xl border border-[var(--border)]/60 bg-[var(--muted)]/20">
+ <button
+ type="button"
+ onClick={() => setExtraOpen((value) => !value)}
+ className="flex w-full items-center justify-between gap-3 px-3.5 py-3 text-left"
+ aria-expanded={extraOpen}
+ >
+ <span>
+ <span className="block text-[12px] font-medium text-[var(--foreground)]">
+ {t("Extra (optional)")}
+ </span>
+ <span className="mt-0.5 block text-[11px] text-[var(--muted-foreground)]">
+ {service === "search"
+ ? t("API version and proxy")
+ : t("API version and extra request headers")}
+ </span>
</span>
- </span>
- <ChevronDown
- className={`h-4 w-4 text-[var(--muted-foreground)] transition-transform ${
- extraOpen ? "rotate-180" : ""
- }`}
- />
- </button>
- {extraOpen && (
- <div className="grid gap-4 border-t border-[var(--border)]/60 px-3.5 py-4 sm:grid-cols-2">
- <div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("API Version")}
- </div>
- <input
- className={inputClass}
- value={profile.api_version}
- onChange={(e) =>
- updateProfileField(service, "api_version", e.target.value)
- }
- placeholder={t("Optional")}
- />
- </div>
- {service === "search" ? (
+ <ChevronDown
+ className={`h-4 w-4 text-[var(--muted-foreground)] transition-transform ${
+ extraOpen ? "rotate-180" : ""
+ }`}
+ />
+ </button>
+ {extraOpen && (
+ <div className="grid gap-4 border-t border-[var(--border)]/60 px-3.5 py-4 sm:grid-cols-2">
<div>
<div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Proxy")}
+ {t("API Version")}
</div>
<input
className={inputClass}
- value={profile.proxy || ""}
+ value={profile.api_version}
onChange={(e) =>
- updateProfileField(service, "proxy", e.target.value)
+ updateProfileField(service, "api_version", e.target.value)
}
- placeholder={t("http://127.0.0.1:7890 (optional)")}
+ placeholder={t("Optional")}
/>
</div>
- ) : (
- <div className="sm:col-span-2">
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Extra Headers (JSON)")}
+ {service === "search" ? (
+ <div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("Proxy")}
+ </div>
+ <input
+ className={inputClass}
+ value={profile.proxy || ""}
+ onChange={(e) =>
+ updateProfileField(service, "proxy", e.target.value)
+ }
+ placeholder={t("http://127.0.0.1:7890 (optional)")}
+ />
</div>
- <textarea
- className={`${inputClass} min-h-[84px] resize-y`}
- value={stringifyExtraHeaders(profile.extra_headers)}
- onChange={(e) =>
- updateProfileField(service, "extra_headers", e.target.value)
- }
- placeholder='{"APP-Code":"your-app-code"}'
- />
- </div>
- )}
- </div>
- )}
- </div>
+ ) : (
+ <div className="sm:col-span-2">
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("Extra Headers (JSON)")}
+ </div>
+ <textarea
+ className={`${inputClass} min-h-[84px] resize-y`}
+ value={stringifyExtraHeaders(profile.extra_headers)}
+ onChange={(e) =>
+ updateProfileField(
+ service,
+ "extra_headers",
+ e.target.value,
+ )
+ }
+ placeholder='{"APP-Code":"your-app-code"}'
+ />
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
</div>
);
}
diff --git a/web/components/settings/SettingsContext.tsx b/web/components/settings/SettingsContext.tsx
index 0a150caee..32a1767bf 100644
--- a/web/components/settings/SettingsContext.tsx
+++ b/web/components/settings/SettingsContext.tsx
@@ -40,6 +40,7 @@ export type CatalogModel = {
id: string;
name: string;
model: string;
+ managed_by?: string;
dimension?: string;
send_dimensions?: boolean;
supported_dimensions?: string;
@@ -75,6 +76,8 @@ export type LlmContextWindowDetection = {
export type CatalogProfile = {
id: string;
name: string;
+ managed_by?: string;
+ read_only?: boolean;
binding?: string;
provider?: string;
base_url: string;
@@ -160,6 +163,7 @@ export type ProviderOption = {
default_dim?: string;
default_model?: string;
default_voice?: string;
+ auth_mode?: "api_key" | "oauth";
};
export type SystemStatus = {
diff --git a/web/components/settings/codex-profile.ts b/web/components/settings/codex-profile.ts
new file mode 100644
index 000000000..f75859db9
--- /dev/null
+++ b/web/components/settings/codex-profile.ts
@@ -0,0 +1,30 @@
+import type { CatalogProfile, ProviderOption, ServiceName } from "./SettingsContext";
+
+/** The tag the backend stamps on the profile its Codex OAuth service owns. */
+export const CODEX_MANAGED_BY = "openai_codex_oauth";
+
+/** Profiles written by the Codex OAuth service are read-only in the settings form. */
+export function isManagedCodexProfile(
+ profile: Pick<CatalogProfile, "managed_by"> | null | undefined,
+): boolean {
+ return profile?.managed_by === CODEX_MANAGED_BY;
+}
+
+/**
+ * Whether a profile authenticates through Codex OAuth instead of typed credentials.
+ *
+ * A managed profile qualifies even before the provider list has loaded, so a
+ * reload can never briefly render API-key fields over an OAuth-only profile.
+ */
+export function isCodexOAuthProfile(
+ service: ServiceName,
+ providerValue: string,
+ providerOption: Pick<ProviderOption, "auth_mode"> | undefined,
+ profile: Pick<CatalogProfile, "managed_by"> | null | undefined,
+): boolean {
+ return (
+ service === "llm" &&
+ providerValue === "openai_codex" &&
+ (providerOption?.auth_mode === "oauth" || isManagedCodexProfile(profile))
+ );
+}
diff --git a/web/lib/codex-oauth.ts b/web/lib/codex-oauth.ts
new file mode 100644
index 000000000..2aec75fa6
--- /dev/null
+++ b/web/lib/codex-oauth.ts
@@ -0,0 +1,116 @@
+import { apiFetch, apiUrl } from "@/lib/api";
+
+export type CodexOAuthStatus = {
+ connection: "disconnected" | "authorizing" | "connected" | "error";
+ operation_id: string | null;
+ operation_state:
+ | "waiting"
+ | "exchanging"
+ | "fetching_models"
+ | "completed"
+ | "cancelled"
+ | "expired"
+ | "failed"
+ | null;
+ model_count: number;
+ catalog_source:
+ | "live"
+ | "fresh-cache"
+ | "revalidated-cache"
+ | "stale-cache"
+ | null;
+ catalog_fetched_at: number | null;
+ active_model: string | null;
+ activated: boolean;
+ error_code: string | null;
+};
+
+export type CodexLoginStart = {
+ operation_id: string;
+ authorize_url: string;
+ expires_in: number;
+};
+
+export class CodexOAuthApiError extends Error {
+ code: string;
+
+ constructor(code: string, message: string) {
+ super(message);
+ this.name = "CodexOAuthApiError";
+ this.code = code;
+ }
+}
+
+const BASE = "/api/v1/settings/providers/openai-codex";
+
+async function request<T>(path: string, method: "GET" | "POST"): Promise<T> {
+ const response = await apiFetch(apiUrl(`${BASE}${path}`), {
+ method,
+ skipAuthRedirect: true,
+ });
+ if (response.ok) return (await response.json()) as T;
+
+ let code = `http_${response.status}`;
+ let message = "Codex request failed.";
+ try {
+ const payload = (await response.json()) as {
+ detail?: { code?: string; message?: string };
+ };
+ if (payload.detail?.code) code = payload.detail.code;
+ if (payload.detail?.message) message = payload.detail.message;
+ } catch {
+ // The UI renders only the stable code mapping below.
+ }
+ throw new CodexOAuthApiError(code, message);
+}
+
+export function getCodexStatus(): Promise<CodexOAuthStatus> {
+ return request<CodexOAuthStatus>("/oauth/status", "GET");
+}
+
+export function startCodexLogin(): Promise<CodexLoginStart> {
+ return request<CodexLoginStart>("/oauth/start", "POST");
+}
+
+export function cancelCodexLogin(): Promise<CodexOAuthStatus> {
+ return request<CodexOAuthStatus>("/oauth/cancel", "POST");
+}
+
+export function refreshCodexModels(): Promise<CodexOAuthStatus> {
+ return request<CodexOAuthStatus>("/models/refresh", "POST");
+}
+
+export function logoutCodex(): Promise<CodexOAuthStatus> {
+ return request<CodexOAuthStatus>("/oauth/logout", "POST");
+}
+
+export function shouldPollCodexStatus(status: CodexOAuthStatus): boolean {
+ return (
+ status.operation_state === "waiting" ||
+ status.operation_state === "exchanging" ||
+ status.operation_state === "fetching_models"
+ );
+}
+
+export function codexErrorMessageKey(code: string | null): string {
+ if (code === "catalog_unavailable" || code === "catalog_invalid") {
+ return "codex.oauth.catalogFailed";
+ }
+ if (code === "inference_in_progress") {
+ return "codex.oauth.inferenceActive";
+ }
+ if (code === "login_timeout") return "codex.oauth.expired";
+ if (code === "login_cancelled") return "codex.oauth.cancelled";
+ if (code === "authorization_denied") return "codex.oauth.denied";
+ return "codex.oauth.requestFailed";
+}
+
+export function codexStatusMessageKey(status: CodexOAuthStatus): string {
+ if (status.error_code) return codexErrorMessageKey(status.error_code);
+ if (shouldPollCodexStatus(status)) return "codex.oauth.waiting";
+ if (status.activated && status.active_model) return "codex.oauth.activated";
+ if (status.connection === "connected") return "codex.oauth.connected";
+ if (status.operation_state === "cancelled") return "codex.oauth.cancelled";
+ if (status.operation_state === "expired") return "codex.oauth.expired";
+ return "codex.oauth.disconnected";
+}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index c2863782b..b9d5ccd2b 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -2685,5 +2685,26 @@
"Connected to LightRAG server": "Connected to LightRAG server",
"Core {{version}}": "Core {{version}}",
"API key accepted": "API key accepted",
- "Open access": "Open access"
+ "Open access": "Open access",
+ "codex.oauth.title": "OpenAI Codex OAuth",
+ "codex.oauth.signIn": "Sign in with Codex",
+ "codex.oauth.waiting": "Waiting for browser authorization…",
+ "codex.oauth.connected": "Codex is connected.",
+ "codex.oauth.refresh": "Refresh models",
+ "codex.oauth.logout": "Sign out",
+ "codex.oauth.experimental": "Experimental connection: the upstream Codex compatibility surface may change.",
+ "codex.oauth.isolated": "Credentials are stored only by DeepTutor. This does not read or modify your Codex CLI login.",
+ "codex.oauth.ownerBound": "Signs in with your own ChatGPT plan. It stays with your account and is never shared with other users of this deployment.",
+ "codex.oauth.localOnly": "Authorization has to complete on the machine running the DeepTutor backend. On a remote server, run `deeptutor provider login openai-codex` there instead.",
+ "codex.oauth.activated": "Codex is connected and now the active model.",
+ "codex.oauth.reloadDeferred": "Codex is connected. Apply your pending changes to see its models in the list.",
+ "codex.oauth.catalogFailed": "The Codex model catalog could not be refreshed. Your login and current model were retained.",
+ "codex.oauth.inferenceActive": "Wait for the active Codex response to finish before signing out.",
+ "codex.oauth.disconnected": "Codex is not connected.",
+ "codex.oauth.cancel": "Cancel",
+ "codex.oauth.cancelled": "Codex sign-in was cancelled.",
+ "codex.oauth.expired": "Codex sign-in expired. Start it again.",
+ "codex.oauth.denied": "Codex authorization was denied.",
+ "codex.oauth.requestFailed": "The Codex request failed. Try again.",
+ "codex.oauth.modelCount": "Models: {{count}}"
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index e47152178..07f38836b 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -2685,5 +2685,26 @@
"Connected to LightRAG server": "已连接到 LightRAG 服务器",
"Core {{version}}": "内核 {{version}}",
"API key accepted": "API 密钥已通过",
- "Open access": "开放访问"
+ "Open access": "开放访问",
+ "codex.oauth.title": "OpenAI Codex OAuth",
+ "codex.oauth.signIn": "使用 Codex 登录",
+ "codex.oauth.waiting": "等待浏览器授权…",
+ "codex.oauth.connected": "Codex 已连接。",
+ "codex.oauth.refresh": "刷新模型",
+ "codex.oauth.logout": "退出登录",
+ "codex.oauth.experimental": "实验性连接:上游 Codex 兼容接口未来可能变化。",
+ "codex.oauth.isolated": "凭据仅由 DeepTutor 保存,不会读取或修改 Codex CLI 的登录状态。",
+ "codex.oauth.ownerBound": "使用你本人的 ChatGPT 套餐登录。凭据仅归你的账号所有,不会共享给本部署的其他用户。",
+ "codex.oauth.localOnly": "授权必须在运行 DeepTutor 后端的机器上完成。远程部署请在服务器上执行 `deeptutor provider login openai-codex`。",
+ "codex.oauth.activated": "Codex 已连接,并已设为当前模型。",
+ "codex.oauth.reloadDeferred": "Codex 已连接。应用当前未保存的更改后即可在列表中看到它的模型。",
+ "codex.oauth.catalogFailed": "无法刷新 Codex 模型目录,登录状态和当前模型均已保留。",
+ "codex.oauth.inferenceActive": "请等待当前 Codex 回复结束后再退出登录。",
+ "codex.oauth.disconnected": "Codex 尚未连接。",
+ "codex.oauth.cancel": "取消",
+ "codex.oauth.cancelled": "已取消 Codex 登录。",
+ "codex.oauth.expired": "Codex 登录已超时,请重新开始。",
+ "codex.oauth.denied": "Codex 授权被拒绝。",
+ "codex.oauth.requestFailed": "Codex 请求失败,请重试。",
+ "codex.oauth.modelCount": "模型:{{count}}"
}
diff --git a/web/scripts/run-node-tests.mjs b/web/scripts/run-node-tests.mjs
index a23c80b3f..2ba21dbad 100644
--- a/web/scripts/run-node-tests.mjs
+++ b/web/scripts/run-node-tests.mjs
@@ -40,7 +40,8 @@ function collectTests(dir) {
rmSync(distRoot, { recursive: true, force: true });
-run(path.join(webRoot, "node_modules", ".bin", "tsc"), [
+run(process.execPath, [
+ path.join(webRoot, "node_modules", "typescript", "bin", "tsc"),
"-p",
"tsconfig.node-tests.json",
]);
diff --git a/web/tests/codex-oauth-client.test.ts b/web/tests/codex-oauth-client.test.ts
new file mode 100644
index 000000000..407a2fecd
--- /dev/null
+++ b/web/tests/codex-oauth-client.test.ts
@@ -0,0 +1,113 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+
+import {
+ codexStatusMessageKey,
+ shouldPollCodexStatus,
+ type CodexOAuthStatus,
+} from "../lib/codex-oauth";
+
+const CODEX_CLIENT = path.resolve(process.cwd(), "lib/codex-oauth.ts");
+const CODEX_CARD = path.resolve(
+ process.cwd(),
+ "components/settings/CodexOAuthCard.tsx",
+);
+
+function status(
+ overrides: Partial<CodexOAuthStatus> = {},
+): CodexOAuthStatus {
+ return {
+ connection: "disconnected",
+ operation_id: null,
+ operation_state: null,
+ model_count: 0,
+ catalog_source: null,
+ catalog_fetched_at: null,
+ active_model: null,
+ activated: false,
+ error_code: null,
+ ...overrides,
+ };
+}
+
+test("Codex terminal operation states stop polling", () => {
+ for (const operation_state of [
+ "completed",
+ "cancelled",
+ "expired",
+ "failed",
+ ] as const) {
+ assert.equal(
+ shouldPollCodexStatus(status({ operation_state })),
+ false,
+ );
+ }
+ for (const operation_state of [
+ "waiting",
+ "exchanging",
+ "fetching_models",
+ ] as const) {
+ assert.equal(shouldPollCodexStatus(status({ operation_state })), true);
+ }
+});
+
+test("Codex public client types contain no secret fields", () => {
+ const source = readFileSync(CODEX_CLIENT, "utf8");
+
+ for (const forbidden of [
+ "access_token",
+ "refresh_token",
+ "account_id",
+ "email",
+ ]) {
+ assert.equal(source.includes(forbidden), false);
+ }
+});
+
+test("A connected account reports connected regardless of which models it has", () => {
+ assert.equal(
+ codexStatusMessageKey(status({ connection: "connected" })),
+ "codex.oauth.connected",
+ );
+ assert.equal(
+ codexStatusMessageKey(
+ status({
+ connection: "connected",
+ activated: true,
+ active_model: "gpt-5.6-sol",
+ }),
+ ),
+ "codex.oauth.activated",
+ );
+});
+
+test("Codex error codes map to stable translation keys", () => {
+ assert.equal(
+ codexStatusMessageKey(
+ status({
+ connection: "error",
+ operation_state: "failed",
+ error_code: "catalog_unavailable",
+ }),
+ ),
+ "codex.oauth.catalogFailed",
+ );
+ assert.equal(
+ codexStatusMessageKey(
+ status({ error_code: "inference_in_progress" }),
+ ),
+ "codex.oauth.inferenceActive",
+ );
+});
+
+test("Codex sign-in opens its browser window before awaiting the API", () => {
+ const source = readFileSync(CODEX_CARD, "utf8");
+ const signIn = source.slice(
+ source.indexOf("const signIn"),
+ source.indexOf("const cancel"),
+ );
+
+ assert.ok(signIn.indexOf("window.open(") < signIn.indexOf("await startCodexLogin()"));
+});
diff --git a/web/tests/codex-oauth-settings-contract.test.ts b/web/tests/codex-oauth-settings-contract.test.ts
new file mode 100644
index 000000000..26e68baef
--- /dev/null
+++ b/web/tests/codex-oauth-settings-contract.test.ts
@@ -0,0 +1,55 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+
+const EDITOR = path.resolve(
+ process.cwd(),
+ "components/settings/ServiceConfigEditor.tsx",
+);
+const HELPER = path.resolve(process.cwd(), "components/settings/codex-profile.ts");
+const EN = path.resolve(process.cwd(), "locales/en/app.json");
+const ZH = path.resolve(process.cwd(), "locales/zh/app.json");
+
+test("Codex OAuth profile renders the OAuth card from provider metadata", () => {
+ const source = readFileSync(EDITOR, "utf8");
+
+ assert.match(source, /isCodexOAuthProfile\(/);
+ assert.match(source, /<CodexOAuthCard/);
+ assert.match(readFileSync(HELPER, "utf8"), /auth_mode === "oauth"/);
+});
+
+test("the Codex profile predicates live in one place", () => {
+ const source = readFileSync(EDITOR, "utf8");
+
+ // Duplicating the tag comparison per component is how the two copies of this
+ // check drifted before; the editor must go through the shared helper.
+ assert.equal(source.includes('=== "openai_codex_oauth"'), false);
+ assert.match(readFileSync(HELPER, "utf8"), /CODEX_MANAGED_BY = "openai_codex_oauth"/);
+});
+
+test("managed Codex profiles cannot expose profile or model editing", () => {
+ const source = readFileSync(EDITOR, "utf8");
+
+ assert.match(source, /isManagedCodexProfile\(/);
+ assert.match(source, /disabled=\{isManagedCodex\}/);
+ assert.match(source, /!isCodexOAuth/);
+});
+
+test("Codex OAuth copy stays in sync across locales", () => {
+ const en = JSON.parse(readFileSync(EN, "utf8")) as Record<string, unknown>;
+ const zh = JSON.parse(readFileSync(ZH, "utf8")) as Record<string, unknown>;
+ const codexKeys = (locale: Record<string, unknown>) =>
+ Object.keys(locale)
+ .filter((key) => key.startsWith("codex.oauth."))
+ .sort();
+
+ assert.deepEqual(codexKeys(en), codexKeys(zh));
+ for (const key of ["codex.oauth.signIn", "codex.oauth.ownerBound"]) {
+ assert.ok(codexKeys(en).includes(key));
+ }
+ for (const key of codexKeys(en)) {
+ assert.equal(typeof en[key], "string");
+ assert.equal(typeof zh[key], "string");
+ }
+});
diff --git a/web/tests/run-node-tests-windows.test.ts b/web/tests/run-node-tests-windows.test.ts
new file mode 100644
index 000000000..ab5ec8ec3
--- /dev/null
+++ b/web/tests/run-node-tests-windows.test.ts
@@ -0,0 +1,13 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+
+const runnerPath = path.resolve(process.cwd(), "scripts/run-node-tests.mjs");
+
+test("node test runner launches TypeScript through the current Node runtime", () => {
+ const source = readFileSync(runnerPath, "utf8");
+
+ assert.match(source, /run\(process\.execPath/);
+ assert.match(source, /"typescript", "bin", "tsc"/);
+});