Skip to content
1        10        20        30        40        50        60        70        80        90        100       110       120       130       1401use std::collections::HashMap;23use actix_multipart::Multipart;4use actix_web::http::StatusCode;5use actix_web::{HttpRequest, HttpResponse, web};6use anyhow::Context;7use futures_util::TryStreamExt;8use maud::{DOCTYPE, Markup, PreEscaped, html};9use serde::Deserialize;10use serde_json::{Map, Value};1112use crate::api::{MAX_CONTENT_BYTES, file_response};13use crate::attachments::{self, MAX_ATTACHMENT_BYTES};14use crate::auth::{self, Principal, Scope};15use crate::db::Db;16use crate::items::{self, Item, ListQuery, check_metadata, normalize_tag, normalize_tags};17use crate::sessions;18use crate::tokens::{self, TokenInfo};19use crate::users;2021const RECENT_LIMIT: i64 = 30;22const SEARCH_LIMIT: i64 = 100;23const HTML: &str = "text/html; charset=utf-8";2425const STYLE: &str = "26:root { color-scheme: light dark; font-family: system-ui, sans-serif; }27body { max-width: 56rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }28header { display: flex; gap: 1rem; align-items: center; justify-content: space-between; flex-wrap: wrap; }29header h1 { margin: 0; }30h1 a { color: inherit; text-decoration: none; }31textarea { width: 100%; min-height: 16rem; box-sizing: border-box; font: 14px ui-monospace, monospace; }32input[type=text], input[type=password] { width: 100%; box-sizing: border-box; padding: .4rem; margin: .25rem 0; }33form.inline { display: inline; }34form.stack { display: grid; gap: .5rem; }35pre { white-space: pre-wrap; word-break: break-word; background: rgba(127, 127, 127, .12); padding: 1rem; border-radius: 6px; }36ul.items, ul.files { list-style: none; padding: 0; }37ul.items li, ul.files li { padding: .5rem 0; border-bottom: 1px solid rgba(127, 127, 127, .25); }38img.preview { display: block; max-width: 100%; max-height: 24rem; margin: .5rem 0; border-radius: 6px; }39dl.meta { display: grid; grid-template-columns: max-content 1fr; gap: .25rem 1rem; }40dl.meta dt { font-weight: 600; }41.muted { opacity: .7; }42.notice { color: #b00020; }43.tag { margin-right: .4rem; }44.copy-block { display: grid; gap: .25rem; margin: .5rem 0 1rem; }45.copy-block button { justify-self: end; }46";4748/// Wires up the Copy buttons on the CLI setup section. The commands themselves are rendered49/// by the server, so they show the configured address.50const CLI_SETUP_SCRIPT: &str = "51(() => {52  for (const button of document.querySelectorAll('button.copy')) {53    button.addEventListener('click', async () => {54      const text = document.getElementById(button.dataset.target).textContent;55      const label = button.textContent;56      try {57        await navigator.clipboard.writeText(text);58        button.textContent = 'Copied';59      } catch (error) {60        button.textContent = 'Copy failed: select the text and copy it';61      }62      setTimeout(() => { button.textContent = label; }, 2000);63    });64  }65})();66";6768/// Lets the paste box take images from the clipboard: they are added to the file picker,69/// so one submit saves the text and the pictures together.70const PASTE_SCRIPT: &str = "71document.getElementById('paste').addEventListener('paste', (event) => {72  const pasted = Array.from(event.clipboardData?.files ?? []);73  if (pasted.length === 0) return;74  const picker = document.getElementById('files');75  const transfer = new DataTransfer();76  for (const file of [...picker.files, ...pasted]) transfer.items.add(file);77  picker.files = transfer.files;78});79";8081type WebResult = actix_web::Result<HttpResponse>;8283/// One file from a multipart form.84struct Upload {85    filename: String,86    data: Vec<u8>,87}8889/// The fields of a multipart form: text fields by name, and every file in order.90#[derive(Default)]91struct Parts {92    text: HashMap<String, String>,93    files: Vec<Upload>,94}9596impl Parts {97    fn text(&self, name: &str) -> String {98        self.text.get(name).cloned().unwrap_or_default()99    }100}101102/// Reads a multipart form, refusing any text field over the content limit or any file103/// over the attachment limit while streaming. Empty file inputs are skipped.104async fn read_parts(mut multipart: Multipart) -> Result<Parts, String> {105    let mut parts = Parts::default();106    while let Some(mut field) = multipart107        .try_next()108        .await109        .map_err(|error| error.to_string())?110    {111        let name = field.name().unwrap_or_default().to_string();112        let filename = field113            .content_disposition()114            .and_then(|disposition| disposition.get_filename())115            .map(str::to_owned);116        let limit = if filename.is_some() {117            MAX_ATTACHMENT_BYTES118        } else {119            MAX_CONTENT_BYTES120        };121        let mut data = Vec::new();122        while let Some(chunk) = field.try_next().await.map_err(|error| error.to_string())? {123            if data.len() + chunk.len() > limit {124                return Err("That is too large to save.".to_string());125            }126            data.extend_from_slice(&chunk);127        }128        match filename {129            Some(_) if data.is_empty() => {}130            Some(filename) => parts.files.push(Upload { filename, data }),131            None => {132                let text = String::from_utf8(data)133                    .map_err(|_| "Form text must be valid UTF-8.".to_string())?;134                parts.text.insert(name, text);135            }136        }137    }138    Ok(parts)139}140141fn internal(error: anyhow::Error) -> actix_web::Error {142    actix_web::error::ErrorInternalServerError(error)143}144145fn html_response(markup: Markup) -> HttpResponse {146    HttpResponse::Ok()147        .content_type(HTML)148        .body(markup.into_string())149}150151fn notice(status: StatusCode, message: &str) -> HttpResponse {152    HttpResponse::build(status).content_type(HTML).body(153        layout(154            "Error",155            &html! {156                p.notice { (message) }157                p { a href="/" { "Back to cairn" } }158            },159        )160        .into_string(),161    )162}163164fn redirect(location: &str) -> HttpResponse {165    HttpResponse::SeeOther()166        .insert_header(("Location", location))167        .finish()168}169170fn forbidden() -> HttpResponse {171    notice(StatusCode::FORBIDDEN, "This token is read-only.")172}173174pub fn configure(config: &mut web::ServiceConfig) {175    config176        .route("/", web::get().to(home))177        .route("/up", web::get().to(up))178        .route("/login", web::post().to(login))179        .route("/logout", web::post().to(logout))180        .route("/tokens", web::get().to(tokens_page))181        .route("/tokens", web::post().to(create_token))182        .route("/tokens/{id}/revoke", web::post().to(revoke_token))183        .route("/account", web::get().to(account))184        .route("/account/password", web::post().to(change_password))185        .route("/search", web::get().to(search))186        .route("/items", web::post().to(create))187        .route("/items/{id}", web::get().to(show))188        .route("/items/{id}/edit", web::post().to(edit))189        .route("/items/{id}/delete", web::post().to(delete))190        .route("/items/{id}/tags", web::post().to(add_tags))191        .route("/items/{id}/tags/{tag}/delete", web::post().to(remove_tag))192        .route("/items/{id}/attachments", web::post().to(attach))193        .route("/attachments/{id}", web::get().to(show_attachment))194        .route(195            "/attachments/{id}/delete",196            web::post().to(remove_attachment),197        );198}199200// Unauthenticated liveness check for load balancers and the deploy server.201async fn up() -> HttpResponse {202    HttpResponse::Ok().finish()203}204205async fn signed_in(req: &HttpRequest, db: &Db) -> actix_web::Result<Option<Principal>> {206    auth::session_principal(req, db).await.map_err(internal)207}208209async fn home(req: HttpRequest, db: web::Data<Db>) -> WebResult {210    let Some(principal) = signed_in(&req, &db).await? else {211        return Ok(html_response(login_page(None)));212    };213    let recent = db214        .call(|conn| {215            items::list(216                conn,217                &ListQuery {218                    limit: RECENT_LIMIT,219                    ..ListQuery::default()220                },221            )222        })223        .await224        .map_err(internal)?;225    Ok(html_response(paste_page(&principal, &recent)))226}227228#[derive(Deserialize)]229struct LoginForm {230    #[serde(default)]231    username: String,232    #[serde(default)]233    password: String,234}235236async fn login(db: web::Data<Db>, form: web::Form<LoginForm>) -> WebResult {237    let LoginForm { username, password } = form.into_inner();238    let user = db239        .call(move |conn| users::verify(conn, username.trim(), &password))240        .await241        .map_err(internal)?;242    let Some(user) = user else {243        return Ok(HttpResponse::Unauthorized()244            .content_type(HTML)245            .body(login_page(Some("That username and password do not match.")).into_string()));246    };247    let secret = auth::generate_session_secret();248    let hash = auth::hash_token(&secret);249    db.call(move |conn| sessions::create(conn, &user.id, &hash))250        .await251        .map_err(internal)?;252    Ok(HttpResponse::SeeOther()253        .cookie(auth::session_cookie(&secret))254        .insert_header(("Location", "/"))255        .finish())256}257258async fn logout(req: HttpRequest, db: web::Data<Db>) -> WebResult {259    auth::end_session(&req, &db).await.map_err(internal)?;260    Ok(HttpResponse::SeeOther()261        .cookie(auth::cleared_session_cookie())262        .insert_header(("Location", "/"))263        .finish())264}265266async fn tokens_page(req: HttpRequest, db: web::Data<Db>) -> WebResult {267    let Some(principal) = signed_in(&req, &db).await? else {268        return Ok(redirect("/"));269    };270    let tokens = db.call(|conn| tokens::list(conn)).await.map_err(internal)?;271    Ok(html_response(tokens_markup(&principal, &tokens, None)))272}273274#[derive(Deserialize)]275struct NewTokenForm {276    #[serde(default)]277    name: String,278    /// A checkbox: present only when ticked.279    read_only: Option<String>,280}281282/// Creates a token and shows its secret once, on this same response.283async fn create_token(284    req: HttpRequest,285    db: web::Data<Db>,286    form: web::Form<NewTokenForm>,287) -> WebResult {288    let Some(principal) = signed_in(&req, &db).await? else {289        return Ok(redirect("/"));290    };291    let NewTokenForm { name, read_only } = form.into_inner();292    let name = name.trim().to_string();293    if name.is_empty() || name.chars().count() > 64 {294        return Ok(notice(295            StatusCode::BAD_REQUEST,296            "Give the token a name of up to 64 characters.",297        ));298    }299    let scopes = if read_only.is_some() {300        vec![Scope::Read]301    } else {302        vec![Scope::Read, Scope::Write]303    };304    let issued = db305        .call(move |conn| tokens::create(conn, &name, &scopes))306        .await307        .map_err(internal)?;308    let tokens = db.call(|conn| tokens::list(conn)).await.map_err(internal)?;309    Ok(html_response(tokens_markup(310        &principal,311        &tokens,312        Some(issued.secret.as_str()),313    )))314}315316async fn revoke_token(req: HttpRequest, db: web::Data<Db>, path: web::Path<String>) -> WebResult {317    let Some(_principal) = signed_in(&req, &db).await? else {318        return Ok(redirect("/"));319    };320    let id = path.into_inner();321    let removed = db322        .call(move |conn| tokens::delete(conn, &id))323        .await324        .map_err(internal)?;325    if !removed {326        return Ok(notice(StatusCode::NOT_FOUND, "No token with that id."));327    }328    Ok(redirect("/tokens"))329}330331async fn account(req: HttpRequest, db: web::Data<Db>) -> WebResult {332    let Some(principal) = signed_in(&req, &db).await? else {333        return Ok(redirect("/"));334    };335    Ok(html_response(account_markup(&principal, None)))336}337338#[derive(Deserialize)]339struct PasswordForm {340    #[serde(default)]341    current: String,342    #[serde(default)]343    new_password: String,344    #[serde(default)]345    confirm: String,346}347348async fn change_password(349    req: HttpRequest,350    db: web::Data<Db>,351    form: web::Form<PasswordForm>,352) -> WebResult {353    let Some(principal) = signed_in(&req, &db).await? else {354        return Ok(redirect("/"));355    };356    let PasswordForm {357        current,358        new_password,359        confirm,360    } = form.into_inner();361    let problem = if let Err(message) = users::check_password(&new_password) {362        Some(message)363    } else if new_password != confirm {364        Some("The new passwords do not match.".to_string())365    } else {366        None367    };368    if let Some(problem) = problem {369        return Ok(html_response(account_markup(370            &principal,371            Some(problem.as_str()),372        )));373    }374    let username = principal.name.clone();375    let checked = db376        .call({377            let username = username.clone();378            move |conn| users::verify(conn, &username, &current)379        })380        .await381        .map_err(internal)?;382    if checked.is_none() {383        return Ok(html_response(account_markup(384            &principal,385            Some("The current password is wrong."),386        )));387    }388    db.call(move |conn| users::reset_password(conn, &username, &new_password))389        .await390        .map_err(internal)?;391    Ok(html_response(account_markup(392        &principal,393        Some("Password changed."),394    )))395}396397#[derive(Deserialize)]398struct SearchParams {399    q: Option<String>,400    tag: Option<String>,401}402403async fn search(404    req: HttpRequest,405    db: web::Data<Db>,406    params: web::Query<SearchParams>,407) -> WebResult {408    let Some(principal) = signed_in(&req, &db).await? else {409        return Ok(redirect("/"));410    };411    let params = params.into_inner();412    let query = ListQuery {413        q: params.q.clone().filter(|q| !q.trim().is_empty()),414        tag: params415            .tag416            .as_deref()417            .and_then(|tag| normalize_tag(tag).ok()),418        limit: SEARCH_LIMIT,419        ..ListQuery::default()420    };421    let results = db422        .call(move |conn| items::list(conn, &query))423        .await424        .map_err(internal)?;425    Ok(html_response(search_page(426        &principal,427        params.q.as_deref().unwrap_or_default(),428        &results,429    )))430}431432/// The paste box. Text, a title, tags, `key=value` metadata, and any number of files.433async fn create(req: HttpRequest, db: web::Data<Db>, multipart: Multipart) -> WebResult {434    let Some(principal) = signed_in(&req, &db).await? else {435        return Ok(redirect("/"));436    };437    if !principal.allows(Scope::Write) {438        return Ok(forbidden());439    }440    let mut parts = match read_parts(multipart).await {441        Ok(parts) => parts,442        Err(message) => return Ok(notice(StatusCode::BAD_REQUEST, &message)),443    };444    let mut title = parts.text("title");445    let content = parts.text("content");446    let files = std::mem::take(&mut parts.files);447    if title.trim().is_empty() && content.trim().is_empty() {448        match files.first() {449            Some(first) => title.clone_from(&first.filename),450            None => {451                return Ok(notice(452                    StatusCode::BAD_REQUEST,453                    "Nothing to save: paste some text, or add a file.",454                ));455            }456        }457    }458    let tags = match normalize_tags(&split_tags(&parts.text("tags"))) {459        Ok(tags) => tags,460        Err(message) => return Ok(notice(StatusCode::BAD_REQUEST, &message)),461    };462    let metadata = match parse_metadata(&parts.text("meta")) {463        Ok(metadata) => metadata,464        Err(message) => return Ok(notice(StatusCode::BAD_REQUEST, &message)),465    };466    let item_id = db467        .call(move |conn| {468            let item = items::create(conn, &title, &content, &tags, &metadata)?;469            for file in &files {470                attachments::add(conn, &item.id, &file.filename, &file.data)?471                    .context("the new item disappeared")?;472            }473            Ok(item.id)474        })475        .await476        .map_err(internal)?;477    Ok(redirect(&format!("/items/{item_id}")))478}479480async fn show(req: HttpRequest, db: web::Data<Db>, path: web::Path<String>) -> WebResult {481    let Some(principal) = signed_in(&req, &db).await? else {482        return Ok(redirect("/"));483    };484    let id = path.into_inner();485    let item = db486        .call(move |conn| items::get(conn, &id))487        .await488        .map_err(internal)?;489    match item {490        Some(item) => Ok(html_response(item_page(&principal, &item))),491        None => Ok(notice(StatusCode::NOT_FOUND, "No item with that id.")),492    }493}494495#[derive(Deserialize)]496struct EditForm {497    #[serde(default)]498    title: String,499    content: String,500    #[serde(default)]501    meta: String,502}503504async fn edit(505    req: HttpRequest,506    db: web::Data<Db>,507    path: web::Path<String>,508    form: web::Form<EditForm>,509) -> WebResult {510    let Some(principal) = signed_in(&req, &db).await? else {511        return Ok(redirect("/"));512    };513    if !principal.allows(Scope::Write) {514        return Ok(forbidden());515    }516    let id = path.into_inner();517    let form = form.into_inner();518    if form.content.trim().is_empty() {519        return Ok(notice(520            StatusCode::BAD_REQUEST,521            "The content cannot be empty.",522        ));523    }524    let Some(existing) = db525        .call({526            let id = id.clone();527            move |conn| items::get(conn, &id)528        })529        .await530        .map_err(internal)?531    else {532        return Ok(notice(StatusCode::NOT_FOUND, "No item with that id."));533    };534    // Untouched metadata is left alone, so values the form cannot show (numbers, nested535    // data from the API) survive an edit of the text.536    let metadata = if form.meta == render_metadata(&existing.metadata) {537        None538    } else {539        match parse_metadata(&form.meta) {540            Ok(metadata) => Some(metadata),541            Err(message) => return Ok(notice(StatusCode::BAD_REQUEST, &message)),542        }543    };544    let updated = db545        .call(move |conn| {546            items::update(547                conn,548                &id,549                Some(form.title.as_str()),550                Some(form.content.as_str()),551                metadata.as_ref(),552            )553        })554        .await555        .map_err(internal)?;556    match updated {557        Some(item) => Ok(redirect(&format!("/items/{}", item.id))),558        None => Ok(notice(StatusCode::NOT_FOUND, "No item with that id.")),559    }560}561562async fn delete(req: HttpRequest, db: web::Data<Db>, path: web::Path<String>) -> WebResult {563    let Some(principal) = signed_in(&req, &db).await? else {564        return Ok(redirect("/"));565    };566    if !principal.allows(Scope::Write) {567        return Ok(forbidden());568    }569    let id = path.into_inner();570    db.call(move |conn| items::delete(conn, &id))571        .await572        .map_err(internal)?;573    Ok(redirect("/"))574}575576#[derive(Deserialize)]577struct TagForm {578    #[serde(default)]579    tags: String,580}581582async fn add_tags(583    req: HttpRequest,584    db: web::Data<Db>,585    path: web::Path<String>,586    form: web::Form<TagForm>,587) -> WebResult {588    let Some(principal) = signed_in(&req, &db).await? else {589        return Ok(redirect("/"));590    };591    if !principal.allows(Scope::Write) {592        return Ok(forbidden());593    }594    let id = path.into_inner();595    let tags = match normalize_tags(&split_tags(&form.into_inner().tags)) {596        Ok(tags) if !tags.is_empty() => tags,597        Ok(_) => return Ok(redirect(&format!("/items/{id}"))),598        Err(message) => return Ok(notice(StatusCode::BAD_REQUEST, &message)),599    };600    db.call({601        let id = id.clone();602        move |conn| items::add_tags(conn, &id, &tags)603    })604    .await605    .map_err(internal)?;606    Ok(redirect(&format!("/items/{id}")))607}608609async fn remove_tag(610    req: HttpRequest,611    db: web::Data<Db>,612    path: web::Path<(String, String)>,613) -> WebResult {614    let Some(principal) = signed_in(&req, &db).await? else {615        return Ok(redirect("/"));616    };617    if !principal.allows(Scope::Write) {618        return Ok(forbidden());619    }620    let (id, tag) = path.into_inner();621    let Ok(tag) = normalize_tag(&tag) else {622        return Ok(notice(StatusCode::BAD_REQUEST, "That tag is not valid."));623    };624    db.call({625        let id = id.clone();626        move |conn| items::remove_tag(conn, &id, &tag)627    })628    .await629    .map_err(internal)?;630    Ok(redirect(&format!("/items/{id}")))631}632633/// Adds files to an existing item from the item page.634async fn attach(635    req: HttpRequest,636    db: web::Data<Db>,637    path: web::Path<String>,638    multipart: Multipart,639) -> WebResult {640    let Some(principal) = signed_in(&req, &db).await? else {641        return Ok(redirect("/"));642    };643    if !principal.allows(Scope::Write) {644        return Ok(forbidden());645    }646    let parts = match read_parts(multipart).await {647        Ok(parts) => parts,648        Err(message) => return Ok(notice(StatusCode::BAD_REQUEST, &message)),649    };650    if parts.files.is_empty() {651        return Ok(notice(StatusCode::BAD_REQUEST, "Choose at least one file."));652    }653    let id = path.into_inner();654    let found = db655        .call({656            let id = id.clone();657            move |conn| {658                for file in &parts.files {659                    if attachments::add(conn, &id, &file.filename, &file.data)?.is_none() {660                        return Ok(false);661                    }662                }663                Ok(true)664            }665        })666        .await667        .map_err(internal)?;668    if !found {669        return Ok(notice(StatusCode::NOT_FOUND, "No item with that id."));670    }671    Ok(redirect(&format!("/items/{id}")))672}673674async fn show_attachment(675    req: HttpRequest,676    db: web::Data<Db>,677    path: web::Path<String>,678) -> WebResult {679    let Some(_principal) = signed_in(&req, &db).await? else {680        return Ok(redirect("/"));681    };682    let id = path.into_inner();683    let attachment = db684        .call(move |conn| attachments::get(conn, &id))685        .await686        .map_err(internal)?;687    match attachment {688        Some(attachment) => Ok(file_response(attachment)),689        None => Ok(notice(StatusCode::NOT_FOUND, "No file with that id.")),690    }691}692693async fn remove_attachment(694    req: HttpRequest,695    db: web::Data<Db>,696    path: web::Path<String>,697) -> WebResult {698    let Some(principal) = signed_in(&req, &db).await? else {699        return Ok(redirect("/"));700    };701    if !principal.allows(Scope::Write) {702        return Ok(forbidden());703    }704    let id = path.into_inner();705    let item_id = db706        .call(move |conn| attachments::delete(conn, &id))707        .await708        .map_err(internal)?;709    match item_id {710        Some(item_id) => Ok(redirect(&format!("/items/{item_id}"))),711        None => Ok(notice(StatusCode::NOT_FOUND, "No file with that id.")),712    }713}714715/// Splits the tag box on commas and whitespace so `rust, web` and `rust web` both work.716fn split_tags(raw: &str) -> Vec<String> {717    raw.split(|c: char| c == ',' || c.is_whitespace())718        .filter(|tag| !tag.is_empty())719        .map(str::to_owned)720        .collect()721}722723/// Reads `key=value, key=value` into a metadata object. Values are always text here.724fn parse_metadata(raw: &str) -> Result<Value, String> {725    let mut object = Map::new();726    for pair in raw727        .split(',')728        .map(str::trim)729        .filter(|pair| !pair.is_empty())730    {731        let Some((key, value)) = pair.split_once('=') else {732            return Err(format!("metadata {pair:?} should look like key=value"));733        };734        object.insert(735            key.trim().to_string(),736            Value::String(value.trim().to_string()),737        );738    }739    let metadata = Value::Object(object);740    check_metadata(&metadata)?;741    Ok(metadata)742}743744fn render_metadata(metadata: &Value) -> String {745    metadata746        .as_object()747        .map(|object| {748            object749                .iter()750                .map(|(key, value)| match value {751                    Value::String(text) => format!("{key}={text}"),752                    other => format!("{key}={other}"),753                })754                .collect::<Vec<_>>()755                .join(", ")756        })757        .unwrap_or_default()758}759760fn human_size(bytes: i64) -> String {761    const KIB: i64 = 1024;762    const MIB: i64 = KIB * 1024;763    if bytes < KIB {764        format!("{bytes} B")765    } else if bytes < MIB {766        format!("{} KiB", bytes / KIB)767    } else {768        format!("{} MiB", bytes / MIB)769    }770}771772fn display_title(item: &Item) -> String {773    if item.title.is_empty() {774        "(untitled)".to_string()775    } else {776        item.title.clone()777    }778}779780fn layout(title: &str, body: &Markup) -> Markup {781    html! {782        (DOCTYPE)783        html lang="en" {784            head {785                meta charset="utf-8";786                meta name="viewport" content="width=device-width, initial-scale=1";787                title { (title) " · cairn" }788                style { (PreEscaped(STYLE)) }789            }790            body { (body) }791        }792    }793}794795fn login_page(error: Option<&str>) -> Markup {796    layout(797        "Sign in",798        &html! {799            h1 { "cairn" }800            p.muted { "Sign in to your archive." }801            form.stack method="post" action="/login" {802                input type="text" name="username" placeholder="Username" required autofocus autocomplete="username";803                input type="password" name="password" placeholder="Password" required autocomplete="current-password";804                button type="submit" { "Sign in" }805            }806            @if let Some(error) = error {807                p.notice { (error) }808            }809        },810    )811}812813fn header(principal: &Principal) -> Markup {814    html! {815        header {816            h1 { a href="/" { "cairn" } }817            nav {818                form.inline method="get" action="/search" {819                    input type="text" name="q" placeholder="Search" aria-label="Search";820                }821                a href="/tokens" { "Tokens" }822                " "823                a href="/account" { "Account" }824                " "825                span.muted { (principal.name) }826                " "827                form.inline method="post" action="/logout" {828                    button type="submit" { "Sign out" }829                }830            }831        }832    }833}834835fn tokens_markup(principal: &Principal, tokens: &[TokenInfo], new_secret: Option<&str>) -> Markup {836    // The CLI defaults to this archive's address, so only the token needs setting.837    let connect = format!(838        "export CAIRN_TOKEN={}\ncairn whoami",839        new_secret.unwrap_or("<paste a token>")840    );841    layout(842        "Tokens",843        &html! {844            (header(principal))845            h2 { "Access tokens" }846            p.muted {847                "Tokens let scripts, agents and the CLI use the API. Send one as "848                code { "Authorization: Bearer …" }849                "."850            }851            @if let Some(secret) = new_secret {852                p { "Copy this token now. It will not be shown again:" }853                pre { (secret) }854            }855            h3 { "Set up the CLI" }856            p.muted { "Install the " code { "cairn" } " command, then point it at this archive." }857            div.copy-block {858                pre id="cli-install" { "cargo install --git https://twig.silenlocatelli.ch/silen/cairn" }859                button.copy type="button" data-target="cli-install" { "Copy install command" }860            }861            div.copy-block {862                pre id="cli-connect" { (connect) }863                button.copy type="button" data-target="cli-connect" { "Copy connect commands" }864            }865            @if new_secret.is_none() {866                p.muted { "Create a token below and this block fills in the token for you." }867            }868            script { (PreEscaped(CLI_SETUP_SCRIPT)) }869            form.stack method="post" action="/tokens" {870                input type="text" name="name" placeholder="Name, e.g. laptop" required;871                label { input type="checkbox" name="read_only"; " Read-only" }872                div { button type="submit" { "Create token" } }873            }874            @if tokens.is_empty() {875                p.muted { "No tokens yet." }876            }877            ul.items {878                @for token in tokens {879                    li {880                        strong { (token.name) }881                        " "882                        span.muted {883                            "…" (token.hint) " · " (Scope::join(&token.scopes)) " · created " (token.created_at)884                        }885                        " "886                        form.inline method="post" action=(format!("/tokens/{}/revoke", token.id)) onsubmit="return confirm('Revoke this token?')" {887                            button type="submit" { "Revoke" }888                        }889                    }890                }891            }892        },893    )894}895896fn account_markup(principal: &Principal, message: Option<&str>) -> Markup {897    layout(898        "Account",899        &html! {900            (header(principal))901            h2 { "Account" }902            p.muted { "Signed in as " (principal.name) "." }903            h3 { "Change password" }904            form.stack method="post" action="/account/password" {905                input type="password" name="current" placeholder="Current password" required autocomplete="current-password";906                input type="password" name="new_password" placeholder="New password (at least 12 characters)" required autocomplete="new-password";907                input type="password" name="confirm" placeholder="Repeat the new password" required autocomplete="new-password";908                div { button type="submit" { "Change password" } }909            }910            @if let Some(message) = message {911                p { (message) }912            }913        },914    )915}916917fn tag_links(tags: &[String]) -> Markup {918    html! {919        @for tag in tags {920            a.tag href=(format!("/search?tag={tag}")) { "#" (tag) }921        }922    }923}924925fn item_list(items: &[Item], empty_message: &str) -> Markup {926    html! {927        @if items.is_empty() {928            p.muted { (empty_message) }929        }930        ul.items {931            @for item in items {932                li {933                    a href=(format!("/items/{}", item.id)) { (display_title(item)) }934                    " "935                    span.muted { (item.updated_at) }936                    @if !item.attachments.is_empty() {937                        " "938                        span.muted { (item.attachments.len()) " file(s)" }939                    }940                    " "941                    (tag_links(&item.tags))942                }943            }944        }945    }946}947948fn paste_page(principal: &Principal, recent: &[Item]) -> Markup {949    layout(950        "Paste",951        &html! {952            (header(principal))953            @if principal.allows(Scope::Write) {954                form.stack method="post" action="/items" enctype="multipart/form-data" {955                    input type="text" name="title" placeholder="Title (optional)";956                    textarea id="paste" name="content" autofocus957                        placeholder="Paste anything: text, or an image from the clipboard" {}958                    input type="file" id="files" name="file" multiple;959                    input type="text" name="tags" placeholder="Tags, separated by commas";960                    input type="text" name="meta" placeholder="Metadata, e.g. source=slack, priority=2";961                    div { button type="submit" { "Save" } }962                }963                script { (PreEscaped(PASTE_SCRIPT)) }964            } @else {965                p.muted { "This token is read-only." }966            }967            h2 { "Recent" }968            (item_list(recent, "Nothing saved yet."))969        },970    )971}972973fn search_page(principal: &Principal, query: &str, results: &[Item]) -> Markup {974    layout(975        "Search",976        &html! {977            (header(principal))978            form.inline method="get" action="/search" {979                input type="text" name="q" value=(query) placeholder="Search";980                button type="submit" { "Search" }981            }982            h2 { "Results" }983            (item_list(results, "No matches."))984        },985    )986}987988fn item_page(principal: &Principal, item: &Item) -> Markup {989    let title = display_title(item);990    let writable = principal.allows(Scope::Write);991    layout(992        &title,993        &html! {994            (header(principal))995            h2 { (title) }996            p.muted { "Created " (item.created_at) " · updated " (item.updated_at) }997            p { (tag_links(&item.tags)) }998            @if !item.metadata.as_object().is_none_or(Map::is_empty) {999                dl.meta {1000                    @for (key, value) in item.metadata.as_object().into_iter().flatten() {1001                        dt { (key) }1002                        dd { (match value { Value::String(text) => text.clone(), other => other.to_string() }) }1003                    }1004                }1005            }1006            pre { (item.content) }1007            @if !item.attachments.is_empty() {1008                h3 { "Files" }1009                ul.files {1010                    @for file in &item.attachments {1011                        li {1012                            @if attachments::is_inline(&file.mime) {1013                                a href=(format!("/attachments/{}", file.id)) {1014                                    img.preview src=(format!("/attachments/{}", file.id)) alt=(file.filename) loading="lazy";1015                                }1016                            }1017                            a href=(format!("/attachments/{}", file.id)) { (file.filename) }1018                            " "1019                            span.muted { (human_size(file.size)) " · " (file.mime) }1020                            @if writable {1021                                " "1022                                form.inline method="post" action=(format!("/attachments/{}/delete", file.id)) {1023                                    button type="submit" { "Remove" }1024                                }1025                            }1026                        }1027                    }1028                }1029            }1030            @if writable {1031                h3 { "Edit" }1032                form.stack method="post" action=(format!("/items/{}/edit", item.id)) {1033                    input type="text" name="title" value=(item.title) placeholder="Title";1034                    textarea name="content" required { (item.content) }1035                    input type="text" name="meta" value=(render_metadata(&item.metadata)) placeholder="Metadata, e.g. source=slack, priority=2";1036                    div { button type="submit" { "Save changes" } }1037                }10381039                h3 { "Attach files" }1040                form.stack method="post" action=(format!("/items/{}/attachments", item.id)) enctype="multipart/form-data" {1041                    input type="file" name="file" multiple;1042                    div { button type="submit" { "Attach" } }1043                }10441045                h3 { "Tags" }1046                form.inline method="post" action=(format!("/items/{}/tags", item.id)) {1047                    input type="text" name="tags" placeholder="Add tags";1048                    button type="submit" { "Add" }1049                }1050                @for tag in &item.tags {1051                    " "1052                    form.inline method="post" action=(format!("/items/{}/tags/{}/delete", item.id, tag)) {1053                        button type="submit" { "remove " (tag) }1054                    }1055                }10561057                h3 { "Danger zone" }1058                form method="post" action=(format!("/items/{}/delete", item.id)) onsubmit="return confirm('Delete this item and its files?')" {1059                    button type="submit" { "Delete item" }1060                }1061            }1062        },1063    )1064}