Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions gui/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { IconGrid, IconServer, IconBoxes, IconBot, IconList, IconActivity, IconH
import { useI18n, useT, LOCALES, localeDisplayName, type Locale, type TKey } from "./i18n/shared";
import { Notice, Select, ToastNotice, type NoticeTone } from "./ui";
import { configureApiTargets, hasApiSession, installApiAuthFetch, installApiSessionFromHtml, logoutApiSession, SESSION_UNAVAILABLE_EVENT } from "./api";
import { apiBaseForPlane, discoverApiTargets, isConnectedRuntime, standaloneApiTargets, type ApiTargets } from "./api-targets";
import { adminTokenPromptAllowed, managementAuthRequiredFromDocument, apiBaseForPlane, discoverApiTargets, isConnectedRuntime, standaloneApiTargets, type ApiTargets } from "./api-targets";
import { ConnectPairingForm } from "./connect-pairing";
import { type Page } from "./app-routing";
import { readModelsTab, type ModelsTab } from "./pages/models-tab";
Expand Down Expand Up @@ -203,6 +203,11 @@ export default function App() {
return () => controller.abort();
}, [page, sharedSessionReady, sharedBase]);
const remoteWorkspaceAvailable = sharedSessionReady && remoteWorkspaceAvailableState;
// A standalone/hub dashboard exposed through an authenticated non-loopback origin can need a
// consent-bearing GUI session even though it is not a connected client. Remote Link requires
// that stronger principal, so offer the existing one-time pairing flow instead of a dead-end
// "sign in" warning. Other pages keep their ordinary admin-token flow unchanged.
const remotePairingRequired = page === "remote" && !sharedSessionReady && managementAuthRequiredFromDocument();

// Narrow screens: the sidebar becomes an off-canvas drawer behind a hamburger toggle.
const [navOpen, setNavOpen] = useState(false);
Expand Down Expand Up @@ -552,7 +557,7 @@ export default function App() {
{targetError && (
<div className="alert alert-err" role="alert">{t("connection.machineUnavailable")}</div>
)}
{targets.connected && !sharedSessionReady && (
{((targets.connected && !sharedSessionReady) || remotePairingRequired) && (
<ConnectPairingForm key={`${targets.shared.serverOrigin}:${targets.shared.bootstrapPath}`} target={targets.shared} onConnected={() => {
setSharedSessionReady(true);
setSharedSessionEpoch(epoch => epoch + 1);
Expand All @@ -567,7 +572,7 @@ export default function App() {
{page === "logs" && <Logs apiBase={sharedBase} />}
{page === "usage" && <Usage apiBase={sharedBase} connected={targets.connected} apiKeyId={targets.apiKeyId} />}
{page === "storage" && <Storage apiBase={sharedBase} />}
{page === "remote" && <RemoteLink apiBase={sharedBase} sessionReady={sharedSessionReady} workspaceAvailable={remoteWorkspaceAvailable} onOpenWorkspace={() => navigateToPage("remote-workspace")} />}
{page === "remote" && !remotePairingRequired && <RemoteLink apiBase={sharedBase} sessionReady={sharedSessionReady} workspaceAvailable={remoteWorkspaceAvailable} onOpenWorkspace={() => navigateToPage("remote-workspace")} />}
{page === "remote-workspace" && <RemoteWorkspaceRoute available={remoteWorkspaceAvailable} apiBase={sharedBase} hubOrigin={targets.shared.serverOrigin} onOpenRemoteLink={() => navigateToPage("remote")} />}
{page === "codex-set" && <CodexSet apiBase={sharedBase} />}
{page === "integrations" && <Integrations apiBase={sharedBase} machineApiBase={machineBase} connected={targets.connected} />}
Expand Down
8 changes: 8 additions & 0 deletions gui/src/api-targets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@ export function isConnectedRuntime(): boolean {
* fall back to the role so a hub dashboard still works against a server that predates the
* tag, and everything else reads as loopback — the safe default this file already uses.
*/
export function managementAuthRequiredFromDocument(): boolean {
if (typeof document === "undefined") return false;
return document
.querySelector('meta[name="opencodex-management-auth-required"]')
?.getAttribute("content")
?.trim() === "1";
}

Comment thread
coderabbitai[bot] marked this conversation as resolved.
export function adminTokenPromptAllowed(): boolean {
if (typeof document !== "undefined") {
const declared = document
Expand Down
70 changes: 62 additions & 8 deletions gui/tests/remote-link-route.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,26 @@ function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
}

function mountWindow(role: "standalone" | "hub"): void {
testWindow = new Window({ url: "http://localhost/#remote" });
function mountWindow(
role: "standalone" | "hub",
options: { session?: boolean; url?: string; managementAuthTag?: "0" | "1" } = {},
): void {
const url = options.url ?? "http://localhost/#remote";
const session = options.session ?? true;
testWindow = new Window({ url });
Object.defineProperty(testWindow.navigator, "language", { configurable: true, value: "en-US" });
const head = testWindow.document.head;
for (const [name, content] of [
const metaEntries: Array<readonly [string, string]> = [
["opencodex-runtime-role", role],
["opencodex-session-token", "ocx_session_route_test"],
["opencodex-session-csrf", "route-test-csrf"],
["opencodex-session-origin", "http://localhost"],
["opencodex-session-server-origin", "http://localhost"],
] as const) {
...(options.managementAuthTag ? [["opencodex-management-auth-required", options.managementAuthTag]] as const : []),
...(session ? [
["opencodex-session-token", "ocx_session_route_test"],
["opencodex-session-csrf", "route-test-csrf"],
["opencodex-session-origin", new URL(url).origin],
["opencodex-session-server-origin", new URL(url).origin],
] as const : []),
];
for (const [name, content] of metaEntries) {
const meta = testWindow.document.createElement("meta");
meta.setAttribute("name", name);
meta.setAttribute("content", content);
Expand Down Expand Up @@ -109,3 +118,48 @@ for (const role of ["standalone", "hub"] as const) {
expect(linkStatusReads).toBeGreaterThan(0);
});
}

test("an authenticated remote hub without a GUI session offers one-time pairing", async () => {
mountWindow("hub", {
session: false,
url: "https://hub.example.test/#remote",
managementAuthTag: "1",
});
const { resetApiAuthFetchForTests, installApiAuthFetch } = await import("../src/api");
resetApiAuthFetchForTests();
installApiAuthFetch();
Object.defineProperty(globalThis, "fetch", { configurable: true, value: window.fetch });
const [{ createRoot }, { LanguageProvider }, { default: App }] = await Promise.all([
import("react-dom/client"),
import("../src/i18n/provider"),
import("../src/App"),
]);
await act(async () => {
root = createRoot(container);
root.render(<LanguageProvider><App /></LanguageProvider>);
});
await waitFor(() => (container.textContent ?? "").includes("Connect this dashboard to the hub"));
expect(container.textContent).not.toContain("Sign in to the local dashboard session");
expect(container.textContent).toContain('ocx gui pair --origin "https://hub.example.test"');
expect(linkStatusReads).toBe(0);
});

for (const managementAuthTag of [undefined, "0"] as const) {
test(`a remote hub without an explicit auth-required declaration does not force pairing (${managementAuthTag ?? "missing"})`, async () => {
mountWindow("hub", { session: false, url: "https://hub.example.test/#remote", managementAuthTag });
const { resetApiAuthFetchForTests, installApiAuthFetch } = await import("../src/api");
resetApiAuthFetchForTests();
installApiAuthFetch();
Object.defineProperty(globalThis, "fetch", { configurable: true, value: window.fetch });
const [{ createRoot }, { LanguageProvider }, { default: App }] = await Promise.all([
import("react-dom/client"), import("../src/i18n/provider"), import("../src/App"),
]);
await act(async () => {
root = createRoot(container);
root.render(<LanguageProvider><App /></LanguageProvider>);
});
await waitFor(() => (container.textContent ?? "").includes("Sign in to the local dashboard session"));
expect(container.textContent).not.toContain("Connect this dashboard to the hub");
expect(container.textContent).not.toContain("ocx gui pair --origin");
});
}
10 changes: 9 additions & 1 deletion src/server/index/serve-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,14 @@ export function trustedLoopbackForIngress(ingress: ServerIngress, hostname: stri
|| (ingress === "public" && isLoopbackHostname(hostname));
}

/** Whether the served GUI document must advertise an explicit pairing/auth requirement. */
export function managementAuthRequiredForGuiDocument(
ingress: ServerIngress,
policy: Parameters<typeof isApiAuthRequired>[0],
): boolean {
return ingress === "hub-management" || isApiAuthRequired(policy);
}

/**
* Routes the Claude intercept TLS listener may reach. Everything else on that socket is relayed
* to the real upstream by the listener itself, so a request that lands here with another path
Expand Down Expand Up @@ -1902,7 +1910,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
undefined,
guiSessionCandidate ?? undefined,
config.runtimeRole ?? "standalone",
isApiAuthRequired(policy),
managementAuthRequiredForGuiDocument(ingress, policy),
);
if (guiFile) return guiFile;
if (url.pathname === "/" && req.method === "GET") {
Expand Down
10 changes: 9 additions & 1 deletion tests/server/link-management-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { OcxConfig } from "../../src/types";
import type { LinkStore } from "../../src/link/store";
import type { LinkSupervisor } from "../../src/link/supervisor";
import type { SshRunner, SshChild, SshRunResult } from "../../src/link/ssh-runner";
import { trustedLoopbackForIngress, type ServerIngress } from "../../src/server/index/serve-options";
import { managementAuthRequiredForGuiDocument, trustedLoopbackForIngress, type ServerIngress } from "../../src/server/index/serve-options";

let temp = "";

Expand Down Expand Up @@ -116,6 +116,14 @@ describe("link management routes", () => {
expect(trustedLoopbackForIngress("public", "::1")).toBe(true);
});

test("hub-management GUI documents advertise pairing even when the local bind policy is loopback", () => {
const loopbackPolicy = { hostname: "127.0.0.1" } as OcxConfig;
const remotePolicy = { hostname: "0.0.0.0" } as OcxConfig;
expect(managementAuthRequiredForGuiDocument("hub-management", loopbackPolicy)).toBe(true);
expect(managementAuthRequiredForGuiDocument("public", loopbackPolicy)).toBe(false);
expect(managementAuthRequiredForGuiDocument("public", remotePolicy)).toBe(true);
});

test("issues and force-revokes a client-initiated link with the K2/K16 DTOs", async () => {
temp = mkdtempSync(join(tmpdir(), "ocx-link-issue-"));
const h = harness();
Expand Down
Loading