3 Commits

Author SHA1 Message Date
restitux 124c22acd0 frontend: add login page and auth guard
Add authentication flow to the frontend:
- authStore with token management (localStorage persistence)
- Login page with username/password form at /login
- Layout-level auth guard that redirects to /login when no valid
  session exists, validates token on load via GET /api/auth/me
- Top navigation bar showing username and admin link when applicable

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 02:37:25 +00:00
restitux f49f470f80 backend: add single-use token auth for spawned stream proxies
Generate a random 256-bit token when spawning a proxy process, pass
it as a CLI argument, and return it to the client in the stream start
response. The proxy validates the token on WebTransport connect and
consumes it after first use, preventing replay. A wrong token attempt
also consumes the token for security. Includes 5 unit tests for token
validation logic.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 02:36:35 +00:00
restitux bfe2d79a59 backend: gate existing endpoints behind auth and app permissions
Move /api/pair, /api/apps, and /api/stream/start under the session
auth middleware so they require a valid session token. Add app-level
permission filtering: non-admin users only see and can stream apps
they have been explicitly granted access to. Admins bypass all
permission checks.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 02:35:05 +00:00
8 changed files with 452 additions and 39 deletions
+75 -22
View File
@@ -1,22 +1,67 @@
<script lang="ts">
//import Header from './Header.svelte';
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { isAuthenticated, getToken, handleUnauthorized } from './stores/authStore.svelte';
import '../app.css';
let { children } = $props();
let userProfile: { username: string; is_admin: boolean } | null = $state(null);
let authChecked = $state(false);
onMount(async () => {
const currentPath = page.url.pathname;
if (currentPath === '/login') {
authChecked = true;
return;
}
if (!isAuthenticated()) {
await goto('/login');
authChecked = true;
return;
}
// Validate token by fetching user profile
try {
const response = await fetch('/api/auth/me', {
headers: { Authorization: `Bearer ${getToken()}` }
});
if (!response.ok) {
handleUnauthorized();
authChecked = true;
return;
}
userProfile = await response.json();
} catch {
handleUnauthorized();
}
authChecked = true;
});
</script>
<div class="app">
<!--<Header />-->
{#if authChecked}
{#if userProfile && page.url.pathname !== '/login'}
<nav class="top-nav">
<a href="/" class="nav-link">Apps</a>
{#if userProfile.is_admin}
<a href="/admin" class="nav-link">Admin</a>
{/if}
<span class="nav-spacer"></span>
<span class="nav-user">{userProfile.username}</span>
</nav>
{/if}
<main>
{@render children()}
</main>
<!--<footer>
<p>
visit <a href="https://svelte.dev/docs/kit">svelte.dev/docs/kit</a> to learn about SvelteKit
</p>
</footer>-->
{/if}
</div>
<style>
@@ -27,31 +72,39 @@
}
main {
/*flex: 1;*/
/*display: flex;*/
/*flex-direction: column;*/
/*padding: 1rem;*/
width: 100%;
/*max-width: 64rem;*/
margin: 0 auto;
box-sizing: border-box;
}
footer {
.top-nav {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 12px;
padding: 0.5rem 1rem;
background-color: #1a1a2e;
border-bottom: 1px solid #333;
}
footer a {
font-weight: bold;
.nav-link {
color: #aaa;
text-decoration: none;
padding: 0.4rem 0.8rem;
border-radius: 4px;
font-size: 0.9rem;
}
@media (min-width: 480px) {
footer {
padding: 12px 0;
.nav-link:hover {
color: #e0e0e0;
background-color: #2a2a4e;
text-decoration: none;
}
.nav-spacer {
flex-grow: 1;
}
.nav-user {
color: #888;
font-size: 0.85rem;
}
</style>
+166
View File
@@ -0,0 +1,166 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { setToken, isAuthenticated } from '../stores/authStore.svelte';
import { onMount } from 'svelte';
let username = $state('');
let password = $state('');
let error = $state('');
let loading = $state(false);
onMount(() => {
if (isAuthenticated()) {
goto('/');
}
});
async function handleLogin(event: Event) {
event.preventDefault();
error = '';
loading = true;
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
if (!response.ok) {
const data = await response.json().catch(() => null);
error = data?.description || 'Invalid username or password';
return;
}
const data = await response.json();
setToken(data.token);
await goto('/');
} catch (e) {
error = 'Connection error. Please try again.';
} finally {
loading = false;
}
}
</script>
<svelte:head>
<title>Login</title>
</svelte:head>
<div class="login-container">
<div class="login-box">
<h1>GameStream</h1>
<form onsubmit={handleLogin}>
<div class="field">
<label for="username">Username</label>
<input
id="username"
type="text"
bind:value={username}
autocomplete="username"
required
disabled={loading}
/>
</div>
<div class="field">
<label for="password">Password</label>
<input
id="password"
type="password"
bind:value={password}
autocomplete="current-password"
required
disabled={loading}
/>
</div>
{#if error}
<div class="error">{error}</div>
{/if}
<button type="submit" disabled={loading}>
{loading ? 'Signing in...' : 'Sign in'}
</button>
</form>
</div>
</div>
<style>
.login-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.login-box {
background-color: #1a1a2e;
border: 1px solid #333;
border-radius: 12px;
padding: 2.5rem;
width: 100%;
max-width: 380px;
}
h1 {
color: #e0e0e0;
margin: 0 0 1.5rem 0;
font-size: 1.5rem;
}
.field {
margin-bottom: 1rem;
}
label {
display: block;
color: #aaa;
font-size: 0.85rem;
margin-bottom: 0.3rem;
}
input {
width: 100%;
padding: 0.6rem 0.8rem;
border: 1px solid #444;
border-radius: 6px;
background-color: #0f0f23;
color: #e0e0e0;
font-size: 1rem;
box-sizing: border-box;
}
input:focus {
outline: none;
border-color: #00aaff;
}
input:disabled {
opacity: 0.6;
}
.error {
color: #ff4444;
font-size: 0.85rem;
margin-bottom: 1rem;
}
button {
width: 100%;
padding: 0.7rem;
border: none;
border-radius: 6px;
background-color: #00aaff;
color: white;
font-size: 1rem;
cursor: pointer;
transition: background-color 0.2s;
}
button:hover:not(:disabled) {
background-color: #0088cc;
}
button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
</style>
@@ -0,0 +1,43 @@
import { goto } from '$app/navigation';
interface AuthState {
token: string | null;
}
function loadToken(): string | null {
if (typeof window === 'undefined') return null;
return localStorage.getItem('auth_token');
}
export const authStore: AuthState = $state({
token: loadToken()
});
export function getToken(): string | null {
return authStore.token;
}
export function setToken(token: string) {
authStore.token = token;
localStorage.setItem('auth_token', token);
}
export function clearToken() {
authStore.token = null;
localStorage.removeItem('auth_token');
}
export function isAuthenticated(): boolean {
return authStore.token !== null;
}
export function requireAuth() {
if (!isAuthenticated()) {
goto('/login');
}
}
export function handleUnauthorized() {
clearToken();
goto('/login');
}
+18 -1
View File
@@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
use tracing::{debug, error};
use crate::{
auth,
common,
common::{AppError, AppResult},
responses,
@@ -45,7 +46,8 @@ struct GetAppsResponse {
#[craft]
impl crate::backend::Backend {
#[craft(endpoint(status_codes(StatusCode::OK, StatusCode::INTERNAL_SERVER_ERROR)))]
pub async fn get_apps(self: ::std::sync::Arc<Self>) -> AppResult<Json<GetAppsResponse>> {
pub async fn get_apps(self: ::std::sync::Arc<Self>, depot: &mut Depot) -> AppResult<Json<GetAppsResponse>> {
let user = auth::get_user_from_depot(depot).cloned();
let standard_error = Err(AppError {
status_code: StatusCode::INTERNAL_SERVER_ERROR,
description: "failed to get available apps".to_string(),
@@ -143,6 +145,21 @@ impl crate::backend::Backend {
get_apps_resp.apps.insert(server.name, resp_vec);
}
// Filter apps by user permissions (admins see everything)
if let Some(ref user) = user {
if !user.is_admin {
let permissions = self.db.get_permissions(&user.id).unwrap_or_default();
for (server_name, apps) in get_apps_resp.apps.iter_mut() {
apps.retain(|app| {
permissions.iter().any(|p| {
p.server == *server_name && p.app_id == app.id as i64
})
});
}
get_apps_resp.apps.retain(|_, apps| !apps.is_empty());
}
}
Ok(Json(get_apps_resp))
}
}
+9 -7
View File
@@ -76,16 +76,15 @@ async fn run_backend(port: u16) -> Result<()> {
let router = Router::new()
// Public auth routes
.push(Router::with_path("api/auth/login").post(backend_arc.login()))
// Existing routes (not yet gated - will be gated in a subsequent commit)
.push(Router::with_path("api/pair").post(backend_arc.post_pair()))
.push(Router::with_path("api/apps").get(backend_arc.get_apps()))
.push(Router::with_path("api/stream/start").post(backend_arc.post_stream_start()))
// Authenticated routes
.push(
Router::with_path("api")
.hoop(auth_middleware)
.push(Router::with_path("auth/logout").post(backend_arc.logout()))
.push(Router::with_path("auth/me").get(backend_arc.me()))
.push(Router::with_path("pair").post(backend_arc.post_pair()))
.push(Router::with_path("apps").get(backend_arc.get_apps()))
.push(Router::with_path("stream/start").post(backend_arc.post_stream_start()))
// Admin-only routes
.push(
Router::with_path("admin")
@@ -125,9 +124,9 @@ async fn run_backend(port: u16) -> Result<()> {
Ok(())
}
async fn run_proxy(port: u16, stream_id: uuid::Uuid) -> Result<()> {
async fn run_proxy(port: u16, stream_id: uuid::Uuid, stream_token: String) -> Result<()> {
let (config, cert_hash) = certs::get_webtransport_stream_config(stream_id)?;
let proxy = proxy::Proxy::new(cert_hash);
let proxy = proxy::Proxy::new(cert_hash, stream_token);
let proxy_arc = std::sync::Arc::new(proxy);
let router = Router::new()
@@ -167,8 +166,11 @@ async fn main() -> anyhow::Result<()> {
.nth(3)
.ok_or(anyhow!("Cert ID argument missing"))?,
)?;
let stream_token = std::env::args()
.nth(4)
.ok_or(anyhow!("Stream token argument missing"))?;
run_proxy(port, stream_id).await
run_proxy(port, stream_id, stream_token).await
}
_ => Err(anyhow!("Unknown mode: {mode}")),
}
@@ -85,6 +85,32 @@ impl crate::proxy::Proxy {
description: "Could not start stream".to_string(),
});
// Validate single-use stream token
let provided_token = req.query::<String>("token").unwrap_or_default();
{
let mut token_guard = self.stream_token.write().await;
match token_guard.take() {
Some(expected) if expected == provided_token => {
// Token consumed successfully (single-use)
info!("Stream token validated and consumed");
}
Some(_) => {
error!("Invalid stream token provided");
return Err(AppError {
status_code: StatusCode::UNAUTHORIZED,
description: "Invalid stream token".to_string(),
});
}
None => {
error!("Stream token already consumed");
return Err(AppError {
status_code: StatusCode::UNAUTHORIZED,
description: "Stream token already used".to_string(),
});
}
}
}
info!("WebTransport connection initiated");
let (wt_stream_send, wt_stream_recv, wt_datagram_send) = match setup_webtransport(req).await
{
+74 -3
View File
@@ -11,16 +11,16 @@ mod video;
pub struct Proxy {
pub cert_hash: [u8; 32],
//pub cert_hash: String,
pub stream: RwLock<Option<backend::Stream>>,
pub stream_token: RwLock<Option<String>>,
}
impl Proxy {
pub fn new(cert_hash: [u8; 32]) -> Self {
//pub fn new(cert_hash: String) -> Self {
pub fn new(cert_hash: [u8; 32], stream_token: String) -> Self {
Proxy {
stream: RwLock::new(None),
cert_hash,
stream_token: RwLock::new(Some(stream_token)),
}
}
}
@@ -78,6 +78,21 @@ async fn proxy_main(
Ok(())
}
/// Validate a provided token against the stored token. Consumes the token on success (single-use).
/// Returns Ok(()) if valid, Err with description if invalid or already consumed.
pub async fn validate_stream_token(proxy: &Proxy, provided: &str) -> std::result::Result<(), String> {
let mut token_guard = proxy.stream_token.write().await;
match token_guard.take() {
Some(expected) if expected == provided => Ok(()),
Some(_) => {
// Put the token back since it wasn't matched
// Actually no — the design is that any attempt consumes it for security
Err("Invalid stream token".to_string())
}
None => Err("Stream token already used".to_string()),
}
}
async fn spawn_gamestream(stream: backend::Stream) -> Result<Channels> {
let (tx, rx) = tokio::sync::oneshot::channel();
let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>();
@@ -99,3 +114,59 @@ async fn spawn_gamestream(stream: backend::Stream) -> Result<Channels> {
.context("Could not get gamestream communication channels")?,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn make_proxy(token: &str) -> Proxy {
Proxy {
cert_hash: [0u8; 32],
stream: RwLock::new(None),
stream_token: RwLock::new(Some(token.to_string())),
}
}
#[tokio::test]
async fn test_valid_token_accepted() {
let proxy = make_proxy("abc123");
let result = validate_stream_token(&proxy, "abc123").await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_wrong_token_rejected() {
let proxy = make_proxy("abc123");
let result = validate_stream_token(&proxy, "wrong").await;
assert!(result.is_err());
assert_eq!(result.unwrap_err(), "Invalid stream token");
}
#[tokio::test]
async fn test_missing_token_rejected() {
let proxy = make_proxy("abc123");
let result = validate_stream_token(&proxy, "").await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_token_consumed_after_use() {
let proxy = make_proxy("abc123");
let first = validate_stream_token(&proxy, "abc123").await;
assert!(first.is_ok());
let second = validate_stream_token(&proxy, "abc123").await;
assert!(second.is_err());
assert_eq!(second.unwrap_err(), "Stream token already used");
}
#[tokio::test]
async fn test_wrong_attempt_consumes_token() {
let proxy = make_proxy("abc123");
// Wrong token attempt should consume it
let _ = validate_stream_token(&proxy, "wrong").await;
// Correct token should also fail now
let result = validate_stream_token(&proxy, "abc123").await;
assert!(result.is_err());
}
}
+37 -2
View File
@@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize};
use tracing::{debug, error, info};
use crate::{
auth,
common::{AppError, AppResult, get_url},
proxy, responses,
state::{GamestreamServer, StateReadAccess, StateReader},
@@ -24,7 +25,7 @@ struct PostStreamStartParams {
struct PostStreamStartResponse {
url: String,
cert_hash: [u8; 32],
//cert_hash: String,
stream_token: String,
}
#[derive(Deserialize)]
@@ -81,12 +82,32 @@ impl crate::backend::Backend {
self: ::std::sync::Arc<Self>,
body: salvo::oapi::extract::JsonBody<PostStreamStartParams>,
req: &mut Request,
depot: &mut Depot,
) -> AppResult<Json<PostStreamStartResponse>> {
let standard_error = Err(crate::common::AppError {
status_code: StatusCode::INTERNAL_SERVER_ERROR,
description: "Could not start stream".to_string(),
});
// Check app permission
if let Some(user) = auth::get_user_from_depot(depot) {
if !user.is_admin {
match self.db.check_app_permission(&user.id, &body.server, body.id as i64) {
Ok(true) => {}
Ok(false) => {
return Err(AppError {
status_code: StatusCode::FORBIDDEN,
description: "You do not have permission to access this application".to_string(),
});
}
Err(e) => {
error!("Permission check error: {e}");
return standard_error;
}
}
}
}
let reader = self.state.read().await;
let server = match get_server(&reader, &body.server) {
@@ -272,6 +293,19 @@ impl crate::backend::Backend {
let port = self.port + <u16>::try_from((*writer).len()).unwrap();
// Generate single-use stream token for proxy authentication
let stream_token = {
let mut bytes = [0u8; 32];
openssl::rand::rand_bytes(&mut bytes).map_err(|e| {
error!("Failed to generate stream token: {e}");
AppError {
status_code: StatusCode::INTERNAL_SERVER_ERROR,
description: "Could not start stream".to_string(),
}
})?;
hex::encode(bytes)
};
// Spawn WebTransport proxy
let binary_path = match std::env::current_exe() {
Ok(b) => b,
@@ -285,7 +319,7 @@ impl crate::backend::Backend {
stream_id, port
);
match tokio::process::Command::new(binary_path)
.args(["proxy", &port.to_string(), &stream_id.to_string()])
.args(["proxy", &port.to_string(), &stream_id.to_string(), &stream_token])
.spawn()
{
Ok(_) => (),
@@ -326,6 +360,7 @@ impl crate::backend::Backend {
let post_stream_response = PostStreamStartResponse {
url: webtransport_url,
cert_hash: setup_resp.cert_hash,
stream_token,
};
Ok(Json(post_stream_response))