From 9bc36e887044bd5f7eff6b4fd5b2103691d67083 Mon Sep 17 00:00:00 2001 From: Coko <91132775+coko7@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:36:09 +0100 Subject: [PATCH 1/2] feat(decrypt): add Decrypt tab and explain sharing protected content Turn /decrypt into a proper sidebar tab: a link + password form that works standalone (link field empty) or prefilled from ?url=. It accepts a raw rustypaste link or a Watari share link, stays public for recipients without an account, and keeps the signed-in sidebar for logged-in users via a new non-redirecting Option extractor. Fetch failures now get specific messages (wrong server, expired / deleted / already-opened one-shot) instead of the generic "wrong password" one, and decrypted short URLs render as a clickable http(s) link. The fetched ciphertext is cached per link, so retrying after a mistyped password no longer refetches and burns one-shot content. After an encrypted upload, paste or shorten, the success flash now shows the Watari share link (APP_BASE_URL/decrypt?url=...) instead of the raw ciphertext URL, with a short explanation of how recipients open it and a reminder to send the password over a separate channel. Co-Authored-By: lazytrek <352825308+lazytrek@users.noreply.github.com> --- CLAUDE.md | 4 +- src/routes/api.rs | 32 +++++++++++-- src/routes/decrypt.rs | 67 +++++++++++++++++++++++---- src/routes/pages.rs | 2 +- src/session.rs | 20 +++++++- static/app.css | 5 ++ static/app.js | 86 ++++++++++++++++++++++++++++++----- templates/base.html | 4 ++ templates/decrypt.html | 35 +++++++++----- templates/partials/flash.html | 7 +++ 10 files changed, 220 insertions(+), 42 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 570078b..e1e5d50 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,13 +26,13 @@ Watari is a Rust/Axum web GUI that sits in front of [rustypaste](https://github. - `config.rs` — `AppConfig::from_env()`; fails fast with a clear error if a required var is missing/invalid. - `state.rs` — `AppState` (the Axum `State`), plus `FromRef` impls so `axum_extra`'s cookie `Key` and `axum_csrf`'s `CsrfConfig` can be extracted from it. - `db.rs` — `sqlx` SQLite pool + typed query functions for `sessions`/`upload_log`. Uses the runtime query API (`sqlx::query`/`query_as`), not the `query!` macro, so there's no compile-time `DATABASE_URL` requirement. -- `session.rs` — the `UserSession` extractor (`FromRequestParts`): reads the `session_id` cookie, loads the session row, does best-effort silent OIDC token refresh, redirects to `/auth/login` on any failure. Also owns the `__oidc_state` cookie helpers (PKCE verifier/state/nonce, private/encrypted via `axum_extra::PrivateCookieJar`). +- `session.rs` — the `UserSession` extractor (`FromRequestParts`): reads the `session_id` cookie, loads the session row, does best-effort silent OIDC token refresh, redirects to `/auth/login` on any failure. `Option` (via `OptionalFromRequestParts`) never redirects, for public pages that still want the signed-in sidebar. Also owns the `__oidc_state` cookie helpers (PKCE verifier/state/nonce, private/encrypted via `axum_extra::PrivateCookieJar`). - `oidc.rs` — OIDC discovery + the `/auth/login`, `/auth/callback`, `/auth/logout` handlers. Deliberately does **not** store the built `openidconnect::CoreClient` anywhere — oauth2 5.x's typestate-encoded endpoint generics make that type impractical to name in a struct field, so it's cheaply rebuilt from plain fields (`ClientId`, discovered `ProviderMetadata`, etc.) wherever needed. - `token_map.rs` — loads `token-bindings.yaml`, resolves each `env_var`, and resolves a user's OIDC groups to a `TokenBinding` (first matching rule wins). `TokenBinding::is_admin()` is defined as "has the `delete` permission". - `rustypaste.rs` — the rustypaste HTTP client. Field names/headers here were confirmed against rustypaste's actual source, not guessed — see the "rustypaste's real API" doc comment at the top of the file before changing it. - `csrf.rs` / `csp.rs` / `ratelimit.rs` — `axum_csrf` verification helper, static CSP header middleware, and `tower_governor` layer factories. - `templates.rs` — `Tpl`, a tiny `IntoResponse` wrapper around `askama::Template::render()` (replaces the `askama_axum` crate, which no longer exists as of askama ≥0.13), and `Layout`, the struct every page template embeds as a `layout: Layout` field for the data `base.html` needs (csrf token, pbkdf2 iterations, user email, admin flag). -- `routes/` — `pages.rs` (home overview at `/home`, dashboard, upload/paste/shorten form pages; the Home diagram in `templates/home.html` is hand-aligned box-drawing text, so keep columns intact when editing it), `api.rs` (the mutating `/api/*` proxy endpoints + pagination), `decrypt.rs` (public, SSRF-guarded), `admin.rs` (token bindings viewer). +- `routes/` — `pages.rs` (home overview at `/home`, dashboard, upload/paste/shorten form pages; the Home diagram in `templates/home.html` is hand-aligned box-drawing text, so keep columns intact when editing it), `api.rs` (the mutating `/api/*` proxy endpoints + pagination), `decrypt.rs` (public, SSRF-guarded; `/decrypt` is also the "Decrypt" sidebar tab, and `share_link` builds the `/decrypt?url=…` link shown after encrypted uploads), `admin.rs` (token bindings viewer). ## Known deviations from `watari.md` diff --git a/src/routes/api.rs b/src/routes/api.rs index 580fdb5..235a20a 100644 --- a/src/routes/api.rs +++ b/src/routes/api.rs @@ -22,13 +22,29 @@ struct FlashTemplate { ok: bool, message: String, url: Option, + /// Adds the "how to open password-protected content" explanation. + protected: bool, } -fn flash_ok(message: impl Into, url: String) -> Response { +/// Success flash after an upload/paste/shorten. For encrypted content the link +/// shown is Watari's decrypt page (what recipients should open), not the raw +/// rustypaste URL, which only serves ciphertext. +fn flash_ok( + state: &AppState, + message: impl Into, + url: String, + encrypted: bool, +) -> Response { + let url = if encrypted { + super::decrypt::share_link(&state.config.app_base_url, &url) + } else { + url + }; Tpl(FlashTemplate { ok: true, message: message.into(), url: Some(url), + protected: encrypted, }) .into_response() } @@ -44,6 +60,7 @@ fn flash_err_status(status: StatusCode, message: impl Into) -> Response ok: false, message: message.into(), url: None, + protected: false, }), ) .into_response() @@ -257,7 +274,12 @@ pub async fn upload( &parsed.expire, ) .await; - flash_ok(format!("Uploaded successfully ({size})."), url) + flash_ok( + &state, + format!("Uploaded successfully ({size})."), + url, + encrypted, + ) } Err(e) => flash_err(upstream_message(e)), } @@ -331,7 +353,7 @@ pub async fn paste( &parsed.expire, ) .await; - flash_ok("Pasted successfully.", url) + flash_ok(&state, "Pasted successfully.", url, encrypted) } Err(e) => flash_err(upstream_message(e)), } @@ -386,7 +408,7 @@ pub async fn shorten( &parsed.expire, ) .await; - flash_ok("Shortened successfully.", short_url) + flash_ok(&state, "Shortened successfully.", short_url, false) } Err(e) => flash_err(upstream_message(e)), }; @@ -424,7 +446,7 @@ pub async fn shorten( &parsed.expire, ) .await; - flash_ok("Shortened successfully.", url) + flash_ok(&state, "Shortened successfully.", url, encrypted) } Err(e) => flash_err(upstream_message(e)), } diff --git a/src/routes/decrypt.rs b/src/routes/decrypt.rs index 835a3e7..13ff76e 100644 --- a/src/routes/decrypt.rs +++ b/src/routes/decrypt.rs @@ -6,9 +6,25 @@ use axum_csrf::CsrfToken; use serde::Deserialize; use crate::error::AppError; +use crate::session::UserSession; use crate::state::AppState; use crate::templates::{Layout, Tpl}; +/// The link to share for password-protected content: Watari's decrypt page +/// with the rustypaste URL prefilled, so recipients only type the password. +pub fn share_link(app_base_url: &str, paste_url: &str) -> String { + let encoded: String = url::form_urlencoded::byte_serialize(paste_url.as_bytes()).collect(); + format!( + "{}/decrypt?url={encoded}", + app_base_url.trim_end_matches('/') + ) +} + +#[derive(Deserialize)] +pub struct DecryptPageQuery { + url: Option, +} + #[derive(Deserialize)] pub struct DecryptQuery { url: String, @@ -18,29 +34,37 @@ pub struct DecryptQuery { #[template(path = "decrypt.html")] struct DecryptTemplate { layout: Layout, + /// Prefills the link field; empty when opened from the sidebar tab. url: String, } -/// `GET /decrypt?url=...` — intentionally unauthenticated (watari.md §9.3) so +/// `GET /decrypt[?url=...]` — intentionally unauthenticated (watari.md §9.3) so /// recipients without an SSO account can decrypt shared content. Renders the -/// password prompt; actual bytes are fetched client-side from `/decrypt/fetch`. +/// link + password form; actual bytes are fetched client-side from +/// `/decrypt/fetch`. Signed-in users (it's also a sidebar tab) keep their +/// normal sidebar. pub async fn page( State(state): State, + session: Option, csrf_token: CsrfToken, - Query(query): Query, + Query(query): Query, ) -> Response { - let csrf = match csrf_token.authenticity_token() { - Ok(t) => t, - Err(e) => { - return AppError::Internal(anyhow::anyhow!("csrf token error: {e}")).into_response(); - } + let layout = match &session { + Some(session) => super::pages::layout_for(&state, &csrf_token, session), + None => csrf_token + .authenticity_token() + .map(|csrf| Layout::anonymous(csrf, state.config.pbkdf2_iterations)) + .map_err(|e| anyhow::anyhow!("csrf token error: {e}")), + }; + let layout = match layout { + Ok(l) => l, + Err(e) => return AppError::Internal(e).into_response(), }; - let layout = Layout::anonymous(csrf, state.config.pbkdf2_iterations); ( csrf_token, Tpl(DecryptTemplate { layout, - url: query.url, + url: query.url.unwrap_or_default(), }), ) .into_response() @@ -90,3 +114,26 @@ pub async fn fetch(State(state): State, Query(query): Query bool { .unwrap_or(false) } -fn layout_for( +pub(crate) fn layout_for( state: &AppState, token: &CsrfToken, session: &UserSession, diff --git a/src/session.rs b/src/session.rs index 8a50f31..78be6a4 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1,4 +1,4 @@ -use axum::extract::FromRequestParts; +use axum::extract::{FromRequestParts, OptionalFromRequestParts}; use axum::http::request::Parts; use axum::response::{IntoResponse, Redirect, Response}; use axum_extra::extract::cookie::{Cookie, CookieJar, PrivateCookieJar, SameSite}; @@ -153,3 +153,21 @@ impl FromRequestParts for UserSession { }) } } + +/// `Option`: for public pages (e.g. `/decrypt`) that show the +/// signed-in sidebar when a valid session exists but must not redirect +/// anonymous visitors to login. +impl OptionalFromRequestParts for UserSession { + type Rejection = std::convert::Infallible; + + async fn from_request_parts( + parts: &mut Parts, + state: &AppState, + ) -> Result, Self::Rejection> { + Ok( + >::from_request_parts(parts, state) + .await + .ok(), + ) + } +} diff --git a/static/app.css b/static/app.css index e97f854..30d527e 100644 --- a/static/app.css +++ b/static/app.css @@ -330,6 +330,11 @@ button.copy-btn { } .flash-ok { border-color: var(--ok); } +.flash-hint { font-size: 0.9rem; opacity: 0.85; line-height: 1.5; } + +.page-intro { max-width: 42rem; line-height: 1.55; opacity: 0.85; } +#decrypt-result { margin-top: 1rem; } +#decrypt-result pre { white-space: pre-wrap; word-break: break-word; } .flash-error { border-color: var(--danger); } .flash-url { diff --git a/static/app.js b/static/app.js index 99a0ba6..5c1f8be 100644 --- a/static/app.js +++ b/static/app.js @@ -330,30 +330,83 @@ document.addEventListener( ); // --- Decrypt page --- +// One-shot content can only be fetched once, so the ciphertext of the last +// fetched link is kept and reused when the user retries another password. +let fetchedEnvelope = null; // { link, bytes } + +// Accepts a raw rustypaste link or a Watari share link (…/decrypt?url=…). +function pasteLinkFrom(value) { + const trimmed = value.trim(); + try { + const u = new URL(trimmed); + if (u.origin === location.origin && u.pathname === "/decrypt" && u.searchParams.has("url")) { + return u.searchParams.get("url"); + } + } catch { + // Not a URL; /decrypt/fetch rejects it with a clear status. + } + return trimmed; +} + +async function fetchEnvelope(link) { + if (fetchedEnvelope?.link === link) return fetchedEnvelope.bytes; + let resp; + try { + resp = await fetch(`/decrypt/fetch?url=${encodeURIComponent(link)}`); + } catch { + throw new Error("Could not reach Watari. Check your connection and try again."); + } + if (resp.status === 400) { + throw new Error("That link doesn't point at this Watari's paste server."); + } + if (!resp.ok) { + throw new Error( + `Could not fetch the content (${resp.status}). It may have expired, been deleted, ` + + "or been a one-shot link that was already opened.", + ); + } + const bytes = new Uint8Array(await resp.arrayBuffer()); + fetchedEnvelope = { link, bytes }; + return bytes; +} + document.addEventListener("submit", async (e) => { const form = e.target; if (form.id !== "decrypt-form") return; e.preventDefault(); - const appEl = document.getElementById("decrypt-app"); const resultEl = document.getElementById("decrypt-result"); + if (!resultEl) return; + const link = pasteLinkFrom(form.querySelector("#decrypt-link")?.value ?? ""); const password = form.querySelector("#decrypt-password")?.value ?? ""; - if (resultEl) resultEl.textContent = "Decrypting…"; + resultEl.textContent = "Decrypting…"; + let envelope; try { - const resp = await fetch(appEl.dataset.fetchUrl); - if (!resp.ok) throw new Error(`could not fetch the paste (${resp.status})`); - const envelope = new Uint8Array(await resp.arrayBuffer()); - const plaintext = await decryptEnvelope(password, envelope); - renderDecrypted(resultEl, plaintext); + envelope = await fetchEnvelope(link); + } catch (err) { + renderFlash(resultEl, false, err.message); + return; + } + try { + renderDecrypted(resultEl, await decryptEnvelope(password, envelope)); } catch { - if (resultEl) { - resultEl.innerHTML = - '

Decryption failed: wrong password, or this isn\'t a Watari encrypted link.

'; - } + renderFlash(resultEl, false, "Decryption failed: wrong password, or this isn't Watari-encrypted content."); } }); +// Decrypted short URLs are a single http(s) URL; anything else stays plain text. +function asHttpUrl(text) { + const trimmed = text.trim(); + if (/\s/.test(trimmed)) return null; + try { + const u = new URL(trimmed); + return u.protocol === "http:" || u.protocol === "https:" ? u : null; + } catch { + return null; + } +} + function renderDecrypted(container, bytes) { if (!container) return; container.replaceChildren(); @@ -365,7 +418,16 @@ function renderDecrypted(container, bytes) { // Not valid UTF-8 text; treat as binary. } - if (text !== null) { + const url = text !== null ? asHttpUrl(text) : null; + if (url) { + const a = document.createElement("a"); + a.href = url.href; + a.rel = "noopener noreferrer"; + a.textContent = url.href; + const p = document.createElement("p"); + p.append("Decrypted link: ", a); + container.appendChild(p); + } else if (text !== null) { const pre = document.createElement("pre"); pre.textContent = text; container.appendChild(pre); diff --git a/templates/base.html b/templates/base.html index 2ae403b..081a7e6 100644 --- a/templates/base.html +++ b/templates/base.html @@ -38,6 +38,10 @@ Shorten + + + Decrypt + {% if layout.is_admin %} diff --git a/templates/decrypt.html b/templates/decrypt.html index dbe51be..d3f55da 100644 --- a/templates/decrypt.html +++ b/templates/decrypt.html @@ -3,15 +3,28 @@ {% block title %}Decrypt — Watari{% endblock %} {% block content %} -

Decrypt a shared paste

-
-
-
- - -
- -
-
-
+

Open protected content

+

+ Paste a link to password-protected content and enter its password. Everything is + decrypted here in your browser: the password never leaves this page. +

+
+
+ + +
+
+ + +
+

+ One-shot links can only be opened once, so keep this page open until the content shows. + A mistyped password is fine: retrying doesn't fetch the content again. +

+ +
+
{% endblock %} diff --git a/templates/partials/flash.html b/templates/partials/flash.html index 0de083c..abb14b6 100644 --- a/templates/partials/flash.html +++ b/templates/partials/flash.html @@ -1,5 +1,12 @@

{{ message }}

+ {% if protected %} +

+ This content is password-protected. Share the link below: the recipient opens it, + enters the password, and the content is decrypted in their browser, no account needed. + Send the password through a different channel than the link (a call, another chat). +

+ {% endif %} {% if let Some(url) = url %}
From 0c3fe2b72cfd9eed1ab9a6ca4c57e7d46cba0eee Mon Sep 17 00:00:00 2001 From: Coko <91132775+coko7@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:38:39 +0100 Subject: [PATCH 2/2] feat(dashboard): copy share link for encrypted items For password-protected rows, the dashboard's Copy button and link now use the Watari share link (APP_BASE_URL/decrypt?url=...) instead of the raw rustypaste URL, which only serves ciphertext. The link text still shows the rustypaste URL to identify the item; unencrypted rows are unchanged. Co-Authored-By: lazytrek <352825308+lazytrek@users.noreply.github.com> --- src/routes/pages.rs | 18 +++++++++++++++--- templates/partials/paste_row.html | 4 ++-- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/routes/pages.rs b/src/routes/pages.rs index ee74194..25f1004 100644 --- a/src/routes/pages.rs +++ b/src/routes/pages.rs @@ -18,6 +18,9 @@ pub struct UploadRowView { pub id: String, pub display_name: String, pub paste_url: String, + /// What to share/open: the Watari decrypt page for encrypted items (the + /// raw rustypaste URL only serves ciphertext), `paste_url` otherwise. + pub share_url: String, pub encrypted: bool, /// RFC 3339 (UTC); `static/app.js` turns it into "14:05" / "3 days ago" in /// the viewer's timezone. @@ -94,20 +97,29 @@ pub async fn load_section_page( SectionPage { has_more: db_rows.len() as i64 == PAGE_SIZE, next_cursor: db_rows.last().map(|r| r.created_at), - rows: db_rows.iter().map(UploadRowView::from).collect(), + rows: db_rows + .iter() + .map(|row| UploadRowView::new(row, &state.config.app_base_url)) + .collect(), } } -impl From<&db::UploadLogRow> for UploadRowView { - fn from(row: &db::UploadLogRow) -> Self { +impl UploadRowView { + fn new(row: &db::UploadLogRow, app_base_url: &str) -> Self { let created_at_iso = OffsetDateTime::from_unix_timestamp(row.created_at) .ok() .and_then(|t| t.format(&Rfc3339).ok()) .unwrap_or_default(); + let share_url = if row.encrypted { + super::decrypt::share_link(app_base_url, &row.paste_url) + } else { + row.paste_url.clone() + }; Self { id: row.id.clone(), display_name: row.display_name.clone(), paste_url: row.paste_url.clone(), + share_url, encrypted: row.encrypted, created_at_iso, } diff --git a/templates/partials/paste_row.html b/templates/partials/paste_row.html index dda6eba..e703267 100644 --- a/templates/partials/paste_row.html +++ b/templates/partials/paste_row.html @@ -1,10 +1,10 @@ {% for row in rows %} {{ row.display_name }}{% if row.encrypted %} encrypted{% endif %} - {{ row.paste_url }} + {{ row.paste_url }} - + {% if can_delete %}