fix(desktop): normalize API base URL across renderer and main

Replace ad-hoc trim/fallback logic with a shared normalizer that strips
trailing slashes and accidental /api suffixes, rejects non-http schemes,
and rewrites Vite dev origins (517x) back to localhost:8080 so the
desktop client never points its API client at the renderer dev server.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-06 12:56:47 +08:00
parent 7b4d7ccf68
commit 13464c7788
4 changed files with 71 additions and 10 deletions
@@ -13,6 +13,8 @@ import type {
UserInfo,
} from '@geo/shared-types'
import { normalizeDesktopApiBaseURL } from '../../shared/api-base-url'
type SessionMode = 'authenticated' | 'preview'
interface DesktopSession {
@@ -35,6 +37,7 @@ const sessionStorageKey = 'geo.desktop.session.v1'
const apiBaseURLStorageKey = 'geo.desktop.api-base-url'
export const DEFAULT_API_BASE_URL =
import.meta.env.VITE_DESKTOP_API_BASE_URL ?? 'https://api.shengxintui.com'
const normalizedDefaultApiBaseURL = normalizeDesktopApiBaseURL(DEFAULT_API_BASE_URL)
const session = shallowRef<DesktopSession | null>(readStoredSession())
const apiBaseURL = shallowRef(readStoredApiBaseURL())
@@ -77,18 +80,23 @@ function persistSession(next: DesktopSession | null): void {
function readStoredApiBaseURL(): string {
if (typeof window === 'undefined') {
return DEFAULT_API_BASE_URL
return normalizedDefaultApiBaseURL
}
return window.localStorage.getItem(apiBaseURLStorageKey) ?? DEFAULT_API_BASE_URL
const stored = window.localStorage.getItem(apiBaseURLStorageKey)
const normalized = normalizeDesktopApiBaseURL(stored, normalizedDefaultApiBaseURL)
if (stored && stored !== normalized) {
window.localStorage.setItem(apiBaseURLStorageKey, normalized)
}
return normalized
}
function persistApiBaseURL(value: string): void {
const trimmed = value.trim() || DEFAULT_API_BASE_URL
apiBaseURL.value = trimmed
const normalized = normalizeDesktopApiBaseURL(value, normalizedDefaultApiBaseURL)
apiBaseURL.value = normalized
if (typeof window !== 'undefined') {
window.localStorage.setItem(apiBaseURLStorageKey, trimmed)
window.localStorage.setItem(apiBaseURLStorageKey, normalized)
}
void syncRuntimeSessionToMain()
@@ -528,7 +536,7 @@ async function logout(): Promise<void> {
if (typeof window !== 'undefined') {
window.addEventListener('storage', (event) => {
if (event.key === apiBaseURLStorageKey) {
apiBaseURL.value = event.newValue?.trim() || DEFAULT_API_BASE_URL
apiBaseURL.value = normalizeDesktopApiBaseURL(event.newValue, normalizedDefaultApiBaseURL)
void syncRuntimeSessionToMain()
}
})