Commit 409a624f authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Fix dev API calls being blocked as mixed content over https

The Geolocation fix made the dev server https://-only, but the backend
it talks to is still plain http:// - browsers hard-block that as mixed
content for fetch/XHR/WebSocket with no user override, so every API call
silently failed once loaded over the required https URL.

Adds a same-origin proxy in vite.config.ts (dev only) so the browser
only ever talks to https://<dev server>/api/..., with the actual
http:// hop happening server-side in Node where mixed-content rules
don't apply. VITE_API_BASE_URL is switched to the relative "/api" for
dev via .env.development.local (gitignored, not committed); production
builds are unaffected and still use the real absolute URL from .env.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 29363679
Pipeline #1063 failed with stage
# Base URL of the stax_backend_api instance to talk to. Point this at the dev server while # Base URL of the stax_backend_api instance to talk to, and where vite.config.ts's dev-only
# developing, and at prod for a production build. # proxy forwards to (see BACKEND_PROXY_TARGET). Point this at the dev server while developing,
# and at prod for a production build.
VITE_API_BASE_URL=http://144.76.210.145:8000 VITE_API_BASE_URL=http://144.76.210.145:8000
BACKEND_PROXY_TARGET=http://144.76.210.145:8000
# `npm run dev` runs over https:// (see the basicSsl comment in vite.config.ts), so calling the
# still-http:// backend directly gets blocked as mixed content - route it through the dev
# server's own same-origin proxy instead by creating .env.development.local (gitignored via
# *.local, not committed) with:
# VITE_API_BASE_URL=/api
# Leave this file's VITE_API_BASE_URL above as the real absolute URL - it's what
# BACKEND_PROXY_TARGET/production builds use.
# Dev-only auto-login (see AuthContext.tsx) - only takes effect under `npm run dev` # Dev-only auto-login (see AuthContext.tsx) - only takes effect under `npm run dev`
# (import.meta.env.DEV), never in a production build, regardless of whether these are set. # (import.meta.env.DEV), never in a production build, regardless of whether these are set.
......
import { API_BASE_URL } from './client' import { API_BASE_URL } from './client'
/** Unlike fetch(), the WebSocket constructor won't resolve a schemeless URL against the page's
* own protocol - it requires ws:/wss: explicitly, so a relative API_BASE_URL (dev's same-origin
* proxy, see vite.config.ts) needs its scheme derived from the current page by hand. */
function resolveWsBase(): string {
if (/^https?:\/\//.test(API_BASE_URL)) {
return API_BASE_URL.replace(/^http/, 'ws')
}
const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws'
return `${scheme}://${window.location.host}${API_BASE_URL}`
}
export interface ChatMessage { export interface ChatMessage {
type: 'chat' type: 'chat'
user_id: number user_id: number
...@@ -20,7 +31,7 @@ export type RoomEvent = ...@@ -20,7 +31,7 @@ export type RoomEvent =
/** Raw WebSocket wrapper for /social/rooms/{id}/ws - auth here is just a user_id query param /** Raw WebSocket wrapper for /social/rooms/{id}/ws - auth here is just a user_id query param
* (matching the backend, which doesn't check the JWT on this route), not a Bearer header. */ * (matching the backend, which doesn't check the JWT on this route), not a Bearer header. */
export function connectToRoom(roomId: number, userId: number, onEvent: (e: RoomEvent) => void): WebSocket { export function connectToRoom(roomId: number, userId: number, onEvent: (e: RoomEvent) => void): WebSocket {
const wsBase = API_BASE_URL.replace(/^http/, 'ws') const wsBase = resolveWsBase()
const ws = new WebSocket(`${wsBase}/social/rooms/${roomId}/ws?user_id=${userId}`) const ws = new WebSocket(`${wsBase}/social/rooms/${roomId}/ws?user_id=${userId}`)
ws.onmessage = (msg) => { ws.onmessage = (msg) => {
try { try {
......
/// <reference types="vitest/config" /> /// <reference types="vitest/config" />
import { defineConfig } from 'vite' import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react' import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite' import tailwindcss from '@tailwindcss/vite'
import basicSsl from '@vitejs/plugin-basic-ssl' import basicSsl from '@vitejs/plugin-basic-ssl'
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig({ export default defineConfig(({ mode }) => {
// The Geolocation API (and other browser APIs) refuse to run at all on a plain http:// // Not VITE_-prefixed on purpose - this is only ever read here, server-side, to configure the
// origin that isn't localhost - "secure context" is a hard browser requirement, not a // proxy target below. It must never end up in the client bundle (unlike VITE_API_BASE_URL,
// permission you can grant around. basicSsl generates a self-signed cert automatically so // which .env.development.local points at the proxy path instead of this directly - see the
// dev can run over https:// (production still needs a real cert via a real domain - a // comment on the proxy block for why).
// self-signed one is only acceptable because we're the ones clicking through the browser's const env = loadEnv(mode, process.cwd(), '')
// one-time warning ourselves). const backendProxyTarget = env.BACKEND_PROXY_TARGET || 'http://144.76.210.145:8000'
plugins: [react(), tailwindcss(), basicSsl()],
server: { return {
host: true, // The Geolocation API (and other browser APIs) refuse to run at all on a plain http://
port: 5173, // origin that isn't localhost - "secure context" is a hard browser requirement, not a
}, // permission you can grant around. basicSsl generates a self-signed cert automatically so
test: { // dev can run over https:// (production still needs a real cert via a real domain - a
environment: 'jsdom', // self-signed one is only acceptable because we're the ones clicking through the browser's
globals: true, // one-time warning ourselves).
setupFiles: './src/test/setup.ts', plugins: [react(), tailwindcss(), basicSsl()],
css: true, server: {
}, host: true,
port: 5173,
// The backend itself is still plain http:// (see BACKEND_PROXY_TARGET) - browsers block
// that as mixed content once the page above is https:// (no user-facing override exists
// for active content like fetch/XHR/WebSocket, unlike old-style passive mixed content).
// Proxying same-origin through the dev server sidesteps it entirely: the browser only
// ever sees https://<this dev server>/api/..., and the actual http:// hop happens
// server-side in Node, which isn't subject to the browser's mixed-content policy.
// VITE_API_BASE_URL is set to "/api" for dev via .env.development.local to route through
// this; production builds still point it at a real absolute URL directly.
proxy: {
'/api': {
target: backendProxyTarget,
changeOrigin: true,
ws: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
test: {
environment: 'jsdom',
globals: true,
setupFiles: './src/test/setup.ts',
css: true,
},
}
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment