rustango_cms/preview_url.rs
1//! Preview a draft in a **decoupled renderer**.
2//!
3//! `preview_token` mints a signed token and `/api/v2/pages/{id}/` accepts
4//! it, so the machinery for reading a draft over the API already worked.
5//! What was missing was the hand-off: the mint endpoint lives inside the
6//! session-gated admin, so the only way an editor could use it was to
7//! copy a token out by hand. In practice that meant decoupled sites had
8//! no preview at all.
9//!
10//! This closes it. A tenant configures where its frontend lives, and the
11//! page editor gains a link that carries a fresh token to it. The
12//! frontend reads the token, calls the API with `?preview_token=`, and
13//! renders the draft with its own templates.
14//!
15//! ## The contract with the frontend
16//!
17//! The configured value is a **URL template**. Each placeholder is
18//! substituted and percent-encoded:
19//!
20//! | Placeholder | Value |
21//! |---|---|
22//! | `{token}` | the signed preview token |
23//! | `{path}` | the page's public URL path, e.g. `/docs/intro` — its `/` separators are **kept**, so the placeholder works in the path position (`https://app.example.com{path}`) as well as in a query value |
24//! | `{id}` | the page id |
25//!
26//! ```text
27//! https://app.example.com/api/preview?token={token}&path={path}
28//! ```
29//!
30//! A value with **no** placeholder is treated as a base URL and the
31//! parameters are appended as a query string — so the simplest possible
32//! configuration (`https://app.example.com/preview`) also works, and an
33//! editor who pastes a bare URL is not left wondering why nothing
34//! happens.
35//!
36//! ## When one page does not follow the pattern
37//!
38//! Substituting `{path}` with the CMS's `url_path` assumes the frontend
39//! mirrors the CMS's URL structure. Many do not — `/features/ai-engine`
40//! here can be `/product/ai-engine` there, or `/p/9`, or a different app
41//! altogether. [`Page::preview_path`](crate::page::Page::preview_path)
42//! overrides it per page, and [`for_page`] is where the two meet.
43
44use crate::widget::{Widget, WidgetKind};
45
46/// The site-settings scope holding the frontend's preview entry point.
47pub const SCOPE: &str = "preview";
48/// The field within that scope.
49pub const FIELD: &str = "base_url";
50
51crate::register_site_setting!(SCOPE, "Headless preview", || vec![Widget::new(
52 WidgetKind::Text,
53 FIELD,
54 "Frontend preview URL",
55)
56.with_help(
57 "Where the page editor's “Preview on site” link sends an editor, for \
58 sites rendered by a separate frontend. Use {token}, {path} and {id} \
59 as placeholders — e.g. https://app.example.com/api/preview?token={token}&path={path}. \
60 A plain URL with no placeholders gets them appended as query \
61 parameters. Leave empty when the CMS renders the site itself.",
62)]);
63
64/// Build the URL an editor should be sent to, or `None` when the tenant
65/// has not configured a frontend.
66///
67/// `base` is the raw configured value; blank counts as unconfigured, so
68/// an editor who clears the field turns the feature off rather than
69/// getting a link to nowhere.
70#[must_use]
71pub fn build(base: &str, token: &str, page_id: i64, url_path: &str) -> Option<String> {
72 let base = base.trim();
73 if base.is_empty() {
74 return None;
75 }
76 let path = if url_path.is_empty() { "/" } else { url_path };
77 let id = page_id.to_string();
78
79 let has_placeholder =
80 base.contains("{token}") || base.contains("{path}") || base.contains("{id}");
81 if has_placeholder {
82 return Some(
83 base.replace("{token}", &encode(token))
84 .replace("{path}", &encode_path(path))
85 .replace("{id}", &encode(&id)),
86 );
87 }
88
89 // No template: append. Respect a base that already carries a query.
90 let sep = if base.contains('?') { '&' } else { '?' };
91 Some(format!(
92 "{base}{sep}token={}&path={}&id={}",
93 encode(token),
94 encode_path(path),
95 encode(&id),
96 ))
97}
98
99/// Percent-encode a value for use in a query string.
100///
101/// Hand-rolled for the same reason `view_restriction_guard` does it: the
102/// framework vends no encoder on its public surface, and pulling a crate
103/// in for three call sites is not worth it. Unreserved characters per
104/// RFC 3986 pass through; everything else, including `/`, is escaped —
105/// the path is a *parameter value* here, not a path segment.
106/// The preview URL for one page: the site-wide template, the page's own
107/// override, or nothing.
108///
109/// Three cases, in the order an editor would expect:
110///
111/// 1. the page's `preview_path` is an **absolute URL** — that page is
112/// rendered by something else entirely, so it wins outright and works
113/// even when no site-wide frontend is configured;
114/// 2. the page's `preview_path` is a **path** — the site template still
115/// supplies the host and the token, and this replaces `{path}`;
116/// 3. it is **empty** — `url_path`, which is the common case.
117///
118/// Returns `None` when there is nothing to link to: no site template and
119/// no absolute override.
120#[must_use]
121pub fn for_page(
122 site_base: Option<&str>,
123 page_override: &str,
124 token: &str,
125 page_id: i64,
126 url_path: &str,
127) -> Option<String> {
128 let over = page_override.trim();
129 if is_absolute(over) {
130 // `{path}` inside an absolute override still resolves, so a page
131 // can point at another host and keep the templating.
132 return build(over, token, page_id, url_path);
133 }
134 let base = site_base?;
135 let path = if over.is_empty() { url_path } else { over };
136 build(base, token, page_id, path)
137}
138
139/// Whether a per-page value names a whole URL rather than a path.
140///
141/// Scheme-relative (`//host/x`) is deliberately *not* absolute here: it
142/// is far more likely to be a typo'd path than a deliberate
143/// protocol-relative URL, and treating it as a whole URL would silently
144/// drop the configured host.
145fn is_absolute(raw: &str) -> bool {
146 let lower = raw.trim().to_ascii_lowercase();
147 lower.starts_with("http://") || lower.starts_with("https://")
148}
149
150/// Percent-encode a **path**, keeping its `/` separators.
151///
152/// `{path}` is routinely placed in the path position — a frontend
153/// configured as `https://app.example.com{path}?token={token}` is the
154/// most natural template there is. Escaping the separators turned that
155/// into `https://app.example.com%2Fdocs%2Fintro`, whose authority is
156/// nonsense and which no browser can follow.
157///
158/// Keeping `/` is also correct in the query position: RFC 3986 permits
159/// `/` unescaped in a query component, so one encoding serves both and
160/// there is no need to ask the author which one they meant.
161fn encode_path(raw: &str) -> String {
162 raw.split('/').map(encode).collect::<Vec<_>>().join("/")
163}
164
165fn encode(raw: &str) -> String {
166 let mut out = String::with_capacity(raw.len());
167 for b in raw.bytes() {
168 if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
169 out.push(char::from(b));
170 } else {
171 out.push_str(&format!("%{b:02X}"));
172 }
173 }
174 out
175}
176
177/// Read the configured frontend URL for this tenant, if any.
178///
179/// # Errors
180/// Driver / query failures.
181pub async fn configured_base(
182 pool: &rustango::sql::Pool,
183) -> Result<Option<String>, rustango::sql::ExecError> {
184 Ok(crate::site_setting::get(pool, SCOPE)
185 .await?
186 .and_then(|row| {
187 row.value_json
188 .get(FIELD)
189 .and_then(|v| v.as_str())
190 .map(str::to_owned)
191 })
192 .filter(|s| !s.trim().is_empty()))
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198
199 #[test]
200 fn an_unconfigured_tenant_gets_no_link() {
201 // Blank must mean "off", not "a link to nowhere".
202 assert_eq!(build("", "tok", 7, "/docs"), None);
203 assert_eq!(build(" ", "tok", 7, "/docs"), None);
204 }
205
206 #[test]
207 fn a_template_substitutes_every_placeholder() {
208 let got = build(
209 "https://app.example.com/api/preview?token={token}&path={path}&id={id}",
210 "abc123",
211 7,
212 "/docs/intro",
213 );
214 assert_eq!(
215 got.unwrap(),
216 "https://app.example.com/api/preview?token=abc123&path=/docs/intro&id=7",
217 );
218 }
219
220 #[test]
221 fn a_placeholder_may_appear_in_the_path_not_just_the_query() {
222 // Some frontends route previews as `/preview/<id>`.
223 let got = build("https://app.example.com/preview/{id}?t={token}", "abc", 42, "/x");
224 assert_eq!(got.unwrap(), "https://app.example.com/preview/42?t=abc");
225 }
226
227 #[test]
228 fn path_in_the_path_position_keeps_its_separators() {
229 // The template a decoupled site actually configures. Escaping the
230 // separators produced `http://host%2Ffeatures%2Fai-engine`, whose
231 // authority is nonsense — and the test above missed it because
232 // `{id}` is a bare number that encoding cannot change.
233 let got = build(
234 "http://localhost:5173{path}?token={token}",
235 "9.123.abc",
236 9,
237 "/features/ai-engine",
238 );
239 assert_eq!(
240 got.unwrap(),
241 "http://localhost:5173/features/ai-engine?token=9.123.abc",
242 );
243 }
244
245 #[test]
246 fn a_path_segment_that_would_break_the_url_is_still_escaped() {
247 // Only the separators are spared; anything inside a segment that
248 // would end the path or start a fragment must not survive raw.
249 let got = build("https://x.test{path}", "t", 1, "/a b/c?d#e").unwrap();
250 assert_eq!(got, "https://x.test/a%20b/c%3Fd%23e");
251 }
252
253 #[test]
254 fn a_plain_base_url_gets_the_parameters_appended() {
255 // The simplest configuration an editor might paste.
256 let got = build("https://app.example.com/preview", "abc", 7, "/docs");
257 assert_eq!(
258 got.unwrap(),
259 "https://app.example.com/preview?token=abc&path=/docs&id=7",
260 );
261 }
262
263 #[test]
264 fn an_existing_query_string_is_preserved() {
265 let got = build("https://app.example.com/preview?mode=draft", "abc", 7, "/x");
266 assert_eq!(
267 got.unwrap(),
268 "https://app.example.com/preview?mode=draft&token=abc&path=/x&id=7",
269 );
270 }
271
272 #[test]
273 fn the_root_page_previews_as_slash() {
274 // `url_path` is stored empty for the root; sending an empty
275 // `path=` would leave the frontend guessing.
276 let got = build("https://app.example.com/p", "abc", 1, "");
277 assert!(got.unwrap().contains("path=/&"), "root must still send a path");
278 }
279
280 #[test]
281 fn a_token_with_url_specials_survives_the_round_trip() {
282 // Tokens are base64url plus `.`, all of which must arrive intact.
283 let got = build("https://x.test/p?t={token}", "a.b-c_d~e", 1, "/x").unwrap();
284 assert!(got.ends_with("t=a.b-c_d~e"), "got {got}");
285 }
286
287 #[test]
288 fn a_page_without_an_override_follows_its_url_path() {
289 let got = for_page(Some("https://app.test{path}?t={token}"), "", "tok", 9, "/features/ai");
290 assert_eq!(got.unwrap(), "https://app.test/features/ai?t=tok");
291 }
292
293 #[test]
294 fn a_page_path_override_replaces_only_the_path() {
295 // The frontend routes this page differently, but the host and
296 // the token still come from the one site-wide template.
297 let got = for_page(
298 Some("https://app.test{path}?t={token}"),
299 "/product/ai-engine",
300 "tok",
301 9,
302 "/features/ai",
303 );
304 assert_eq!(got.unwrap(), "https://app.test/product/ai-engine?t=tok");
305 }
306
307 #[test]
308 fn an_absolute_override_wins_outright() {
309 // "This page is rendered by a different app."
310 let got = for_page(
311 Some("https://app.test{path}?t={token}"),
312 "https://other.test/x?t={token}",
313 "tok",
314 9,
315 "/features/ai",
316 );
317 assert_eq!(got.unwrap(), "https://other.test/x?t=tok");
318 }
319
320 #[test]
321 fn an_absolute_override_works_with_no_site_template_at_all() {
322 // The whole point of the case: one page lives elsewhere, and the
323 // tenant has configured no site-wide frontend.
324 let got = for_page(None, "https://other.test/x?t={token}", "tok", 9, "/a");
325 assert_eq!(got.unwrap(), "https://other.test/x?t=tok");
326 }
327
328 #[test]
329 fn no_template_and_no_override_is_no_link() {
330 assert_eq!(for_page(None, "", "tok", 9, "/a"), None);
331 assert_eq!(for_page(None, " ", "tok", 9, "/a"), None);
332 // A *path* override cannot stand on its own — it has no host.
333 assert_eq!(for_page(None, "/product/x", "tok", 9, "/a"), None);
334 }
335
336 #[test]
337 fn an_override_is_trimmed_before_it_is_judged() {
338 let got = for_page(Some("https://app.test{path}"), " /p/9 ", "t", 9, "/a");
339 assert_eq!(got.unwrap(), "https://app.test/p/9");
340 }
341
342 #[test]
343 fn scheme_relative_is_treated_as_a_path_not_a_url() {
344 // `//host/x` is far more likely a typo'd path than a deliberate
345 // protocol-relative URL; treating it as absolute would silently
346 // drop the configured host.
347 assert!(!is_absolute("//other.test/x"));
348 let got = for_page(Some("https://app.test{path}"), "//other.test/x", "t", 9, "/a");
349 assert_eq!(got.unwrap(), "https://app.test//other.test/x");
350 }
351
352 #[test]
353 fn an_absolute_override_is_recognised_case_insensitively() {
354 assert!(is_absolute("HTTPS://other.test/x"));
355 assert!(is_absolute("Http://other.test/x"));
356 assert!(!is_absolute("ftp://other.test/x"));
357 }
358
359 #[test]
360 fn encoding_escapes_what_would_break_a_query() {
361 assert_eq!(encode("/a b&c=d?e#f"), "%2Fa%20b%26c%3Dd%3Fe%23f");
362 assert_eq!(encode("plain-Text_1.0~"), "plain-Text_1.0~");
363 }
364}