Skip to content

Commit 79cafcb

Browse files
committed
feat(auth): non-loopback source-IP aware API key gate
When the proxy is bound to a non-loopback hostname (LAN or public), the management API now requires an X-OpenCodex-API-Key header from non-loopback sources, but loopback sources (127.0.0.1, ::1, 127.x.x.x) bypass auth regardless of bind hostname. The host's own loopback traffic keeps working without a key while LAN clients still get 401s. - src/server/auth-cors.ts: sourceIp-aware isApiAuthRequiredForRequest; hasValidApiAuth / requireApiAuth take the source IP. Loopback hostname OR loopback source = bypass. - src/server/index.ts: thread source IP from Bun's requestIP through every requireApiAuth call site and into handleManagementAPI. - src/server/management-api.ts: handleManagementAPI gains a sourceIp param (used by the next commit for reveal audit logging). - assertServerAuthConfig accepts an entry in config.apiKeys (not just OPENCODEX_API_AUTH_TOKEN) as the auth requirement for non-loopback binds. - gui: new ApiKeyModal + lock screen; page-load probe of /api/keys decides whether to gate the UI. Token held in sessionStorage only. - i18n: authKey.* keys in en/zh/ko/de; Trans component now supports multiple named slot placeholders (used by authKey.firstTimeDesc). - Package rename @bitkyc08/opencodex -> @zamelee/opencodex across the bundle / config / update check / CLI bin shims. Tests: - /v1/models + non-loopback management API tests assert that 127.0.0.1 sources are accepted without a token on a non-loopback bind, matching the new auth contract.
1 parent 182ddae commit 79cafcb

18 files changed

Lines changed: 467 additions & 59 deletions

File tree

‎bin/ocx.mjs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
* opencodex npm bin launcher.
44
*
55
* The package source is TypeScript that runs on the Bun runtime. To let
6-
* `npm install -g @bitkyc08/opencodex` work without a separately-installed Bun,
6+
* `npm install -g @zamelee/opencodex` work without a separately-installed Bun,
77
* we bundle the runtime via the `bun` npm dependency and exec it from this
88
* Node shim. (Dev still runs `bun run src/cli/index.ts` directly via the shebang on
99
* src/cli/index.ts — only the published npm `bin` routes through here.)
@@ -15,7 +15,7 @@ import { homedir } from "node:os";
1515
import { dirname, join, resolve } from "node:path";
1616
import { fileURLToPath } from "node:url";
1717

18-
const PKG = "@bitkyc08/opencodex";
18+
const PKG = "@zamelee/opencodex";
1919
const require = createRequire(import.meta.url);
2020
const here = dirname(fileURLToPath(import.meta.url));
2121
const cliPath = join(here, "..", "src", "cli", "index.ts");
@@ -192,7 +192,7 @@ function fail(msg) {
192192
`opencodex: ${msg}\n` +
193193
"The bundled Bun runtime could not be prepared. This usually means the\n" +
194194
"install skipped lifecycle scripts or optional dependencies. Reinstall with:\n" +
195-
" npm install -g @bitkyc08/opencodex\n" +
195+
" npm install -g @zamelee/opencodex\n" +
196196
"(without --ignore-scripts and without --omit=optional / optional=false)"
197197
);
198198
process.exit(1);

‎bin/package-main.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
export const packageName = "@bitkyc08/opencodex";
1+
export const packageName = "@zamelee/opencodex";
22
export const cliCommand = "ocx";
33

44
export async function loadBunApi() {

‎gui/src/App.tsx‎

Lines changed: 112 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect, useState } from "react";
1+
import { useEffect, useRef, useState } from "react";
22
import Dashboard from "./pages/Dashboard";
33
import Providers from "./pages/Providers";
44
import Models from "./pages/Models";
@@ -7,27 +7,22 @@ import Logs from "./pages/Logs";
77
import Debug from "./pages/Debug";
88
import Usage from "./pages/Usage";
99
import CodexAuth from "./pages/CodexAuth";
10+
import ApiKeyModal from "./components/ApiKeyModal";
1011
import ApiKeys from "./pages/ApiKeys";
11-
import { IconGrid, IconServer, IconBoxes, IconBot, IconList, IconTerminal, IconActivity, IconKey, IconGithub, IconSun, IconMoon, IconMonitor, IconGlobe, IconPower } from "./icons";
12+
import { IconGrid, IconServer, IconBoxes, IconBot, IconList, IconTerminal, IconActivity, IconKey, IconLock, IconGithub, IconSun, IconMoon, IconMonitor, IconGlobe, IconPower } from "./icons";
1213
import { useI18n, useT, LOCALES, type Locale, type TKey } from "./i18n";
1314
import { Select } from "./ui";
14-
import { installApiAuthFetch } from "./api";
15-
15+
import { installApiAuthFetch, registerApiKeyPrompt } from "./api";
1616
installApiAuthFetch();
17-
1817
type Page = "dashboard" | "providers" | "models" | "subagents" | "logs" | "debug" | "usage" | "codex-auth" | "api";
1918
type Theme = "light" | "dark" | "system";
20-
2119
const VALID_PAGES = new Set<Page>(["dashboard", "providers", "models", "subagents", "logs", "debug", "usage", "codex-auth", "api"]);
22-
2320
function readPageFromHash(): Page {
2421
const raw = location.hash.replace(/^#\/?/, "");
2522
return VALID_PAGES.has(raw as Page) ? (raw as Page) : "dashboard";
2623
}
27-
2824
const API_BASE = import.meta.env.VITE_API_BASE || "";
2925
const THEME_KEY = "ocx-theme";
30-
3126
const NAV: { id: Page; tkey: TKey; Icon: typeof IconGrid }[] = [
3227
{ id: "dashboard", tkey: "nav.dashboard", Icon: IconGrid },
3328
{ id: "providers", tkey: "nav.providers", Icon: IconServer },
@@ -39,41 +34,80 @@ const NAV: { id: Page; tkey: TKey; Icon: typeof IconGrid }[] = [
3934
{ id: "codex-auth", tkey: "nav.codexAuth", Icon: IconKey },
4035
{ id: "api", tkey: "nav.api", Icon: IconGlobe },
4136
];
42-
4337
const THEME_ICON = { light: IconSun, dark: IconMoon, system: IconMonitor } as const;
4438
const THEME_TKEY: Record<Theme, TKey> = { light: "theme.light", dark: "theme.dark", system: "theme.system" };
45-
4639
function readRuntimeVersion(data: unknown): string | null {
4740
if (!data || typeof data !== "object" || !("version" in data)) return null;
4841
const version = (data as { version?: unknown }).version;
4942
return typeof version === "string" && version.length > 0 ? version : null;
5043
}
51-
5244
function readStoredTheme(): Theme {
5345
const t = localStorage.getItem(THEME_KEY);
5446
return t === "light" || t === "dark" ? t : "system";
5547
}
56-
5748
export default function App() {
49+
// --- API-key auth gate: lock the entire UI behind the proxy admission secret until a valid
50+
// key is verified. The wrapper (gui/src/api.ts) surfaces 401s into this modal; the gate below
51+
// keeps the sidebar/main page hidden so a non-authenticated visitor cannot read structure.
52+
const TOKEN_KEY = "opencodex-api-token";
53+
const [authUnlocked, setAuthUnlocked] = useState(false);
54+
const [authPromptOpen, setAuthPromptOpen] = useState(false);
55+
const [authError, setAuthError] = useState<string | undefined>(undefined);
56+
const authResolverRef = useRef<((k: string | null) => void) | null>(null);
57+
useEffect(() => {
58+
registerApiKeyPrompt((error) => new Promise<string | null>((resolve) => {
59+
authResolverRef.current = resolve;
60+
setAuthError(error);
61+
setAuthPromptOpen(true);
62+
}));
63+
}, []);
64+
// Probe a management endpoint WITHOUT sending any token to decide whether the proxy
65+
// requires auth. See submitApiKey below for the user-submitted-key flow.
66+
const submitApiKey = (key: string) => {
67+
fetch(`${API_BASE}/api/keys`, { headers: { "X-OpenCodex-API-Key": key } })
68+
.then((r) => {
69+
if (r.ok) {
70+
try { sessionStorage.setItem(TOKEN_KEY, key); } catch {}
71+
setAuthUnlocked(true);
72+
setAuthPromptOpen(false);
73+
setAuthError(undefined);
74+
authResolverRef.current?.(key);
75+
authResolverRef.current = null;
76+
} else if (r.status === 401) {
77+
setAuthError(t("authKey.errorRejected"));
78+
authResolverRef.current?.(null);
79+
} else {
80+
setAuthError(t("authKey.errorUnexpected").replace("{status}", String(r.status)));
81+
authResolverRef.current?.(null);
82+
}
83+
})
84+
.catch(() => {
85+
setAuthError(t("authKey.errorNetwork"));
86+
authResolverRef.current?.(null);
87+
});
88+
};
89+
const cancelApiKey = () => {
90+
setAuthPromptOpen(false);
91+
setAuthError(undefined);
92+
authResolverRef.current?.(null);
93+
authResolverRef.current = null;
94+
};
5895
const [page, setPageState] = useState<Page>(readPageFromHash);
5996
const setPage = (p: Page) => { location.hash = p; setPageState(p); };
6097
const [theme, setTheme] = useState<Theme>(readStoredTheme);
6198
const [runtimeVersion, setRuntimeVersion] = useState<string | null>(null);
6299
const { locale, setLocale } = useI18n();
63100
const t = useT();
64-
65101
useEffect(() => {
66102
const onHash = () => setPageState(readPageFromHash());
67103
window.addEventListener("hashchange", onHash);
68104
return () => window.removeEventListener("hashchange", onHash);
69105
}, []);
70-
71106
useEffect(() => {
72107
const el = document.documentElement;
73108
if (theme === "system") { el.removeAttribute("data-theme"); localStorage.removeItem(THEME_KEY); }
74109
else { el.setAttribute("data-theme", theme); localStorage.setItem(THEME_KEY, theme); }
75110
}, [theme]);
76-
77111
useEffect(() => {
78112
let cancelled = false;
79113
const fetchRuntimeVersion = async () => {
@@ -91,19 +125,79 @@ export default function App() {
91125
return () => { cancelled = true; clearInterval(interval); };
92126
}, []);
93127

128+
129+
useEffect(() => {
130+
const tRef = useRef(t);
131+
let cancelled = false;
132+
// Keep latest `t` in a ref so the probe effect does not re-run on every locale change.
133+
tRef.current = t;
134+
135+
// 1. Loopback short-circuit: page loaded via localhost / 127.0.0.1 / [::1] → skip
136+
// the probe entirely. The server grants admission for any loopback source IP,
137+
// so a modal here would be surprising and contradicts "no key needed on the
138+
// proxy host itself".
139+
const hostIsLoopback = /^(localhost|127\.|::1|\[::1\])$/i.test(location.hostname);
140+
if (hostIsLoopback) { setAuthUnlocked(true); return; }
141+
// 3. Network probe — runs after the loopback / stored-key shortcuts.
142+
const probe = () => fetch(`${API_BASE}/api/keys`)
143+
.then((r) => {
144+
if (cancelled) return;
145+
if (r.ok) {
146+
setAuthUnlocked(true);
147+
} else if (r.status === 401) {
148+
setAuthPromptOpen(true);
149+
} else {
150+
setAuthPromptOpen(true);
151+
setAuthError(tRef.current("authKey.errorUnexpected").replace("{status}", String(r.status)));
152+
}
153+
})
154+
.catch(() => {
155+
if (cancelled) return;
156+
setAuthPromptOpen(true);
157+
setAuthError(tRef.current("authKey.errorNetwork"));
158+
});
159+
// 2. Reuse a key the user already validated in this tab. Without this, every
160+
// page reload re-prompts even though the previous submission succeeded.
161+
const storedKey = (() => { try { return sessionStorage.getItem(TOKEN_KEY); } catch { return null; } })();
162+
if (storedKey) {
163+
fetch(`${API_BASE}/api/keys`, { headers: { "X-OpenCodex-API-Key": storedKey } })
164+
.then((r) => {
165+
if (cancelled) return;
166+
if (r.ok) setAuthUnlocked(true);
167+
else probe();
168+
})
169+
.catch(() => { if (!cancelled) probe(); });
170+
} else {
171+
probe();
172+
}
173+
return () => { cancelled = true; };
174+
}, []);
94175
const cycleTheme = () => setTheme(t => (t === "light" ? "dark" : t === "dark" ? "system" : "light"));
95176
const ThemeIcon = THEME_ICON[theme];
96177
const displayedVersion = runtimeVersion ?? __APP_VERSION__;
97-
98178
const [stopping, setStopping] = useState(false);
99179
const handleStop = async () => {
100180
if (!confirm(t("dash.stopConfirm"))) return;
101181
setStopping(true);
102182
try { await fetch(`${API_BASE}/api/stop`, { method: "POST" }); } catch { /* connection drops */ }
103183
};
104-
184+
if (!authUnlocked) {
185+
return (
186+
<>
187+
<div className="empty" style={{ marginTop: "20vh", textAlign: "center", maxWidth: 420, margin: "20vh auto 0" }}>
188+
<div style={{ display: "flex", justifyContent: "center" }}><IconLock width={48} height={48} /></div>
189+
<div className="title" style={{ marginTop: 12 }}>{t("authKey.lockTitle")}</div>
190+
<div style={{ fontSize: 13, color: "var(--muted)", marginTop: 6 }}>
191+
{t("authKey.lockDesc")}
192+
</div>
193+
</div>
194+
<ApiKeyModal open={authPromptOpen} error={authError} onSubmit={submitApiKey} onCancel={cancelApiKey} />
195+
</>
196+
);
197+
}
105198
return (
106199
<div className="app">
200+
<ApiKeyModal open={authPromptOpen} error={authError} onSubmit={submitApiKey} onCancel={cancelApiKey} />
107201
<aside className="sidebar">
108202
<div className="brand">
109203
<span className="brand-logo" role="img" aria-label="opencodex logo" />
@@ -143,7 +237,6 @@ export default function App() {
143237
</a>
144238
</div>
145239
</aside>
146-
147240
<main className="main">
148241
<div className="main-inner">
149242
{page === "dashboard" && <Dashboard apiBase={API_BASE} />}

‎gui/src/api.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@ const TOKEN_KEY = "opencodex-api-token";
22

33
let installed = false;
44
let promptInFlight: Promise<string | null> | null = null;
5+
let registeredPrompt: ((error?: string) => Promise<string | null>) | null = null;
6+
7+
/** Register a custom prompt handler (e.g. a React modal). Falls back to window.prompt if unset. */
8+
export function registerApiKeyPrompt(fn: (error?: string) => Promise<string | null>): void {
9+
registeredPrompt = fn;
10+
}
511

612
function apiPath(input: RequestInfo | URL): string | null {
713
try {
@@ -44,7 +50,7 @@ function withToken(input: RequestInfo | URL, init: RequestInit | undefined, toke
4450
async function promptForToken(): Promise<string | null> {
4551
if (promptInFlight) return promptInFlight;
4652
promptInFlight = Promise.resolve()
47-
.then(() => window.prompt("OpenCodex API token")?.trim() || null)
53+
.then(async () => (registeredPrompt ? registeredPrompt() : window.prompt("OpenCodex API token")?.trim() || null))
4854
.finally(() => { promptInFlight = null; });
4955
return promptInFlight;
5056
}

0 commit comments

Comments
 (0)