tshare 1.0.5

Share your terminal session with anyone through a simple web link
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//! # TShare Web Server Module
//!
//! The web server provides the browser-based interface for viewing and interacting
//! with shared terminal sessions. It serves HTML/CSS/JavaScript assets and acts
//! as a WebSocket proxy between web browsers and the tunnel server.
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────┐    HTTP/WS     ┌─────────────┐    HTTP/WS     ┌─────────────┐
//! │   Browser   │◄──────────────►│ Web Server  │◄──────────────►│   Tunnel    │
//! │   Client    │                │             │                │   Server    │
//! │             │                │ - HTML/CSS  │                │             │
//! │ - Terminal  │                │ - Auth UI   │                │ - Sessions  │
//! │ - Auth UI   │                │ - WS Proxy  │                │ - Auth      │
//! │ - xterm.js  │                │             │                │ - Data      │
//! └─────────────┘                └─────────────┘                └─────────────┘
//! ```
//!
//! ## Key Features
//!
//! ### Static Content Serving
//! - **HTML Templates**: Embedded terminal interface and connection pages
//! - **Template Variables**: Dynamic session ID and authentication state injection
//! - **No External Dependencies**: All assets embedded at compile time
//!
//! ### Authentication Interface
//! - **Password Prompts**: Modal dialogs for owner/guest authentication
//! - **Role Detection**: Automatic UI adaptation based on user permissions
//! - **Session Validation**: Real-time verification with tunnel server
//!
//! ### WebSocket Proxying
//! - **Transparent Proxy**: Forwards WebSocket connections to tunnel server
//! - **Protocol Translation**: Handles message format differences between clients
//! - **Connection Management**: Automatic reconnection and error handling
//!
//! ### REST API Proxy
//! - **Session Details**: Fetches session info from tunnel server
//! - **User Management**: Connected user listing and heartbeat forwarding
//! - **Authentication**: Password verification against tunnel server
//!
//! ## Endpoints
//!
//! ### Pages
//! - `GET /` - Home page
//! - `GET /session/{id}` - Terminal session page
//!
//! ### API
//! - `GET /api/session/{id}` - Get session details
//! - `GET /api/session/{id}/users` - List connected users
//! - `POST /api/session/{session_id}/heartbeat/{user_id}` - Send heartbeat
//! - `GET /api/auth/{id}?password=...` - Authenticate with session
//! - `POST /api/logout` - Logout from session
//!
//! ### WebSocket
//! - `WS /ws/session/{id}?user_type={owner|guest}` - Terminal WebSocket proxy
//!
//! ## Example Usage
//!
//! ```bash
//! # Start web server with defaults
//! tshare web
//!
//! # Custom configuration
//! tshare web --host 0.0.0.0 --port 8080 --tunnel-url http://tunnel.example.com:8385
//! ```

use anyhow::Result;
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::response::{Html, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use clap::Parser;
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};

use tokio_tungstenite::{connect_async, tungstenite::Message as TungsteniteMessage};
use tracing::{error, info};

// Embed HTML templates at compile time
const INDEX_HTML: &str = include_str!("../../public/index.html");
const CONNECT_HTML: &str = include_str!("../../public/connect.html");

#[derive(Clone)]
struct AppState {
    tunnel_base: String,
}

#[derive(Serialize, Deserialize, Clone)]
struct SessionDetails {
    session_id: String,
    owner_password_hash: Option<String>,
    guest_password_hash: Option<String>,
    is_guest_readonly: bool,
}

#[derive(Deserialize)]
struct AuthQuery {
    password: Option<String>,
}

#[derive(Deserialize)]
struct WebSocketQuery {
    user_type: Option<String>,
}

#[derive(Parser, Debug)]
#[command(
    author,
    version,
    about = "TShare web server - serves terminal sessions via web interface"
)]
pub struct Args {
    /// Host to bind the web server to
    #[arg(long, default_value = "127.0.0.1")]
    pub host: String,

    /// Port for the web server
    #[arg(long, default_value_t = 8386)]
    pub port: u16,

    /// Tunnel server base URL
    #[arg(long, default_value = "http://127.0.0.1:8385")]
    pub tunnel_url: String,
}

/// Starts the web server for serving terminal session interfaces
///
/// The web server provides the browser-based interface for viewing shared terminal
/// sessions. It serves HTML/CSS/JavaScript assets and proxies connections to the
/// tunnel server for real-time terminal interaction.
///
/// # Architecture
///
/// The server acts as a proxy/gateway between web browsers and the tunnel server:
/// - **Static Assets**: Serves embedded HTML templates with terminal UI
/// - **Authentication**: Handles password verification and user role management  
/// - **WebSocket Proxy**: Forwards real-time terminal data between browser and tunnel server
/// - **REST Proxy**: Proxies API calls for session management
///
/// # Arguments
///
/// * `args` - Server configuration including host, port, and tunnel server URL
///
/// # Returns
///
/// * `Result<()>` - Success or error result
///
/// # Example
///
/// ```rust,no_run
/// use tshare::web::{Args, run_web_server};
///
/// # async fn example() -> anyhow::Result<()> {
/// let args = Args {
///     host: "0.0.0.0".to_string(),
///     port: 8386,
///     tunnel_url: "http://localhost:8385".to_string(),
/// };
///
/// run_web_server(args).await?;
/// # Ok(())
/// # }
/// ```
///
/// # Behavior
///
/// The server will:
/// - Validate connectivity to the tunnel server on startup
/// - Bind to the specified host and port
/// - Serve HTML interfaces for terminal sessions
/// - Handle authentication workflows
/// - Proxy WebSocket connections for real-time terminal data
/// - Forward REST API calls to the tunnel server
///
/// # Panics
///
/// Will panic if the tunnel server is unreachable during startup validation.
pub async fn run_web_server(args: Args) -> Result<()> {
    // Validate connection to tunnel server before starting
    info!(
        "Validating connection to tunnel server at: {}",
        args.tunnel_url
    );
    let client = reqwest::Client::new();
    let test_url = format!("{}/api/session/connection-test", args.tunnel_url);

    match client.get(&test_url).send().await {
        Ok(response) => {
            // We expect 404 for a non-existent session, which means the server is running
            if response.status() == 404 || response.status().is_success() {
                info!("Successfully validated tunnel server connection");
            } else {
                error!(
                    "Tunnel server returned unexpected status: {}",
                    response.status()
                );
                panic!(
                    "Cannot start web server: tunnel server is not responding properly at {}",
                    args.tunnel_url
                );
            }
        }
        Err(e) => {
            error!("Failed to connect to tunnel server: {}", e);
            panic!(
                "Cannot start web server: tunnel server is unreachable at {}",
                args.tunnel_url
            );
        }
    }

    let app_state = AppState {
        tunnel_base: args.tunnel_url,
    };

    let app = Router::new()
        .route("/", get(home_page))
        .route("/session/{id}", get(session_page))
        .route("/ws/session/{id}", get(handle_session_ws))
        .route("/api/session/{id}", get(get_session_details))
        .route("/api/session/{id}/users", get(get_connected_users))
        .route(
            "/api/session/{session_id}/heartbeat/{user_id}",
            post(send_heartbeat),
        )
        .route("/api/auth/{id}", get(authenticate_session))
        .route("/api/logout", post(logout_session))
        .with_state(app_state);

    let addr = format!("{}:{}", args.host, args.port);
    let listener = tokio::net::TcpListener::bind(&addr).await?;

    info!("Web server starting on http://{}", addr);

    axum::serve(listener, app).await?;

    Ok(())
}

async fn home_page() -> Html<String> {
    Html(INDEX_HTML.to_string())
}

async fn session_page(
    Path(session_id): Path<String>,
    State(state): State<AppState>,
) -> Result<Html<String>, StatusCode> {
    // Check if session exists
    let client = reqwest::Client::new();
    let url = format!("{}/api/session/{}", state.tunnel_base, session_id);

    let response = client
        .get(&url)
        .send()
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    if !response.status().is_success() {
        return Err(StatusCode::NOT_FOUND);
    }

    let details: SessionDetails = response
        .json()
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    let needs_auth = details.owner_password_hash.is_some() || details.guest_password_hash.is_some();

    let html = CONNECT_HTML
        .replace("{{ session_id }}", &session_id)
        .replace(
            "{{ modal_display }}",
            if needs_auth { "" } else { "hidden" },
        )
        .replace(
            "{{ terminal_display }}",
            if needs_auth { "hidden" } else { "" },
        )
        .replace(
            "{{ needs_auth_js }}",
            if needs_auth { "true" } else { "false" },
        );

    Ok(Html(html))
}

async fn get_session_details(
    Path(session_id): Path<String>,
    State(state): State<AppState>,
) -> Result<Json<SessionDetails>, StatusCode> {
    let client = reqwest::Client::new();
    let url = format!("{}/api/session/{}", state.tunnel_base, session_id);

    let response = client
        .get(&url)
        .send()
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    if !response.status().is_success() {
        return Err(StatusCode::NOT_FOUND);
    }

    let details: SessionDetails = response
        .json()
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(Json(details))
}

async fn get_connected_users(
    Path(session_id): Path<String>,
    State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    let client = reqwest::Client::new();
    let url = format!("{}/api/session/{}/users", state.tunnel_base, session_id);

    let response = client
        .get(&url)
        .send()
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    if !response.status().is_success() {
        return Err(StatusCode::NOT_FOUND);
    }

    let users: serde_json::Value = response
        .json()
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(Json(users))
}

async fn send_heartbeat(
    Path((session_id, user_id)): Path<(String, String)>,
    State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    let client = reqwest::Client::new();
    let url = format!(
        "{}/api/session/{}/heartbeat/{}",
        state.tunnel_base, session_id, user_id
    );

    let response = client
        .post(&url)
        .send()
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    if response.status().is_success() {
        Ok(Json(serde_json::json!({"success": true})))
    } else {
        Err(StatusCode::INTERNAL_SERVER_ERROR)
    }
}

async fn authenticate_session(
    Path(session_id): Path<String>,
    Query(auth): Query<AuthQuery>,
    State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    let client = reqwest::Client::new();
    let url = format!("{}/api/session/{}", state.tunnel_base, session_id);

    let response = client
        .get(&url)
        .send()
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    if !response.status().is_success() {
        return Err(StatusCode::NOT_FOUND);
    }

    let details: SessionDetails = response
        .json()
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    let password = auth.password.unwrap_or_default();
    let mut authenticated = false;
    let mut user_type = "guest";

    // If no passwords are set, authenticate automatically as owner
    if details.owner_password_hash.is_none() && details.guest_password_hash.is_none() {
        authenticated = true;
        user_type = "owner";
    } else {
        // Check owner password first, then guest password
        if let Some(owner_hash) = &details.owner_password_hash {
            if bcrypt::verify(&password, owner_hash).unwrap_or(false) {
                authenticated = true;
                user_type = "owner";
            }
        }

        if !authenticated {
            if let Some(guest_hash) = &details.guest_password_hash {
                if bcrypt::verify(&password, guest_hash).unwrap_or(false) {
                    authenticated = true;
                    user_type = "guest";
                }
            }
        }
    }

    let is_readonly = match user_type {
        "owner" => false,
        "guest" => details.is_guest_readonly,
        _ => true,
    };

    Ok(Json(serde_json::json!({
        "authenticated": authenticated,
        "user_type": user_type,
        "is_readonly": is_readonly
    })))
}

async fn logout_session() -> Result<Json<serde_json::Value>, StatusCode> {
    Ok(Json(serde_json::json!({
        "success": true,
        "message": "Logged out successfully"
    })))
}

async fn handle_session_ws(
    State(state): State<AppState>,
    Path(session_id): Path<String>,
    Query(query): Query<WebSocketQuery>,
    ws: WebSocketUpgrade,
) -> Response {
    let user_type = query.user_type.unwrap_or_else(|| "guest".to_string());
    ws.on_upgrade(move |socket| proxy_to_tunnel_server(socket, session_id, state, user_type))
}

async fn proxy_to_tunnel_server(
    client_socket: WebSocket,
    session_id: String,
    state: AppState,
    user_type: String,
) {
    let tunnel_url = format!(
        "{}/ws/web/{}?user_type={}",
        state.tunnel_base.replace("http", "ws"),
        session_id,
        user_type
    );

    info!("Attempting to connect to tunnel server: {}", tunnel_url);

    match connect_async(&tunnel_url).await {
        Ok((tunnel_stream, _)) => {
            let (mut tunnel_sink, mut tunnel_stream) = tunnel_stream.split();
            let (mut client_sink, mut client_stream) = client_socket.split();

            info!("Proxying WebSocket for session: {}", session_id);

            let client_to_tunnel = tokio::spawn(async move {
                while let Some(msg) = client_stream.next().await {
                    match msg {
                        Ok(Message::Binary(data)) => {
                            if tunnel_sink
                                .send(TungsteniteMessage::Binary(data))
                                .await
                                .is_err()
                            {
                                break;
                            }
                        }
                        Ok(Message::Text(text)) => {
                            if tunnel_sink
                                .send(TungsteniteMessage::Text(text.to_string().into()))
                                .await
                                .is_err()
                            {
                                break;
                            }
                        }
                        Ok(Message::Close(_)) => break,
                        Err(_) => break,
                        _ => {}
                    }
                }
            });

            let tunnel_to_client = tokio::spawn(async move {
                while let Some(msg) = tunnel_stream.next().await {
                    match msg {
                        Ok(TungsteniteMessage::Binary(data)) => {
                            if client_sink.send(Message::Binary(data)).await.is_err() {
                                break;
                            }
                        }
                        Ok(TungsteniteMessage::Text(text)) => {
                            if client_sink
                                .send(Message::Text(text.to_string().into()))
                                .await
                                .is_err()
                            {
                                break;
                            }
                        }
                        Ok(TungsteniteMessage::Close(_)) => break,
                        Err(_) => break,
                        _ => {}
                    }
                }
            });

            tokio::select! {
                _ = client_to_tunnel => {},
                _ = tunnel_to_client => {},
            }
        }
        Err(e) => {
            error!("Failed to connect to tunnel server: {}", e);
        }
    }

    info!("WebSocket proxy ended for session: {}", session_id);
}