forge
Explore
Log in

Don't you dare go Hollow

hezarfen_mobile

Clone
★ 0

0 watching0 forksRust5.5 MiB3424bc6Burak Boduroğlu3 months ago13 commits

proxy.rs416 lines, 14.9 KiBHistoryRawDownload
1//! The in-app origin.
2//!
3//! The web app assumes it is served same-origin with the backend: it calls
4//! `fetch("/api/...")` with `credentials: "same-origin"`, points `<img src>` at
5//! `/api/...` (so the session cookie authenticates the image request), opens an
6//! `EventSource` on `/api/chatbot/...`, and builds its exam-room / whiteboard
7//! WebSocket URLs from `window.location.host`. In the browser deployment
8//! `server.ts` provides that origin; a Tauri webview loaded from
9//! `tauri://localhost` would break every one of those.
10//!
11//! So we reproduce `server.ts` in-process: a loopback HTTP server that serves
12//! the bundled SPA and reverse-proxies `/api/*` (HTTP *and* WebSocket) to the
13//! backend. The webview is pointed at it, `window.location.host` becomes
14//! `127.0.0.1:<port>`, and the frontend needs no changes at all.
15
16use std::net::{Ipv4Addr, SocketAddr};
17use std::sync::Arc;
18
19use axum::body::Body;
20use axum::extract::ws::{Message as AxumMessage, WebSocket, WebSocketUpgrade};
21use axum::extract::{FromRequestParts, Request, State};
22use axum::http::{header, HeaderMap, HeaderValue, StatusCode, Uri};
23use axum::response::{IntoResponse, Response};
24use axum::Router;
25use futures_util::{SinkExt, StreamExt};
26use tauri::{AppHandle, Runtime};
27use tokio_tungstenite::tungstenite::client::IntoClientRequest;
28use tokio_tungstenite::tungstenite::Message as WsMessage;
29
30/// First port we try. Kept fixed across launches on purpose: the session cookie
31/// is scoped to `127.0.0.1:<port>`, so a port that moved between launches would
32/// sign the user out every time.
33const PREFERRED_PORT: u16 = 18420;
34const PORT_SCAN: u16 = 32;
35
36struct Inner<R: Runtime> {
37 app: AppHandle<R>,
38 http: reqwest::Client,
39 /// Backend origin, no trailing slash, e.g. `https://api.example.com`.
40 backend: String,
41 /// Vite's dev server, when running under `tauri dev`. Non-`/api` requests
42 /// are proxied there instead of read from the embedded bundle, so HMR keeps
43 /// working through our origin.
44 dev_url: Option<String>,
45}
46
47type Shared<R> = Arc<Inner<R>>;
48
49/// Binds the loopback server and spawns it. Returns the port the webview should
50/// be pointed at.
51pub fn start<R: Runtime>(
52 app: AppHandle<R>,
53 backend: String,
54 dev_url: Option<String>,
55) -> Result<u16, std::io::Error> {
56 let listener = bind()?;
57 let port = listener.local_addr()?.port();
58
59 let state: Shared<R> = Arc::new(Inner {
60 app,
61 http: reqwest::Client::builder()
62 // The frontend sets its own 20s deadline per request; letting the
63 // proxy time out first would turn every slow call into an opaque
64 // 502 instead of the client's translated error message.
65 .timeout(std::time::Duration::from_secs(120))
66 .build()
67 .expect("failed to build the HTTP client"),
68 backend: backend.trim_end_matches('/').to_string(),
69 dev_url: dev_url.map(|u| u.trim_end_matches('/').to_string()),
70 });
71
72 let router = Router::new().fallback(handle::<R>).with_state(state);
73
74 std::thread::Builder::new()
75 .name("hezarfen-origin".into())
76 .spawn(move || {
77 let rt = tokio::runtime::Builder::new_multi_thread()
78 .enable_all()
79 .build()
80 .expect("failed to start the proxy runtime");
81 rt.block_on(async move {
82 let listener = tokio::net::TcpListener::from_std(listener)
83 .expect("failed to adopt the listening socket");
84 if let Err(err) = axum::serve(listener, router).await {
85 log::error!("origin server stopped: {err}");
86 }
87 });
88 })?;
89
90 Ok(port)
91}
92
93/// Prefers [`PREFERRED_PORT`] so the cookie jar survives restarts, but falls
94/// back to the next free port rather than refusing to launch.
95fn bind() -> Result<std::net::TcpListener, std::io::Error> {
96 let mut last = None;
97 for offset in 0..PORT_SCAN {
98 let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, PREFERRED_PORT + offset));
99 match std::net::TcpListener::bind(addr) {
100 Ok(listener) => {
101 listener.set_nonblocking(true)?;
102 return Ok(listener);
103 }
104 Err(err) => last = Some(err),
105 }
106 }
107 // Every candidate was taken; let the OS choose so the app still starts.
108 let listener = std::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
109 .map_err(|err| last.unwrap_or(err))?;
110 listener.set_nonblocking(true)?;
111 Ok(listener)
112}
113
114fn is_api(path: &str) -> bool {
115 path == "/api" || path.starts_with("/api/")
116}
117
118/// `/api/exams/x` -> `/exams/x`, `/api` -> `` — the same rewrite nginx and
119/// `server.ts` do, so backend paths are untouched by the prefix.
120fn backend_path(uri: &Uri) -> String {
121 let path = uri.path();
122 let stripped = path
123 .strip_prefix("/api")
124 .filter(|rest| rest.is_empty() || rest.starts_with('/'))
125 .unwrap_or(path);
126 match uri.query() {
127 Some(q) => format!("{stripped}?{q}"),
128 None => stripped.to_string(),
129 }
130}
131
132fn wants_websocket(headers: &HeaderMap) -> bool {
133 headers
134 .get(header::UPGRADE)
135 .and_then(|v| v.to_str().ok())
136 .is_some_and(|v| v.eq_ignore_ascii_case("websocket"))
137}
138
139async fn handle<R: Runtime>(State(state): State<Shared<R>>, req: Request) -> Response {
140 let api = is_api(req.uri().path());
141
142 if wants_websocket(req.headers()) {
143 // Both the exam-room/whiteboard sockets (/api/**) and Vite's HMR socket
144 // arrive here; the only difference is which upstream they bridge to.
145 let upstream = if api {
146 format!("{}{}", ws_scheme(&state.backend), backend_path(req.uri()))
147 } else if let Some(dev) = &state.dev_url {
148 format!("{}{}", ws_scheme(dev), path_and_query(req.uri()))
149 } else {
150 return (StatusCode::NOT_FOUND, "no websocket upstream").into_response();
151 };
152 return bridge_websocket(req, upstream).await;
153 }
154
155 if api {
156 let target = format!("{}{}", state.backend, backend_path(req.uri()));
157 return proxy_http(&state.http, req, target, true).await;
158 }
159
160 if let Some(dev) = state.dev_url.clone() {
161 let target = format!("{dev}{}", path_and_query(req.uri()));
162 return proxy_http(&state.http, req, target, false).await;
163 }
164
165 serve_asset(&state.app, req.uri().path())
166}
167
168fn path_and_query(uri: &Uri) -> &str {
169 uri.path_and_query().map(|pq| pq.as_str()).unwrap_or("/")
170}
171
172fn ws_scheme(origin: &str) -> String {
173 if let Some(rest) = origin.strip_prefix("https") {
174 format!("wss{rest}")
175 } else if let Some(rest) = origin.strip_prefix("http") {
176 format!("ws{rest}")
177 } else {
178 origin.to_string()
179 }
180}
181
182/// Serves a file from the bundle, falling back to `index.html` so client-side
183/// routes deep-link correctly (the SPA fallback `server.ts` implements).
184fn serve_asset<R: Runtime>(app: &AppHandle<R>, path: &str) -> Response {
185 let resolver = app.asset_resolver();
186 let wanted = if path == "/" { "/index.html" } else { path };
187
188 let asset = resolver
189 .get(wanted.to_string())
190 .or_else(|| resolver.get("/index.html".to_string()));
191
192 let Some(asset) = asset else {
193 return (StatusCode::NOT_FOUND, "asset not found").into_response();
194 };
195
196 let mut headers = HeaderMap::new();
197 if let Ok(mime) = HeaderValue::from_str(&asset.mime_type) {
198 headers.insert(header::CONTENT_TYPE, mime);
199 }
200 // Hashed assets are immutable; the shell must never be cached, or a new
201 // build would keep booting the previous bundle.
202 let cache = if wanted.starts_with("/assets/") {
203 "public, max-age=31536000, immutable"
204 } else {
205 "no-store"
206 };
207 headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache));
208
209 (headers, asset.bytes).into_response()
210}
211
212async fn proxy_http(
213 client: &reqwest::Client,
214 req: Request,
215 target: String,
216 rewrite_cookies: bool,
217) -> Response {
218 let (parts, body) = req.into_parts();
219
220 let method = match reqwest::Method::from_bytes(parts.method.as_str().as_bytes()) {
221 Ok(m) => m,
222 Err(_) => return (StatusCode::BAD_REQUEST, "bad method").into_response(),
223 };
224
225 let mut headers = parts.headers.clone();
226 // Hop-by-hop headers must not be forwarded, and the browser's Host (our
227 // loopback address) would confuse the backend's cookie-domain and
228 // absolute-URL logic — reqwest sets the right one from the target.
229 for name in [
230 header::HOST,
231 header::CONNECTION,
232 header::TRANSFER_ENCODING,
233 header::CONTENT_LENGTH,
234 header::ACCEPT_ENCODING,
235 ] {
236 headers.remove(name);
237 }
238
239 let has_body = !matches!(
240 parts.method,
241 axum::http::Method::GET | axum::http::Method::HEAD
242 );
243 let mut out = client.request(method, &target).headers(headers);
244 if has_body {
245 out = out.body(reqwest::Body::wrap_stream(body.into_data_stream()));
246 }
247
248 let upstream = match out.send().await {
249 Ok(resp) => resp,
250 Err(err) => {
251 log::error!("proxy {target} failed: {err}");
252 return (StatusCode::BAD_GATEWAY, "backend unreachable").into_response();
253 }
254 };
255
256 let status =
257 StatusCode::from_u16(upstream.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
258 let mut headers = HeaderMap::new();
259 for (name, value) in upstream.headers() {
260 if matches!(
261 *name,
262 header::TRANSFER_ENCODING | header::CONNECTION | header::CONTENT_LENGTH
263 ) {
264 continue;
265 }
266 if rewrite_cookies && name == header::SET_COOKIE {
267 if let Some(cookie) = rewrite_set_cookie(value) {
268 headers.append(header::SET_COOKIE, cookie);
269 }
270 continue;
271 }
272 headers.append(name.clone(), value.clone());
273 }
274
275 let body = Body::from_stream(upstream.bytes_stream());
276 (status, headers, body).into_response()
277}
278
279/// The session cookie is minted for the backend's own host over TLS, so it
280/// arrives with `Domain=` and `Secure`. Our origin is plain HTTP on 127.0.0.1;
281/// the webview would silently drop such a cookie and the user could never stay
282/// signed in. Both attributes are safe to drop here because the cookie never
283/// leaves the device's loopback interface. `SameSite=None` is downgraded to
284/// `Lax` for the same reason: browsers reject `None` without `Secure`.
285fn rewrite_set_cookie(value: &HeaderValue) -> Option<HeaderValue> {
286 let raw = value.to_str().ok()?;
287 let kept: Vec<&str> = raw
288 .split(';')
289 .map(str::trim)
290 .filter(|attr| {
291 let lower = attr.to_ascii_lowercase();
292 !(lower == "secure" || lower.starts_with("domain=") || lower == "samesite=none")
293 })
294 .collect();
295 let mut cookie = kept.join("; ");
296 if !cookie.to_ascii_lowercase().contains("samesite=") {
297 cookie.push_str("; SameSite=Lax");
298 }
299 HeaderValue::from_str(&cookie).ok()
300}
301
302/// Holds one upstream socket open per browser socket and pipes frames both
303/// ways. The session cookie is forwarded on the handshake — it is what
304/// authenticates the exam-room and whiteboard sockets.
305async fn bridge_websocket(req: Request, upstream_url: String) -> Response {
306 let (mut parts, _body) = req.into_parts();
307
308 let cookie = parts.headers.get(header::COOKIE).cloned();
309 let protocol = parts.headers.get("sec-websocket-protocol").cloned();
310
311 let upgrade = match WebSocketUpgrade::from_request_parts(&mut parts, &()).await {
312 Ok(upgrade) => upgrade,
313 Err(rejection) => return rejection.into_response(),
314 };
315
316 upgrade.on_upgrade(move |client| async move {
317 let mut request = match upstream_url.as_str().into_client_request() {
318 Ok(req) => req,
319 Err(err) => {
320 log::error!("bad websocket url {upstream_url}: {err}");
321 return;
322 }
323 };
324 if let Some(cookie) = cookie {
325 request.headers_mut().insert(header::COOKIE, cookie);
326 }
327 if let Some(protocol) = protocol {
328 request
329 .headers_mut()
330 .insert("sec-websocket-protocol", protocol);
331 }
332
333 let upstream = match tokio_tungstenite::connect_async(request).await {
334 Ok((stream, _)) => stream,
335 Err(err) => {
336 log::error!("websocket upstream {upstream_url} failed: {err}");
337 return;
338 }
339 };
340
341 pipe(client, upstream).await;
342 })
343}
344
345async fn pipe(
346 client: WebSocket,
347 upstream: tokio_tungstenite::WebSocketStream<
348 tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
349 >,
350) {
351 let (mut client_tx, mut client_rx) = client.split();
352 let (mut up_tx, mut up_rx) = upstream.split();
353
354 let to_upstream = async {
355 while let Some(Ok(msg)) = client_rx.next().await {
356 let msg = match msg {
357 AxumMessage::Text(text) => WsMessage::Text(text.as_str().into()),
358 AxumMessage::Binary(bin) => WsMessage::Binary(bin),
359 AxumMessage::Ping(p) => WsMessage::Ping(p),
360 AxumMessage::Pong(p) => WsMessage::Pong(p),
361 AxumMessage::Close(_) => break,
362 };
363 if up_tx.send(msg).await.is_err() {
364 break;
365 }
366 }
367 let _ = up_tx.close().await;
368 };
369
370 let to_client = async {
371 while let Some(Ok(msg)) = up_rx.next().await {
372 let msg = match msg {
373 WsMessage::Text(text) => AxumMessage::Text(text.as_str().into()),
374 WsMessage::Binary(bin) => AxumMessage::Binary(bin),
375 WsMessage::Ping(p) => AxumMessage::Ping(p),
376 WsMessage::Pong(p) => AxumMessage::Pong(p),
377 WsMessage::Close(_) => break,
378 WsMessage::Frame(_) => continue,
379 };
380 if client_tx.send(msg).await.is_err() {
381 break;
382 }
383 }
384 let _ = client_tx.close().await;
385 };
386
387 tokio::join!(to_upstream, to_client);
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393
394 #[test]
395 fn strips_the_api_prefix_like_the_web_deployment() {
396 let uri: Uri = "/api/exams/1?page=2".parse().unwrap();
397 assert_eq!(backend_path(&uri), "/exams/1?page=2");
398 assert_eq!(backend_path(&"/api".parse().unwrap()), "");
399 // A path that merely starts with the letters "api" is not the prefix.
400 assert_eq!(backend_path(&"/apiary".parse().unwrap()), "/apiary");
401 }
402
403 #[test]
404 fn makes_the_session_cookie_storable_on_a_loopback_origin() {
405 let raw = HeaderValue::from_static(
406 "session=abc; Path=/; Domain=api.hezarfen.co; Secure; HttpOnly; SameSite=None",
407 );
408 let out = rewrite_set_cookie(&raw).unwrap();
409 let out = out.to_str().unwrap();
410 assert!(!out.to_ascii_lowercase().contains("secure"));
411 assert!(!out.to_ascii_lowercase().contains("domain="));
412 assert!(out.contains("SameSite=Lax"));
413 assert!(out.contains("HttpOnly"));
414 assert!(out.starts_with("session=abc"));
415 }
416}