Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/apps/desktop/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -349,8 +349,9 @@ and rechecks its authorization binding before publishing the result. Model-scope
requests require the separately advertised `subscription_model_quota_v1` capability;
legacy requests retain the exact account-slot path. These tests do not contact billing.

For workspace HTML gateway authentication, chunking, cancellation and peer
capability negotiation and encrypted loopback Relay transfer, run:
For workspace HTML gateway authentication, chunking, cancellation, site-root
entry URLs, document-route fallback, owner-error preservation, peer capability
negotiation and encrypted loopback Relay transfer, run:

```bash
cargo test --locked -p openbitfun-desktop --lib html_preview
Expand Down
99 changes: 96 additions & 3 deletions src/apps/desktop/src/api/html_preview_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,11 @@ async fn preview_handler(
.status(StatusCode::FOUND)
.header(
header::LOCATION,
format!("/{}", encode_url_path(&state.entry_path)),
if index_entry_filename(&state.entry_path).is_some() {
"/".to_string()
} else {
format!("/{}", encode_url_path(&state.entry_path))
},
)
.header(
header::SET_COOKIE,
Expand All @@ -359,20 +363,55 @@ async fn preview_handler(
Ok(relative) => relative.into_owned(),
Err(_) => return response(StatusCode::BAD_REQUEST, "Invalid preview path"),
};
let index_entry = index_entry_filename(&state.entry_path);
if index_entry.is_some_and(|filename| relative == filename || relative == state.entry_path) {
// The site router must see its public root, including when a link uses
// the entry filename or an older workspace-prefixed preview URL.
return Response::builder()
.status(StatusCode::FOUND)
.header(header::LOCATION, site_root_url(&uri))
.header(header::CACHE_CONTROL, "no-store")
.header(header::REFERRER_POLICY, "no-referrer")
.body(Body::empty())
.unwrap_or_else(|_| response(StatusCode::BAD_REQUEST, "Invalid preview path"));
}
let mut request = state.request.clone();
request.resource_path = Some(relative);
request.resource_path = if index_entry.is_some() && relative.is_empty() {
None
} else {
Some(relative.clone())
};
request.metadata_only = method == Method::HEAD;
let bypass_cache = force_resource_reload(&headers);
let resource = match state
.transfer
.open(
request,
request.clone(),
bypass_cache,
uri.path_and_query().map(|path| path.as_str().to_string()),
)
.await
{
Ok(resource) => resource,
Err(error)
if error.code == Code::NotFound
&& index_entry.is_some()
&& is_document_route(&relative, &headers) =>
{
// Existing files always win. Only document navigation can use the
// selected index as a history-router fallback; assets, authorization
// failures and offline owners retain their original error. None is
// the existing v1 entry request, so older peer hosts work unchanged.
request.resource_path = None;
match state
.transfer
.open(request, bypass_cache, Some(site_root_url(&uri)))
.await
{
Ok(resource) => resource,
Err(error) => return preview_error_response(error),
}
}
Err(error) => return preview_error_response(error),
};
let size = resource.metadata.size;
Expand All @@ -399,6 +438,60 @@ async fn preview_handler(
})
}

fn index_entry_filename(entry_path: &str) -> Option<&str> {
entry_path.rsplit('/').next().filter(|filename| {
filename.eq_ignore_ascii_case("index.html") || filename.eq_ignore_ascii_case("index.htm")
})
}

fn site_root_url(uri: &Uri) -> String {
match uri.query() {
Some(query) => format!("/?{query}"),
None => "/".to_string(),
}
}

fn is_document_route(path: &str, headers: &HeaderMap) -> bool {
// Explicit filenames (including missing .html pages) remain ordinary file
// requests. Browser fetches that accept */* are not page navigations.
if path
.trim_end_matches('/')
.rsplit('/')
.next()
.is_some_and(|part| part.contains('.'))
{
return false;
}
if headers
.get("sec-fetch-dest")
.is_some_and(|value| value != "document" && value != "iframe" && value != "frame")
{
return false;
}
headers
.get_all(header::ACCEPT)
.iter()
.filter_map(|value| value.to_str().ok())
.any(|value| {
value.split(',').any(|range| {
let mut parts = range.trim().split(';');
parts
.next()
.is_some_and(|mime| mime.trim().eq_ignore_ascii_case("text/html"))
&& parts.all(|parameter| {
let Some((name, value)) = parameter.trim().split_once('=') else {
return true;
};
!name.trim().eq_ignore_ascii_case("q")
|| value
.trim()
.parse::<f32>()
.is_ok_and(|quality| quality > 0.0 && quality <= 1.0)
})
})
})
}

fn force_resource_reload(headers: &HeaderMap) -> bool {
[header::CACHE_CONTROL, header::PRAGMA].iter().any(|name| {
headers
Expand Down
Loading
Loading