Share an episode as a page, on ipx-play (#447)

Share handed over the raw file address or the item's link: no preview,
no time, nothing a person without iPX could do much with. Now, as
Overcast does, an episode shares as a short link to its own page,
play.ipxreader.app/e/<id>, which anyone can open: the show's art and
name, the episode's title, date, length and notes, a player on the
publisher's own file starting at ?t= if a time was shared, buttons to
subscribe in Apple Podcasts, Overcast, Pocket Casts or Castro, and Open
Graph tags for a preview where the link is pasted.

ipx-play is a service of its own (crates/play), built like the
directory: ipx sends it the episode with its token (POST /v1/shares)
and gets the link back. The id comes from the feed's address and the
guid, so the same episode is one link whoever shares it. Only episodes
of feeds the directory would be sent go there, by the directory's own
rule (snapshot_entries), so the two cannot disagree on what is private;
ipx-play also refuses an address that looks private. Anything else, and
any server without ipx-play set up, shares as before.

In the page, Share on an episode opens a menu once the link is back:
Share link, Share from 12:34 (the player's clock, or where you left
off), Copy link. A menu because the share sheet needs a press of its
own, and the request for the link used up the one that opened it.

The page runs no script: the start time is the media fragment #t=, and
its CSP loads nothing but its stylesheet, the art and the file.

Admin, Directory, Sharing episodes sets the address and token. The
browser suite starts its own ipx-play; it was not run here (no Caddy on
this Mac).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ray Slakinski
2026-11-13 09:24:18 -05:00
parent 171c77475a
commit 679a674fc9
32 changed files with 1595 additions and 24 deletions

316
crates/play/src/lib.rs Normal file
View File

@@ -0,0 +1,316 @@
//! `ipx-play` (#447): the page a shared episode opens, at `play.ipxreader.app/e/<id>`, as
//! Overcast's links do. When someone shares an episode, their ipx server sends it here with its
//! token and gets back a short link; anyone with the link sees the episode, its show and its
//! notes, and plays it from the publisher's own file, from the time it was shared at if it was.
//!
//! Only public episodes come here: ipx sends none from a private or paid feed, and this refuses
//! an address that looks like one (`ipx_feed::url_looks_private`), which would hand out the
//! sharer's subscription. The files stay the publisher's; this keeps what an episode is and where
//! its file is, nothing more.
pub mod config;
mod page;
pub mod store;
use axum::extract::{Path, Query, Request, State};
use axum::http::{StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Extension, Json, Router};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Instant;
use tracing::Instrument;
/// An episode as ipx sends it to be shared.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Episode {
pub feed_url: String,
pub guid: String,
pub feed_title: Option<String>,
pub feed_image: Option<String>,
pub title: Option<String>,
/// The feed's own HTML for it, sanitized here when the page is drawn.
pub description: Option<String>,
pub link: Option<String>,
/// Unix seconds.
pub published: Option<i64>,
/// Seconds.
pub duration: Option<i64>,
/// The publisher's file, which the page plays.
pub audio_url: String,
pub mime: Option<String>,
}
/// What ipx gets back: the link to hand on, to which it adds `?t=` for a time.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Shared {
pub id: String,
pub url: String,
}
/// An episode kept, by its id.
#[derive(Debug, Clone)]
pub struct Share {
pub id: String,
pub episode: Episode,
}
/// Longer than any real one, short enough that nobody keeps a book here.
const MAX_TEXT: usize = 100_000;
const MAX_SHORT: usize = 2_000;
impl Episode {
/// What makes an episode unfit to keep, in words for whoever sent it; None when it is fine.
/// Over-long text is cut to fit rather than refused: a show's notes can be long.
fn check(&mut self) -> Option<&'static str> {
let web = |u: &str| url::Url::parse(u).is_ok_and(|u| matches!(u.scheme(), "http" | "https"));
if !web(&self.feed_url) || !web(&self.audio_url) {
return Some("the feed and its file need http(s) addresses");
}
if ipx_feed::url_looks_private(&self.feed_url) || ipx_feed::url_looks_private(&self.audio_url) {
return Some("that looks like a private or paid feed, whose addresses carry someone's access");
}
if self.guid.trim().is_empty() || self.guid.len() > MAX_SHORT {
return Some("an episode needs its guid");
}
if self.feed_image.as_deref().is_some_and(|u| !web(u)) {
self.feed_image = None;
}
if self.link.as_deref().is_some_and(|u| !web(u)) {
self.link = None;
}
for (s, max) in
[(&mut self.title, MAX_SHORT), (&mut self.feed_title, MAX_SHORT), (&mut self.description, MAX_TEXT)]
{
if let Some(t) = s
&& t.len() > max
{
let mut end = max;
while !t.is_char_boundary(end) {
end -= 1;
}
t.truncate(end);
}
}
None
}
}
/// What every request shares.
pub struct Play {
pub store: store::Store,
pub tokens: Vec<config::Token>,
pub base: String,
}
type St = Arc<Play>;
pub fn router(play: Play) -> Router {
let st = Arc::new(play);
let api = Router::new()
.route("/v1/shares", post(share))
.layer(axum::middleware::from_fn_with_state(st.clone(), authenticate));
Router::new()
.route("/healthz", get(healthz))
.route("/e/{id}", get(episode_page))
.route("/play.css", get(|| async { page::asset("text/css; charset=utf-8", include_bytes!("play.css")) }))
.route("/logo.svg", get(|| async { page::asset("image/svg+xml", include_bytes!("../../../web/logo.svg")) }))
.route("/favicon.png", get(|| async { page::asset("image/png", include_bytes!("../../../web/favicon.png")) }))
.merge(api)
.fallback(|| async { page::not_found() })
.layer(axum::middleware::from_fn(access_log))
.with_state(st)
}
/// Which server made the request, for the log and the share, set by `authenticate`.
#[derive(Clone)]
struct Who(String);
async fn authenticate(State(st): State<St>, mut req: Request, next: Next) -> Response {
let presented = req
.headers()
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.map(str::trim)
.filter(|t| !t.is_empty());
let who = presented.and_then(|t| {
let h = ipx_directory::config::hash(t);
st.tokens.iter().find(|k| ipx_directory::config::same_secret(&k.sha256, &h)).map(|k| k.name.clone())
});
let Some(who) = who else {
return error(StatusCode::UNAUTHORIZED, "a valid token is needed: Authorization: Bearer <token>");
};
req.extensions_mut().insert(Who(who.clone()));
let mut resp = next.run(req).await;
resp.extensions_mut().insert(Who(who));
resp
}
fn error(status: StatusCode, msg: &str) -> Response {
(status, Json(serde_json::json!({ "error": msg }))).into_response()
}
#[tracing::instrument(name = "share", skip_all, fields(server = %who.0))]
async fn share(State(st): State<St>, Extension(who): Extension<Who>, Json(mut e): Json<Episode>) -> Response {
if let Some(why) = e.check() {
return error(StatusCode::UNPROCESSABLE_ENTITY, why);
}
match st.store.put(&who.0, &e).await {
Ok(id) => {
tracing::info!(server = %who.0, id = %id, "an episode was shared");
Json(Shared { url: format!("{}/e/{id}", st.base), id }).into_response()
}
Err(err) => {
tracing::error!(error = %format!("{err:#}"), "keeping a share failed");
error(StatusCode::INTERNAL_SERVER_ERROR, "it could not be kept; ipx-play's log says why")
}
}
}
#[derive(Deserialize)]
struct At {
/// Where to start: seconds, or as written, `12:34` or `1:02:03`.
t: Option<String>,
}
async fn episode_page(State(st): State<St>, Path(id): Path<String>, Query(at): Query<At>) -> Response {
match st.store.get(&id).instrument(tracing::info_span!("step", of = "get_share")).await {
Ok(Some(s)) => page::episode(&s, at.t.as_deref().and_then(page::parse_time), &st.base),
Ok(None) => page::not_found(),
Err(err) => {
tracing::error!(error = %format!("{err:#}"), "reading a share failed");
page::failed()
}
}
}
async fn healthz(State(st): State<St>) -> Response {
match st.store.ping().await {
Ok(()) => (StatusCode::OK, "ok").into_response(),
Err(e) => (StatusCode::SERVICE_UNAVAILABLE, format!("database: {e:#}")).into_response(),
}
}
/// A span a request, joined to the caller's trace when it sent a traceparent, as ipx does on its
/// calls here; and a line, with the server's name and never its token.
async fn access_log(req: Request, next: Next) -> Response {
let (method, path) = (req.method().clone(), req.uri().path().to_owned());
let start = Instant::now();
let span = if path == "/healthz" {
tracing::Span::none()
} else {
tracing::info_span!(
"http",
otel.name = %format!("{method} {}", if path.starts_with("/e/") { "/e/{id}" } else { path.as_str() }),
http.request.method = %method,
url.path = %path,
http.response.status_code = tracing::field::Empty,
)
};
if let Some(parent) = ipx_directory::otel::remote_parent(req.headers(), None) {
use tracing_opentelemetry::OpenTelemetrySpanExt;
let _ = span.set_parent(parent);
}
let resp = next.run(req).instrument(span.clone()).await;
let status = resp.status().as_u16();
span.record("http.response.status_code", status);
if path != "/healthz" {
let _in = span.enter();
let who = resp.extensions().get::<Who>().map_or("", |w| w.0.as_str()).to_owned();
tracing::info!(
target: "ipx_play::http",
method = %method, path = %path, status, duration_ms = start.elapsed().as_millis() as u64, token = %who,
"{method} {path} -> {status}"
);
}
resp
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::Body;
use tower::ServiceExt;
const TOKEN: &str = "ipxd_test";
async fn app() -> Router {
router(Play {
store: store::Store::scratch().await,
tokens: vec![config::Token { name: "tower".into(), sha256: ipx_directory::config::hash(TOKEN) }],
base: "https://play.test".into(),
})
}
fn episode() -> Episode {
Episode {
feed_url: "https://example.com/feed.xml".into(),
guid: "ep-1".into(),
feed_title: Some("A Show".into()),
feed_image: Some("https://example.com/art.jpg".into()),
title: Some("Episode <One>".into()),
description: Some("<p>Notes</p><script>alert(1)</script>".into()),
link: Some("javascript:alert(1)".into()),
published: Some(1_800_000_000),
duration: Some(3600),
audio_url: "https://example.com/ep1.mp3".into(),
mime: Some("audio/mpeg".into()),
}
}
async fn post(app: &Router, token: Option<&str>, e: &Episode) -> (StatusCode, serde_json::Value) {
let mut req = axum::http::Request::post("/v1/shares").header("content-type", "application/json");
if let Some(t) = token {
req = req.header("authorization", format!("Bearer {t}"));
}
let resp = app.clone().oneshot(req.body(Body::from(serde_json::to_vec(e).unwrap())).unwrap()).await.unwrap();
let status = resp.status();
let body = axum::body::to_bytes(resp.into_body(), 1 << 20).await.unwrap();
(status, serde_json::from_slice(&body).unwrap_or_default())
}
async fn get(app: &Router, path: &str) -> (StatusCode, String) {
let resp = app.clone().oneshot(axum::http::Request::get(path).body(Body::empty()).unwrap()).await.unwrap();
let status = resp.status();
let body = axum::body::to_bytes(resp.into_body(), 1 << 20).await.unwrap();
(status, String::from_utf8_lossy(&body).into_owned())
}
#[tokio::test]
async fn a_server_with_a_token_makes_a_link_and_anyone_opens_it() {
let app = app().await;
assert_eq!(post(&app, None, &episode()).await.0, StatusCode::UNAUTHORIZED);
assert_eq!(post(&app, Some("wrong"), &episode()).await.0, StatusCode::UNAUTHORIZED);
let (status, body) = post(&app, Some(TOKEN), &episode()).await;
assert_eq!(status, StatusCode::OK);
let url = body["url"].as_str().unwrap();
assert!(url.starts_with("https://play.test/e/"), "{url}");
let path = url.trim_start_matches("https://play.test");
let (status, html) = get(&app, &format!("{path}?t=12:34")).await;
assert_eq!(status, StatusCode::OK);
assert!(html.contains("Episode &lt;One&gt;"), "the title, escaped");
assert!(html.contains("ep1.mp3#t=754"), "the player starts at the time shared");
assert!(html.contains("Starts at 12:34"));
assert!(html.contains(r#"property="og:title""#), "a link preview");
assert!(!html.contains("<script>alert"), "the notes are sanitized");
assert!(!html.contains("javascript:"), "a link that is not a web address is dropped");
assert_eq!(get(&app, "/e/nothere").await.0, StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn a_private_feed_is_refused() {
let app = app().await;
let mut e = episode();
e.feed_url = "https://www.patreon.com/rss/show?auth=secret".into();
assert_eq!(post(&app, Some(TOKEN), &e).await.0, StatusCode::UNPROCESSABLE_ENTITY);
let mut e = episode();
e.audio_url = "file:///etc/passwd".into();
assert_eq!(post(&app, Some(TOKEN), &e).await.0, StatusCode::UNPROCESSABLE_ENTITY);
}
}