fttyd 0.0.1

Web terminal with a system stats sidebar and file manager, drop-in compatible with ttyd
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
//! HTTP routing: ttyd's endpoints plus the fttyd API surface.

use std::sync::Arc;

use axum::Router;
use axum::body::Body;
use axum::extract::{Path, Request, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::get;

use crate::auth::{self, Auth};
use crate::state::{AppState, AuthUser};
use crate::ws;

pub fn router(state: Arc<AppState>) -> Router {
    let cfg = &state.cfg;
    let mut router = Router::new()
        .route(&cfg.index_path(), get(index_handler))
        .route(&cfg.token_path(), get(token_handler))
        .route(&cfg.ws_path(), get(ws::ws_handler))
        .route(
            &format!("{}assets/{{*path}}", cfg.index_path()),
            get(asset_handler),
        )
        .route(
            &format!("{}favicon.svg", cfg.index_path()),
            get(favicon_handler),
        )
        .route(
            &format!("{}api/info", cfg.index_path()),
            get(crate::api::info),
        )
        .route(
            &format!("{}api/download", cfg.index_path()),
            get(crate::api::download),
        )
        .route(
            &format!("{}api/archive", cfg.index_path()),
            get(crate::api::archive),
        )
        .route(
            &format!("{}api/stats", cfg.index_path()),
            get(stats_handler),
        )
        .route(
            &format!("{}api/upload", cfg.index_path()),
            axum::routing::put(crate::api::upload_put).post(crate::api::upload_multipart),
        )
        .route(
            &format!("{}api/fs", cfg.index_path()),
            get(crate::api::list)
                .patch(crate::api::mutate)
                .delete(crate::api::delete),
        )
        .fallback(not_found);

    if !cfg.base_path.is_empty() {
        // ttyd redirects `/base-path` to `/base-path/`.
        router = router.route(&cfg.base_path, get(redirect_handler));
    }

    router
        .layer(middleware::from_fn_with_state(state.clone(), authenticate))
        .with_state(state)
}

async fn authenticate(
    State(state): State<Arc<AppState>>,
    mut request: Request,
    next: Next,
) -> Response {
    match auth::check(&state.cfg, request.headers()) {
        Auth::Allowed { user } => {
            request.extensions_mut().insert(AuthUser(user));
            next.run(request).await
        }
        Auth::Unauthorized => (
            StatusCode::UNAUTHORIZED,
            [(
                header::WWW_AUTHENTICATE,
                HeaderValue::from_static("Basic realm=\"ttyd\""),
            )],
            "",
        )
            .into_response(),
        Auth::ProxyUnauthorized => (
            StatusCode::PROXY_AUTHENTICATION_REQUIRED,
            [(
                header::PROXY_AUTHENTICATE,
                HeaderValue::from_static("Basic realm=\"ttyd\""),
            )],
            "",
        )
            .into_response(),
    }
}

async fn index_handler(State(state): State<Arc<AppState>>, headers: HeaderMap) -> Response {
    if let Some(path) = &state.cfg.index {
        return match tokio::fs::read(path).await {
            Ok(body) => html_response(body),
            Err(err) => {
                tracing::error!("failed to read index {}: {err}", path.display());
                (StatusCode::INTERNAL_SERVER_ERROR, "failed to read index").into_response()
            }
        };
    }
    let body = crate::assets::index_html();
    let etag = crate::assets::etag_for(&body);
    if not_modified(&headers, &etag) {
        return StatusCode::NOT_MODIFIED.into_response();
    }
    let mut response = html_response(body);
    response.headers_mut().insert(
        header::ETAG,
        HeaderValue::from_str(&etag).unwrap_or(HeaderValue::from_static("\"0\"")),
    );
    response
}

fn html_response(body: Vec<u8>) -> Response {
    (
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, HeaderValue::from_static("text/html")),
            (header::CACHE_CONTROL, HeaderValue::from_static("no-cache")),
        ],
        body,
    )
        .into_response()
}

/// ttyd's `/token`: it echoes the configured credential, which is what its client
/// sends back in the `AuthToken` field of the control message.
async fn token_handler(State(state): State<Arc<AppState>>) -> Response {
    let credential = state.cfg.credential.as_deref().unwrap_or("");
    let body = format!("{{\"token\": \"{credential}\"}}");
    (
        StatusCode::OK,
        [(
            header::CONTENT_TYPE,
            HeaderValue::from_static("application/json;charset=utf-8"),
        )],
        body,
    )
        .into_response()
}

async fn redirect_handler(State(state): State<Arc<AppState>>) -> Response {
    let location = HeaderValue::from_str(&state.cfg.index_path())
        .unwrap_or_else(|_| HeaderValue::from_static("/"));
    (StatusCode::FOUND, [(header::LOCATION, location)], "").into_response()
}

async fn asset_handler(
    State(_state): State<Arc<AppState>>,
    Path(path): Path<String>,
    headers: HeaderMap,
) -> Response {
    // The route prefix `/assets/` is not part of the capture, but embedded paths
    // are bundler-relative, so it has to be restored.
    let path = format!("assets/{}", path.trim_start_matches('/'));
    let Some(asset) = crate::assets::get(&path) else {
        return (StatusCode::NOT_FOUND, "asset not found").into_response();
    };
    if not_modified(&headers, &asset.etag) {
        return StatusCode::NOT_MODIFIED.into_response();
    }

    let cache = if asset.immutable {
        HeaderValue::from_static("public, max-age=31536000, immutable")
    } else {
        HeaderValue::from_static("no-cache")
    };

    let gzip = asset.is_compressible() && accepts_gzip(&headers);
    let body = if gzip {
        crate::assets::gzipped(&path, &asset.body)
    } else {
        Arc::new(asset.body)
    };

    let mut response = Response::new(Body::from(body.as_ref().clone()));
    let headers_out = response.headers_mut();
    headers_out.insert(
        header::CONTENT_TYPE,
        HeaderValue::from_static(asset.content_type),
    );
    headers_out.insert(header::CACHE_CONTROL, cache);
    if let Ok(value) = HeaderValue::from_str(&asset.etag) {
        headers_out.insert(header::ETAG, value);
    }
    if gzip {
        headers_out.insert(header::CONTENT_ENCODING, HeaderValue::from_static("gzip"));
        headers_out.insert(header::VARY, HeaderValue::from_static("accept-encoding"));
    }
    response
}

/// The bundler copies `public/` to the root of the bundle, outside `assets/`, so the
/// favicon needs its own route.
async fn favicon_handler(headers: HeaderMap) -> Response {
    let Some(asset) = crate::assets::get("favicon.svg") else {
        return (StatusCode::NOT_FOUND, "favicon not found").into_response();
    };
    if not_modified(&headers, &asset.etag) {
        return StatusCode::NOT_MODIFIED.into_response();
    }
    let mut response = Response::new(Body::from(asset.body));
    let headers_out = response.headers_mut();
    headers_out.insert(
        header::CONTENT_TYPE,
        HeaderValue::from_static(asset.content_type),
    );
    headers_out.insert(
        header::CACHE_CONTROL,
        HeaderValue::from_static("public, max-age=86400"),
    );
    if let Ok(value) = HeaderValue::from_str(&asset.etag) {
        headers_out.insert(header::ETAG, value);
    }
    response
}

async fn stats_handler(State(state): State<Arc<AppState>>) -> Response {
    let stop = {
        let state = state.clone();
        async move { state.stopped().await }
    };
    crate::stats::stream(state.stats.subscribe(), stop).into_response()
}

async fn not_found() -> Response {
    (StatusCode::NOT_FOUND, "not found").into_response()
}

fn not_modified(headers: &HeaderMap, etag: &str) -> bool {
    headers
        .get(header::IF_NONE_MATCH)
        .and_then(|value| value.to_str().ok())
        .map(|value| value.split(',').any(|candidate| candidate.trim() == etag))
        .unwrap_or(false)
}

fn accepts_gzip(headers: &HeaderMap) -> bool {
    headers
        .get(header::ACCEPT_ENCODING)
        .and_then(|value| value.to_str().ok())
        .map(|value| value.contains("gzip"))
        .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::HeaderValue;
    use tower::ServiceExt;

    fn test_state() -> Arc<AppState> {
        AppState::new(
            crate::cli::Config {
                command: vec!["bash".into()],
                ..crate::cli::Config::default()
            },
            crate::stats::Stats::new(),
        )
    }

    async fn status(app: &Router, uri: &str) -> StatusCode {
        let request = Request::builder().uri(uri).body(Body::empty()).unwrap();
        app.clone().oneshot(request).await.unwrap().status()
    }

    #[tokio::test]
    async fn routes_index_token_and_assets() {
        let app = router(test_state());
        assert_eq!(status(&app, "/").await, StatusCode::OK);
        assert_eq!(status(&app, "/token").await, StatusCode::OK);
        assert_eq!(status(&app, "/nope").await, StatusCode::NOT_FOUND);
        let js = crate::assets::paths()
            .into_iter()
            .find(|path| path.ends_with(".js"))
            .unwrap();
        assert_eq!(status(&app, &format!("/{js}")).await, StatusCode::OK);
        // A nested path below assets/ still resolves.
        assert_eq!(
            status(&app, "/assets/nested/missing.js").await,
            StatusCode::NOT_FOUND
        );
    }

    #[tokio::test]
    async fn serves_the_favicon() {
        let app = router(test_state());
        let request = Request::builder()
            .uri("/favicon.svg")
            .body(Body::empty())
            .unwrap();
        let response = app.clone().oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response.headers()[header::CONTENT_TYPE],
            "image/svg+xml",
            "browsers only use the icon when it is served as an image"
        );
        let etag = response.headers()[header::ETAG].clone();
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert!(
            body.starts_with(b"<svg"),
            "the embedded icon must be the file the bundler copied"
        );

        // Revalidation, so a cached tab does not re-download it.
        let request = Request::builder()
            .uri("/favicon.svg")
            .header(header::IF_NONE_MATCH, etag)
            .body(Body::empty())
            .unwrap();
        assert_eq!(
            app.oneshot(request).await.unwrap().status(),
            StatusCode::NOT_MODIFIED
        );
    }

    #[tokio::test]
    async fn token_echoes_the_credential() {
        let mut cfg = crate::cli::Config {
            command: vec!["bash".into()],
            ..crate::cli::Config::default()
        };
        cfg.credential = Some("dXNlcjpwYXNz".into());
        let app = router(AppState::new(cfg, crate::stats::Stats::new()));
        let request = Request::builder()
            .uri("/token")
            .header("authorization", "Basic dXNlcjpwYXNz")
            .body(Body::empty())
            .unwrap();
        let response = app.oneshot(request).await.unwrap();
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(body.as_ref(), br#"{"token": "dXNlcjpwYXNz"}"#);
    }

    #[tokio::test]
    async fn missing_credential_is_challenged() {
        let mut cfg = crate::cli::Config {
            command: vec!["bash".into()],
            ..crate::cli::Config::default()
        };
        cfg.credential = Some("dXNlcjpwYXNz".into());
        let app = router(AppState::new(cfg, crate::stats::Stats::new()));
        let request = Request::builder().uri("/").body(Body::empty()).unwrap();
        let response = app.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(
            response.headers()[header::WWW_AUTHENTICATE],
            "Basic realm=\"ttyd\""
        );
    }

    #[tokio::test]
    async fn base_path_moves_every_endpoint() {
        let mut cfg = crate::cli::Config {
            command: vec!["bash".into()],
            ..crate::cli::Config::default()
        };
        cfg.base_path = "/mounted/here".into();
        let app = router(AppState::new(cfg, crate::stats::Stats::new()));
        assert_eq!(status(&app, "/mounted/here").await, StatusCode::FOUND);
        assert_eq!(status(&app, "/mounted/here/").await, StatusCode::OK);
        assert_eq!(status(&app, "/mounted/here/token").await, StatusCode::OK);
        assert_eq!(
            status(&app, "/mounted/here/favicon.svg").await,
            StatusCode::OK
        );
        assert_eq!(status(&app, "/").await, StatusCode::NOT_FOUND);
    }

    #[test]
    fn gzip_is_only_used_when_accepted() {
        let mut headers = HeaderMap::new();
        assert!(!accepts_gzip(&headers));
        headers.insert(header::ACCEPT_ENCODING, HeaderValue::from_static("deflate"));
        assert!(!accepts_gzip(&headers));
        headers.insert(
            header::ACCEPT_ENCODING,
            HeaderValue::from_static("gzip, deflate"),
        );
        assert!(accepts_gzip(&headers));
    }

    #[test]
    fn etag_matching_handles_lists() {
        let mut headers = HeaderMap::new();
        assert!(!not_modified(&headers, "\"a\""));
        headers.insert(
            header::IF_NONE_MATCH,
            HeaderValue::from_static("\"b\", \"a\""),
        );
        assert!(not_modified(&headers, "\"a\""));
    }
}