diff --git a/Cargo.lock b/Cargo.lock index 1e7db4c..4a278d7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1036,7 +1036,7 @@ dependencies = [ ] [[package]] -name = "pastable" +name = "pastabble" version = "0.1.0" dependencies = [ "argon2", diff --git a/Cargo.toml b/Cargo.toml index c6e52aa..e75ef54 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "pastable" +name = "pastabble" version = "0.1.0" edition = "2024" diff --git a/Containerfile b/Containerfile index 41915aa..019055a 100644 --- a/Containerfile +++ b/Containerfile @@ -8,9 +8,9 @@ RUN cargo build --release --locked FROM docker.io/library/alpine:latest WORKDIR /app -COPY --from=build /app/target/release/pastable /usr/local/bin/pastable +COPY --from=build /app/target/release/pastabble /usr/local/bin/pastabble COPY static ./static ENV DATABASE_URL=sqlite:///data/pastable.db VOLUME ["/data"] EXPOSE 3000 -CMD ["pastable"] +CMD ["pastabble"] diff --git a/README.md b/README.md index a96c62e..e6c9a29 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# Pastable +# Pastabble -Pastable is a free and open-source Plabble initiative for sharing text, code, short links, and one-time secrets. +Pastabble is a free and open-source Plabble initiative for sharing text, code, short links, and one-time secrets. ## Run locally @@ -24,11 +24,11 @@ Route handlers can access the shared database pool with the `State(pool): State< ## Browser app -Open `/gui` for the browser workspace. Create text pastes, one-time secrets, and short links; choose custom IDs, languages, expiry, and view limits. After saving, a dialog prominently displays the returned link for copying or opening. Opening a share navigates directly to its page or redirect. +Open `/` for the browser workspace. Create text pastes, one-time secrets, and short links; choose custom IDs, languages, expiry, and view limits. After saving, a dialog prominently displays the returned link for copying or opening. Opening a share navigates directly to its page or redirect. -The language dropdown is populated from irosashi's supported grammars. The home page renders this README as HTML and shares the browser app's logo, navigation, and styling. +The language dropdown is populated from irosashi's supported grammars. The documentation page at `/docs` renders this README as HTML and shares the browser app's logo, navigation, and styling. -Sign in with HTTP Basic credentials to browse, filter, edit, and delete your own shares. A new username creates an account. Credentials stay in page memory and are cleared on sign-out or reload. Creating and managing shares uses the existing API without page reloads. +Sign in with HTTP Basic credentials to browse, filter, edit, and delete your own shares. A new username creates an account. Credentials are stored in localStorage to keep you signed in across page reloads and browser restarts. Signing out removes the saved credentials. Creating and managing shares uses the existing API without page reloads. Opening a paste or following a short link counts as a view. Listing records and loading them into the editor do not. Updates preserve omitted options and view counters. @@ -66,7 +66,7 @@ All paths are relative to the server URL. `{id}` is a path parameter containing **Returns:** the assigned ID as plain text. This is an ID, not a full URL. Always use the returned ID, since a requested custom ID may already be taken. -Generated IDs contain exactly 8 alphanumeric characters, generated in Rust with `rand`. Confusing characters (`0`, `1`, `I`, `L`, `O`, `i`, `l`, `o`) are excluded. IDs are shared by pastes and short links. Reserved route names (`gui`, `list`, `once`, `to`, and `static`) and IDs containing `/` are unavailable as custom IDs; these also receive a generated ID. +Generated IDs contain exactly 8 alphanumeric characters, generated in Rust with `rand`. Confusing characters (`0`, `1`, `I`, `L`, `O`, `i`, `l`, `o`) are excluded. IDs are shared by pastes and short links. Reserved route names (`docs`, `list`, `once`, `to`, and `static`) and IDs containing `/` are unavailable as custom IDs; these also receive a generated ID. Create a paste from raw text: @@ -106,7 +106,7 @@ curl --request POST 'http://localhost:3000/once/my-secret' \ HTML paste pages show the view counter, including the current read, and the maximum when set. HTML and plain-text responses include `X-Paste-Views` and, when limited, `X-Paste-Max-Views` response headers, so displaying the counter does not require another read. -The HTML page includes a **Copy raw code** button that preserves the original content and whitespace without another request or view. If clipboard access is unavailable, the raw text is selected for manual copying. +The HTML page includes a **Copy** button that preserves the original content and whitespace without another request or view. If clipboard access is unavailable, the raw text is selected for manual copying. Each successful read increments `views`. The final permitted read returns the content and deletes the paste. Missing, expired, and exhausted pastes return `404`. Expired and exhausted records are also cleaned up in the background every minute. @@ -198,4 +198,6 @@ curl --user 'alice:example-password' 'http://localhost:3000/list' ### Home page -`GET /` returns the home page. +`GET /` returns a plain-text welcome message with a link to `/docs` by default, including via curl. With `Accept: text/html`, it returns the browser workspace. + +`GET /docs` returns the README as Markdown by default, including via curl. With `Accept: text/html`, it returns the documentation page as HTML. diff --git a/src/main.rs b/src/main.rs index d151236..8c03191 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,7 +13,7 @@ mod db; mod paste; mod routes; use crate::routes::{ - delete_note, get_note, get_redirect, gui_page, home_page, list_notes, post_note, post_once, + delete_note, docs_page, get_note, get_redirect, home_page, list_notes, post_note, post_once, post_redirect, put_note, put_redirect, }; @@ -26,7 +26,7 @@ async fn main() -> Result<(), Box> { let app = Router::new() .route("/", get(home_page).post(post_note)) - .route("/gui", get(gui_page)) + .route("/docs", get(docs_page)) .route("/once", post(post_once)) .route("/once/{id}", post(post_once)) .route("/to", post(post_redirect)) diff --git a/src/routes.rs b/src/routes.rs index 50becd6..f5e9a50 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -2,9 +2,9 @@ use axum::http::{HeaderMap, header::ACCEPT}; mod create; mod delete_note; +mod docs; mod get_note; mod get_redirect; -mod gui; mod home; mod input; mod list_notes; @@ -17,9 +17,9 @@ mod put_redirect; mod update; pub use delete_note::delete_note; +pub use docs::docs_page; pub use get_note::get_note; pub use get_redirect::get_redirect; -pub use gui::gui_page; pub use home::home_page; pub use list_notes::list_notes; pub use post_note::post_note; diff --git a/src/routes/create.rs b/src/routes/create.rs index 6b5aea9..0d278dc 100644 --- a/src/routes/create.rs +++ b/src/routes/create.rs @@ -14,7 +14,7 @@ pub async fn create( paste_type: PasteType, ) -> Result { let mut id = id.map(|Path(id)| id).filter(|id| { - !matches!(id.as_str(), "gui" | "list" | "once" | "to" | "static") && !id.contains('/') + !matches!(id.as_str(), "docs" | "list" | "once" | "to" | "static") && !id.contains('/') }); if matches!(paste_type, PasteType::TextV1) && input.language.is_none() { diff --git a/src/routes/docs.rs b/src/routes/docs.rs new file mode 100644 index 0000000..8dedb93 --- /dev/null +++ b/src/routes/docs.rs @@ -0,0 +1,40 @@ +use std::sync::LazyLock; + +use askama::Template; +use askama_web::WebTemplate; +use axum::{ + http::{HeaderMap, header::CONTENT_TYPE}, + response::{IntoResponse, Response}, +}; +use pulldown_cmark::{Options, Parser, html}; + +use super::return_html; + +static README_MD: &str = include_str!("../../README.md"); + +static README_HTML: LazyLock = LazyLock::new(|| { + let parser = Parser::new_ext( + README_MD, + Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS, + ); + let mut rendered = String::new(); + html::push_html(&mut rendered, parser); + rendered +}); + +#[derive(Template, WebTemplate)] +#[template(path = "docs.html")] +pub struct DocsPage { + readme: &'static str, +} + +pub async fn docs_page(headers: HeaderMap) -> Response { + if return_html(&headers) { + DocsPage { + readme: &README_HTML, + } + .into_response() + } else { + ([(CONTENT_TYPE, "text/markdown; charset=utf-8")], README_MD).into_response() + } +} diff --git a/src/routes/gui.rs b/src/routes/gui.rs deleted file mode 100644 index 63fc514..0000000 --- a/src/routes/gui.rs +++ /dev/null @@ -1,17 +0,0 @@ -use askama::Template; -use askama_web::WebTemplate; -use axum::http::StatusCode; -use irosashi::Highlighter; - -#[derive(Template, WebTemplate)] -#[template(path = "gui.html")] -pub struct GuiPage { - languages: Vec, -} - -pub async fn gui_page() -> Result { - let highlighter = Highlighter::new().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - Ok(GuiPage { - languages: highlighter.languages(), - }) -} diff --git a/src/routes/home.rs b/src/routes/home.rs index faad15c..e91ca7d 100644 --- a/src/routes/home.rs +++ b/src/routes/home.rs @@ -1,50 +1,28 @@ -use std::sync::LazyLock; - use askama::Template; use askama_web::WebTemplate; -use pulldown_cmark::{Event, Options, Parser, Tag, html}; +use axum::{ + http::{HeaderMap, StatusCode}, + response::{IntoResponse, Response}, +}; +use irosashi::Highlighter; -static README_HTML: LazyLock = LazyLock::new(|| { - let events: Vec<_> = Parser::new_ext( - include_str!("../../README.md"), - Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS, - ) - .collect(); - let anchored = events.iter().enumerate().map(|(index, event)| { - if let Event::Start(Tag::Heading(level, None, _)) = event { - let title: String = events[index + 1..] - .iter() - .take_while(|event| !matches!(event, Event::End(Tag::Heading(..)))) - .filter_map(|event| match event { - Event::Text(text) | Event::Code(text) => Some(text.as_ref()), - _ => None, - }) - .collect(); - let slug: String = title - .to_lowercase() - .chars() - .filter(|character| { - character.is_alphanumeric() || *character == '-' || character.is_whitespace() - }) - .collect(); - let slug = slug.split_whitespace().collect::>().join("-"); - return Event::Html(format!("<{level} id=\"{slug}\">").into()); - } - event.clone() - }); - let mut rendered = String::new(); - html::push_html(&mut rendered, anchored); - rendered -}); +use super::return_html; #[derive(Template, WebTemplate)] #[template(path = "home.html")] pub struct HomePage { - readme: &'static str, + languages: Vec, } -pub async fn home_page() -> HomePage { - HomePage { - readme: &README_HTML, +pub async fn home_page(headers: HeaderMap) -> Result { + if !return_html(&headers) { + return Ok("Welcome @ Pastabble!\n\nShare text, code, short links, and one-time secrets.\nDocumentation: /docs\n".into_response()); } + + let highlighter = Highlighter::new().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + Ok(HomePage { + languages: highlighter.languages(), + } + .into_response()) } diff --git a/static/gui.js b/static/workspace.js similarity index 91% rename from static/gui.js rename to static/workspace.js index fb44f39..b47c72e 100644 --- a/static/gui.js +++ b/static/workspace.js @@ -192,16 +192,27 @@ function reference(value, url) { let id = value.trim(); if (/^(https?:\/\/|\/)/i.test(id)) { const parsed = new URL(id, location.origin); - if (parsed.origin !== location.origin) throw new Error("Use an ID or a link from this Pastable server."); + if (parsed.origin !== location.origin) throw new Error("Use an ID or a link from this Pastabble server."); url = parsed.pathname.startsWith("/to/"); id = decodeURIComponent(parsed.pathname.slice(url ? 4 : 1)); } - if (!id || id.includes("/") || ["gui", "list", "once", "to", "static"].includes(id)) { - throw new Error("Enter a valid share ID or a full Pastable share URL."); + if (!id || id.includes("/") || ["docs", "list", "once", "to", "static"].includes(id)) { + throw new Error("Enter a valid share ID or a full Pastabble share URL."); } return { id, url }; } +function setSession(username, auth, result = []) { + if (authorization !== auth) resetEditor(); + authorization = auth; + notes = result; + $("username").value = username; + $("session-label").textContent = username || "Anonymous"; + $("logout").hidden = !auth; + renderNotes(); + updateEditor(); +} + $("login-form").addEventListener("submit", event => { event.preventDefault(); busy(event.submitter, async () => { @@ -209,27 +220,18 @@ $("login-form").addEventListener("submit", event => { const credentials = new TextEncoder().encode(`${username}:${$("password").value}`); const auth = `Basic ${btoa(Array.from(credentials, byte => String.fromCharCode(byte)).join(""))}`; const result = await api("/list", { accept: "application/json" }, auth); - if (authorization && authorization !== auth) resetEditor(); - authorization = auth; - notes = result; + localStorage.setItem("pastable.session", JSON.stringify({ username, authorization: auth })); + setSession(username, auth, result); $("password").value = ""; - $("session-label").textContent = username; - $("logout").hidden = false; $("account").open = false; - renderNotes(); - updateEditor(); notify(`Signed in as ${username}. New shares will belong to your account.`); }); }); $("logout").addEventListener("click", () => { - authorization = null; - notes = []; + localStorage.removeItem("pastable.session"); $("login-form").reset(); - $("logout").hidden = true; - $("session-label").textContent = "Anonymous"; - resetEditor(); - renderNotes(); + setSession("", null); notify("Signed out."); }); @@ -305,3 +307,13 @@ window.addEventListener("hashchange", () => showPanel(location.hash.slice(1))); showPanel(location.hash.slice(1)); renderNotes(); updateEditor(); + +try { + const session = JSON.parse(localStorage.getItem("pastable.session")); + if (session && typeof session.username === "string" && typeof session.authorization === "string") { + setSession(session.username, session.authorization); + loadNotes().catch(error => notify(error.message, true)); + } +} catch { + notify("Could not restore your saved sign-in. Please sign in again.", true); +} diff --git a/templates/base.html b/templates/base.html index c57728d..2f7b5ca 100644 --- a/templates/base.html +++ b/templates/base.html @@ -3,23 +3,23 @@ - - {% block title %}Pastable{% endblock %} + + {% block title %}Pastabble{% endblock %} {% block head %}{% endblock %}
diff --git a/templates/docs.html b/templates/docs.html new file mode 100644 index 0000000..cf23650 --- /dev/null +++ b/templates/docs.html @@ -0,0 +1,8 @@ +{% extends "base.html" %} +{% block title %}Documentation · Pastabble{% endblock %} +{% block docs_nav %}aria-current="page"{% endblock %} +{% block content %} +
+ {{ readme|safe }} +
+{% endblock %} diff --git a/templates/gui.html b/templates/gui.html deleted file mode 100644 index 27c6571..0000000 --- a/templates/gui.html +++ /dev/null @@ -1,136 +0,0 @@ -{% extends "base.html" %} -{% block title %}Browser app · Pastable{% endblock %} -{% block gui_nav %}aria-current="page"{% endblock %} -{% block content %} -
-
-

YOUR SHARING WORKSPACE

-

Pastes, links & secrets.

-

A little space for things you want to pass along.

-
- Anonymous -
- - - - - - - -
-
-
-
-

Create a share

- -
-
-
- - -
- -
- -
- -
- - Shared anonymously. -
-
-
- -
-
- - - - - -

READY TO SHARE

-

Your share is ready

-

- -
- - -
-
- Open share ↗ -
-
-

Opening counts as a view. Copying the link does not.

-
- - -{% endblock %} diff --git a/templates/home.html b/templates/home.html index 9c134fd..b199edd 100644 --- a/templates/home.html +++ b/templates/home.html @@ -1,7 +1,136 @@ {% extends "base.html" %} +{% block title %}Browser app · Pastabble{% endblock %} {% block home_nav %}aria-current="page"{% endblock %} {% block content %} -
- {{ readme|safe }} -
+
+
+

YOUR SHARING WORKSPACE

+

Pastes, links & secrets.

+

A little space for things you want to pass along.

+
+ Anonymous +
+ + + + + + + +
+
+
+
+

Create a share

+ +
+
+
+ + +
+ +
+ +
+ +
+ + Shared anonymously. +
+
+
+ +
+
+ + + + + +

READY TO SHARE

+

Your share is ready

+

+ +
+ + +
+
+ Open share ↗ +
+
+

Opening counts as a view. Copying the link does not.

+
+ + {% endblock %} diff --git a/templates/list.html b/templates/list.html index d71855c..0e70479 100644 --- a/templates/list.html +++ b/templates/list.html @@ -1,5 +1,5 @@ {% extends "base.html" %} -{% block title %}Your pastes · Pastable{% endblock %} +{% block title %}Your pastes · Pastabble{% endblock %} {% block content %}

Your pastes and short links

diff --git a/templates/note.html b/templates/note.html index a1233b2..d67405d 100644 --- a/templates/note.html +++ b/templates/note.html @@ -1,12 +1,12 @@ {% extends "base.html" %} -{% block title %}{{ paste.id }} · Pastable{% endblock %} +{% block title %}{{ paste.id }} · Pastabble{% endblock %} {% block content %}

SHARED PASTE

{{ paste.id }}

Views: {{ paste.views }} / {% match paste.max_views %}{% when Some with (max) %}{{ max }}{% when None %}∞{% endmatch %}

- +
{{ code|safe }}