defter 0.3.3

Self-hosted Zotero sync and file storage server, with metadata in SQLite and attachments in S3.
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
//! The web UI, rendered on the server from the askama templates in
//! `templates/`: the dashboard, shown after signing in with an API key, and
//! the login consent page for Zotero. htmx refreshes the dashboard's status in
//! place. It and the Tailwind stylesheet are built from `ui/` by `build.rs` and
//! embedded in the binary. Every page works without JavaScript and is served
//! under a strict Content-Security-Policy.

use std::collections::HashMap;

use askama::Template;
use axum::{
    Form, Json, Router,
    extract::{Path, State},
    http::{HeaderMap, HeaderValue, StatusCode, header},
    response::{Html, IntoResponse, Redirect, Response},
    routing::{get, post},
};
use serde_json::json;

use crate::app::AppState;
use crate::error::AppError;
use crate::{auth, store, zotero};

/// The stylesheet and script, under names carrying their content hash
/// (`STYLESHEET`, `SCRIPT`, `UI_ASSETS`), generated by `build.rs`.
mod assets {
    include!(concat!(env!("OUT_DIR"), "/ui_assets.rs"));
}

pub fn routes() -> Router<AppState> {
    Router::new()
        .route("/", get(dashboard))
        .route("/login", get(auth::login_page).post(auth::login_authorize))
        .route("/assets/{name}", get(asset))
        .route("/ui/status", get(status))
        .route("/ui/session", post(sign_in))
        .route("/ui/logout", post(sign_out))
}

// ── sign-in ─────────────────────────────────────────────────────────────────────

/// Whether the request carries a live web UI session cookie.
fn signed_in(app: &AppState, headers: &HeaderMap) -> bool {
    auth::cookie(headers, auth::UI_SESSION_COOKIE).is_some_and(|t| app.ui_sessions.get(t).is_some())
}

/// A web UI session, or an API key in the request (for scripts and
/// monitoring). Any key will do, read-only included: the UI only shows.
fn authorized(app: &AppState, headers: &HeaderMap) -> bool {
    signed_in(app, headers)
        || auth::request_key(headers).is_some_and(|k| app.keys.access(k).is_some())
}

/// `Set-Cookie` for the session cookie: `token`, or `None` to clear it.
fn session_cookie(app: &AppState, token: Option<&str>) -> HeaderValue {
    let secure = if app.cfg.public_url.starts_with("https://") {
        "; Secure"
    } else {
        ""
    };
    let (value, max_age) = match token {
        Some(token) => (token, auth::UI_SESSION_TTL.as_secs()),
        None => ("", 0),
    };
    // Lax, so following a link to the dashboard keeps one signed in; every
    // POST also checks its Origin.
    HeaderValue::from_str(&format!(
        "{}={value}; Path=/; HttpOnly; SameSite=Lax; Max-Age={max_age}{secure}",
        auth::UI_SESSION_COOKIE
    ))
    .expect("cookie of hex and fixed attributes")
}

#[derive(Template)]
#[template(path = "signin.html")]
struct SignInPage<'a> {
    layout: Layout,
    error: Option<&'a str>,
}

fn sign_in_page(app: &AppState, status: StatusCode, error: Option<&str>) -> Response {
    let signin = SignInPage {
        layout: Layout::new(false),
        error,
    };
    let mut response = page(status, &signin.layout, signin.render());
    let headers = response.headers_mut();
    headers.extend(zotero::server_headers(&app.server_id));
    headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
    response
}

/// `POST /ui/session` (form `key`): sign in to the web UI with an API key.
async fn sign_in(
    State(app): State<AppState>,
    headers: HeaderMap,
    Form(form): Form<HashMap<String, String>>,
) -> Response {
    if auth::foreign_origin(&headers, &app.cfg.public_url) {
        return sign_in_page(
            &app,
            StatusCode::FORBIDDEN,
            Some("The sign-in was sent from another site."),
        );
    }
    let key = form.get("key").map(|k| k.trim()).unwrap_or_default();
    if app.keys.access(key).is_none() {
        tracing::warn!("web UI sign-in with a wrong key");
        tokio::time::sleep(auth::WRONG_KEY_DELAY).await;
        return sign_in_page(
            &app,
            StatusCode::FORBIDDEN,
            Some("That is not an API key of this library."),
        );
    }
    let (token, _) = app.ui_sessions.insert(());
    let mut response = Redirect::to("/").into_response();
    response
        .headers_mut()
        .insert(header::SET_COOKIE, session_cookie(&app, Some(&token)));
    response
}

/// `POST /ui/logout`: end the web UI session.
async fn sign_out(State(app): State<AppState>, headers: HeaderMap) -> Response {
    if auth::foreign_origin(&headers, &app.cfg.public_url) {
        return StatusCode::FORBIDDEN.into_response();
    }
    if let Some(token) = auth::cookie(&headers, auth::UI_SESSION_COOKIE) {
        app.ui_sessions.remove(token);
    }
    let mut response = Redirect::to("/").into_response();
    response
        .headers_mut()
        .insert(header::SET_COOKIE, session_cookie(&app, None));
    response
}

// ── layout ───────────────────────────────────────────────────────────────────────

/// What `templates/base.html` needs.
struct Layout {
    stylesheet: &'static str,
    script: &'static str,
    /// Offer to sign out.
    signed_in: bool,
    /// Allows the one inline script, the theme switch, under the CSP.
    nonce: String,
}

impl Layout {
    fn new(signed_in: bool) -> Self {
        Layout {
            stylesheet: assets::STYLESHEET,
            script: assets::SCRIPT,
            signed_in,
            nonce: auth::random_hex(16),
        }
    }

    /// Scripts and styles only from this server (plus the theme switch's
    /// nonce), requests only to it, and no framing, so a button cannot be
    /// clickjacked.
    fn content_security_policy(&self) -> String {
        format!(
            "default-src 'none'; script-src 'self' 'nonce-{}'; style-src 'self'; \
             img-src 'self' data:; connect-src 'self'; form-action 'self'; \
             frame-ancestors 'none'; base-uri 'none'",
            self.nonce
        )
    }
}

/// A rendered page, with the headers every page carries.
fn page(status: StatusCode, layout: &Layout, rendered: askama::Result<String>) -> Response {
    let html = match rendered {
        Ok(html) => html,
        Err(error) => {
            return AppError::Internal(format!("rendering a page: {error}")).into_response();
        }
    };
    let mut response = (status, Html(html)).into_response();
    let headers = response.headers_mut();
    headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
    if let Ok(csp) = HeaderValue::from_str(&layout.content_security_policy()) {
        headers.insert(header::CONTENT_SECURITY_POLICY, csp);
    }
    response
}

// ── dashboard ────────────────────────────────────────────────────────────────

struct Stat {
    label: &'static str,
    value: String,
}

/// What the dashboard's status block shows.
struct Status {
    version: String,
    user_id: u64,
    defter_version: &'static str,
    commonmeta_version: &'static str,
    stats: Vec<Stat>,
    storage_location: String,
    signed_downloads: bool,
    max_upload: String,
    api_url: String,
}

impl Status {
    fn new(app: &AppState, library: &store::LibraryStats) -> Self {
        let stat = |label, value| Stat { label, value };
        Status {
            version: format_count(library.version),
            user_id: app.cfg.user_id,
            defter_version: env!("CARGO_PKG_VERSION"),
            commonmeta_version: commonmeta::VERSION,
            stats: vec![
                stat("Items", format_count(library.items)),
                stat("Attachments", format_count(library.attachments)),
                stat("Notes", format_count(library.notes)),
                stat("Collections", format_count(library.collections)),
                stat("Tags", format_count(library.tags)),
                stat("In trash", format_count(library.trashed)),
                stat("Files", format_count(library.files)),
                stat("Stored", format_bytes(library.file_bytes as u64)),
            ],
            storage_location: app.storage.description().to_string(),
            signed_downloads: app.storage.signs_downloads(),
            max_upload: format_bytes(app.cfg.max_upload),
            api_url: format!("{}/api", app.cfg.public_url),
        }
    }
}

#[derive(Template)]
#[template(path = "dashboard.html", blocks = ["status"])]
struct DashboardPage {
    layout: Layout,
    status: Status,
}

/// `GET /`: the dashboard. htmx's poll (`HX-Request`) gets only the status
/// block. The page also carries the server headers, so `/` identifies the
/// server the way `/api/` does.
async fn dashboard(State(app): State<AppState>, request: HeaderMap) -> Result<Response, AppError> {
    let fragment = request.get("hx-request").is_some_and(|v| v == "true")
        && !request.contains_key("hx-history-restore-request");
    if !signed_in(&app, &request) {
        if fragment {
            // htmx's poll after the session ended: reload, to the sign-in page.
            let mut response = StatusCode::UNAUTHORIZED.into_response();
            response
                .headers_mut()
                .insert("hx-refresh", HeaderValue::from_static("true"));
            return Ok(response);
        }
        return Ok(sign_in_page(&app, StatusCode::UNAUTHORIZED, None));
    }
    let library = app.db.read(store::stats).await?;
    let dashboard = DashboardPage {
        layout: Layout::new(true),
        status: Status::new(&app, &library),
    };
    let rendered = if fragment {
        dashboard.as_status().render()
    } else {
        dashboard.render()
    };
    let mut response = page(StatusCode::OK, &dashboard.layout, rendered);
    let headers = response.headers_mut();
    headers.extend(zotero::server_headers(&app.server_id));
    headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
    // The same URL answers with a page or a fragment.
    headers.insert(header::VARY, HeaderValue::from_static("HX-Request"));
    Ok(response)
}

/// A count with thousands separators: 12345 → "12,345".
fn format_count(n: i64) -> String {
    let digits = n.unsigned_abs().to_string();
    let mut out = String::new();
    for (i, digit) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i).is_multiple_of(3) {
            out.push(',');
        }
        out.push(digit);
    }
    if n < 0 { format!("-{out}") } else { out }
}

/// A byte count for people: 1536 → "1.5 KB".
fn format_bytes(bytes: u64) -> String {
    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
    let mut value = bytes as f64;
    let mut unit = 0;
    while value >= 1024.0 && unit < UNITS.len() - 1 {
        value /= 1024.0;
        unit += 1;
    }
    if unit == 0 || value >= 10.0 {
        format!("{value:.0} {}", UNITS[unit])
    } else {
        format!("{value:.1} {}", UNITS[unit])
    }
}

// ── login page ───────────────────────────────────────────────────────────────

/// What the login page shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoginView<'a> {
    /// A pending session, with the form that approves it with an API key, and
    /// why the last attempt failed.
    Pending {
        token: &'a str,
        error: Option<&'a str>,
    },
    Approved,
    /// Unknown or expired session.
    Expired,
    /// No session in the URL.
    Missing,
    /// The approval was refused, and why.
    Refused(&'a str),
}

impl<'a> LoginView<'a> {
    fn title(&self) -> &'static str {
        match self {
            LoginView::Pending { .. } => "Authorize Zotero?",
            LoginView::Approved => "Authorized",
            LoginView::Expired => "Login expired",
            LoginView::Missing => "No login request",
            LoginView::Refused(_) => "Not authorized",
        }
    }

    fn message(&self) -> &'a str {
        match self {
            LoginView::Pending { .. } => {
                "A Zotero client asked to sync with this library. Approve with an API key \
                 that may write to it, and only if you just started the login yourself."
            }
            LoginView::Approved => "You can close this page and return to Zotero.",
            LoginView::Expired => {
                "This login request is unknown or has expired. Start the login in Zotero again."
            }
            LoginView::Missing => "Open this page from Zotero’s Settings → Sync → Log In.",
            LoginView::Refused(reason) => reason,
        }
    }
}

#[derive(Template)]
#[template(path = "login.html")]
struct LoginPage<'a> {
    layout: Layout,
    view: LoginView<'a>,
}

/// The login page as a complete response. Besides the page headers it is
/// never cached, and its URL, which carries the session token, is sent as a
/// referrer to defter only.
///
/// Not `no-referrer`: under that policy browsers send `Origin: null` with the
/// Approve form's POST (Fetch standard, "append a request `Origin` header"),
/// which the cross-site check in [`auth::login_authorize`] must reject.
/// `same-origin` keeps the real `Origin` on the form's own POST and sends
/// nothing to other sites.
pub fn login_page(status: StatusCode, view: LoginView) -> Response {
    let login = LoginPage {
        layout: Layout::new(false),
        view,
    };
    let mut response = page(status, &login.layout, login.render());
    let headers = response.headers_mut();
    headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
    headers.insert(
        header::REFERRER_POLICY,
        HeaderValue::from_static("same-origin"),
    );
    response
}

// ── assets and status ────────────────────────────────────────────────────────

/// An embedded asset. Its name carries its content hash, so it can be cached
/// for good.
async fn asset(Path(name): Path<String>) -> Response {
    let Some((_, bytes)) = assets::UI_ASSETS.iter().find(|(n, _)| *n == name) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let content_type = match name.rsplit('.').next() {
        Some("js") => "text/javascript; charset=utf-8",
        Some("css") => "text/css; charset=utf-8",
        Some("svg") => "image/svg+xml",
        Some("woff2") => "font/woff2",
        Some("png") => "image/png",
        _ => "application/octet-stream",
    };
    (
        [
            (header::CONTENT_TYPE, content_type),
            (header::CACHE_CONTROL, "public, max-age=31536000, immutable"),
        ],
        *bytes,
    )
        .into_response()
}

/// `GET /ui/status`: the dashboard's data as JSON, for monitoring, with an
/// API key (`Zotero-API-Key` or `Authorization: Bearer`) or a UI session.
async fn status(State(app): State<AppState>, headers: HeaderMap) -> Result<Response, AppError> {
    if !authorized(&app, &headers) {
        return Ok((
            StatusCode::UNAUTHORIZED,
            Json(json!({ "error": "an API key or a signed-in session is required" })),
        )
            .into_response());
    }
    let library = app.db.read(store::stats).await?;
    Ok(Json(json!({
        "name": "defter",
        "version": env!("CARGO_PKG_VERSION"),
        "commonmetaVersion": commonmeta::VERSION,
        "serverId": app.server_id,
        "publicUrl": app.cfg.public_url,
        "apiUrl": format!("{}/api", app.cfg.public_url),
        "userId": app.cfg.user_id,
        "username": app.cfg.username,
        "storage": {
            "location": app.storage.description(),
            "signedDownloads": app.storage.signs_downloads(),
            "maxUpload": app.cfg.max_upload,
        },
        "library": library,
    }))
    .into_response())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_assets_are_named_by_content() {
        assert!(assets::STYLESHEET.starts_with("/assets/app-"));
        assert!(assets::STYLESHEET.ends_with(".css"));
        assert!(assets::SCRIPT.starts_with("/assets/app-"));
        assert!(assets::SCRIPT.ends_with(".js"));
        let names: Vec<&str> = assets::UI_ASSETS.iter().map(|(n, _)| *n).collect();
        assert_eq!(
            names,
            [&assets::STYLESHEET[8..], &assets::SCRIPT[8..]],
            "the URLs name the embedded files"
        );
        let (_, script) = assets::UI_ASSETS[1];
        assert!(script.starts_with(b"var htmx="));
        assert!(String::from_utf8_lossy(script).contains("data-theme-toggle"));
    }

    #[test]
    fn the_session_token_is_escaped_in_the_form() {
        let html = LoginPage {
            layout: Layout::new(false),
            view: LoginView::Pending {
                token: "\"><script>alert(1)</script>",
                error: None,
            },
        }
        .render()
        .unwrap();
        assert!(
            html.contains(r#"value="&#34;&#62;&#60;script&#62;alert(1)"#),
            "{html}"
        );
        assert!(!html.contains("<script>alert"));
    }

    #[test]
    fn formats_counts_and_bytes() {
        assert_eq!(format_count(0), "0");
        assert_eq!(format_count(999), "999");
        assert_eq!(format_count(1234567), "1,234,567");
        assert_eq!(format_count(-1000), "-1,000");
        assert_eq!(format_bytes(512), "512 B");
        assert_eq!(format_bytes(1536), "1.5 KB");
        assert_eq!(format_bytes(1024 * 1024 * 1024), "1.0 GB");
        assert_eq!(format_bytes(20 * 1024 * 1024), "20 MB");
    }
}