Skip to content

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

fix(codex-auth): guide remote Codex OAuth loopback callbacks (#716)

TyrionH-is-coding1117e6fe93cb
diff --git a/README.md b/README.md
index a2fa6c5a6..74f2125d7 100644
--- a/README.md
+++ b/README.md
@@ -621,7 +621,25 @@ 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.
+**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. Because a token authorizes one person's plan, the profile is not shareable through user grants — each account signs in for itself.
+
+For a remote deployment, the browser's `localhost` and the server's `localhost` are different machines, so an ordinary reverse proxy alone cannot carry the browser's localhost callback to the server. Use an SSH tunnel as the callback bridge. The tunnel reaches the already-published Web port; Next.js rewrites only the exact callback path to the public callback broker, and the broker validates `state` before routing to the original OAuth operation. The callback listener remains on the backend loopback, ports `1455` and `1457` are not published, and this path supports the default Docker bridge network.
+
+```bash
+ssh -N -L 1455:127.0.0.1:3782 <ssh-user>@<server-host>
+```
+
+If DeepTutor reports fallback callback port `1457`, use:
+
+```bash
+ssh -N -L 1457:127.0.0.1:3782 <ssh-user>@<server-host>
+```
+
+Run only the one command that matches the actual callback port; never run both. `3782` is only the example Web port: it is the configured frontend/container port reported as `callback_forward_port`. That value does not guarantee that the same port is listening on the SSH host's `127.0.0.1`. If Docker or Podman publishes a different host port, or a reverse proxy listens on a different port, replace only the right-hand target port (`3782` above) with the Web port actually listening on the SSH host's `127.0.0.1`; keep the left-hand callback port as `1455` or `1457`. `<server-host>` is the SSH host whose loopback owns that listening port. If the browser URL names a reverse proxy or load balancer, replace it with the correct SSH frontend host.
+
+The CLI prints the tunnel command and then immediately tries to open the browser. On a remote deployment, keep the authorization page open without completing it, establish the printed tunnel in another terminal, and only then continue authorization.
+
+Remote-topology detection has a localhost boundary. If Web itself is reached through an SSH or IDE localhost forward, the browser cannot tell that the server is remote. For the current Web operation, leave its authorization page unfinished, read `redirect_uri` in that operation's authorize URL to identify callback port `1455` or `1457`, and create the second tunnel from that local port to the actual Web port. Alternatively, cancel that Web operation and start a new one with the CLI; the CLI output belongs to the new operation and must not be used for the existing Web operation. 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>
diff --git a/assets/README/README_CN.md b/assets/README/README_CN.md
index 7d56d0fa7..b925eb618 100644
--- a/assets/README/README_CN.md
+++ b/assets/README/README_CN.md
@@ -478,7 +478,25 @@ Settings 是操作控制面板,带有实时状态条(后端、LLM、嵌入
大多数部分采用草稿-应用流程,因此你可以在提交前测试提供商配置。开箱即提供四种主题 — Default、Cream、Dark 和 Glass。项目根目录的 `.env` 文件被刻意忽略;运行时配置存储在 `data/user/settings/*.json` 下,除非 `DEEPTUTOR_HOME` 或 `deeptutor start --home` 将应用指向其他位置。
-**OpenAI Codex OAuth(实验性)。** 在 **模型 → LLM** 下选择 **OpenAI Codex**,会用基于你自己 ChatGPT 订阅运行的浏览器登录取代 API Key 输入框,因此无需 `OPENAI_API_KEY`。令牌仅保存在 `<user-root>/private/openai-codex/` 中,DeepTutor 绝不会读取或修改你的 `~/.codex` CLI 登录状态。模型列表来自该账号的实时目录;登录会发布该配置,但只有在尚未配置任何 LLM 时才会成为活跃模型,因此它不会在你毫不知情的情况下改变已有部署的指向。由于令牌只授权一个人的订阅,该配置无法通过用户授权共享 — 每个账号都需自行登录,且浏览器必须能够访问运行后端的机器(在远程服务器上,请改为在该服务器上运行 `deeptutor provider login openai-codex`)。配额错误和目录获取失败会如实报告,绝不会回退到付费提供商。此兼容路径为实验性功能:上游接口可能发生变化。
+**OpenAI Codex OAuth(实验性)。** 在 **模型 → LLM** 下选择 **OpenAI Codex**,会用基于你自己 ChatGPT 订阅运行的浏览器登录取代 API Key 输入框,因此无需 `OPENAI_API_KEY`。令牌仅保存在 `<user-root>/private/openai-codex/` 中,DeepTutor 绝不会读取或修改你的 `~/.codex` CLI 登录状态。模型列表来自该账号的实时目录;只有尚未配置任何 LLM 时,登录后的 Codex 才会成为活跃模型。令牌只授权一个人的订阅,无法通过用户授权共享,因此每个账号都需自行登录。
+
+远程部署时,浏览器的 `localhost` 和服务器的 `localhost` 不是同一台机器,仅有普通反向代理无法把浏览器的 localhost callback 送到服务器,必须用 SSH 隧道建立 callback 桥。隧道通向已发布的 Web 端口;Next.js 只把精确的 callback 路径改写到 public callback broker,broker 校验 `state` 后才路由到原 OAuth operation。callback listener 仍位于后端 loopback,不发布 `1455`/`1457`,并支持默认 Docker bridge 网络。
+
+```bash
+ssh -N -L 1455:127.0.0.1:3782 <ssh-user>@<server-host>
+```
+
+若 DeepTutor 显示 fallback callback 端口 `1457`,则使用:
+
+```bash
+ssh -N -L 1457:127.0.0.1:3782 <ssh-user>@<server-host>
+```
+
+只运行与实际 callback 端口对应的其中一条命令,不能两条都运行。`3782` 只是示例 Web 端口:它是 DeepTutor 配置并作为 `callback_forward_port` 显示的 frontend/container 端口,不保证 SSH 主机的 `127.0.0.1` 正在监听同一端口。若 Docker/Podman 映射到不同宿主机端口,或反向代理监听不同端口,只替换 SSH 命令右侧的目标端口(上例中的 `3782`)为 SSH 主机 `127.0.0.1` 实际监听的 Web 端口;左侧 callback 端口仍保持 `1455` 或 `1457`。`<server-host>` 是该 loopback 监听端口所在的 SSH 主机;若浏览器域名指向反向代理或负载均衡器,请替换为正确的 SSH 前端主机。
+
+CLI 会先打印隧道命令,随后立即尝试打开浏览器。远程用户应先保持授权页打开但不要完成授权,在另一终端建立所显示的隧道,然后再继续授权。
+
+localhost 检测存在边界:若 Web 本身已通过 SSH 或 IDE localhost 转发访问,浏览器无法判断服务器是远程的。对于当前 Web operation,应保持其授权页未完成,从该 operation 的 authorize URL 中读取 `redirect_uri`,确认 callback 是 `1455` 还是 `1457`,再把该本地端口通过第二条隧道转到实际 Web 端口。另一种方法是取消该 Web operation,再通过 CLI 启动一个新 operation;CLI 输出只属于新 operation,不能用于当前 Web operation。配额错误和目录获取失败会如实报告,绝不会回退到付费提供商。此兼容路径为实验性功能:上游接口可能发生变化。
</details>
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index f8652a6a9..0909c5db4 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -11,12 +11,13 @@ from fastapi import (
File,
Header,
HTTPException,
+ Request,
Response,
UploadFile,
WebSocket,
status,
)
-from fastapi.responses import FileResponse
+from fastapi.responses import FileResponse, HTMLResponse
from pydantic import BaseModel, field_validator
from deeptutor.services.config import load_auth_settings
@@ -48,6 +49,8 @@ from deeptutor.services.auth import (
set_avatar,
set_role,
)
+from deeptutor.services.codex_auth.contracts import CodexAuthError
+from deeptutor.services.codex_auth.service import get_codex_oauth_service
logger = logging.getLogger(__name__)
@@ -367,6 +370,35 @@ def _local_admin_token_payload() -> TokenPayload:
# ---------------------------------------------------------------------------
[email protected]("/openai-codex/callback")
+async def receive_codex_oauth_callback(
+ request: Request,
+ code: str | None = None,
+ state: str | None = None,
+ error: str | None = None,
+) -> HTMLResponse:
+ headers = {"Cache-Control": "no-store"}
+ try:
+ callback_state = state if len(request.query_params.getlist("state")) == 1 else None
+ await get_codex_oauth_service().receive_callback(code, callback_state, error)
+ except CodexAuthError as exc:
+ return HTMLResponse(
+ (
+ "<!doctype html><title>DeepTutor Codex</title>"
+ "<p>Authentication could not be received. Return to DeepTutor and try again.</p>"
+ ),
+ status_code=exc.http_status,
+ headers=headers,
+ )
+ return HTMLResponse(
+ (
+ "<!doctype html><title>DeepTutor Codex</title>"
+ "<p>Authentication received. You can return to DeepTutor.</p>"
+ ),
+ headers=headers,
+ )
+
+
@router.get("/status", response_model=AuthStatusResponse)
async def auth_status(
authorization: str | None = Header(default=None, alias="Authorization"),
diff --git a/deeptutor/services/codex_auth/oauth.py b/deeptutor/services/codex_auth/oauth.py
index 60d813e69..4948cefa9 100644
--- a/deeptutor/services/codex_auth/oauth.py
+++ b/deeptutor/services/codex_auth/oauth.py
@@ -38,6 +38,27 @@ class OAuthCallbackResult:
error: str | None
+_OAUTH_STATE_MAX_LENGTH = 128
+_BASE64URL_STATE_CHARS = frozenset(
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
+)
+
+
+def oauth_state_matches(value: str | None, expected: str) -> bool:
+ if (
+ not value
+ or len(value) > _OAUTH_STATE_MAX_LENGTH
+ or any(character not in _BASE64URL_STATE_CHARS for character in value)
+ ):
+ return False
+ try:
+ value_bytes = value.encode("ascii")
+ expected_bytes = expected.encode("ascii")
+ except UnicodeEncodeError:
+ return False
+ return secrets.compare_digest(value_bytes, expected_bytes)
+
+
def generate_pkce() -> PkceCodes:
verifier = secrets.token_urlsafe(64)
digest = hashlib.sha256(verifier.encode("ascii")).digest()
@@ -83,10 +104,15 @@ class LoopbackCallback:
self._server = server
self._result = result
self._cancelled = False
+ self._accepting = True
self.port = port
@classmethod
- async def start(cls, ports: Iterable[int]) -> LoopbackCallback:
+ async def start(
+ cls,
+ ports: Iterable[int],
+ expected_state: str | None = None,
+ ) -> LoopbackCallback:
loop = asyncio.get_running_loop()
result: asyncio.Future[OAuthCallbackResult] = loop.create_future()
@@ -96,24 +122,42 @@ class LoopbackCallback:
"<!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>"
- )
+ query = parse_qs(parsed.query, keep_blank_values=True)
+ states = query.get("state", [])
+ if expected_state is not None and (
+ len(states) != 1 or not oauth_state_matches(states[0], expected_state)
+ ):
+ status = "400 Bad Request"
+ body = (
+ "<!doctype html><title>DeepTutor Codex</title>"
+ "<p>The authentication callback was invalid.</p>"
+ )
+ else:
+ callback_result = OAuthCallbackResult(
+ code=_first(query.get("code")),
+ state=_first(states),
+ error=_first(query.get("error")),
+ )
+ try:
+ callback.submit(callback_result)
+ except CodexAuthError:
+ status = "409 Conflict"
+ body = (
+ "<!doctype html><title>DeepTutor Codex</title>"
+ "<p>Authentication could not be received.</p>"
+ )
+ else:
+ 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 = (
@@ -138,12 +182,14 @@ class LoopbackCallback:
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.Server | None:
try:
- server = await asyncio.start_server(handle, hosts, port)
+ server = await asyncio.start_server(
+ handle,
+ hosts,
+ port,
+ start_serving=False,
+ )
except OSError:
return None
if len({int(sock.getsockname()[1]) for sock in server.sockets}) == 1:
@@ -166,7 +212,19 @@ class LoopbackCallback:
503,
)
bound_port = int(server.sockets[0].getsockname()[1])
- return cls(server=server, result=result, port=bound_port)
+ callback = cls(server=server, result=result, port=bound_port)
+ await server.start_serving()
+ return callback
+
+ def submit(self, result: OAuthCallbackResult) -> None:
+ if not self._accepting or self._result.done():
+ raise CodexAuthError(
+ "login_not_active",
+ "Codex sign-in is not waiting for a callback.",
+ 409,
+ )
+ self._accepting = False
+ self._result.set_result(result)
async def _close(self) -> None:
self._server.close()
@@ -176,13 +234,19 @@ class LoopbackCallback:
try:
callback = await asyncio.wait_for(asyncio.shield(self._result), timeout=timeout)
except TimeoutError as exc:
+ self._accepting = False
await self._close()
raise CodexAuthError(
"login_timeout",
- "Codex sign-in timed out.",
+ (
+ "The DeepTutor server did not receive the Codex OAuth callback "
+ f"on localhost:{self.port}. For a remote deployment, keep the "
+ "SSH port-forwarding tunnel open and try again."
+ ),
408,
) from exc
except asyncio.CancelledError as exc:
+ self._accepting = False
await self._close()
if self._cancelled:
raise CodexAuthError(
@@ -191,11 +255,13 @@ class LoopbackCallback:
409,
) from exc
raise
+ self._accepting = False
await self._close()
return callback
async def cancel(self) -> None:
self._cancelled = True
+ self._accepting = False
if not self._result.done():
self._result.cancel()
await self._close()
diff --git a/deeptutor/services/codex_auth/service.py b/deeptutor/services/codex_auth/service.py
index 92e4047d2..164df7df2 100644
--- a/deeptutor/services/codex_auth/service.py
+++ b/deeptutor/services/codex_auth/service.py
@@ -18,6 +18,7 @@ from deeptutor.services.config.model_catalog import (
ModelCatalogService,
get_model_catalog_service,
)
+from deeptutor.services.config.runtime_settings import load_system_settings
from .catalog import CodexModelCatalog
from .constants import (
@@ -40,6 +41,7 @@ from .oauth import (
PkceCodes,
build_authorize_url,
generate_pkce,
+ oauth_state_matches,
)
from .storage import CodexCredentialStore
@@ -69,6 +71,10 @@ class _LoginOperation:
task: asyncio.Task[None] | None = None
+def ssh_forward_command(callback_port: int, forward_port: int) -> str:
+ return f"ssh -N -L {callback_port}:127.0.0.1:{forward_port} <ssh-user>@<server-host>"
+
+
def codex_model_id(slug: str) -> str:
digest = hashlib.sha256(slug.encode("utf-8")).hexdigest()[:16]
return f"llm-model-openai-codex-{digest}"
@@ -185,12 +191,20 @@ class CodexOAuthService:
model_catalog: ModelCatalogService,
*,
oauth_client: CodexOAuthClient | None = None,
- callback_factory: Callable[[], Awaitable[Any]] | None = None,
+ callback_factory: Callable[[str], Awaitable[Any]] | None = None,
clock: Callable[[], float] = time.time,
+ callback_forward_port: int = 3782,
) -> None:
+ if (
+ isinstance(callback_forward_port, bool)
+ or not isinstance(callback_forward_port, int)
+ or not 1 <= callback_forward_port <= 65535
+ ):
+ raise ValueError("callback_forward_port must be between 1 and 65535")
self._store = store
self._catalog = catalog
self._model_catalog = model_catalog
+ self._callback_forward_port = callback_forward_port
self._owned_http: httpx.AsyncClient | None = None
if oauth_client is None:
self._owned_http = httpx.AsyncClient(timeout=30)
@@ -208,17 +222,20 @@ class CodexOAuthService:
self._logging_out = False
@staticmethod
- async def _start_default_callback() -> LoopbackCallback:
- return await LoopbackCallback.start(CODEX_CALLBACK_PORTS)
+ async def _start_default_callback(expected_state: str) -> LoopbackCallback:
+ return await LoopbackCallback.start(
+ CODEX_CALLBACK_PORTS,
+ expected_state=expected_state,
+ )
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)
+ callback = await self._callback_factory(state_secret)
redirect_uri = f"http://localhost:{callback.port}{CODEX_CALLBACK_PATH}"
operation = _LoginOperation(
operation_id=secrets.token_urlsafe(24),
@@ -245,10 +262,18 @@ class CodexOAuthService:
"Codex sign-in has not been started.",
409,
)
+ callback_port = operation.callback.port
return {
"operation_id": operation.operation_id,
"authorize_url": operation.authorize_url,
"expires_in": max(0, int(operation.deadline - self._clock())),
+ "callback_port": callback_port,
+ "callback_forward_port": self._callback_forward_port,
+ "redirect_uri": operation.redirect_uri,
+ "ssh_forward_command": ssh_forward_command(
+ callback_port,
+ self._callback_forward_port,
+ ),
}
def _operation_is_active(self) -> bool:
@@ -259,6 +284,28 @@ class CodexOAuthService:
and (operation.task is None or not operation.task.done())
)
+ async def receive_callback(
+ self,
+ code: str | None,
+ state: str | None,
+ error: str | None,
+ ) -> None:
+ async with self._operation_lock:
+ operation = self._operation
+ if operation is None or not self._operation_is_active():
+ raise CodexAuthError(
+ "login_not_active",
+ "Codex sign-in is not waiting for a callback.",
+ 409,
+ )
+ if not oauth_state_matches(state, operation.state_secret):
+ raise CodexAuthError(
+ "state_mismatch",
+ "Codex sign-in returned an invalid state.",
+ 400,
+ )
+ operation.callback.submit(OAuthCallbackResult(code=code, state=state, error=error))
+
async def _run_login(self, operation: _LoginOperation) -> None:
try:
callback = await operation.callback.wait(
@@ -314,10 +361,7 @@ class CodexOAuthService:
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,
- ):
+ if not oauth_state_matches(callback.state, expected_state):
raise CodexAuthError(
"state_mismatch",
"Codex sign-in returned an invalid state.",
@@ -484,6 +528,19 @@ class CodexOAuthService:
"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),
+ "authorize_url": (
+ operation.authorize_url if active_operation and operation is not None else None
+ ),
+ "expires_in": (
+ max(0, int(operation.deadline - self._clock()))
+ if active_operation and operation is not None
+ else None
+ ),
+ "callback_port": (operation.callback.port if operation is not None else None),
+ "callback_forward_port": (
+ self._callback_forward_port if operation is not None else None
+ ),
+ "redirect_uri": operation.redirect_uri 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),
@@ -639,6 +696,7 @@ def get_codex_oauth_service() -> CodexOAuthService:
key = str(user_root)
service = _SERVICE_INSTANCES.get(key)
if service is None:
+ callback_forward_port = load_system_settings()["frontend_port"]
store = CodexCredentialStore(user_root)
http = httpx.AsyncClient(timeout=30)
catalog = CodexModelCatalog(store, http=http)
@@ -647,6 +705,7 @@ def get_codex_oauth_service() -> CodexOAuthService:
catalog,
get_model_catalog_service(),
oauth_client=CodexOAuthClient(http),
+ callback_forward_port=callback_forward_port,
)
_SERVICE_INSTANCES[key] = service
return service
@@ -660,5 +719,6 @@ __all__ = [
"codex_model_id",
"get_codex_oauth_service",
"remove_codex_catalog",
+ "ssh_forward_command",
"sync_codex_catalog",
]
diff --git a/deeptutor_cli/README.md b/deeptutor_cli/README.md
index a8964ec11..a16be6060 100644
--- a/deeptutor_cli/README.md
+++ b/deeptutor_cli/README.md
@@ -228,7 +228,25 @@ 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 设置页共用。授权回调监听本机回环地址,因此须在运行后端的机器上完成登录。
+`openai-codex` 使用 DeepTutor 自己的独立 OAuth 流程登录。它不需要 `OPENAI_API_KEY`,也不会读取或同步本机 `~/.codex`;凭据保存在 `<user-root>/private/openai-codex/`,与 Web 设置页共用。
+
+远程部署时,浏览器的 `localhost` 和服务器的 `localhost` 不是同一台机器,仅有普通反向代理无法把浏览器的 localhost callback 送到服务器,必须用 SSH 隧道建立 callback 桥。隧道通向已发布的 Web 端口;Next.js 只把精确的 callback 路径改写到 public callback broker,broker 校验 `state` 后才路由到原 OAuth operation。callback listener 仍位于后端 loopback,不发布 `1455`/`1457`,并支持默认 Docker bridge 网络。
+
+```bash
+ssh -N -L 1455:127.0.0.1:3782 <ssh-user>@<server-host>
+```
+
+若 DeepTutor 显示 fallback callback 端口 `1457`,则使用:
+
+```bash
+ssh -N -L 1457:127.0.0.1:3782 <ssh-user>@<server-host>
+```
+
+只运行与实际 callback 端口对应的其中一条命令,不能两条都运行。`3782` 只是示例 Web 端口:它是 DeepTutor 配置并作为 `callback_forward_port` 显示的 frontend/container 端口,不保证 SSH 主机的 `127.0.0.1` 正在监听同一端口。若 Docker/Podman 映射到不同宿主机端口,或反向代理监听不同端口,只替换 SSH 命令右侧的目标端口(上例中的 `3782`)为 SSH 主机 `127.0.0.1` 实际监听的 Web 端口;左侧 callback 端口仍保持 `1455` 或 `1457`。`<server-host>` 是该 loopback 监听端口所在的 SSH 主机;若浏览器域名指向反向代理或负载均衡器,请替换为正确的 SSH 前端主机。
+
+CLI 会先打印隧道命令,随后立即尝试打开浏览器。远程用户应先保持授权页打开但不要完成授权,在另一终端建立所显示的隧道,然后再继续授权。
+
+localhost 检测存在边界:若 Web 本身已通过 SSH 或 IDE localhost 转发访问,浏览器无法判断服务器是远程的。对于当前 Web operation,应保持其授权页未完成,从该 operation 的 authorize URL 中读取 `redirect_uri`,确认 callback 是 `1455` 还是 `1457`,再把该本地端口通过第二条隧道转到实际 Web 端口。另一种方法是取消该 Web operation,再通过 CLI 启动一个新 operation;CLI 输出只属于新 operation,不能用于当前 Web operation。
Codex 令牌授权的是**你本人**的 ChatGPT 套餐,因此凭据只归当前登录用户,不会通过模型授权共享给部署内的其他用户——每位用户各自登录。登录成功后,模型列表来自该账号的动态目录;仅当此前尚未配置任何 LLM 时,Codex 才会被自动设为活动模型,否则不改动你已选的模型。目录刷新失败、上游 `429` 或其他错误都会如实报告,不会回退到付费 API Provider。这条 Codex backend 兼容路径目前属于实验性能力。
diff --git a/deeptutor_cli/provider_cmd.py b/deeptutor_cli/provider_cmd.py
index 32f73fa36..468ebc785 100644
--- a/deeptutor_cli/provider_cmd.py
+++ b/deeptutor_cli/provider_cmd.py
@@ -38,6 +38,9 @@ async def _login_openai_codex() -> None:
try:
started = await service.start_login()
authorize_url = str(started["authorize_url"])
+ typer.echo(f"Callback: {started['redirect_uri']}")
+ typer.echo(f"Authorization URL: {authorize_url}")
+ typer.echo(f"Remote server tunnel command: {started['ssh_forward_command']}")
typer.echo(
"Opening the OpenAI Codex sign-in in your browser; "
"credentials are written only to DeepTutor's private directory."
diff --git a/tests/api/test_codex_oauth_callback.py b/tests/api/test_codex_oauth_callback.py
new file mode 100644
index 000000000..a1f0646a7
--- /dev/null
+++ b/tests/api/test_codex_oauth_callback.py
@@ -0,0 +1,201 @@
+from __future__ import annotations
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+import pytest
+
+from deeptutor.api.routers import auth as auth_router
+from deeptutor.services.codex_auth.contracts import CodexAuthError
+from deeptutor.services.codex_auth.oauth import oauth_state_matches
+
+
+class FakeCodexOAuthService:
+ def __init__(
+ self,
+ error: CodexAuthError | None = None,
+ expected_state: str | None = None,
+ ) -> None:
+ self.error = error
+ self.expected_state = expected_state
+ self.received: list[tuple[str | None, str | None, str | None]] = []
+
+ async def receive_callback(
+ self,
+ code: str | None,
+ state: str | None,
+ error: str | None,
+ ) -> None:
+ self.received.append((code, state, error))
+ if self.error is not None:
+ raise self.error
+ if self.expected_state is not None and not oauth_state_matches(
+ state,
+ self.expected_state,
+ ):
+ raise CodexAuthError(
+ "state_mismatch",
+ "Codex sign-in returned an invalid state.",
+ 400,
+ )
+
+
+def _client(
+ monkeypatch: pytest.MonkeyPatch,
+ service: FakeCodexOAuthService,
+) -> TestClient:
+ monkeypatch.setattr(auth_router, "get_codex_oauth_service", lambda: service)
+ app = FastAPI()
+ app.include_router(auth_router.router, prefix="/api/v1/auth")
+ return TestClient(app)
+
+
+def test_codex_callback_endpoint_delivers_without_echoing_secrets(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ service = FakeCodexOAuthService()
+ client = _client(monkeypatch, service)
+
+ response = client.get(
+ "/api/v1/auth/openai-codex/callback",
+ params={
+ "code": "private-code",
+ "state": "private-state",
+ "error": "private-error",
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.headers["cache-control"] == "no-store"
+ assert response.headers["content-type"].startswith("text/html")
+ assert "Authentication received. You can return to DeepTutor." in response.text
+ assert service.received == [
+ ("private-code", "private-state", "private-error"),
+ ]
+ for secret in ("private-code", "private-state", "private-error"):
+ assert secret not in response.text
+
+
+def test_codex_callback_endpoint_rejects_repeated_state_for_active_login(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ service = FakeCodexOAuthService(expected_state="expected-state")
+ client = _client(monkeypatch, service)
+
+ response = client.get(
+ "/api/v1/auth/openai-codex/callback",
+ params=[
+ ("code", "private-code"),
+ ("state", "first-state"),
+ ("state", "second-state"),
+ ],
+ )
+
+ assert response.status_code == 400
+ assert response.headers["cache-control"] == "no-store"
+ assert response.headers["content-type"].startswith("text/html")
+ assert service.received == [("private-code", None, None)]
+ for secret in ("private-code", "first-state", "second-state"):
+ assert secret not in response.text
+
+
+ "params",
+ [
+ [("code", "private-code")],
+ [
+ ("code", "private-code"),
+ ("state", "first-state"),
+ ("state", "second-state"),
+ ],
+ ],
+)
+def test_codex_callback_endpoint_prioritizes_no_active_login(
+ monkeypatch: pytest.MonkeyPatch,
+ params: list[tuple[str, str]],
+) -> None:
+ service = FakeCodexOAuthService(
+ error=CodexAuthError(
+ "login_not_active",
+ "Codex sign-in is not waiting for a callback.",
+ 409,
+ )
+ )
+ client = _client(monkeypatch, service)
+
+ response = client.get(
+ "/api/v1/auth/openai-codex/callback",
+ params=params,
+ )
+
+ assert response.status_code == 409
+ assert response.headers["cache-control"] == "no-store"
+ assert response.headers["content-type"].startswith("text/html")
+ assert service.received == [("private-code", None, None)]
+ for secret in ("private-code", "first-state", "second-state"):
+ assert secret not in response.text
+
+
[email protected]("invalid_state", ["snowman-\u2603", "a" * 129])
+def test_codex_callback_endpoint_returns_safe_html_for_malformed_state(
+ monkeypatch: pytest.MonkeyPatch,
+ invalid_state: str,
+) -> None:
+ service = FakeCodexOAuthService(expected_state="expected-state")
+ client = _client(monkeypatch, service)
+
+ response = client.get(
+ "/api/v1/auth/openai-codex/callback",
+ params={"code": "private-code", "state": invalid_state},
+ )
+
+ assert response.status_code == 400
+ assert response.headers["cache-control"] == "no-store"
+ assert response.headers["content-type"].startswith("text/html")
+ for secret in ("private-code", invalid_state):
+ assert secret not in response.text
+
+
+ ("service_error", "expected_status"),
+ [
+ (
+ CodexAuthError(
+ "state_mismatch",
+ "Codex sign-in returned an invalid state.",
+ 400,
+ ),
+ 400,
+ ),
+ (
+ CodexAuthError(
+ "login_not_active",
+ "Codex sign-in is not waiting for a callback.",
+ 409,
+ ),
+ 409,
+ ),
+ ],
+)
+def test_codex_callback_endpoint_returns_safe_html_errors(
+ monkeypatch: pytest.MonkeyPatch,
+ service_error: CodexAuthError,
+ expected_status: int,
+) -> None:
+ service = FakeCodexOAuthService(service_error)
+ client = _client(monkeypatch, service)
+
+ response = client.get(
+ "/api/v1/auth/openai-codex/callback",
+ params={
+ "code": "private-code",
+ "state": "private-state",
+ "error": "access-token",
+ },
+ )
+
+ assert response.status_code == expected_status
+ assert response.headers["cache-control"] == "no-store"
+ assert response.headers["content-type"].startswith("text/html")
+ assert "Authentication could not be received." in response.text
+ for secret in ("private-code", "private-state", "access-token"):
+ assert secret not in response.text
diff --git a/tests/cli/test_provider_cli.py b/tests/cli/test_provider_cli.py
index 90ba4641d..3dd7eca6b 100644
--- a/tests/cli/test_provider_cli.py
+++ b/tests/cli/test_provider_cli.py
@@ -44,6 +44,10 @@ class _FakeCliCodexService:
return {
"operation_id": "operation-1",
"authorize_url": "https://auth.openai.com/oauth/authorize?state=opaque",
+ "callback_port": 1457,
+ "callback_forward_port": 3782,
+ "redirect_uri": "http://localhost:1457/auth/callback",
+ "ssh_forward_command": ("ssh -N -L 1457:127.0.0.1:3782 <ssh-user>@<server-host>"),
"expires_in": 300,
}
@@ -71,16 +75,24 @@ def test_openai_codex_cli_does_not_import_codex_cli_credentials() -> None:
def test_cli_opens_authorize_url_and_waits_for_completion(monkeypatch) -> None:
service = _FakeCliCodexService()
urls: list[str] = []
+ events: list[tuple[str, str]] = []
+ original_echo = provider_cmd.typer.echo
+
+ def record_echo(message: object, *args: object, **kwargs: object) -> None:
+ events.append(("echo", str(message)))
+ original_echo(message, *args, **kwargs)
+
monkeypatch.setattr(
provider_cmd,
"get_codex_oauth_service",
lambda: service,
raising=False,
)
+ monkeypatch.setattr(provider_cmd.typer, "echo", record_echo)
monkeypatch.setattr(
provider_cmd.webbrowser,
"open",
- lambda url: urls.append(url) or True,
+ lambda url: events.append(("open", url)) or urls.append(url) or True,
raising=False,
)
@@ -91,6 +103,16 @@ def test_cli_opens_authorize_url_and_waits_for_completion(monkeypatch) -> None:
assert urls == ["https://auth.openai.com/oauth/authorize?state=opaque"]
assert result.exit_code == 0
+ assert "http://localhost:1457/auth/callback" in result.stdout
+ assert "https://auth.openai.com/oauth/authorize?state=opaque" in result.stdout
+ assert "ssh -N -L 1457:127.0.0.1:3782 <ssh-user>@<server-host>" in result.stdout
+ assert "ssh -N -L 1457:127.0.0.1:1457" not in result.stdout
+ open_index = events.index(("open", "https://auth.openai.com/oauth/authorize?state=opaque"))
+ output_before_open = "\n".join(message for kind, message in events[:open_index])
+ assert "http://localhost:1457/auth/callback" in output_before_open
+ assert "https://auth.openai.com/oauth/authorize?state=opaque" in output_before_open
+ assert "ssh -N -L 1457:127.0.0.1:3782 <ssh-user>@<server-host>" in output_before_open
+ assert "ssh -N -L 1457:127.0.0.1:1457" not in output_before_open
# 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
diff --git a/tests/services/codex_auth/test_oauth.py b/tests/services/codex_auth/test_oauth.py
index 4f8e936f3..9b3aa9d36 100644
--- a/tests/services/codex_auth/test_oauth.py
+++ b/tests/services/codex_auth/test_oauth.py
@@ -15,6 +15,7 @@ from deeptutor.services.codex_auth.contracts import CodexAuthError, CodexCredent
from deeptutor.services.codex_auth.oauth import (
CodexOAuthClient,
LoopbackCallback,
+ OAuthCallbackResult,
PkceCodes,
build_authorize_url,
generate_pkce,
@@ -33,6 +34,67 @@ async def _send_get(port: int, target: str) -> str:
return response
+class _EagerReader:
+ async def readuntil(self, _separator: bytes) -> bytes:
+ return (
+ b"GET /auth/callback?code=eager-code&state=eager-state HTTP/1.1\r\n"
+ b"Host: localhost\r\n\r\n"
+ )
+
+
+class _EagerWriter:
+ def __init__(self) -> None:
+ self.response = bytearray()
+
+ def write(self, data: bytes) -> None:
+ self.response.extend(data)
+
+ async def drain(self) -> None:
+ return None
+
+ def close(self) -> None:
+ return None
+
+ async def wait_closed(self) -> None:
+ return None
+
+
+class _EagerSocket:
+ def getsockname(self) -> tuple[str, int]:
+ return ("127.0.0.1", 1455)
+
+
+class _EagerServer:
+ def __init__(self, handler: object) -> None:
+ self._handler = handler
+ self.sockets = [_EagerSocket()]
+
+ async def start_serving(self) -> None:
+ await self._handler(_EagerReader(), _EagerWriter()) # type: ignore[operator]
+
+ def close(self) -> None:
+ return None
+
+ async def wait_closed(self) -> None:
+ return None
+
+
+def _pause_callback_close(
+ callback: LoopbackCallback,
+) -> tuple[asyncio.Event, asyncio.Event]:
+ original_close = callback._close
+ close_started = asyncio.Event()
+ release_close = asyncio.Event()
+
+ async def blocked_close() -> None:
+ close_started.set()
+ await release_close.wait()
+ await original_close()
+
+ callback._close = blocked_close # type: ignore[method-assign]
+ return close_started, release_close
+
+
def _credentials() -> CodexCredentials:
return CodexCredentials(
schema_version=1,
@@ -91,6 +153,53 @@ async def test_loopback_accepts_callback_without_echoing_secrets() -> None:
assert "expected" not in response
+async def test_loopback_submit_wakes_waiter_and_rejects_late_delivery() -> None:
+ callback = await LoopbackCallback.start(ports=(0,))
+ waiter = asyncio.create_task(callback.wait(timeout=1))
+ result = OAuthCallbackResult(
+ code="authorization-code",
+ state="expected-state",
+ error=None,
+ )
+
+ callback.submit(result)
+
+ assert await waiter == result
+ with pytest.raises(CodexAuthError) as exc_info:
+ callback.submit(result)
+ assert exc_info.value.code == "login_not_active"
+ assert exc_info.value.http_status == 409
+
+
+async def test_loopback_does_not_serve_before_callback_closure_is_ready(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def eager_start_server(
+ handler: object,
+ _hosts: object,
+ _port: int,
+ *,
+ start_serving: bool = True,
+ ) -> _EagerServer:
+ server = _EagerServer(handler)
+ if start_serving:
+ await server.start_serving()
+ return server
+
+ monkeypatch.setattr(asyncio, "start_server", eager_start_server)
+
+ callback = await LoopbackCallback.start(ports=(0,))
+ result = await callback.wait(timeout=1)
+
+ assert result == OAuthCallbackResult(
+ code="eager-code",
+ state="eager-state",
+ error=None,
+ )
+
+
@pytest.mark.asyncio
async def test_loopback_ignores_wrong_path_then_accepts_oauth_error() -> None:
callback = await LoopbackCallback.start(ports=(0,))
@@ -111,6 +220,57 @@ async def test_loopback_ignores_wrong_path_then_accepts_oauth_error() -> None:
assert result.state == "expected"
+async def test_loopback_rejects_invalid_state_then_accepts_correct_callback() -> None:
+ callback = await LoopbackCallback.start(ports=(0,), expected_state="expected-state")
+ waiter = asyncio.create_task(callback.wait(timeout=1))
+
+ invalid_targets = (
+ "/auth/callback?code=wrong-code&state=wrong-state",
+ "/auth/callback?code=missing-state",
+ "/auth/callback?code=unicode-state&state=snowman-%E2%98%83",
+ f"/auth/callback?code=long-state&state={'a' * 129}",
+ "/auth/callback?code=repeated-state&state=expected-state&state=expected-state",
+ )
+ for target in invalid_targets:
+ response = await _send_get(callback.port, target)
+ assert "400 Bad Request" in response
+ assert not waiter.done()
+
+ response = await _send_get(
+ callback.port,
+ "/auth/callback?code=correct-code&state=expected-state",
+ )
+ result = await waiter
+
+ assert "200 OK" in response
+ assert result == OAuthCallbackResult(
+ code="correct-code",
+ state="expected-state",
+ error=None,
+ )
+
+
+async def test_loopback_returns_conflict_when_callback_cannot_be_submitted() -> None:
+ callback = await LoopbackCallback.start(ports=(0,), expected_state="expected-state")
+ first = OAuthCallbackResult(
+ code="first-code",
+ state="expected-state",
+ error=None,
+ )
+ callback.submit(first)
+
+ response = await _send_get(
+ callback.port,
+ "/auth/callback?code=second-code&state=expected-state",
+ )
+
+ assert "409 Conflict" in response
+ assert "200 OK" not in response
+ assert await callback.wait(timeout=1) == first
+
+
@pytest.mark.asyncio
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)
@@ -132,6 +292,8 @@ async def test_loopback_timeout_and_cancel_are_public_errors() -> None:
with pytest.raises(CodexAuthError) as timeout_error:
await timed_out.wait(timeout=0.01)
assert timeout_error.value.code == "login_timeout"
+ assert f"localhost:{timed_out.port}" in timeout_error.value.public_message
+ assert "did not receive" in timeout_error.value.public_message
cancelled = await LoopbackCallback.start(ports=(0,))
waiter = asyncio.create_task(cancelled.wait(timeout=1))
@@ -140,6 +302,60 @@ async def test_loopback_timeout_and_cancel_are_public_errors() -> None:
with pytest.raises(CodexAuthError) as cancel_error:
await waiter
assert cancel_error.value.code == "login_cancelled"
+ with pytest.raises(CodexAuthError) as late_submit:
+ cancelled.submit(OAuthCallbackResult(code="late-code", state="late-state", error=None))
+ assert late_submit.value.code == "login_not_active"
+ assert late_submit.value.http_status == 409
+
+
+async def test_loopback_timeout_stops_submit_before_close_finishes() -> None:
+ callback = await LoopbackCallback.start(ports=(0,))
+ close_started, release_close = _pause_callback_close(callback)
+ waiter = asyncio.create_task(callback.wait(timeout=0.01))
+ await asyncio.wait_for(close_started.wait(), timeout=1)
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ callback.submit(OAuthCallbackResult(code="too-late", state="too-late", error=None))
+
+ assert exc_info.value.code == "login_not_active"
+ release_close.set()
+ with pytest.raises(CodexAuthError) as timeout_error:
+ await waiter
+ assert timeout_error.value.code == "login_timeout"
+
+
+async def test_loopback_wait_cancellation_stops_submit_before_close_finishes() -> None:
+ callback = await LoopbackCallback.start(ports=(0,))
+ close_started, release_close = _pause_callback_close(callback)
+ waiter = asyncio.create_task(callback.wait(timeout=1))
+ await asyncio.sleep(0)
+ waiter.cancel()
+ await asyncio.wait_for(close_started.wait(), timeout=1)
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ callback.submit(OAuthCallbackResult(code="too-late", state="too-late", error=None))
+
+ assert exc_info.value.code == "login_not_active"
+ release_close.set()
+ with pytest.raises(asyncio.CancelledError):
+ await waiter
+
+
+async def test_loopback_cancel_stops_submit_before_close_finishes() -> None:
+ callback = await LoopbackCallback.start(ports=(0,))
+ close_started, release_close = _pause_callback_close(callback)
+ cancel_task = asyncio.create_task(callback.cancel())
+ await asyncio.wait_for(close_started.wait(), timeout=1)
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ callback.submit(OAuthCallbackResult(code="too-late", state="too-late", error=None))
+
+ assert exc_info.value.code == "login_not_active"
+ release_close.set()
+ await cancel_task
@pytest.mark.asyncio
diff --git a/tests/services/codex_auth/test_service.py b/tests/services/codex_auth/test_service.py
index 4f8956fd6..77d034121 100644
--- a/tests/services/codex_auth/test_service.py
+++ b/tests/services/codex_auth/test_service.py
@@ -23,6 +23,7 @@ from deeptutor.services.codex_auth.service import (
CodexOAuthService,
codex_model_id,
remove_codex_catalog,
+ ssh_forward_command,
sync_codex_catalog,
)
from deeptutor.services.codex_auth.storage import CodexCredentialStore
@@ -81,6 +82,67 @@ def test_partner_turn_inherits_its_owner_codex_login(
reset_current_user(token)
+def test_ssh_forward_command_maps_callback_to_frontend_port() -> None:
+ assert (
+ ssh_forward_command(1457, 4782) == "ssh -N -L 1457:127.0.0.1:4782 <ssh-user>@<server-host>"
+ )
+
+
[email protected]("callback_forward_port", [0, 65_536, True, "3782"])
+def test_callback_forward_port_must_be_a_valid_integer(
+ tmp_path: Path,
+ callback_forward_port: object,
+) -> None:
+ store = CodexCredentialStore(tmp_path)
+ model_catalog, _original = _seeded_service(tmp_path)
+
+ with pytest.raises(ValueError):
+ CodexOAuthService(
+ store,
+ FakeCatalog(_snapshot("live")),
+ model_catalog,
+ oauth_client=FakeOAuthClient(),
+ callback_forward_port=callback_forward_port, # type: ignore[arg-type]
+ )
+
+
+def test_service_singleton_reads_frontend_port_only_when_created(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ settings_calls = 0
+ captured: dict[str, Any] = {}
+
+ def load_settings() -> dict[str, int]:
+ nonlocal settings_calls
+ settings_calls += 1
+ return {"frontend_port": 4782}
+
+ class CapturingService:
+ def __init__(self, *_args: object, **kwargs: object) -> None:
+ captured.update(kwargs)
+
+ monkeypatch.setattr(service_module, "_SERVICE_INSTANCES", {})
+ monkeypatch.setattr(service_module, "_codex_user_root", lambda: tmp_path)
+ monkeypatch.setattr(service_module, "load_system_settings", load_settings)
+ monkeypatch.setattr(service_module, "CodexCredentialStore", lambda _root: object())
+ monkeypatch.setattr(
+ service_module,
+ "CodexModelCatalog",
+ lambda _store, *, http: object(),
+ )
+ monkeypatch.setattr(service_module, "CodexOAuthClient", lambda _http: object())
+ monkeypatch.setattr(service_module, "get_model_catalog_service", lambda: object())
+ monkeypatch.setattr(service_module, "CodexOAuthService", CapturingService)
+
+ first = service_module.get_codex_oauth_service()
+ second = service_module.get_codex_oauth_service()
+
+ assert first is second
+ assert settings_calls == 1
+ assert captured["callback_forward_port"] == 4782
+
+
def _model(
slug: str,
*,
@@ -292,6 +354,7 @@ class FakeCallback:
asyncio.get_running_loop().create_future()
)
self.error = error
+ self.expected_state: str | None = None
async def wait(self, timeout: float) -> OAuthCallbackResult:
if self.error is not None:
@@ -304,14 +367,21 @@ class FakeCallback:
CodexAuthError("login_cancelled", "Codex sign-in was cancelled.", 409)
)
+ def submit(self, result: OAuthCallbackResult) -> None:
+ if self._result.done():
+ raise CodexAuthError(
+ "login_not_active",
+ "Codex sign-in is not waiting for a callback.",
+ 409,
+ )
+ self._result.set_result(result)
+
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))
+ self.submit(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)
- )
+ self.submit(OAuthCallbackResult(code="authorization-code", state=state, error=None))
class FakeOAuthClient:
@@ -415,6 +485,7 @@ async def _oauth_service(
callback_error: CodexAuthError | None = None,
catalog_error: CodexAuthError | None = None,
clock: list[int] | None = None,
+ callback_forward_port: int = 3_782,
) -> tuple[
CodexOAuthService,
FakeCallback,
@@ -430,7 +501,8 @@ async def _oauth_service(
store = CodexCredentialStore(tmp_path)
model_catalog, _original = _seeded_service(tmp_path)
- async def callback_factory() -> FakeCallback:
+ async def callback_factory(expected_state: str) -> FakeCallback:
+ callback.expected_state = expected_state
return callback
service = CodexOAuthService(
@@ -440,6 +512,7 @@ async def _oauth_service(
oauth_client=oauth,
callback_factory=callback_factory,
clock=(lambda: (clock or [1_000])[0]),
+ callback_forward_port=callback_forward_port,
)
return service, callback, oauth, catalog, store, model_catalog
@@ -462,7 +535,10 @@ async def _wait_until_terminal(service: CodexOAuthService) -> dict[str, Any]:
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)
+ service, callback, _oauth, _catalog, _store, model_catalog = await _oauth_service(
+ tmp_path,
+ callback_forward_port=4_782,
+ )
original_selection = _selection(model_catalog.load())
started = await service.start_login()
@@ -471,15 +547,164 @@ async def test_successful_live_login_keeps_the_existing_model_selection(
status = await _wait_until_terminal(service)
assert duplicate == started
+ assert callback.expected_state == parse_qs(urlsplit(started["authorize_url"]).query)["state"][0]
assert status["connection"] == "connected"
assert status["operation_state"] == "completed"
+ assert status["authorize_url"] is None
+ assert status["expires_in"] is None
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"}
+ assert started["callback_port"] == 1455
+ assert started["callback_forward_port"] == 4782
+ assert started["redirect_uri"] == "http://localhost:1455/auth/callback"
+ assert (
+ started["ssh_forward_command"] == "ssh -N -L 1455:127.0.0.1:4782 <ssh-user>@<server-host>"
+ )
+ assert set(started) == {
+ "operation_id",
+ "authorize_url",
+ "expires_in",
+ "callback_port",
+ "callback_forward_port",
+ "redirect_uri",
+ "ssh_forward_command",
+ }
+
+
+async def test_callback_broker_keeps_waiting_after_wrong_state_then_completes(
+ tmp_path: Path,
+) -> None:
+ service, _callback, _oauth, _catalog, _store, _models = await _oauth_service(tmp_path)
+ started = await service.start_login()
+ expected_state = parse_qs(urlsplit(started["authorize_url"]).query)["state"][0]
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ await service.receive_callback(
+ code="do-not-accept",
+ state="wrong-state",
+ error=None,
+ )
+
+ assert exc_info.value.code == "state_mismatch"
+ assert exc_info.value.http_status == 400
+ assert service.public_status()["operation_state"] == "waiting"
+
+ await service.receive_callback(
+ code="authorization-code",
+ state=expected_state,
+ error=None,
+ )
+ status = await _wait_until_terminal(service)
+ assert status["operation_state"] == "completed"
+
+
+async def test_callback_broker_rejects_when_no_login_is_active(tmp_path: Path) -> None:
+ service, _callback, _oauth, _catalog, _store, _models = await _oauth_service(tmp_path)
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ await service.receive_callback(
+ code="authorization-code",
+ state="untrusted-state",
+ error=None,
+ )
+
+ assert exc_info.value.code == "login_not_active"
+ assert exc_info.value.http_status == 409
+
+
[email protected]("invalid_state", ["snowman-\u2603", "a" * 129])
+async def test_callback_broker_rejects_malformed_state_without_ending_login(
+ tmp_path: Path,
+ invalid_state: str,
+) -> None:
+ service, _callback, _oauth, _catalog, _store, _models = await _oauth_service(tmp_path)
+ await service.start_login()
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ await service.receive_callback(
+ code="do-not-accept",
+ state=invalid_state,
+ error=None,
+ )
+
+ assert exc_info.value.code == "state_mismatch"
+ assert exc_info.value.http_status == 400
+ assert service.public_status()["operation_state"] == "waiting"
+ await service.cancel_login()
+
+
+async def test_background_callback_unicode_state_has_stable_error(
+ tmp_path: Path,
+) -> None:
+ service, callback, _oauth, _catalog, _store, _models = await _oauth_service(tmp_path)
+ await service.start_login()
+
+ callback.complete_with_state("snowman-\u2603")
+ status = await _wait_until_terminal(service)
+
+ assert status["operation_state"] == "failed"
+ assert status["error_code"] == "state_mismatch"
+
+
+async def test_login_status_keeps_callback_metadata_without_exposing_secrets(
+ tmp_path: Path,
+) -> None:
+ clock = [1_000]
+ service, _callback, _oauth, _catalog, _store, _models = await _oauth_service(
+ tmp_path,
+ callback_error=CodexAuthError(
+ "login_timeout",
+ "Codex sign-in timed out.",
+ 408,
+ ),
+ clock=clock,
+ callback_forward_port=4_782,
+ )
+
+ started = await service.start_login()
+ waiting = service.public_status()
+ clock[0] += 17
+ later_waiting = service.public_status()
+ timed_out = await _wait_until_terminal(service)
+
+ assert waiting["operation_state"] == "waiting"
+ assert waiting["authorize_url"] == started["authorize_url"]
+ assert waiting["expires_in"] == started["expires_in"]
+ assert later_waiting["authorize_url"] == started["authorize_url"]
+ assert later_waiting["expires_in"] == started["expires_in"] - 17
+ assert timed_out["operation_state"] == "expired"
+ for status in (waiting, timed_out):
+ assert status["callback_port"] == started["callback_port"] == 1455
+ assert status["callback_forward_port"] == started["callback_forward_port"] == 4782
+ assert (
+ status["redirect_uri"]
+ == started["redirect_uri"]
+ == "http://localhost:1455/auth/callback"
+ )
+ assert timed_out["authorize_url"] is None
+ assert timed_out["expires_in"] is None
+
+ forbidden_fields = {
+ "state_secret",
+ "pkce",
+ "verifier",
+ "access_token",
+ "refresh_token",
+ "account_id",
+ "email",
+ }
+ for payload in (started, waiting, timed_out):
+ serialized = json.loads(json.dumps(payload))
+ assert forbidden_fields.isdisjoint(serialized)
@pytest.mark.asyncio
@@ -539,6 +764,8 @@ async def test_login_failures_do_not_overwrite_old_credentials(
assert loaded is not None
assert loaded.access_token == old.access_token
assert status["operation_state"] == ("expired" if failure == "timeout" else "failed")
+ assert status["authorize_url"] is None
+ assert status["expires_in"] is None
@pytest.mark.asyncio
@@ -553,6 +780,8 @@ async def test_cancel_login_preserves_existing_credentials(tmp_path: Path) -> No
assert loaded is not None
assert loaded.access_token == old.access_token
assert status["operation_state"] == "cancelled"
+ assert status["authorize_url"] is None
+ assert status["expires_in"] is None
@pytest.mark.asyncio
@@ -712,7 +941,7 @@ async def test_restarted_service_restores_connection_without_operation_or_secret
catalog,
model_catalog,
oauth_client=oauth,
- callback_factory=lambda: None, # type: ignore[arg-type,return-value]
+ callback_factory=lambda _state: None, # type: ignore[arg-type,return-value]
clock=lambda: 1_000,
)
@@ -722,6 +951,11 @@ async def test_restarted_service_restores_connection_without_operation_or_secret
assert status["connection"] == "connected"
assert status["operation_id"] is None
assert status["operation_state"] is None
+ assert status["callback_port"] is None
+ assert status["callback_forward_port"] is None
+ assert status["redirect_uri"] is None
+ assert status["authorize_url"] is None
+ assert status["expires_in"] is None
assert "top-secret" not in serialized
assert "full-account-secret" not in serialized
diff --git a/web/components/settings/CodexOAuthCard.tsx b/web/components/settings/CodexOAuthCard.tsx
index bfc749b87..9b0ad6370 100644
--- a/web/components/settings/CodexOAuthCard.tsx
+++ b/web/components/settings/CodexOAuthCard.tsx
@@ -6,15 +6,19 @@ import { useTranslation } from "react-i18next";
import Button from "@/components/ui/Button";
import {
+ buildSshForwardCommand,
cancelCodexLogin,
+ codexRemoteGuidance,
CodexOAuthApiError,
codexErrorMessageKey,
codexStatusMessageKey,
getCodexStatus,
+ isLoopbackHostname,
logoutCodex,
refreshCodexModels,
shouldPollCodexStatus,
startCodexLogin,
+ type CodexLoginStart,
type CodexOAuthStatus,
} from "@/lib/codex-oauth";
@@ -27,39 +31,91 @@ export function CodexOAuthCard() {
const [pending, setPending] = useState(false);
const [errorKey, setErrorKey] = useState<string | null>(null);
const [pollTick, setPollTick] = useState(0);
+ const [loginStart, setLoginStart] = useState<CodexLoginStart | null>(null);
const reloadedOperation = useRef<string | null>(null);
+ const statusRequestSequence = useRef(0);
+ const remoteAccess =
+ typeof window !== "undefined" &&
+ !isLoopbackHostname(window.location.hostname);
- 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;
- }
+ const recordStatus = useCallback((nextStatus: CodexOAuthStatus) => {
+ setStatus(nextStatus);
+ const terminalOperation =
+ nextStatus.operation_state === "completed" ||
+ nextStatus.operation_state === "cancelled" ||
+ nextStatus.operation_state === "expired" ||
+ nextStatus.operation_state === "failed";
+ if (!terminalOperation) return;
+ setLoginStart((loginStart) =>
+ loginStart && nextStatus.operation_id === loginStart.operation_id
+ ? null
+ : loginStart,
+ );
+ }, []);
+
+ const invalidateStatusRequests = useCallback(() => {
+ statusRequestSequence.current += 1;
}, []);
+ const loadStatus = useCallback(
+ async (shouldApply: () => boolean = () => true) => {
+ statusRequestSequence.current += 1;
+ const requestSequence = statusRequestSequence.current;
+ try {
+ const next = await getCodexStatus();
+ if (
+ requestSequence !== statusRequestSequence.current ||
+ !shouldApply()
+ ) {
+ return null;
+ }
+ recordStatus(next);
+ setErrorKey(null);
+ return next;
+ } catch (error) {
+ if (
+ requestSequence !== statusRequestSequence.current ||
+ !shouldApply()
+ ) {
+ return null;
+ }
+ setErrorKey(
+ codexErrorMessageKey(
+ error instanceof CodexOAuthApiError ? error.code : null,
+ ),
+ );
+ return null;
+ }
+ },
+ [recordStatus],
+ );
+
useEffect(() => {
- void loadStatus();
- }, [loadStatus]);
+ let cancelled = false;
+ void loadStatus(() => !cancelled);
+ return () => {
+ cancelled = true;
+ invalidateStatusRequests();
+ };
+ }, [invalidateStatusRequests, loadStatus]);
useEffect(() => {
- if (!status || !shouldPollCodexStatus(status)) return;
+ if (pending || !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.
+ let cancelled = false;
const timer = window.setTimeout(() => {
- void loadStatus();
- setPollTick((tick) => tick + 1);
+ void (async () => {
+ await loadStatus(() => !cancelled);
+ if (!cancelled) setPollTick((tick) => tick + 1);
+ })();
}, 1_000);
- return () => window.clearTimeout(timer);
- }, [loadStatus, status, pollTick]);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(timer);
+ };
+ }, [loadStatus, pending, 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.
@@ -83,7 +139,8 @@ export function CodexOAuthCard() {
void syncCatalog();
}, [syncCatalog, status]);
- const signIn = async () => {
+ const localSignIn = async () => {
+ invalidateStatusRequests();
const authWindow = window.open("about:blank", "_blank", "popup");
if (authWindow) authWindow.opener = null;
setPending(true);
@@ -95,7 +152,7 @@ export function CodexOAuthCard() {
} else {
window.location.assign(started.authorize_url);
}
- setStatus(await getCodexStatus());
+ await loadStatus();
} catch (error) {
authWindow?.close();
setErrorKey(
@@ -108,10 +165,58 @@ export function CodexOAuthCard() {
}
};
+ const remoteSignIn = async () => {
+ invalidateStatusRequests();
+ setPending(true);
+ setErrorKey(null);
+ try {
+ const started = await startCodexLogin();
+ setLoginStart(started);
+ await loadStatus();
+ } catch (error) {
+ setErrorKey(
+ codexErrorMessageKey(
+ error instanceof CodexOAuthApiError ? error.code : null,
+ ),
+ );
+ } finally {
+ setPending(false);
+ }
+ };
+
+ const signIn = remoteAccess ? remoteSignIn : localSignIn;
+
+ const remoteGuidance = codexRemoteGuidance(status, loginStart);
+ const sshCommand = remoteGuidance
+ ? buildSshForwardCommand(
+ remoteGuidance.callback_port,
+ window.location.hostname,
+ remoteGuidance.callback_forward_port,
+ )
+ : "";
+
+ const copyCommand = async () => {
+ if (!sshCommand) return;
+ try {
+ await navigator.clipboard.writeText(sshCommand);
+ setToast(t("codex.oauth.commandCopied"));
+ } catch {
+ setToast(t("codex.oauth.copyFailed"));
+ }
+ };
+
+ const openAuthorization = () => {
+ if (!remoteGuidance) return;
+ window.open(remoteGuidance.authorize_url, "_blank", "noopener");
+ };
+
const cancel = async () => {
+ invalidateStatusRequests();
setPending(true);
try {
- setStatus(await cancelCodexLogin());
+ const nextStatus = await cancelCodexLogin();
+ invalidateStatusRequests();
+ recordStatus(nextStatus);
} catch (error) {
setErrorKey(
codexErrorMessageKey(
@@ -119,14 +224,18 @@ export function CodexOAuthCard() {
),
);
} finally {
+ setLoginStart(null);
setPending(false);
}
};
const refresh = async () => {
+ invalidateStatusRequests();
setPending(true);
try {
- setStatus(await refreshCodexModels());
+ const nextStatus = await refreshCodexModels();
+ invalidateStatusRequests();
+ recordStatus(nextStatus);
await syncCatalog();
setErrorKey(null);
} catch (error) {
@@ -141,9 +250,13 @@ export function CodexOAuthCard() {
};
const logout = async () => {
+ invalidateStatusRequests();
setPending(true);
try {
- setStatus(await logoutCodex());
+ const nextStatus = await logoutCodex();
+ invalidateStatusRequests();
+ recordStatus(nextStatus);
+ setLoginStart(null);
await syncCatalog();
setErrorKey(null);
} catch (error) {
@@ -161,6 +274,12 @@ export function CodexOAuthCard() {
const connected = status?.connection === "connected";
const messageKey =
errorKey || (status ? codexStatusMessageKey(status) : null);
+ const callbackPort =
+ status?.callback_port ?? loginStart?.callback_port;
+ const displayMessageKey =
+ messageKey === "codex.oauth.callbackMissing" && callbackPort == null
+ ? "codex.oauth.callbackMissingUnknown"
+ : messageKey;
return (
<section className="rounded-xl border border-[var(--border)] bg-[var(--muted)]/30 p-4">
@@ -182,9 +301,11 @@ export function CodexOAuthCard() {
<p className="mt-1 text-xs text-amber-600 dark:text-amber-400">
{t("codex.oauth.experimental")}
</p>
- {messageKey && (
+ {displayMessageKey && (
<p className="mt-3 text-sm text-[var(--foreground)]">
- {t(messageKey)}
+ {t(displayMessageKey, {
+ port: callbackPort,
+ })}
</p>
)}
{connected && status?.model_count !== undefined && (
@@ -192,6 +313,57 @@ export function CodexOAuthCard() {
{t("codex.oauth.modelCount", { count: status.model_count })}
</p>
)}
+ {remoteAccess && remoteGuidance && (
+ <div className="mt-4 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3">
+ <p className="text-sm font-medium">
+ {t("codex.oauth.remoteTitle")}
+ </p>
+ <p className="mt-2 text-xs text-[var(--muted-foreground)]">
+ {t("codex.oauth.remoteSteps")}
+ </p>
+ <p className="mt-3 text-xs font-medium">
+ {t("codex.oauth.callbackAddress")}
+ </p>
+ <code className="mt-1 block break-all text-xs">
+ {remoteGuidance.redirect_uri}
+ </code>
+ <p className="mt-2 text-xs text-[var(--muted-foreground)]">
+ {t("codex.oauth.expiresIn", {
+ seconds: remoteGuidance.expires_in,
+ })}
+ </p>
+ <pre className="mt-3 overflow-x-auto rounded-md bg-[var(--muted)] p-2 text-xs">
+ <code>{sshCommand}</code>
+ </pre>
+ <div className="mt-3 flex flex-wrap gap-2">
+ <Button
+ type="button"
+ size="sm"
+ variant="secondary"
+ onClick={() => void copyCommand()}
+ >
+ {t("codex.oauth.copyCommand")}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ onClick={openAuthorization}
+ icon={<ExternalLink className="h-4 w-4" />}
+ >
+ {t("codex.oauth.openAuthorization")}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="secondary"
+ disabled={pending}
+ onClick={() => void cancel()}
+ >
+ {t("codex.oauth.cancel")}
+ </Button>
+ </div>
+ </div>
+ )}
<div className="mt-4 flex flex-wrap gap-2">
{!connected && !polling && (
<Button
@@ -204,7 +376,7 @@ export function CodexOAuthCard() {
{t("codex.oauth.signIn")}
</Button>
)}
- {polling && (
+ {polling && !(remoteAccess && remoteGuidance) && (
<Button
type="button"
size="sm"
diff --git a/web/lib/codex-oauth.ts b/web/lib/codex-oauth.ts
index 2aec75fa6..4d044462f 100644
--- a/web/lib/codex-oauth.ts
+++ b/web/lib/codex-oauth.ts
@@ -12,6 +12,11 @@ export type CodexOAuthStatus = {
| "expired"
| "failed"
| null;
+ authorize_url: string | null;
+ expires_in: number | null;
+ callback_port: number | null;
+ callback_forward_port: number | null;
+ redirect_uri: string | null;
model_count: number;
catalog_source:
| "live"
@@ -29,8 +34,17 @@ export type CodexLoginStart = {
operation_id: string;
authorize_url: string;
expires_in: number;
+ callback_port: number;
+ callback_forward_port: number;
+ redirect_uri: string;
+ ssh_forward_command: string;
};
+export type CodexRemoteGuidance = Omit<
+ CodexLoginStart,
+ "ssh_forward_command"
+>;
+
export class CodexOAuthApiError extends Error {
code: string;
@@ -43,12 +57,90 @@ export class CodexOAuthApiError extends Error {
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}`), {
+export function isLoopbackHostname(hostname: string): boolean {
+ const normalized = hostname.trim().toLowerCase().replace(/\.$/, "");
+ if (
+ normalized === "localhost" ||
+ normalized.endsWith(".localhost") ||
+ normalized === "::1" ||
+ normalized === "[::1]"
+ ) {
+ return true;
+ }
+
+ const octets = normalized.split(".");
+ return (
+ octets.length === 4 &&
+ octets[0] === "127" &&
+ octets.every(
+ (octet) =>
+ /^\d+$/.test(octet) && Number(octet) >= 0 && Number(octet) <= 255,
+ )
+ );
+}
+
+export function buildSshForwardCommand(
+ callbackPort: number,
+ hostname: string,
+ forwardPort: number,
+): string {
+ const serverHost = hostname.trim() || "<server-host>";
+ return `ssh -N -L ${callbackPort}:127.0.0.1:${forwardPort} <ssh-user>@${serverHost}`;
+}
+
+export function codexRemoteGuidance(
+ status: CodexOAuthStatus | null,
+ loginStart: CodexLoginStart | null,
+): CodexRemoteGuidance | null {
+ if (status?.operation_state !== "waiting" || !status.operation_id) {
+ return null;
+ }
+ const matchingStart =
+ loginStart?.operation_id === status.operation_id ? loginStart : null;
+ const authorizeUrl = status.authorize_url ?? matchingStart?.authorize_url;
+ const expiresIn = status.expires_in ?? matchingStart?.expires_in;
+ const callbackPort = status.callback_port ?? matchingStart?.callback_port;
+ const callbackForwardPort =
+ status.callback_forward_port ?? matchingStart?.callback_forward_port;
+ const redirectUri = status.redirect_uri ?? matchingStart?.redirect_uri;
+ if (
+ !authorizeUrl ||
+ expiresIn == null ||
+ callbackPort == null ||
+ callbackForwardPort == null ||
+ !redirectUri
+ ) {
+ return null;
+ }
+ return {
+ operation_id: status.operation_id,
+ authorize_url: authorizeUrl,
+ expires_in: expiresIn,
+ callback_port: callbackPort,
+ callback_forward_port: callbackForwardPort,
+ redirect_uri: redirectUri,
+ };
+}
+
+export async function requestCodex<T>(
+ path: string,
+ method: "GET" | "POST",
+ fetchImpl: typeof apiFetch = apiFetch,
+): Promise<T> {
+ const response = await fetchImpl(apiUrl(`${BASE}${path}`), {
method,
skipAuthRedirect: true,
});
- if (response.ok) return (await response.json()) as T;
+ if (response.ok) {
+ try {
+ return (await response.json()) as T;
+ } catch {
+ throw new CodexOAuthApiError(
+ "invalid_response",
+ "DeepTutor returned an invalid Codex OAuth response.",
+ );
+ }
+ }
let code = `http_${response.status}`;
let message = "Codex request failed.";
@@ -65,23 +157,23 @@ async function request<T>(path: string, method: "GET" | "POST"): Promise<T> {
}
export function getCodexStatus(): Promise<CodexOAuthStatus> {
- return request<CodexOAuthStatus>("/oauth/status", "GET");
+ return requestCodex<CodexOAuthStatus>("/oauth/status", "GET");
}
export function startCodexLogin(): Promise<CodexLoginStart> {
- return request<CodexLoginStart>("/oauth/start", "POST");
+ return requestCodex<CodexLoginStart>("/oauth/start", "POST");
}
export function cancelCodexLogin(): Promise<CodexOAuthStatus> {
- return request<CodexOAuthStatus>("/oauth/cancel", "POST");
+ return requestCodex<CodexOAuthStatus>("/oauth/cancel", "POST");
}
export function refreshCodexModels(): Promise<CodexOAuthStatus> {
- return request<CodexOAuthStatus>("/models/refresh", "POST");
+ return requestCodex<CodexOAuthStatus>("/models/refresh", "POST");
}
export function logoutCodex(): Promise<CodexOAuthStatus> {
- return request<CodexOAuthStatus>("/oauth/logout", "POST");
+ return requestCodex<CodexOAuthStatus>("/oauth/logout", "POST");
}
export function shouldPollCodexStatus(status: CodexOAuthStatus): boolean {
@@ -99,7 +191,11 @@ export function codexErrorMessageKey(code: string | null): string {
if (code === "inference_in_progress") {
return "codex.oauth.inferenceActive";
}
- if (code === "login_timeout") return "codex.oauth.expired";
+ if (code === "login_timeout") return "codex.oauth.callbackMissing";
+ if (code === "callback_unavailable") {
+ return "codex.oauth.callbackUnavailable";
+ }
+ if (code === "invalid_response") return "codex.oauth.invalidResponse";
if (code === "login_cancelled") return "codex.oauth.cancelled";
if (code === "authorization_denied") return "codex.oauth.denied";
return "codex.oauth.requestFailed";
diff --git a/web/lib/proxy-policy.ts b/web/lib/proxy-policy.ts
index 320d3867f..9071c502b 100644
--- a/web/lib/proxy-policy.ts
+++ b/web/lib/proxy-policy.ts
@@ -8,6 +8,13 @@
export const LOGIN_PATH = "/login";
export const COOKIE_NAME = "dt_token";
+export const CODEX_CALLBACK_PATH = "/auth/callback";
+export const CODEX_CALLBACK_API_PATH =
+ "/api/v1/auth/openai-codex/callback";
+
+export function isCodexCallbackPath(pathname: string): boolean {
+ return pathname === CODEX_CALLBACK_PATH;
+}
// Paths whose responses come from the backend, not the Next app. The middleware
// rewrites these to DEEPTUTOR_API_BASE_URL so the browser can use frontend-
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 1035cbf1b..c734ddc2a 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -2739,7 +2739,19 @@
"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.localOnly": "Local access opens authorization directly. Remote access first shows an SSH tunnel command.",
+ "codex.oauth.remoteTitle": "Remote OAuth authorization",
+ "codex.oauth.remoteSteps": "First run the command below and keep the SSH tunnel running. Then click Open authorization.",
+ "codex.oauth.callbackAddress": "OAuth callback address",
+ "codex.oauth.copyCommand": "Copy command",
+ "codex.oauth.commandCopied": "SSH tunnel command copied.",
+ "codex.oauth.copyFailed": "Could not copy the SSH tunnel command.",
+ "codex.oauth.openAuthorization": "Open authorization",
+ "codex.oauth.expiresIn": "Expires in {{seconds}} seconds.",
+ "codex.oauth.callbackMissing": "The DeepTutor server did not receive the OAuth callback on localhost:{{port}}. For a remote deployment, keep the SSH tunnel running and try again.",
+ "codex.oauth.callbackMissingUnknown": "The DeepTutor server did not receive the OAuth callback. Start the login again and follow the authorization instructions shown for the new attempt.",
+ "codex.oauth.callbackUnavailable": "DeepTutor cannot listen on either localhost:1455 or localhost:1457. Free one of these ports and try again.",
+ "codex.oauth.invalidResponse": "The DeepTutor OAuth endpoint returned an unexpected response. Check that the reverse proxy forwards /api/v1/settings/providers/openai-codex/ correctly.",
"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.",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 4add6cfc0..764cde426 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -2739,7 +2739,19 @@
"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.localOnly": "本地访问会直接打开授权页面;远程访问会先显示 SSH 隧道命令。",
+ "codex.oauth.remoteTitle": "远程 OAuth 授权",
+ "codex.oauth.remoteSteps": "先运行下方命令并保持 SSH 隧道运行,再点击“打开授权页面”。",
+ "codex.oauth.callbackAddress": "OAuth 回调地址",
+ "codex.oauth.copyCommand": "复制命令",
+ "codex.oauth.commandCopied": "SSH 隧道命令已复制。",
+ "codex.oauth.copyFailed": "无法复制 SSH 隧道命令。",
+ "codex.oauth.openAuthorization": "打开授权页面",
+ "codex.oauth.expiresIn": "剩余 {{seconds}} 秒。",
+ "codex.oauth.callbackMissing": "DeepTutor 服务器未在 localhost:{{port}} 收到 OAuth 回调。远程部署请保持 SSH 隧道运行并重试。",
+ "codex.oauth.callbackMissingUnknown": "DeepTutor 服务器未收到 OAuth 回调。请重新开始登录,并按照新一轮显示的授权说明操作。",
+ "codex.oauth.callbackUnavailable": "DeepTutor 无法监听 localhost:1455 和 localhost:1457。请释放其中一个端口后重试。",
+ "codex.oauth.invalidResponse": "DeepTutor OAuth 接口返回了异常响应。请检查反向代理是否正确转发 /api/v1/settings/providers/openai-codex/。",
"codex.oauth.activated": "Codex 已连接,并已设为当前模型。",
"codex.oauth.reloadDeferred": "Codex 已连接。应用当前未保存的更改后即可在列表中看到它的模型。",
"codex.oauth.catalogFailed": "无法刷新 Codex 模型目录,登录状态和当前模型均已保留。",
diff --git a/web/proxy.ts b/web/proxy.ts
index f758a9c65..bc4cb136f 100644
--- a/web/proxy.ts
+++ b/web/proxy.ts
@@ -1,11 +1,13 @@
import { NextRequest, NextResponse } from "next/server";
import { parseAuthEnabled } from "./lib/api";
import {
+ CODEX_CALLBACK_API_PATH,
COOKIE_NAME,
LOGIN_PATH,
classifyToken,
isAuthExempt,
isBackendPath,
+ isCodexCallbackPath,
} from "./lib/proxy-policy";
// Backend base URL for `/api/*` and `/ws/*` rewrites. The container entrypoint
@@ -36,6 +38,12 @@ function redirectToLogin(
export function proxy(req: NextRequest): NextResponse {
const { pathname, search } = req.nextUrl;
+ if (isCodexCallbackPath(pathname)) {
+ return NextResponse.rewrite(
+ new URL(CODEX_CALLBACK_API_PATH + search, API_BASE_URL),
+ );
+ }
+
// 1. Bridge the origin gap: forward backend-relative paths to the API server.
// This keeps the URL knowledge in one place (the entrypoint + system.json)
// rather than baked into the frontend bundle.
diff --git a/web/tests/codex-oauth-client.test.ts b/web/tests/codex-oauth-client.test.ts
index 9dc249809..5da356fa5 100644
--- a/web/tests/codex-oauth-client.test.ts
+++ b/web/tests/codex-oauth-client.test.ts
@@ -4,8 +4,15 @@ import path from "node:path";
import test from "node:test";
import {
+ buildSshForwardCommand,
+ CodexOAuthApiError,
+ codexRemoteGuidance,
+ codexErrorMessageKey,
codexStatusMessageKey,
+ isLoopbackHostname,
+ requestCodex,
shouldPollCodexStatus,
+ type CodexLoginStart,
type CodexOAuthStatus,
} from "../lib/codex-oauth";
@@ -20,6 +27,11 @@ function status(overrides: Partial<CodexOAuthStatus> = {}): CodexOAuthStatus {
connection: "disconnected",
operation_id: null,
operation_state: null,
+ authorize_url: null,
+ expires_in: null,
+ callback_port: null,
+ callback_forward_port: null,
+ redirect_uri: null,
model_count: 0,
catalog_source: null,
catalog_fetched_at: null,
@@ -30,6 +42,222 @@ function status(overrides: Partial<CodexOAuthStatus> = {}): CodexOAuthStatus {
};
}
+function waitingStatus(
+ overrides: Partial<CodexOAuthStatus> = {},
+): CodexOAuthStatus {
+ return status({
+ operation_id: "operation-1",
+ operation_state: "waiting",
+ authorize_url: "https://auth.example.com",
+ expires_in: 275,
+ callback_port: 1457,
+ callback_forward_port: 4782,
+ redirect_uri: "http://localhost:1457/auth/callback",
+ ...overrides,
+ });
+}
+
+test("Codex OAuth response types expose remote-login guidance", () => {
+ const login: CodexLoginStart = {
+ operation_id: "operation-1",
+ authorize_url: "https://auth.example.com",
+ expires_in: 300,
+ callback_port: 1457,
+ callback_forward_port: 4782,
+ redirect_uri: "http://localhost:1457/auth/callback",
+ ssh_forward_command:
+ "ssh -N -L 1457:127.0.0.1:4782 <ssh-user>@deeptutor.example.com",
+ };
+ const current = waitingStatus();
+
+ assert.equal(login.callback_port, 1457);
+ assert.equal(login.callback_forward_port, 4782);
+ assert.equal(
+ login.ssh_forward_command,
+ "ssh -N -L 1457:127.0.0.1:4782 <ssh-user>@deeptutor.example.com",
+ );
+ assert.equal(current.callback_forward_port, 4782);
+ assert.equal(current.redirect_uri, "http://localhost:1457/auth/callback");
+ assert.equal(current.authorize_url, "https://auth.example.com");
+ assert.equal(current.expires_in, 275);
+});
+
+test("Codex remote guidance recovers from a complete waiting status", () => {
+ const guidance = codexRemoteGuidance(waitingStatus(), null);
+
+ assert.deepEqual(guidance, {
+ operation_id: "operation-1",
+ authorize_url: "https://auth.example.com",
+ expires_in: 275,
+ callback_port: 1457,
+ callback_forward_port: 4782,
+ redirect_uri: "http://localhost:1457/auth/callback",
+ });
+});
+
+test("Codex remote guidance requires waiting state and complete operation fields", () => {
+ const complete = waitingStatus();
+
+ for (const operation_state of [
+ null,
+ "exchanging",
+ "fetching_models",
+ "completed",
+ "cancelled",
+ "expired",
+ "failed",
+ ] as const) {
+ assert.equal(
+ codexRemoteGuidance({ ...complete, operation_state }, null),
+ null,
+ );
+ }
+ for (const field of [
+ "operation_id",
+ "authorize_url",
+ "expires_in",
+ "callback_port",
+ "callback_forward_port",
+ "redirect_uri",
+ ] as const) {
+ assert.equal(codexRemoteGuidance({ ...complete, [field]: null }, null), null);
+ }
+});
+
+test("Codex remote guidance prefers status expiry and only falls back to the matching start", () => {
+ const login: CodexLoginStart = {
+ operation_id: "operation-1",
+ authorize_url: "https://auth.example.com",
+ expires_in: 300,
+ callback_port: 1457,
+ callback_forward_port: 4782,
+ redirect_uri: "http://localhost:1457/auth/callback",
+ ssh_forward_command:
+ "ssh -N -L 1457:127.0.0.1:4782 <ssh-user>@deeptutor.example.com",
+ };
+ const waiting = waitingStatus({ expires_in: 42 });
+
+ assert.equal(codexRemoteGuidance(waiting, login)?.expires_in, 42);
+ assert.equal(
+ codexRemoteGuidance({ ...waiting, expires_in: null }, login)?.expires_in,
+ 300,
+ );
+ assert.equal(
+ codexRemoteGuidance(
+ { ...waiting, expires_in: null },
+ { ...login, operation_id: "stale-operation" },
+ ),
+ null,
+ );
+});
+
+test("Codex OAuth recognizes loopback hostnames", () => {
+ for (const hostname of [
+ "localhost",
+ "localhost.",
+ "app.localhost",
+ "app.localhost.",
+ "127.0.0.1",
+ "127.12.34.56",
+ "::1",
+ "[::1]",
+ ]) {
+ assert.equal(isLoopbackHostname(hostname), true, hostname);
+ }
+
+ for (const hostname of [
+ "192.168.1.10",
+ "deeptutor.example.com",
+ "deeptutor.example.com.",
+ "localhost..",
+ "app.localhost..",
+ "10.0.0.8",
+ "127.0.0.256",
+ "127.12.999.56",
+ "127.1.2.-1",
+ "127.1.2",
+ "127.1.2.3.4",
+ ]) {
+ assert.equal(isLoopbackHostname(hostname), false, hostname);
+ }
+});
+
+test("Codex OAuth builds SSH forwarding guidance for the current server", () => {
+ assert.equal(
+ buildSshForwardCommand(1457, "deeptutor.example.com", 4782),
+ "ssh -N -L 1457:127.0.0.1:4782 <ssh-user>@deeptutor.example.com",
+ );
+ assert.equal(
+ buildSshForwardCommand(1457, "", 4782),
+ "ssh -N -L 1457:127.0.0.1:4782 <ssh-user>@<server-host>",
+ );
+});
+
+test("SSH forwarding source contract requires distinct callback and forward ports", () => {
+ const source = readFileSync(CODEX_CLIENT, "utf8");
+ const commandBuilder = componentBlock(
+ source,
+ "export function buildSshForwardCommand",
+ "export async function requestCodex",
+ );
+
+ assert.match(
+ commandBuilder,
+ /callbackPort:\s*number,\s*hostname:\s*string,\s*forwardPort:\s*number,/,
+ );
+ assert.match(
+ commandBuilder,
+ /\$\{callbackPort\}:127\.0\.0\.1:\$\{forwardPort\}/,
+ );
+});
+
+test("Codex OAuth reports a stable error for an invalid successful response", async () => {
+ const responseBody = "<!doctype html><title>Proxy error</title>";
+ const fetchImpl = async (): Promise<Response> =>
+ new Response(responseBody, {
+ status: 200,
+ headers: { "content-type": "text/html; charset=utf-8" },
+ });
+
+ await assert.rejects(
+ requestCodex("/oauth/status", "GET", fetchImpl),
+ (error: unknown) => {
+ assert.ok(error instanceof CodexOAuthApiError);
+ assert.equal(error.code, "invalid_response");
+ assert.equal(
+ error.message,
+ "DeepTutor returned an invalid Codex OAuth response.",
+ );
+ assert.equal(error.message.includes(responseBody), false);
+ assert.equal(error.message.includes("text/html"), false);
+ return true;
+ },
+ );
+});
+
+test("Codex OAuth preserves structured errors from non-successful responses", async () => {
+ const fetchImpl = async (): Promise<Response> =>
+ new Response(
+ JSON.stringify({
+ detail: { code: "login_timeout", message: "Login timed out." },
+ }),
+ {
+ status: 408,
+ headers: { "content-type": "application/json" },
+ },
+ );
+
+ await assert.rejects(
+ requestCodex("/oauth/status", "GET", fetchImpl),
+ (error: unknown) => {
+ assert.ok(error instanceof CodexOAuthApiError);
+ assert.equal(error.code, "login_timeout");
+ assert.equal(error.message, "Login timed out.");
+ return true;
+ },
+ );
+});
+
test("Codex terminal operation states stop polling", () => {
for (const operation_state of [
"completed",
@@ -93,16 +321,288 @@ test("Codex error codes map to stable translation keys", () => {
codexStatusMessageKey(status({ error_code: "inference_in_progress" })),
"codex.oauth.inferenceActive",
);
+ assert.equal(
+ codexErrorMessageKey("login_timeout"),
+ "codex.oauth.callbackMissing",
+ );
+ assert.equal(
+ codexErrorMessageKey("callback_unavailable"),
+ "codex.oauth.callbackUnavailable",
+ );
+ assert.equal(
+ codexErrorMessageKey("invalid_response"),
+ "codex.oauth.invalidResponse",
+ );
+});
+
+function componentBlock(
+ source: string,
+ startMarker: string,
+ endMarker: string,
+): string {
+ const start = source.indexOf(startMarker);
+ const end = source.indexOf(endMarker, start);
+ assert.notEqual(start, -1, `missing ${startMarker}`);
+ assert.notEqual(end, -1, `missing ${endMarker}`);
+ return source.slice(start, end);
+}
+
+test("Codex status polling waits for each request and stops state updates after cleanup", () => {
+ const source = readFileSync(CODEX_CARD, "utf8");
+ const loadStatus = componentBlock(
+ source,
+ "const loadStatus",
+ "useEffect(() =>",
+ );
+ const pollingEffect = componentBlock(
+ source,
+ "if (pending || !status || !shouldPollCodexStatus(status)) return;",
+ "// Reloading replaces",
+ );
+
+ assert.match(
+ loadStatus,
+ /async \(shouldApply: \(\) => boolean = \(\) => true\)/,
+ );
+ assert.match(loadStatus, /!shouldApply\(\)/);
+ assert.match(pollingEffect, /let cancelled = false;/);
+ assert.match(pollingEffect, /await loadStatus\(\(\) => !cancelled\);/);
+ assert.ok(
+ pollingEffect.indexOf("await loadStatus") <
+ pollingEffect.indexOf("setPollTick"),
+ );
+ assert.match(pollingEffect, /if \(!cancelled\) setPollTick/);
+ assert.match(
+ pollingEffect,
+ /return \(\) => \{\s*cancelled = true;\s*window\.clearTimeout\(timer\);\s*\};/,
+ );
+ assert.match(pollingEffect, /}, 1_000\);/);
+ assert.match(
+ pollingEffect,
+ /if \(\s*pending \|\|\s*!status \|\| !shouldPollCodexStatus\(status\)\s*\) return;/,
+ );
+ assert.match(
+ pollingEffect,
+ /\[loadStatus, pending, status, pollTick\]/,
+ );
+});
+
+test("Codex status request epochs reject stale responses across user actions", () => {
+ const source = readFileSync(CODEX_CARD, "utf8");
+ const loadStatus = componentBlock(
+ source,
+ "const loadStatus",
+ "useEffect(() =>",
+ );
+
+ assert.match(source, /const statusRequestSequence = useRef\(0\);/);
+ assert.match(
+ source,
+ /const invalidateStatusRequests = useCallback\(\(\) => \{\s*statusRequestSequence\.current \+= 1;\s*\}, \[\]\);/,
+ );
+ assert.match(
+ loadStatus,
+ /const requestSequence = statusRequestSequence\.current;/,
+ );
+ assert.match(
+ loadStatus,
+ /requestSequence !== statusRequestSequence\.current/,
+ );
+ assert.ok(
+ loadStatus.indexOf("requestSequence !== statusRequestSequence.current") <
+ loadStatus.indexOf("recordStatus(next)"),
+ );
+ assert.match(
+ source,
+ /return \(\) => \{\s*cancelled = true;\s*invalidateStatusRequests\(\);\s*\};/,
+ );
+
+ const actionBlocks = [
+ componentBlock(source, "const localSignIn", "const remoteSignIn"),
+ componentBlock(source, "const remoteSignIn", "const signIn"),
+ componentBlock(source, "const cancel", "const refresh"),
+ componentBlock(source, "const refresh", "const logout"),
+ componentBlock(source, "const logout", "const polling"),
+ ];
+ for (const action of actionBlocks) {
+ assert.ok(
+ action.indexOf("invalidateStatusRequests()") <
+ action.indexOf("await "),
+ );
+ }
+
+ for (const login of actionBlocks.slice(0, 2)) {
+ assert.match(login, /await loadStatus\(\);/);
+ assert.equal(login.includes("recordStatus(await getCodexStatus())"), false);
+ }
+ for (const [action, request] of [
+ [actionBlocks[2], "cancelCodexLogin"],
+ [actionBlocks[3], "refreshCodexModels"],
+ [actionBlocks[4], "logoutCodex"],
+ ]) {
+ assert.match(
+ action,
+ new RegExp(
+ `const nextStatus = await ${request}\\(\\);\\s*invalidateStatusRequests\\(\\);\\s*recordStatus\\(nextStatus\\);`,
+ ),
+ );
+ }
+});
+
+test("Local Codex sign-in opens its browser window before awaiting the API", () => {
+ const source = readFileSync(CODEX_CARD, "utf8");
+ const localSignIn = componentBlock(
+ source,
+ "const localSignIn",
+ "const remoteSignIn",
+ );
+
+ assert.ok(
+ localSignIn.indexOf('window.open("about:blank"') <
+ localSignIn.indexOf("await startCodexLogin()"),
+ );
+ assert.match(localSignIn, /authWindow\.location\.replace\(started\.authorize_url\)/);
+ assert.match(localSignIn, /window\.location\.assign\(started\.authorize_url\)/);
});
-test("Codex sign-in opens its browser window before awaiting the API", () => {
+test("Codex sign-in detects remote browsers and retains the login start", () => {
const source = readFileSync(CODEX_CARD, "utf8");
- const signIn = source.slice(
- source.indexOf("const signIn"),
- source.indexOf("const cancel"),
+
+ assert.match(
+ source,
+ /isLoopbackHostname\(window\.location\.hostname\)/,
);
+ assert.match(
+ source,
+ /useState<CodexLoginStart \| null>\(null\)/,
+ );
+ assert.match(
+ source,
+ /const signIn = remoteAccess \? remoteSignIn : localSignIn;/,
+ );
+
+ const remoteSignIn = componentBlock(
+ source,
+ "const remoteSignIn",
+ "const signIn",
+ );
+ assert.ok(
+ remoteSignIn.indexOf("await startCodexLogin()") <
+ remoteSignIn.indexOf("setLoginStart(started)"),
+ );
+ assert.ok(
+ remoteSignIn.indexOf("setLoginStart(started)") <
+ remoteSignIn.indexOf("await loadStatus()"),
+ );
+});
+
+test("Remote Codex sign-in never opens or redirects the browser automatically", () => {
+ const source = readFileSync(CODEX_CARD, "utf8");
+ const remoteSignIn = componentBlock(
+ source,
+ "const remoteSignIn",
+ "const signIn",
+ );
+
+ assert.equal(remoteSignIn.includes("window.open("), false);
+ assert.equal(remoteSignIn.includes("window.location.assign("), false);
+});
+
+test("Remote Codex guidance uses the real callback port and explicit user actions", () => {
+ const source = readFileSync(CODEX_CARD, "utf8");
+ const current = status({ callback_port: 1457 });
+
+ assert.equal(current.callback_port, 1457);
+ assert.match(
+ source,
+ /const callbackPort\s*=\s*status\?\.callback_port\s*\?\?\s*loginStart\?\.callback_port/,
+ );
+ assert.match(
+ source,
+ /messageKey === "codex\.oauth\.callbackMissing"\s*&&\s*callbackPort == null/,
+ );
+ assert.match(
+ source,
+ /\?\s*"codex\.oauth\.callbackMissingUnknown"\s*:\s*messageKey/,
+ );
+ assert.match(
+ source,
+ /t\(displayMessageKey,\s*\{\s*port:\s*callbackPort,?\s*\}\s*\)/,
+ );
+
+ assert.match(
+ source,
+ /buildSshForwardCommand\(\s*remoteGuidance\.callback_port,\s*window\.location\.hostname,\s*remoteGuidance\.callback_forward_port,\s*\)/,
+ );
+ assert.match(source, /\{remoteGuidance\.redirect_uri\}/);
+ assert.match(
+ source,
+ /const remoteGuidance = codexRemoteGuidance\(status,\s*loginStart\)/,
+ );
+ assert.match(
+ source,
+ /t\("codex\.oauth\.expiresIn",\s*\{\s*seconds:\s*remoteGuidance\.expires_in,\s*\}\)/,
+ );
+
+ const copyCommand = componentBlock(
+ source,
+ "const copyCommand",
+ "const openAuthorization",
+ );
+ assert.match(copyCommand, /navigator\.clipboard\.writeText\(sshCommand\)/);
+ assert.match(copyCommand, /setToast\(t\("codex\.oauth\.commandCopied"\)\)/);
+ assert.match(copyCommand, /setToast\(t\("codex\.oauth\.copyFailed"\)\)/);
+
+ const openAuthorization = componentBlock(
+ source,
+ "const openAuthorization",
+ "const cancel",
+ );
+ assert.match(
+ openAuthorization,
+ /window\.open\(remoteGuidance\.authorize_url,\s*"_blank",\s*"noopener"\)/,
+ );
+});
+
+test("Cancelling Codex sign-in clears remote guidance", () => {
+ const source = readFileSync(CODEX_CARD, "utf8");
+ const cancel = componentBlock(source, "const cancel", "const refresh");
+
+ assert.match(cancel, /setLoginStart\(null\)/);
+});
+
+test("Terminal Codex status clears guidance only for the matching operation", () => {
+ const source = readFileSync(CODEX_CARD, "utf8");
+ const recordStatus = componentBlock(
+ source,
+ "const recordStatus",
+ "const loadStatus",
+ );
+
+ for (const operationState of [
+ "completed",
+ "cancelled",
+ "expired",
+ "failed",
+ ]) {
+ assert.match(
+ recordStatus,
+ new RegExp(`nextStatus\\.operation_state === "${operationState}"`),
+ );
+ }
+ assert.match(
+ recordStatus,
+ /nextStatus\.operation_id === loginStart\.operation_id/,
+ );
+ assert.match(recordStatus, /\? null\s*: loginStart/);
+});
+
+test("Logging out clears remote authorization guidance after success", () => {
+ const source = readFileSync(CODEX_CARD, "utf8");
+ const logout = componentBlock(source, "const logout", "const polling");
assert.ok(
- signIn.indexOf("window.open(") < signIn.indexOf("await startCodexLogin()"),
+ logout.indexOf("recordStatus(await logoutCodex())") <
+ logout.indexOf("setLoginStart(null)"),
);
});
diff --git a/web/tests/codex-oauth-settings-contract.test.ts b/web/tests/codex-oauth-settings-contract.test.ts
index 23f38ae10..9dd02e7d2 100644
--- a/web/tests/codex-oauth-settings-contract.test.ts
+++ b/web/tests/codex-oauth-settings-contract.test.ts
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import path from "node:path";
import test from "node:test";
+import { createInstance } from "i18next";
const EDITOR = path.resolve(
process.cwd(),
@@ -51,11 +52,60 @@ test("Codex OAuth copy stays in sync across locales", () => {
.sort();
assert.deepEqual(codexKeys(en), codexKeys(zh));
- for (const key of ["codex.oauth.signIn", "codex.oauth.ownerBound"]) {
+ for (const key of [
+ "codex.oauth.signIn",
+ "codex.oauth.ownerBound",
+ "codex.oauth.remoteTitle",
+ "codex.oauth.remoteSteps",
+ "codex.oauth.callbackAddress",
+ "codex.oauth.copyCommand",
+ "codex.oauth.commandCopied",
+ "codex.oauth.copyFailed",
+ "codex.oauth.openAuthorization",
+ "codex.oauth.expiresIn",
+ "codex.oauth.callbackMissing",
+ "codex.oauth.callbackMissingUnknown",
+ "codex.oauth.callbackUnavailable",
+ "codex.oauth.invalidResponse",
+ ]) {
assert.ok(codexKeys(en).includes(key));
+ assert.equal(typeof en[key], "string");
+ assert.equal(typeof zh[key], "string");
}
for (const key of codexKeys(en)) {
assert.equal(typeof en[key], "string");
assert.equal(typeof zh[key], "string");
}
});
+
+test("Codex OAuth callback copy interpolates real ports and has a safe unknown-port fallback", async () => {
+ const en = JSON.parse(readFileSync(EN, "utf8")) as Record<string, string>;
+ const zh = JSON.parse(readFileSync(ZH, "utf8")) as Record<string, string>;
+ const i18n = createInstance();
+ await i18n.init({
+ lng: "en",
+ fallbackLng: false,
+ resources: {
+ en: { translation: en },
+ zh: { translation: zh },
+ },
+ });
+
+ for (const locale of ["en", "zh"]) {
+ await i18n.changeLanguage(locale);
+ assert.match(
+ i18n.t("codex.oauth.callbackMissing", { port: 1457 }),
+ /localhost:1457/,
+ );
+ const fallback = i18n.t("codex.oauth.callbackMissingUnknown");
+ assert.notEqual(fallback, "codex.oauth.callbackMissingUnknown");
+ assert.equal(fallback.includes("{{port}}"), false);
+ assert.equal(fallback.includes("localhost:"), false);
+ assert.equal(fallback.includes("SSH"), false);
+ assert.equal(fallback.includes("隧道"), false);
+ assert.match(
+ i18n.t("codex.oauth.expiresIn", { seconds: 42 }),
+ /42/,
+ );
+ }
+});
diff --git a/web/tests/proxy-policy.test.ts b/web/tests/proxy-policy.test.ts
index 3dbc90472..d558cd5e7 100644
--- a/web/tests/proxy-policy.test.ts
+++ b/web/tests/proxy-policy.test.ts
@@ -1,5 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
// Unit tests for the pure middleware routing policy (web/lib/proxy-policy.ts).
// The policy is deliberately decoupled from `next/server`, so it can be
@@ -7,9 +9,12 @@ import assert from "node:assert/strict";
// adapter that maps these decisions onto NextResponse.
import {
+ CODEX_CALLBACK_API_PATH,
+ CODEX_CALLBACK_PATH,
classifyToken,
isAuthExempt,
isBackendPath,
+ isCodexCallbackPath,
} from "../lib/proxy-policy";
function makeToken(payload: Record<string, unknown>): string {
@@ -26,6 +31,41 @@ test("isBackendPath matches /api and /ws paths only", () => {
assert.equal(isBackendPath("/logo.png"), false);
});
+test("isCodexCallbackPath matches only the exact public callback path", () => {
+ assert.equal(CODEX_CALLBACK_PATH, "/auth/callback");
+ assert.equal(
+ CODEX_CALLBACK_API_PATH,
+ "/api/v1/auth/openai-codex/callback",
+ );
+ assert.equal(isCodexCallbackPath("/auth/callback"), true);
+ assert.equal(isCodexCallbackPath("/auth/callback/"), false);
+ assert.equal(isCodexCallbackPath("/auth/callback/extra"), false);
+ assert.equal(isCodexCallbackPath("/auth/callback-near"), false);
+ assert.equal(isCodexCallbackPath("/Auth/callback"), false);
+});
+
+test("proxy rewrites the exact callback before backend routing and auth gating", () => {
+ const source = readFileSync(
+ path.resolve(process.cwd(), "proxy.ts"),
+ "utf8",
+ );
+ const callbackBranch = source.indexOf(
+ "if (isCodexCallbackPath(pathname))",
+ );
+ const backendBranch = source.indexOf("if (isBackendPath(pathname))");
+ const authGate = source.indexOf("if (!AUTH_ENABLED");
+
+ assert.notEqual(callbackBranch, -1);
+ assert.notEqual(backendBranch, -1);
+ assert.notEqual(authGate, -1);
+ assert.ok(callbackBranch < backendBranch);
+ assert.ok(callbackBranch < authGate);
+ assert.match(
+ source,
+ /NextResponse\.rewrite\(\s*new URL\(\s*CODEX_CALLBACK_API_PATH \+ search,\s*API_BASE_URL,?\s*\),?\s*\)/,
+ );
+});
+
test("isAuthExempt allows public static assets through the auth gate (issue #599)", () => {
// The Next image optimizer re-fetches these over a cookie-less loopback; if
// the gate blocked them the sidebar logo/banner would render broken.