Skip to content

Commit d85a5cc

Browse files
shoootyouyui-soul
andauthored
feat(server,app): replace Basic Auth dialog with custom login page
Makes the static frontend fully public and introduces a custom /login page when OPENCODE_SERVER_PASSWORD is set, eliminating the native browser Basic Auth dialog. - uiRoute /*: no auth middleware — HTML, JS, CSS, fonts served publicly - API routes: bare 401, no WWW-Authenticate header - /login page with redirect-back, open-redirect guard, and debounced in-flight guard - timingSafeEqual (SHA-256) for password comparison - OPENCODE_LOCAL_WEB_UI=1 dev flag to serve local packages/app/dist Closes anomalyco#16493 (upstream) Addresses anomalyco#31484 (upstream) Co-authored-by: yui-soul <[email protected]>
1 parent 9e29a89 commit d85a5cc

23 files changed

Lines changed: 1398 additions & 141 deletions

‎packages/app/src/context/server-sdk.test.ts‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,41 @@
1+
/**
2+
* @spec-handoff
3+
* @interface isUnauthorizedSseError(error: unknown): boolean
4+
* @behavior
5+
* - Returns true when error is an Error whose message indicates HTTP 401.
6+
* - The SSE stream throws a generic Error with the shape
7+
* `SSE failed: ${status} ${statusText}` (confirmed at
8+
* packages/sdk/js/src/v2/gen/core/serverSentEvents.gen.ts:131). For a 401 the
9+
* message is exactly "SSE failed: 401 Unauthorized".
10+
* - Detection is string-based against error.message using a word-boundary 401 match
11+
* (the accepted fallback per RFC 017 B2/D7, since the thrown error carries no
12+
* structured status field).
13+
* - Returns false for non-401 status messages ("SSE failed: 500 ..."), generic
14+
* network errors, and non-Error values.
15+
* @edge-cases
16+
* - new Error("SSE failed: 401 Unauthorized") → true
17+
* - new Error("SSE failed: 500 Internal Server Error") → false
18+
* - new Error("network down") → false
19+
* - "not an error" (string, not an Error) → false
20+
* - null / undefined → false
21+
* - A 401 substring must match on word boundary: "SSE failed: 1401 ..." → false
22+
* @testability
23+
* - isUnauthorizedSseError MUST be importable from "./server-sdk" without triggering
24+
* a failure at module load. The existing test in this file already imports
25+
* resumeStreamAfterPageShow from server-sdk.tsx and runs green under
26+
* `bun test --preload ./happydom.ts`, so co-locating this pure helper there is
27+
* acceptable. If a future UI import makes the module explode at load, extract
28+
* isUnauthorizedSseError to a plain .ts sibling and re-export it.
29+
* - The SSE error guard wiring (calling redirectToLogin in onSseError and the
30+
* for-await catch when isUnauthorizedSseError(error) && shouldRedirectToLogin(...))
31+
* is integration-level and not unit-tested here; its decision is fully covered by
32+
* isUnauthorizedSseError (this file) + shouldRedirectToLogin (server.test.ts).
33+
* @see ./server-sdk.tsx
34+
* @see ../utils/server.ts (shouldRedirectToLogin + redirectToLogin shared by the guard)
35+
*/
36+
137
import { describe, expect, test } from "bun:test"
2-
import { resumeStreamAfterPageShow } from "./server-sdk"
38+
import { isUnauthorizedSseError, resumeStreamAfterPageShow } from "./server-sdk"
339

440
describe("resumeStreamAfterPageShow", () => {
541
test("restarts a stream only after a back-forward cache restore", () => {
@@ -12,3 +48,34 @@ describe("resumeStreamAfterPageShow", () => {
1248
expect(starts).toBe(1)
1349
})
1450
})
51+
52+
// ---------------------------------------------------------------------------
53+
// isUnauthorizedSseError — D7: detect a 401 from the generic SSE error
54+
// ---------------------------------------------------------------------------
55+
56+
describe("isUnauthorizedSseError", () => {
57+
test("true for the real SDK 401 message shape", () => {
58+
expect(isUnauthorizedSseError(new Error("SSE failed: 401 Unauthorized"))).toBe(true)
59+
})
60+
61+
test("false for a 500 SSE failure", () => {
62+
expect(isUnauthorizedSseError(new Error("SSE failed: 500 Internal Server Error"))).toBe(false)
63+
})
64+
65+
test("false for a generic network error", () => {
66+
expect(isUnauthorizedSseError(new Error("network down"))).toBe(false)
67+
})
68+
69+
test("false for a non-Error value", () => {
70+
expect(isUnauthorizedSseError("not an error")).toBe(false)
71+
})
72+
73+
test("false for null and undefined", () => {
74+
expect(isUnauthorizedSseError(null)).toBe(false)
75+
expect(isUnauthorizedSseError(undefined)).toBe(false)
76+
})
77+
78+
test("does not match 401 embedded in a larger number (word boundary)", () => {
79+
expect(isUnauthorizedSseError(new Error("SSE failed: 1401 Weird"))).toBe(false)
80+
})
81+
})

‎packages/app/src/context/server-sdk.tsx‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { createSimpleContext } from "@opencode-ai/ui/context"
33
import { createGlobalEmitter } from "@solid-primitives/event-bus"
44
import { makeEventListener } from "@solid-primitives/event-listener"
55
import { batch, onCleanup, onMount } from "solid-js"
6-
import { createSdkForServer } from "@/utils/server"
6+
import { createSdkForServer, redirectToLogin, shouldRedirectToLogin } from "@/utils/server"
77
import { useLanguage } from "./language"
88
import { usePlatform } from "./platform"
99
import { ServerConnection, useServer } from "./server"
@@ -21,6 +21,14 @@ export function resumeStreamAfterPageShow(event: PageTransitionEvent, start: ()
2121
start()
2222
}
2323

24+
// Detects a 401 from the generic SSE error (RFC 017 B2/D7). The stream throws a
25+
// plain Error shaped `SSE failed: ${status} ${statusText}` with no structured
26+
// status field, so we match the status string on a word boundary (so "1401"
27+
// does not match).
28+
export function isUnauthorizedSseError(error: unknown): boolean {
29+
return error instanceof Error && /\b401\b/.test(error.message)
30+
}
31+
2432
export function createServerSdkContext(server: ServerConnection.Any, scope: ServerScope) {
2533
const platform = usePlatform()
2634
const abort = new AbortController()
@@ -144,6 +152,8 @@ export function createServerSdkContext(server: ServerConnection.Any, scope: Serv
144152
signal: attempt.signal,
145153
onSseError: (error) => {
146154
if (isStreamClosed(error, attempt?.signal)) return
155+
if (isUnauthorizedSseError(error) && shouldRedirectToLogin(server.http.url, location.origin, location.pathname))
156+
redirectToLogin()
147157
if (streamErrorLogged) return
148158
streamErrorLogged = true
149159
console.error("[global-sdk] event stream error", {
@@ -186,6 +196,8 @@ export function createServerSdkContext(server: ServerConnection.Any, scope: Serv
186196
await wait(0)
187197
}
188198
} catch (error) {
199+
if (isUnauthorizedSseError(error) && shouldRedirectToLogin(server.http.url, location.origin, location.pathname))
200+
redirectToLogin()
189201
if (!isStreamClosed(error, attempt?.signal) && !streamErrorLogged) {
190202
streamErrorLogged = true
191203
console.error("[global-sdk] event stream failed", {

‎packages/app/src/entry.tsx‎

Lines changed: 57 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@ import { render } from "solid-js/web"
55
import { AppBaseProviders, AppInterface } from "@/app"
66
import { PwaUpdatePrompt } from "@/components/PwaUpdatePrompt"
77
import { type Platform, PlatformProvider } from "@/context/platform"
8+
import LoginPage from "@/pages/login"
89
import { dict as en } from "@/i18n/en"
910
import { dict as zh } from "@/i18n/zh"
1011
import { handleNotificationClick } from "@/utils/notification-click"
11-
import { authFromToken } from "@/utils/server"
12+
import { authFromToken, getCurrentServerUrl } from "@/utils/server"
1213
import pkg from "../package.json"
1314
import { ServerConnection } from "./context/server"
1415

@@ -100,17 +101,10 @@ if (!(root instanceof HTMLElement) && import.meta.env.DEV) {
100101
throw new Error(getRootNotFoundError())
101102
}
102103

103-
const getCurrentUrl = () => {
104-
if (location.hostname.includes("opencode.ai")) return "http://localhost:4096"
105-
if (import.meta.env.DEV)
106-
return `http://${import.meta.env.VITE_OPENCODE_SERVER_HOST ?? "localhost"}:${import.meta.env.VITE_OPENCODE_SERVER_PORT ?? "4096"}`
107-
return location.origin
108-
}
109-
110104
const getDefaultUrl = () => {
111105
const lsDefault = readDefaultServerUrl()
112106
if (lsDefault) return lsDefault
113-
return getCurrentUrl()
107+
return getCurrentServerUrl()
114108
}
115109

116110
const clearAuthToken = () => {
@@ -135,6 +129,15 @@ const platform: Platform = {
135129
setDefaultServer: writeDefaultServerUrl,
136130
}
137131

132+
// Capture before clearAuthToken() strips the URL. Null on /login because
133+
// the login page reads auth_token directly and handles it via buildFastPathRedirect.
134+
const rawAuthToken = location.pathname !== "/login" ? new URLSearchParams(location.search).get("auth_token") : null
135+
136+
// Strip auth_token before Sentry captures the URL.
137+
if (location.pathname !== "/login") {
138+
clearAuthToken()
139+
}
140+
138141
if (import.meta.env.VITE_SENTRY_DSN) {
139142
Sentry.init({
140143
dsn: import.meta.env.VITE_SENTRY_DSN,
@@ -155,34 +158,50 @@ if (import.meta.env.VITE_SENTRY_DSN) {
155158
}
156159

157160
if (root instanceof HTMLElement) {
158-
const auth = authFromToken(new URLSearchParams(location.search).get("auth_token"))
159-
clearAuthToken()
160-
const server: ServerConnection.Http = {
161-
type: "http",
162-
authToken: !!auth,
163-
http: {
164-
url: getCurrentUrl(),
165-
...auth,
166-
},
161+
// Render the login page without the full app shell when the path is /login.
162+
if (location.pathname === "/login") {
163+
render(
164+
() => (
165+
<>
166+
<PlatformProvider value={platform}>
167+
<AppBaseProviders>
168+
<LoginPage />
169+
</AppBaseProviders>
170+
</PlatformProvider>
171+
<PwaUpdatePrompt />
172+
</>
173+
),
174+
root,
175+
)
176+
} else {
177+
const auth = authFromToken(rawAuthToken)
178+
const server: ServerConnection.Http = {
179+
type: "http",
180+
authToken: !!auth,
181+
http: {
182+
url: getCurrentServerUrl(),
183+
...auth,
184+
},
185+
}
186+
render(
187+
() => (
188+
<>
189+
<PlatformProvider value={platform}>
190+
<AppBaseProviders>
191+
<AppInterface
192+
defaultServer={ServerConnection.Key.make(getDefaultUrl())}
193+
canonicalLocalServer={ServerConnection.key(server)}
194+
servers={[server]}
195+
disableHealthCheck
196+
/>
197+
</AppBaseProviders>
198+
</PlatformProvider>
199+
{/* Mounted outside AppBaseProviders so it remains visible during connection errors
200+
and is not caught by inner ErrorBoundaries. */}
201+
<PwaUpdatePrompt />
202+
</>
203+
),
204+
root,
205+
)
167206
}
168-
render(
169-
() => (
170-
<>
171-
<PlatformProvider value={platform}>
172-
<AppBaseProviders>
173-
<AppInterface
174-
defaultServer={ServerConnection.Key.make(getDefaultUrl())}
175-
canonicalLocalServer={ServerConnection.key(server)}
176-
servers={[server]}
177-
disableHealthCheck
178-
/>
179-
</AppBaseProviders>
180-
</PlatformProvider>
181-
{/* Mounted outside AppBaseProviders so it remains visible during connection errors
182-
and is not caught by inner ErrorBoundaries. */}
183-
<PwaUpdatePrompt />
184-
</>
185-
),
186-
root,
187-
)
188207
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Pure utility functions used by the login page.
2+
// Kept in a separate module so they can be imported and tested
3+
// without loading the SolidJS component tree.
4+
5+
// Only accept relative paths to prevent open redirect.
6+
// Decodes URL encoding before checking to prevent %2F%2F bypass.
7+
export function safeRedirect(value: string | undefined | null): string {
8+
if (!value) return "/"
9+
const trimmed = value.trim()
10+
let decoded: string
11+
try {
12+
decoded = decodeURIComponent(trimmed)
13+
} catch {
14+
return "/"
15+
}
16+
if (!decoded.startsWith("/") || decoded.startsWith("//") || decoded.includes("\\")) return "/"
17+
return decoded
18+
}
19+
20+
// Returns the URL to redirect to when an auth_token is already present in the
21+
// URL query params (fast-path, e.g. back-navigation or bookmarked post-login URL).
22+
// Returns null when no auth_token is present.
23+
// Exported as a pure helper so it can be unit-tested without a SolidJS renderer.
24+
export function buildFastPathRedirect(params: URLSearchParams): string | null {
25+
const existingToken = params.get("auth_token")
26+
if (!existingToken) return null
27+
const target = safeRedirect(params.get("redirect"))
28+
const separator = target.includes("?") ? "&" : "?"
29+
return `${target}${separator}auth_token=${encodeURIComponent(existingToken)}`
30+
}
31+
32+
// Probe the server health endpoint with the given Basic-auth credentials.
33+
// Returns "ok" on 2xx, "unauthorized" on 401, or "unreachable" for
34+
// network errors and any other status we don't want to loop on.
35+
// Network errors are absorbed here so callers don't need try/catch.
36+
export async function probeCredentials(
37+
serverUrl: string,
38+
token: string,
39+
): Promise<"ok" | "unauthorized" | "unreachable"> {
40+
const res = await fetch(`${serverUrl}/api/health`, {
41+
headers: { Authorization: `Basic ${token}` },
42+
}).catch(() => null)
43+
if (!res) return "unreachable"
44+
if (res.status === 401) return "unauthorized"
45+
if (res.ok) return "ok"
46+
return "unreachable"
47+
}

0 commit comments

Comments
 (0)