fetchlet_http/dev/
service.rs1use std::fmt;
2use std::future::{Future, poll_fn};
3use std::pin::Pin;
4use std::sync::Arc;
5use std::task::{Context, Poll};
6use std::time::Duration;
7
8use bytes::Bytes;
9use http::header::{
10 ACCEPT_ENCODING, CACHE_CONTROL, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue,
11};
12use http::{Method, Request, Response, StatusCode};
13use tower_service::Service;
14
15use super::body::DevBody;
16use super::reload::Shared;
17
18pub const RELOAD_POLL_PATH: &str = "/__fetchlet/reload";
20
21pub const RELOAD_SCRIPT_PATH: &str = "/__fetchlet/reload.js";
23
24const RELOAD_SCRIPT: &str = include_str!("../../js/dev-reload.js");
27
28const POLL_TIMEOUT: Duration = Duration::from_secs(25);
32
33pub struct DevService<S> {
44 shared: Arc<Shared<S>>,
45}
46
47impl<S> Clone for DevService<S> {
48 fn clone(&self) -> Self {
49 Self {
50 shared: self.shared.clone(),
51 }
52 }
53}
54
55impl<S> fmt::Debug for DevService<S> {
56 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
57 formatter.debug_struct("DevService").finish_non_exhaustive()
58 }
59}
60
61impl<S> DevService<S> {
62 pub(super) fn new(shared: Arc<Shared<S>>) -> Self {
63 Self { shared }
64 }
65}
66
67impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for DevService<S>
68where
69 S: Service<Request<ReqBody>, Response = Response<ResBody>> + Clone + Send + Sync + 'static,
70 S::Future: Send + 'static,
71 S::Error: Send + 'static,
72 ReqBody: Send + 'static,
73 ResBody: http_body::Body<Data = Bytes>,
74{
75 type Response = Response<DevBody<ResBody>>;
76
77 type Error = S::Error;
78
79 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, S::Error>> + Send>>;
80
81 fn poll_ready(&mut self, _context: &mut Context<'_>) -> Poll<Result<(), S::Error>> {
82 Poll::Ready(Ok(()))
83 }
84
85 fn call(&mut self, mut request: Request<ReqBody>) -> Self::Future {
86 let get = request.method() == Method::GET;
87 if get && request.uri().path() == RELOAD_SCRIPT_PATH {
88 return Box::pin(async {
89 Ok(fixed_response(
90 Bytes::from_static(RELOAD_SCRIPT.as_bytes()),
91 "text/javascript",
92 ))
93 });
94 }
95 if get && request.uri().path() == RELOAD_POLL_PATH {
96 let seen = seen_token(request.uri().query());
97 let mut tokens = self.shared.token.subscribe();
98 return Box::pin(async move {
99 let wait = tokens.wait_for(|token| Some(token.as_str()) != seen.as_deref());
100 let _ = tokio::time::timeout(POLL_TIMEOUT, wait).await;
101 let token = tokens.borrow().clone();
102 Ok(fixed_response(Bytes::from(token), "text/plain"))
103 });
104 }
105 let (mut service, token) = self.shared.current();
106 request.headers_mut().remove(ACCEPT_ENCODING);
107 let head = request.method() == Method::HEAD;
108 Box::pin(async move {
109 poll_fn(|context| service.poll_ready(context)).await?;
110 let response = service.call(request).await?;
111 Ok(inject(response, &token, head))
112 })
113 }
114}
115
116fn seen_token(query: Option<&str>) -> Option<String> {
120 query?
121 .split('&')
122 .find_map(|pair| pair.strip_prefix("token="))
123 .and_then(percent_decode)
124}
125
126fn percent_decode(value: &str) -> Option<String> {
127 let bytes = value.as_bytes();
128 let mut decoded = Vec::with_capacity(bytes.len());
129 let mut index = 0;
130 while index < bytes.len() {
131 if bytes[index] == b'%' {
132 let hex = std::str::from_utf8(bytes.get(index + 1..index + 3)?).ok()?;
133 decoded.push(u8::from_str_radix(hex, 16).ok()?);
134 index += 3;
135 } else {
136 decoded.push(bytes[index]);
137 index += 1;
138 }
139 }
140 String::from_utf8(decoded).ok()
141}
142
143fn percent_encode(value: &str) -> String {
146 let mut encoded = String::with_capacity(value.len());
147 for byte in value.bytes() {
148 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
149 encoded.push(char::from(byte));
150 } else {
151 encoded.push_str(&format!("%{byte:02X}"));
152 }
153 }
154 encoded
155}
156
157fn escape_attribute(value: &str) -> String {
159 let mut escaped = String::with_capacity(value.len());
160 for character in value.chars() {
161 match character {
162 '&' => escaped.push_str("&"),
163 '"' => escaped.push_str("""),
164 '<' => escaped.push_str("<"),
165 '>' => escaped.push_str(">"),
166 other => escaped.push(other),
167 }
168 }
169 escaped
170}
171
172fn fixed_response<B>(body: Bytes, content_type: &'static str) -> Response<DevBody<B>> {
173 let mut response = Response::new(DevBody::full(body));
174 let headers = response.headers_mut();
175 headers.insert(CONTENT_TYPE, HeaderValue::from_static(content_type));
176 headers.insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
177 response
178}
179
180fn inject<B>(response: Response<B>, token: &str, head: bool) -> Response<DevBody<B>> {
182 let (mut parts, body) = response.into_parts();
183 let html = parts
184 .headers
185 .get(CONTENT_TYPE)
186 .and_then(|value| value.to_str().ok())
187 .is_some_and(|value| {
188 value
189 .split(';')
190 .next()
191 .is_some_and(|kind| kind.trim().eq_ignore_ascii_case("text/html"))
192 });
193 let injectable = html
194 && !head
195 && parts.status != StatusCode::NOT_MODIFIED
196 && !parts.headers.contains_key(CONTENT_ENCODING);
197 if !injectable {
198 return Response::from_parts(parts, DevBody::plain(body));
199 }
200 parts.headers.remove(CONTENT_LENGTH);
201 Response::from_parts(
202 parts,
203 DevBody::appended(body, Bytes::from(script_element(token))),
204 )
205}
206
207fn script_element(token: &str) -> String {
213 let source = format!("{RELOAD_SCRIPT_PATH}?token={}", percent_encode(token));
214 format!(
215 "<script type=\"module\" src=\"{}\"></script>",
216 escape_attribute(&source)
217 )
218}
219
220#[cfg(test)]
221mod tests {
222 use super::*;
223
224 #[test]
225 fn the_seen_token_comes_from_the_query() {
226 assert_eq!(seen_token(Some("token=ab-1")).as_deref(), Some("ab-1"));
227 assert_eq!(seen_token(Some("x=1&token=ab-2")).as_deref(), Some("ab-2"));
228 assert_eq!(seen_token(Some("x=1")), None);
229 assert_eq!(seen_token(None), None);
230 assert_eq!(
231 seen_token(Some("token=a%22%3C%20b")).as_deref(),
232 Some("a\"< b")
233 );
234 assert_eq!(
235 seen_token(Some("token=%E3%81%82")).as_deref(),
236 Some("\u{3042}")
237 );
238 for broken in ["token=%", "token=%4", "token=%zz", "token=%FF"] {
239 assert_eq!(seen_token(Some(broken)), None, "{broken}");
240 }
241 }
242
243 #[test]
244 fn tokens_round_trip_through_the_query() {
245 for token in ["ab-1", "a\"<b>&c", "x y/z?#", "\u{3042}"] {
246 assert_eq!(
247 seen_token(Some(&format!("token={}", percent_encode(token)))).as_deref(),
248 Some(token)
249 );
250 }
251 }
252
253 #[test]
254 fn the_element_escapes_the_token() {
255 let element = script_element("\"></script><script>alert(1)</script>&");
256 assert_eq!(
257 element,
258 "<script type=\"module\" src=\"/__fetchlet/reload.js?token=\
259 %22%3E%3C%2Fscript%3E%3Cscript%3Ealert%281%29%3C%2Fscript%3E%26\"></script>"
260 );
261 assert_eq!(escape_attribute("a&\"<>b"), "a&"<>b");
262 }
263
264 #[test]
265 fn the_element_loads_the_script_with_the_token() {
266 assert_eq!(
267 script_element("ab-3"),
268 "<script type=\"module\" src=\"/__fetchlet/reload.js?token=ab-3\"></script>"
269 );
270 }
271
272 #[test]
273 fn the_script_polls_the_poll_path() {
274 assert!(RELOAD_SCRIPT.contains(&format!("`{RELOAD_POLL_PATH}?token=")));
275 }
276}