arcature 0.1.1

Arcature: an opinionated full-stack Rust web framework. One package, batteries included.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! The Inertia adapter configuration and root document renderer.

use std::fmt;
use std::sync::Arc;

use super::error::InertiaError;
use super::head::{Head, escape};
use super::props::SharedProps;
use crate::http::security::CspNonce;

/// The current asset version, compared against `X-Inertia-Version`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AssetVersion(Arc<str>);

impl AssetVersion {
    /// Create a validated asset version (must be header-encodable).
    pub fn new(version: impl AsRef<str>) -> Result<Self, InertiaError> {
        let version = version.as_ref();
        axum::http::HeaderValue::from_str(version)
            .map_err(axum::http::Error::from)
            .map_err(InertiaError::Header)?;
        Ok(AssetVersion(Arc::from(version)))
    }

    /// The version as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for AssetVersion {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

/// The safely-embeddable Inertia page payload.
///
/// Contains the `<script data-page="..." type="application/json">ESCAPED</script>`
/// element followed by the `<div id="...">` mount point — already escaped for
/// safe embedding. Constructed only by the adapter; applications receive it
/// in their root document renderer and embed it via `Display`.
///
/// It also carries this request's [`CspNonce`], when there is one, and the
/// [`Head`] this page asked for. That is why the type is a struct rather than
/// a `String`: each of those could be added to it without touching
/// [`RootDocument::render`], and every application that passes a plain
/// `Fn(ScriptBody) -> String` closure kept compiling. Whatever a root document
/// needs next arrives the same way.
#[derive(Debug, Clone)]
pub struct ScriptBody {
    html: Arc<str>,
    nonce: Option<CspNonce>,
    head: Option<Head>,
}

impl ScriptBody {
    pub(crate) fn from_escaped(
        html: Arc<str>,
        nonce: Option<CspNonce>,
        head: Option<Head>,
    ) -> ScriptBody {
        ScriptBody { html, nonce, head }
    }

    /// The [`Head`] this page asked for: its title, meta description,
    /// canonical URL and Open Graph and Twitter card fields, every value
    /// already HTML-escaped.
    ///
    /// `None` when the handler set none, which is the case for every
    /// application written before this existed. A root document that wants
    /// server-rendered metadata reads it here and falls back to whatever it
    /// used before; the stock [`default_root_document`] and
    /// [`vite_root_document`] do exactly that with their own `title`.
    ///
    /// This is the entire server-side SEO story and it is deliberately small.
    /// Google runs JavaScript, so a client-rendered title reaches it
    /// eventually; Facebook, Zalo, Slack, Discord, LinkedIn, Telegram and X
    /// do not run any, so whatever is not in these bytes does not exist to
    /// them. Rendering the application itself on the server would mean a
    /// JavaScript runtime in the request path, which buys nothing a scraper
    /// reads.
    ///
    /// ```
    /// use arcature::axum::body::{Body, to_bytes};
    /// use arcature::axum::http::Request;
    /// use arcature::axum::routing::get;
    /// use arcature::axum::Router;
    /// use arcature::inertia::{Head, Inertia, InertiaConfig, InertiaLayer, ScriptBody};
    /// use tower::ServiceExt as _;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let config = InertiaConfig::versionless(|body: ScriptBody| {
    ///     let title = body.head().and_then(Head::title).unwrap_or("Acme");
    ///     format!(
    ///         "<!doctype html><html><head><title>{title}</title></head>\
    ///          <body>{body}</body></html>"
    ///     )
    /// });
    ///
    /// let app = Router::new()
    ///     .route(
    ///         "/",
    ///         get(|inertia: Inertia| async move {
    ///             inertia
    ///                 .render("Home", arcature::serde_json::json!({}))
    ///                 .await
    ///                 .unwrap()
    ///         }),
    ///     )
    ///     .layer(InertiaLayer::new(config));
    ///
    /// let response = app
    ///     .oneshot(Request::get("/").body(Body::empty()).unwrap())
    ///     .await
    ///     .unwrap();
    /// let bytes = to_bytes(response.into_body(), 64 * 1024).await.unwrap();
    /// let html = String::from_utf8(bytes.to_vec()).unwrap();
    ///
    /// // Nothing set a head on this render, so the document's own title
    /// // stands -- exactly what it did before heads existed.
    /// assert!(html.contains("<title>Acme</title>"), "{html}");
    /// # }
    /// ```
    #[must_use]
    pub fn head(&self) -> Option<&Head> {
        self.head.as_ref()
    }

    /// This request's Content-Security-Policy nonce, if the application
    /// installed [`SecurityHeaders::with_csp_nonce`].
    ///
    /// The payload script this body contains already carries it. This is for
    /// the *other* elements a hand-written root document writes — its own
    /// `<script>` and `<style>` tags, an analytics snippet — which the
    /// framework cannot stamp because it never sees them.
    ///
    /// [`SecurityHeaders::with_csp_nonce`]: crate::http::security::SecurityHeaders::with_csp_nonce
    #[must_use]
    pub fn nonce(&self) -> Option<&CspNonce> {
        self.nonce.as_ref()
    }

    /// The nonce as an HTML attribute with a leading space, or the empty
    /// string when there is none.
    ///
    /// Written to be interpolated straight into a tag, which is what makes a
    /// nonce-aware root document readable:
    ///
    /// ```
    /// use arcature::inertia::{RootDocument, ScriptBody};
    ///
    /// // A root document is any `Fn(ScriptBody) -> String`, so this function
    /// // is one: the framework builds the body and hands it over, nonce and
    /// // all, and the document decides what surrounds it.
    /// fn document(body: ScriptBody) -> String {
    ///     let nonce = body.nonce_attribute();
    ///     format!("<body>{body}<script{nonce} src=\"/js/app.js\"></script></body>")
    /// }
    ///
    /// # fn takes_root_document(_: impl RootDocument) {}
    /// # takes_root_document(document as fn(ScriptBody) -> String);
    /// ```
    #[must_use]
    pub fn nonce_attribute(&self) -> String {
        self.nonce
            .as_ref()
            .map(CspNonce::attribute)
            .unwrap_or_default()
    }
}

impl fmt::Display for ScriptBody {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.html)
    }
}

/// The application-supplied root document renderer.
///
/// Implement this for your own type, or pass any `Fn(ScriptBody) -> String`
/// closure/function (a blanket impl covers closures).
pub trait RootDocument: Send + Sync {
    /// Produce the full HTML document, embedding `body`.
    fn render(&self, body: ScriptBody) -> String;
}

impl<T> RootDocument for T
where
    T: Fn(ScriptBody) -> String + Send + Sync,
{
    fn render(&self, body: ScriptBody) -> String {
        self(body)
    }
}

/// The configuration for an Inertia adapter.
///
/// Built once at startup and shared (cheaply cloned) across requests.
#[derive(Clone)]
pub struct InertiaConfig {
    inner: Arc<ConfigInner>,
}

impl fmt::Debug for InertiaConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InertiaConfig")
            .field("version", &self.inner.version)
            .field("shared_props", &self.inner.shared_props.is_empty())
            .finish_non_exhaustive()
    }
}

#[derive(Clone)]
struct ConfigInner {
    version: Option<AssetVersion>,
    root_document: Arc<dyn RootDocument>,
    shared_props: SharedProps,
    page_id: String,
}

impl InertiaConfig {
    /// Create a configuration with an asset version and a root document renderer.
    pub fn new(
        version: impl AsRef<str>,
        root_document: impl RootDocument + 'static,
    ) -> Result<InertiaConfig, InertiaError> {
        Ok(InertiaConfig {
            inner: Arc::new(ConfigInner {
                version: Some(AssetVersion::new(version)?),
                root_document: Arc::new(root_document),
                shared_props: SharedProps::new(),
                page_id: "app".to_string(),
            }),
        })
    }

    /// Create a configuration with no asset version.
    ///
    /// The client types `version` as `string | null` and sends back whatever
    /// it was given, so an application with no build step has a coherent
    /// answer: `null` in the page object, no `X-Inertia-Version` to compare,
    /// and therefore no version mismatch to force a hard reload. There is
    /// nothing to invalidate when nothing is hashed.
    ///
    /// Every application that does build assets wants
    /// [`new`](Self::new) instead -- without a version the client keeps
    /// running last deploy's JavaScript against this deploy's props until
    /// something else makes it reload.
    pub fn versionless(root_document: impl RootDocument + 'static) -> InertiaConfig {
        InertiaConfig {
            inner: Arc::new(ConfigInner {
                version: None,
                root_document: Arc::new(root_document),
                shared_props: SharedProps::new(),
                page_id: "app".to_string(),
            }),
        }
    }

    /// Register shared props.
    pub fn with_shared(mut self, shared: SharedProps) -> Self {
        Arc::make_mut(&mut self.inner).shared_props = shared;
        self
    }

    /// Use a different id for the page element and its mount point.
    ///
    /// `app` is the default on both sides. Change it only alongside the
    /// client's `createInertiaApp({ id })` -- the two names are one
    /// agreement, and a server that renames alone renders a page the client
    /// cannot find.
    pub fn with_page_id(mut self, id: impl Into<String>) -> Self {
        Arc::make_mut(&mut self.inner).page_id = id.into();
        self
    }

    /// The current asset version, if the application has one.
    pub fn version(&self) -> Option<&AssetVersion> {
        self.inner.version.as_ref()
    }

    /// The asset version as the protocol compares it: the empty string when
    /// there is none, which is exactly what a client with no version sends.
    pub(crate) fn version_str(&self) -> &str {
        self.inner.version.as_ref().map_or("", AssetVersion::as_str)
    }

    pub(crate) fn root_document(&self) -> &Arc<dyn RootDocument> {
        &self.inner.root_document
    }

    pub(crate) fn shared_props(&self) -> &SharedProps {
        &self.inner.shared_props
    }

    pub(crate) fn page_id(&self) -> &str {
        &self.inner.page_id
    }
}

/// The `<head>` metadata both stock root documents emit: the page's [`Head`]
/// when a handler set one, and the application title on its own when nobody
/// did.
///
/// The application title is the fallback for the page title, never a prefix
/// for it. A document title is what a search result and a browser tab show,
/// and `Acme -- Acme` or a 90-character concatenation helps neither; an
/// application that wants a suffix builds it into the head it sets.
///
/// The fallback is escaped here even though it comes from the application
/// rather than from a request. It costs nothing on the ordinary title, and
/// the alternative is a rule that holds only until someone passes a
/// configuration value through.
fn head_markup(head: Option<&Head>, title: &str) -> String {
    match head {
        // Byte-for-byte what this document emitted before heads existed,
        // apart from the escape.
        None => format!("<title>{}</title>", escape(title)),
        Some(head) if head.title().is_some() => head.to_html(),
        Some(head) => head.clone().with_title(title).to_html(),
    }
}

/// A minimal root document that references fixed asset paths.
///
/// Kept for applications with no build step, where `public/css/app.css` and
/// `public/js/app.js` are files that genuinely exist. A Vite application
/// wants [`vite_root_document`] instead: a production build emits hashed
/// names that nothing can spell in advance.
// `use<>`: the returned document owns a copy of everything it needs, so it
// must not capture the argument lifetime. Without the bound, Rust 2024
// captures `'_` and a caller cannot build a config that outlives its title.
pub fn default_root_document(title: &str) -> impl RootDocument + use<> {
    let title = title.to_string();
    move |body: ScriptBody| {
        // Both the stylesheet link and the module script carry the request's
        // nonce when there is one, and nothing when there is not. A
        // `script-src 'nonce-X'` policy that this document did not satisfy
        // would render the page blank rather than merely unstyled.
        let nonce = body.nonce_attribute();
        // Rendered into the bytes the server sends, because a link-preview
        // scraper reads those bytes and runs none of the JavaScript below.
        let head = head_markup(body.head(), &title);
        format!(
            "<!doctype html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\" />\n  \
             <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n  \
             {head}\n  <link{nonce} rel=\"stylesheet\" href=\"/css/app.css\" />\n</head>\n\
             <body>\n  {body}\n  <script{nonce} type=\"module\" src=\"/js/app.js\"></script>\n</body>\n</html>"
        )
    }
}

/// A root document that gets its asset URLs from [`Assets`].
///
/// `entry` is the manifest key -- the entry's path relative to the project
/// root, `resources/js/app.tsx` in a scaffolded app. In development that
/// resolves to the source path plus Vite's HMR client; in production it
/// resolves through `manifest.json` to the hashed build output, which is the
/// only way the reference can still be correct after a rebuild.
///
/// The entry is resolved **once**, here, not per request: [`Assets`] is
/// already the loaded manifest, and the answer cannot change while the
/// process runs. Only the tags are re-formatted per request, and only because
/// they carry that request's Content-Security-Policy nonce -- the URLs inside
/// them were settled at startup.
///
/// ```no_run
/// use arcature::assets::{Assets, AssetsConfig};
/// use arcature::inertia::{InertiaConfig, vite_root_document};
///
/// let assets = Assets::detect(&AssetsConfig::new())?;
/// let config = InertiaConfig::new(
///     env!("CARGO_PKG_VERSION"),
///     vite_root_document("Acme", &assets, "resources/js/app.tsx"),
/// )?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// [`Assets`]: crate::assets::Assets
pub fn vite_root_document(
    title: &str,
    assets: &crate::assets::Assets,
    entry: &str,
) -> impl RootDocument + use<> {
    let title = title.to_string();
    let resolved = assets.resolve(entry);
    let dev = assets.is_dev();
    move |body: ScriptBody| {
        let nonce = body.nonce().map(CspNonce::as_str);
        let styles = crate::assets::style_tags(
            resolved.as_ref().map(|r| r.css.as_slice()).unwrap_or(&[]),
            nonce,
        );
        let scripts =
            crate::assets::script_tags(resolved.as_ref().map(|r| r.js.as_str()), dev, nonce);
        // Before the bundle, before hydration: the only version of this page
        // a scraper will ever see.
        let head = head_markup(body.head(), &title);
        format!(
            "<!doctype html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\" />\n  \
             <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n  \
             {head}\n  {styles}\n</head>\n\
             <body>\n  {body}\n  {scripts}\n</body>\n</html>"
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::assets::{Assets, AssetsConfig};

    /// A body with the mount point a real render would carry, and whatever
    /// head the case under test is about.
    fn body(head: Option<Head>) -> ScriptBody {
        ScriptBody::from_escaped(Arc::from("<div id=\"app\"></div>"), None, head)
    }

    /// The Vite document in development mode, which resolves an entry to its
    /// own source path without touching a manifest on disk.
    fn vite(title: &str) -> impl RootDocument + use<> {
        vite_root_document(
            title,
            &Assets::dev(&AssetsConfig::new()),
            "resources/js/app.tsx",
        )
    }

    #[test]
    fn the_default_document_without_a_head_is_the_document_it_always_was() {
        let html = default_root_document("Acme").render(body(None));

        assert_eq!(
            html,
            "<!doctype html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\" />\n  \
             <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n  \
             <title>Acme</title>\n  <link rel=\"stylesheet\" href=\"/css/app.css\" />\n</head>\n\
             <body>\n  <div id=\"app\"></div>\n  \
             <script type=\"module\" src=\"/js/app.js\"></script>\n</body>\n</html>"
        );
    }

    #[test]
    fn the_vite_document_without_a_head_is_the_document_it_always_was() {
        let html = vite("Acme").render(body(None));

        assert_eq!(
            html,
            "<!doctype html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\" />\n  \
             <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n  \
             <title>Acme</title>\n  \n</head>\n\
             <body>\n  <div id=\"app\"></div>\n  \
             <script type=\"module\" src=\"/@vite/client\"></script>\n  \
             <script type=\"module\" src=\"/resources/js/app.tsx\"></script>\n</body>\n</html>"
        );
    }

    #[test]
    fn a_head_with_a_title_replaces_the_application_title() {
        let head = Head::new()
            .with_title("Ada Lovelace")
            .with_description("Notes on the Analytical Engine.");

        for html in [
            default_root_document("Acme").render(body(Some(head.clone()))),
            vite("Acme").render(body(Some(head.clone()))),
        ] {
            assert!(html.contains("<title>Ada Lovelace</title>"), "{html}");
            assert!(
                html.contains(
                    "<meta name=\"description\" \
                     content=\"Notes on the Analytical Engine.\" />"
                ),
                "{html}"
            );
            // The application title is a fallback, not a prefix or a suffix:
            // when the page says what it is, the application name is gone.
            assert!(!html.contains("Acme"), "{html}");
        }
    }

    #[test]
    fn a_head_without_a_title_borrows_the_application_title() {
        let head = Head::new().with_og_image("https://example.com/og.png");

        for html in [
            default_root_document("Acme").render(body(Some(head.clone()))),
            vite("Acme").render(body(Some(head.clone()))),
        ] {
            assert!(html.contains("<title>Acme</title>"), "{html}");
            // Filled in as the title proper, so everything that falls back to
            // the title -- `og:title` here -- gets it too. A preview with an
            // image and no title is the failure this whole path exists to
            // prevent.
            assert!(
                html.contains("<meta property=\"og:title\" content=\"Acme\" />"),
                "{html}"
            );
            assert!(
                html.contains(
                    "<meta property=\"og:image\" content=\"https://example.com/og.png\" />"
                ),
                "{html}"
            );
        }
    }

    #[test]
    fn a_hostile_application_title_cannot_open_a_tag_in_either_document() {
        let hostile = "<script>alert(1)</script>";

        for html in [
            default_root_document(hostile).render(body(None)),
            vite(hostile).render(body(None)),
            // Also on the fallback path, where the configured title is
            // escaped by the same helper before it becomes a `Head` title.
            default_root_document(hostile).render(body(Some(Head::new()))),
            vite(hostile).render(body(Some(Head::new()))),
        ] {
            assert!(
                html.contains("<title>&lt;script&gt;alert(1)&lt;/script&gt;</title>"),
                "{html}"
            );
            assert!(!html.contains("<script>alert(1)"), "{html}");
        }
    }

    #[test]
    fn a_hostile_page_title_cannot_open_a_tag_in_either_document() {
        let head = Head::new().with_title("<script>alert(1)</script>");

        for html in [
            default_root_document("Acme").render(body(Some(head.clone()))),
            vite("Acme").render(body(Some(head.clone()))),
        ] {
            assert!(
                html.contains("<title>&lt;script&gt;alert(1)&lt;/script&gt;</title>"),
                "{html}"
            );
            // Escaped in the `content="..."` attribute `og:title` falls back
            // into, not only in the element text.
            assert!(
                html.contains(
                    "<meta property=\"og:title\" \
                     content=\"&lt;script&gt;alert(1)&lt;/script&gt;\" />"
                ),
                "{html}"
            );
            assert!(!html.contains("<script>alert(1)"), "{html}");
        }
    }
}