-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathsingle_page_app.rs
161 lines (147 loc) · 4.86 KB
/
single_page_app.rs
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
use std::fmt::Display;
use std::fmt::Formatter;
use crate::helpers::get_subject;
use crate::{appstate::AppState, errors::AtomicServerResult};
use actix_web::HttpResponse;
/// Returns the atomic-data-browser single page application
#[tracing::instrument(skip(appstate))]
pub async fn single_page(
appstate: actix_web::web::Data<AppState>,
path: actix_web::web::Path<String>,
req: actix_web::HttpRequest,
conn: actix_web::dev::ConnectionInfo,
) -> AtomicServerResult<HttpResponse> {
let template = include_str!("../../assets_tmp/index.html");
let (subject, _content_type) = get_subject(&req, &conn, &appstate)?;
let meta_tags: MetaTags = if let Ok(resource) =
appstate
.store
.get_resource_extended(&subject, true, &ForAgent::Public)
{
resource.into()
} else {
MetaTags::default()
};
let script = format!("<script>{}</script>", appstate.config.opts.script);
let body = template
.replace("<!-- { inject_html_head } -->", &meta_tags.to_string())
.replace("<!-- { inject_script } -->", &script);
let resp = HttpResponse::Ok()
.content_type("text/html")
// This prevents the browser from displaying the JSON response upon re-opening a closed tab
// https://github.com/atomicdata-dev/atomic-server/issues/137
.insert_header((
"Cache-Control",
"no-store, no-cache, must-revalidate, private",
))
.append_header(("Vary", "Accept"))
.body(body);
Ok(resp)
}
use atomic_lib::agents::ForAgent;
use atomic_lib::urls;
use atomic_lib::Resource;
use atomic_lib::Storelike;
/* HTML tags for social media and link previews. Also includes JSON-AD body of the requested resource, if publicly available. */
struct MetaTags {
description: String,
title: String,
image: String,
json: Option<String>,
}
impl From<Resource> for MetaTags {
fn from(r: Resource) -> Self {
let description = if let Ok(d) = r.get(urls::DESCRIPTION) {
d.to_string()
} else {
"Open this resource in your browser to view its contents.".to_string()
};
let title = if let Ok(d) = r.get(urls::NAME) {
d.to_string()
} else {
"Atomic Server".to_string()
};
let image = if let Ok(d) = r.get(urls::DOWNLOAD_URL) {
// TODO: check if thefile is actually an image
d.to_string()
} else {
"/default_social_preview.jpg".to_string()
};
let json = if let Ok(serialized) = r.to_json_ad() {
// TODO: also fetch the parents for extra fast first renders.
Some(serialized)
} else {
None
};
Self {
description,
title,
image,
json,
}
}
}
impl Default for MetaTags {
fn default() -> Self {
Self {
description: "Sign in to view this resource".to_string(),
title: "Atomic Server".to_string(),
image: "/default_social_preview.jpg".to_string(),
json: None,
}
}
}
impl Display for MetaTags {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let description = escape_html(&self.description)
.chars()
.take(250)
.collect::<String>();
let image = &self.image;
let title = escape_html(&self.title);
write!(
f,
"<meta name=\"description\" content=\"{description}\">
<meta property=\"og:title\" content=\"{title}\">
<meta property=\"og:description\" content=\"{description}\">
<meta property=\"og:image\" content=\"{image}\">
<meta property=\"twitter:card\" content=\"summary_large_image\">
<meta property=\"twitter:title\" content=\"{title}\">
<meta property=\"twitter:description\" content=\"{description}\">
<meta property=\"twitter:image\" content=\"{image}\">"
)?;
if let Some(json_unsafe) = &self.json {
use base64::Engine;
let json_base64 = base64::engine::general_purpose::STANDARD.encode(json_unsafe);
write!(
f,
"\n<meta property=\"json-ad-initial\" content=\"{}\">",
json_base64
)?;
};
Ok(())
}
}
fn escape_html(s: &str) -> String {
s.replace('<', "<")
.replace('>', ">")
.replace('&', "&")
.replace('\'', "'")
.replace('"', """)
.replace('/', "/")
}
#[cfg(test)]
mod test {
use super::MetaTags;
#[test]
// Malicious test: try escaping html and adding script tag
fn evil_meta_tags() {
let html = MetaTags {
description: "\"<script>alert('evil')</script>\"".to_string(),
..Default::default()
}
.to_string();
println!("{}", html);
assert!(!html.contains("<script>"));
}
}