Files
DeepTutor/web/proxy.ts
TyrionH-is-coding 1117e6fe93 fix(codex-auth): guide remote Codex OAuth loopback callbacks (#716)
For a remote or containerized deployment the browser's localhost is the
user's workstation while the OAuth listener runs on the server, so a
reverse proxy cannot deliver http://localhost:1455/auth/callback to that
private listener and Codex sign-in could never complete.

Keep the listener loopback-only and forward just the exact browser
callback path through the Web origin to a state-validating broker. The
settings card and CLI now show the real callback address, the SSH tunnel
command, an explicit authorize action and a countdown, and survive a page
reload; the deployment docs cover the Docker host-port and reverse-proxy
caveats.

The listener stays bound to loopback and ports 1455/1457 are never
published; the Web bridge rewrites only /auth/callback; the broker
requires an active operation and a constant-time state match; callback
responses are no-store HTML that never echo the code or state; PKCE and
the token exchange are unchanged. Binding the listener with
start_serving=False also closes a window where a connection could be
accepted before the callback object existed.
2026-07-28 19:20:27 +08:00

78 lines
2.9 KiB
TypeScript

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
// exports `DEEPTUTOR_API_BASE_URL` from `data/user/settings/system.json`
// (preferring `next_public_api_base`, then `next_public_api_base_external`,
// then `http://localhost:${BACKEND_PORT}`). In dev (`deeptutor start`) it
// defaults to `http://localhost:8001`.
const API_BASE_URL =
process.env.DEEPTUTOR_API_BASE_URL ?? "http://localhost:8001";
const AUTH_ENABLED = parseAuthEnabled(process.env.DEEPTUTOR_AUTH_ENABLED);
// Redirect to the login page, preserving the intended destination in `next`.
// A present-but-invalid cookie is cleared so the browser stops resending it;
// when no cookie was sent there is nothing to clear.
function redirectToLogin(
req: NextRequest,
{ clearCookie }: { clearCookie: boolean },
): NextResponse {
const loginUrl = req.nextUrl.clone();
loginUrl.pathname = LOGIN_PATH;
loginUrl.searchParams.set("next", req.nextUrl.pathname);
const response = NextResponse.redirect(loginUrl);
if (clearCookie) response.cookies.delete(COOKIE_NAME);
return response;
}
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.
if (isBackendPath(pathname)) {
return NextResponse.rewrite(new URL(pathname + search, API_BASE_URL));
}
// 2. Auth gate — multi-user mode only. Disabled by default, and never blocks
// auth pages, Next.js internals, or public static assets (see
// isAuthExempt: that exemption is what keeps the logo/banner images
// loading once login is enabled — issue #599).
if (!AUTH_ENABLED || isAuthExempt(pathname)) {
return NextResponse.next();
}
const token = req.cookies.get(COOKIE_NAME)?.value;
if (classifyToken(token, Date.now()) !== "valid") {
return redirectToLogin(req, { clearCookie: Boolean(token) });
}
return NextResponse.next();
}
export const config = {
// Run on every request except Next.js internals and the favicon. The /api/*
// and /ws/* paths are explicitly handled above (rewritten to the backend);
// the browser's /_next/image optimizer requests are excluded here, while the
// optimizer's loopback fetch for the source image (e.g. /logo.png) is let
// through the auth gate by isAuthExempt.
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};