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
use std::sync::Arc;

use axum::extract::{FromRequestParts, OriginalUri, Path, Query, State as Extract};
use axum::http::header::{
    CONTENT_SECURITY_POLICY, CONTENT_TYPE, HOST, ORIGIN, REFERRER_POLICY, X_CONTENT_TYPE_OPTIONS,
};
use axum::http::request::Parts;
use axum::http::{HeaderMap, Method};
use axum::response::{IntoResponse, Redirect};
use axum::routing::{get, post};
use axum::{Form, Router};
use maud::Markup;
use serde::Deserialize;
use tower_http::compression::CompressionLayer;
use tower_http::trace::TraceLayer;

use crate::lists::{self, View};
use crate::model::{MessageId, State, ThreadId, User};
use crate::store::{Change, Store};
use crate::views::{self, Page, ThreadView};
use crate::{Error, html};

// caddy-tailscale sets both from the tailnet identity, overwriting whatever
// the client sent.
pub(crate) const IDENTITY_HEADER: &str = "Remote-User";
pub(crate) const SLUG_HEADER: &str = "X-User-Slug";

#[derive(Clone)]
pub struct AppState {
    pub store: Arc<Store>,
}

impl AppState {
    pub fn new(store: Store) -> Self {
        Self {
            store: Arc::new(store),
        }
    }
}

pub fn router(state: AppState) -> Router {
    Router::new()
        .route("/health", get(health))
        .route("/", get(for_me))
        .route("/{lane}", get(lane))
        .route("/search", get(search))
        .route("/messages/{id}/html", get(message_html))
        .route("/messages/{id}/state", post(set_state))
        .route("/messages/{id}/folder", post(set_folder))
        .route("/messages/{id}/delete", post(delete_message))
        .route("/messages/{id}/assignees", post(toggle_assignee))
        .route("/threads/{id}/comments", post(add_comment))
        .route("/undo", post(undo))
        .route("/assets/gloss.css", get(gloss_css))
        .route("/assets/docket.css", get(docket_css))
        .route("/assets/alpine.js", get(alpine_js))
        .layer(CompressionLayer::new())
        .layer(TraceLayer::new_for_http())
        .with_state(state)
}

async fn health() -> &'static str {
    "ok"
}

/// The requesting user, from the identity headers caddy-tailscale adds. Anyone
/// Tailscale lets through is a user; the first request adds them. Missing
/// either header means the proxy isn't doing its job, so nobody gets in.
struct Me(User);

impl FromRequestParts<AppState> for Me {
    type Rejection = Error;

    async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Error> {
        // Tailscale identifies every request from this machine, so a page on
        // another site could post forms as us; browsers send Origin on those.
        if parts.method == Method::POST && !same_origin(&parts.headers) {
            return Err(Error::Forbidden("cross-site request"));
        }
        let present = |name| header(&parts.headers, name).filter(|v| !v.trim().is_empty());
        let (Some(login), Some(slug)) = (present(IDENTITY_HEADER), present(SLUG_HEADER)) else {
            return Err(Error::Unauthenticated);
        };
        Ok(Me(state.store.sign_in(login, slug)?))
    }
}

pub(crate) fn header<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
    headers.get(name).and_then(|v| v.to_str().ok())
}

pub(crate) fn same_origin(headers: &HeaderMap) -> bool {
    let Some(origin) = header(headers, ORIGIN.as_str()) else {
        return true;
    };
    let origin_host = origin.split_once("://").map(|(_, host)| host);
    origin_host.is_some() && origin_host == header(headers, HOST.as_str())
}

#[derive(Deserialize)]
struct Selection {
    m: Option<MessageId>,
    q: Option<String>,
}

async fn for_me(
    Extract(state): Extract<AppState>,
    Me(me): Me,
    OriginalUri(uri): OriginalUri,
    Query(sel): Query<Selection>,
) -> Result<Markup, Error> {
    render(&state, &me, &View::ForMe, sel.m, &uri.to_string())
}

async fn lane(
    Extract(state): Extract<AppState>,
    Me(me): Me,
    OriginalUri(uri): OriginalUri,
    Path(lane): Path<String>,
    Query(sel): Query<Selection>,
) -> Result<Markup, Error> {
    let lane = State::from_slug(&lane)
        .filter(|s| State::LANES.contains(s))
        .ok_or(Error::NotFound("lane"))?;
    render(&state, &me, &View::Lane(lane), sel.m, &uri.to_string())
}

async fn search(
    Extract(state): Extract<AppState>,
    Me(me): Me,
    OriginalUri(uri): OriginalUri,
    Query(sel): Query<Selection>,
) -> Result<Markup, Error> {
    let view = View::Search(sel.q.unwrap_or_default());
    render(&state, &me, &view, sel.m, &uri.to_string())
}

fn render(
    state: &AppState,
    me: &User,
    view: &View,
    selected: Option<MessageId>,
    here: &str,
) -> Result<Markup, Error> {
    let store = &state.store;
    let thread = selected
        .clone()
        .map(|id| open_thread(store, me, &id))
        .transpose()?;
    let nav = std::iter::once(View::ForMe)
        .chain(State::LANES.map(View::Lane))
        .map(|v| lists::count(store, me, &v).map(|n| (v, n)))
        .collect::<Result<_, _>>()?;
    Ok(views::page(&Page {
        me,
        view,
        now: store.now(),
        users: store.users()?,
        folders: store.folders()?,
        nav,
        sections: lists::sections(store, me, view)?,
        unread: store.unread(&me.login)?,
        selected,
        thread,
        flash: store.take_flash(&me.login),
        here,
    }))
}

/// Opening a thread reads the selected message and the latest one, the two
/// that open expanded.
fn open_thread(store: &Store, me: &User, id: &str) -> Result<ThreadView, Error> {
    let msg = store.message(id)?.ok_or(Error::NotFound("message"))?;
    let latest = store
        .thread_messages(&msg.thread)?
        .last()
        .map_or_else(|| id.to_owned(), |m| m.id.clone());
    store.mark_read(&me.login, id)?;
    store.mark_read(&me.login, &latest)?;
    Ok(ThreadView {
        thread: store
            .thread(&msg.thread)?
            .ok_or(Error::NotFound("thread"))?,
        account: store
            .thread_account(&msg.thread)?
            .ok_or(Error::NotFound("account"))?,
        timeline: store.timeline(&msg.thread)?,
        latest,
    })
}

/// Only same-site paths, so a form can't bounce the browser elsewhere.
pub(crate) fn safe_back(back: &str) -> &str {
    if back.starts_with('/') && !back.starts_with("//") && !back.contains('\\') {
        back
    } else {
        "/"
    }
}

#[derive(Deserialize)]
struct StateForm {
    state: String,
    back: String,
}

async fn set_state(
    Extract(state): Extract<AppState>,
    Me(me): Me,
    Path(id): Path<MessageId>,
    Form(form): Form<StateForm>,
) -> Result<Redirect, Error> {
    let to = State::from_slug(&form.state).ok_or(Error::BadRequest("unknown state"))?;
    edit(&state, &me, id, Change::State(to), &form.back).await
}

#[derive(Deserialize)]
struct FolderForm {
    folder: String,
    back: String,
}

async fn set_folder(
    Extract(state): Extract<AppState>,
    Me(me): Me,
    Path(id): Path<MessageId>,
    Form(form): Form<FolderForm>,
) -> Result<Redirect, Error> {
    let folder = Some(form.folder).filter(|f| !f.is_empty());
    edit(&state, &me, id, Change::Folder(folder), &form.back).await
}

#[derive(Deserialize)]
pub(crate) struct UserForm {
    pub(crate) user: String,
    pub(crate) back: String,
}

async fn toggle_assignee(
    Extract(state): Extract<AppState>,
    Me(me): Me,
    Path(id): Path<MessageId>,
    Form(form): Form<UserForm>,
) -> Result<Redirect, Error> {
    edit(
        &state,
        &me,
        id,
        Change::ToggleAssignee(form.user),
        &form.back,
    )
    .await
}

async fn edit(
    state: &AppState,
    me: &User,
    id: MessageId,
    change: Change,
    back: &str,
) -> Result<Redirect, Error> {
    state.store.edit(&me.login, &id, change)?;
    Ok(Redirect::to(safe_back(back)))
}

async fn delete_message(
    Extract(state): Extract<AppState>,
    Me(me): Me,
    Path(id): Path<MessageId>,
    Form(form): Form<BackForm>,
) -> Result<Redirect, Error> {
    state.store.delete(&me.login, &id)?;
    Ok(Redirect::to(safe_back(&form.back)))
}

#[derive(Deserialize)]
struct CommentForm {
    text: String,
    back: String,
}

async fn add_comment(
    Extract(state): Extract<AppState>,
    Me(me): Me,
    Path(thread): Path<ThreadId>,
    Form(form): Form<CommentForm>,
) -> Result<Redirect, Error> {
    state.store.add_comment(&me.login, &thread, &form.text)?;
    Ok(Redirect::to(safe_back(&form.back)))
}

#[derive(Deserialize)]
struct BackForm {
    back: String,
}

async fn undo(
    Extract(state): Extract<AppState>,
    Me(me): Me,
    Form(form): Form<BackForm>,
) -> Result<Redirect, Error> {
    state.store.undo(&me.login)?;
    Ok(Redirect::to(safe_back(&form.back)))
}

#[derive(Deserialize)]
struct HtmlQuery {
    /// Set by the "Show images" link: remote images may load.
    images: Option<String>,
}

/// The message's HTML part as a page of its own, for the thread view's
/// sandboxed frame. The CSP is the frame's real wall: it holds even if
/// the page is opened directly, outside the frame.
async fn message_html(
    Extract(state): Extract<AppState>,
    Me(_me): Me,
    Path(id): Path<MessageId>,
    Query(query): Query<HtmlQuery>,
) -> Result<impl IntoResponse, Error> {
    let raw = state.store.html(&id)?.ok_or(Error::NotFound("HTML part"))?;
    Ok((
        [
            (CONTENT_TYPE, "text/html; charset=utf-8".to_owned()),
            (CONTENT_SECURITY_POLICY, html::csp(query.images.is_some())),
            (X_CONTENT_TYPE_OPTIONS, "nosniff".to_owned()),
            // Remote images, once allowed, don't learn where they're seen.
            (REFERRER_POLICY, "no-referrer".to_owned()),
        ],
        html::document(&raw),
    ))
}

async fn gloss_css() -> impl IntoResponse {
    (
        [(CONTENT_TYPE, "text/css; charset=utf-8")],
        include_str!("../assets/gloss.css"),
    )
}

async fn docket_css() -> impl IntoResponse {
    (
        [(CONTENT_TYPE, "text/css; charset=utf-8")],
        include_str!("../assets/docket.css"),
    )
}

async fn alpine_js() -> impl IntoResponse {
    (
        [(CONTENT_TYPE, "text/javascript; charset=utf-8")],
        include_str!("../assets/vendor/alpine-3.17.4.min.js"),
    )
}

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

    #[test]
    fn back_stays_on_site() {
        assert_eq!(safe_back("/do?m=4"), "/do?m=4");
        assert_eq!(safe_back("//evil.example"), "/");
        assert_eq!(safe_back("https://evil.example"), "/");
        assert_eq!(safe_back("/\\evil.example"), "/");
    }
}