forge
Explore
Log in

Don't you dare go Hollow

im-web: cached family probes, refusal i18n, soft-nav // guard, escape fixes

Browse files at this commit

c097a7cbfa306379c152582f8acb4a64794355d4Ahmet Kaan GümüşParent: 3bc2d00
- health.rs: shared LazyLock reqwest client + 30s TTL probe cache; no more
  per-render Client::new + inline 2s sibling stalls on every page
- pages.rs/i18n.rs: 'unavailable' error arm (En+Tr) for photo store failures
- layout.rs: soft-nav rejects protocol-relative // hrefs (foreign-HTML swap hole)
- escape(): map ' -> '; drop redundant manual escape at view! text sinks
  (pages.rs:837,1110; admin.rs:209) that double-escaped
- directory/oidc/photo: handler unwraps mapped to error paths
- people.rs: single avatar fetch; admin placeholders via t();
  sessions created_at formatted like seen
crates/im-web/src/admin.rsmodified+23 -15
@@ -15,7 +15,7 @@ use topcoat::router::response::{IntoResponse, Response};
15 use topcoat::router::{HeaderValue, StatusCode, header, route};15 use topcoat::router::{HeaderValue, StatusCode, header, route};
16 use topcoat::view::{Child, ViewExt, view};16 use topcoat::view::{Child, ViewExt, view};
17 17
18-use crate::health::{Probe, probe_healthz};18+use crate::health::{Probe, probe_family};
19 use crate::i18n::{self, Key, lang_of, t};19 use crate::i18n::{self, Key, lang_of, t};
20 use crate::layout::shell;20 use crate::layout::shell;
21 use crate::mailer;21 use crate::mailer;
@@ -48,6 +48,7 @@ fn escape(raw: &str) -> String {
48 .replace('<', "&lt;")48 .replace('<', "&lt;")
49 .replace('>', "&gt;")49 .replace('>', "&gt;")
50 .replace('"', "&quot;")50 .replace('"', "&quot;")
51+ .replace('\'', "&#39;")
51 }52 }
52 53
53 /// One row action as a two-step disclosure — iz's `confirm-details` idiom:54 /// One row action as a two-step disclosure — iz's `confirm-details` idiom:
@@ -205,7 +206,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> {
205 _ => None,206 _ => None,
206 };207 };
207 208
208- let my_email = escape(&me.email);209+ let my_email = me.email.clone();
209 let stage = view! {210 let stage = view! {
210 cx =>211 cx =>
211 <main class="admin-shell">212 <main class="admin-shell">
@@ -256,6 +257,12 @@ fn sessions_row(
256 "[year]-[month]-[day] [hour]:[minute]"257 "[year]-[month]-[day] [hour]:[minute]"
257 ))258 ))
258 .unwrap_or_else(|_| seen_at.date().to_string());259 .unwrap_or_else(|_| seen_at.date().to_string());
260+ let created = session
261+ .created_at
262+ .format(&time::macros::format_description!(
263+ "[year]-[month]-[day] [hour]:[minute]"
264+ ))
265+ .unwrap_or_else(|_| session.created_at.date().to_string());
259 rows.push_str(&format!(266 rows.push_str(&format!(
260 concat!(267 concat!(
261 r#"<tr><td title="{}">{}</td>"#,268 r#"<tr><td title="{}">{}</td>"#,
@@ -283,7 +290,7 @@ fn sessions_row(
283 .as_deref()290 .as_deref()
284 .map(escape)291 .map(escape)
285 .unwrap_or_else(|| "—".to_string()),292 .unwrap_or_else(|| "—".to_string()),
286- session.created_at.date(),293+ created,
287 seen,294 seen,
288 escape(&session.token_hash),295 escape(&session.token_hash),
289 t(lang, Key::RevokeButton),296 t(lang, Key::RevokeButton),
@@ -640,13 +647,13 @@ async fn services_section(
640 <form method="post" action="/admin/services_add" class="admin-invite">647 <form method="post" action="/admin/services_add" class="admin-invite">
641 <input class="auth-input auth-input-mono" type="text" name="key" placeholder="in" aria-label="{key_label}" required>648 <input class="auth-input auth-input-mono" type="text" name="key" placeholder="in" aria-label="{key_label}" required>
642 <input class="auth-input" type="text" name="name" placeholder="{name_label}" aria-label="{name_label}" required>649 <input class="auth-input" type="text" name="name" placeholder="{name_label}" aria-label="{name_label}" required>
643- <input class="auth-input auth-input-mono" type="text" name="url" placeholder="https://in.dizey.sh" aria-label="{url_label}" required>650+ <input class="auth-input auth-input-mono" type="text" name="url" placeholder="{url_placeholder}" aria-label="{url_label}" required>
644 <button class="auth-submit admin-invite-go" type="submit"><span class="auth-submit-text">{add}</span></button>651 <button class="auth-submit admin-invite-go" type="submit"><span class="auth-submit-text">{add}</span></button>
645 </form>652 </form>
646 <div class="muted">{client_add_label}</div>653 <div class="muted">{client_add_label}</div>
647 <form method="post" action="/admin/clients_add" class="admin-invite">654 <form method="post" action="/admin/clients_add" class="admin-invite">
648 <input class="auth-input" type="text" name="name" placeholder="drive" aria-label="{name_label}" required>655 <input class="auth-input" type="text" name="name" placeholder="drive" aria-label="{name_label}" required>
649- <input class="auth-input auth-input-mono" type="text" name="redirect_uris" placeholder="http://127.0.0.1:9000/callback https://drive.dizey.sh/callback" aria-label="{uris_label}" required>656+ <input class="auth-input auth-input-mono" type="text" name="redirect_uris" placeholder="{uris_placeholder}" aria-label="{uris_label}" required>
650 <button class="auth-submit admin-invite-go" type="submit"><span class="auth-submit-text">{client_add}</span></button>657 <button class="auth-submit admin-invite-go" type="submit"><span class="auth-submit-text">{client_add}</span></button>
651 </form>658 </form>
652 </div>"#,659 </div>"#,
@@ -654,8 +661,10 @@ async fn services_section(
654 key_label = t(lang, Key::ServiceKeyLabel),661 key_label = t(lang, Key::ServiceKeyLabel),
655 name_label = t(lang, Key::NameCol),662 name_label = t(lang, Key::NameCol),
656 url_label = t(lang, Key::AddressLabel),663 url_label = t(lang, Key::AddressLabel),
664+ url_placeholder = t(lang, Key::ServiceUrlPlaceholder),
657 id_label = t(lang, Key::ClientIdLabel),665 id_label = t(lang, Key::ClientIdLabel),
658 uris_label = t(lang, Key::RedirectUrisLabel),666 uris_label = t(lang, Key::RedirectUrisLabel),
667+ uris_placeholder = t(lang, Key::RedirectUrisPlaceholder),
659 registered_label = t(lang, Key::RegisteredCol),668 registered_label = t(lang, Key::RegisteredCol),
660 service_add_label = t(lang, Key::ServiceAdd),669 service_add_label = t(lang, Key::ServiceAdd),
661 add = t(lang, Key::ServiceAdd),670 add = t(lang, Key::ServiceAdd),
@@ -1443,22 +1452,21 @@ async fn logs_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::Erro
1443 /// way it refreshes every other section.1452 /// way it refreshes every other section.
1444 async fn health_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::Error> {1453 async fn health_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::Error> {
1445 let services = im_core::services::list(&app(cx).store).await?;1454 let services = im_core::services::list(&app(cx).store).await?;
1446- // Every probe at once: a family member that is down costs its two1455+ // One shared reading: this table and the chrome's flyout share the
1447- // seconds, not two seconds each.1456+ // cached probe round, so a family member that is down costs its two
1448- let http = reqwest::Client::new();1457+ // seconds once per window, not once per page view.
1449- let mut probes = Vec::new();1458+ let urls = services
1450- for service in &services {1459+ .iter()
1451- let http = http.clone();1460+ .map(|service| format!("{}/healthz", service.url.trim_end_matches('/')))
1452- let url = format!("{}/healthz", service.url.trim_end_matches('/'));1461+ .collect::<Vec<_>>();
1453- probes.push(tokio::spawn(async move { probe_healthz(&http, &url).await }));1462+ let probes = probe_family(&urls).await;
1454- }
1455 1463
1456 let mut rows = String::new();1464 let mut rows = String::new();
1457 for (service, probe) in services.iter().zip(probes) {1465 for (service, probe) in services.iter().zip(probes) {
1458 let key = escape(&service.key);1466 let key = escape(&service.key);
1459 let name = escape(&service.name);1467 let name = escape(&service.name);
1460 let url = escape(&service.url);1468 let url = escape(&service.url);
1461- let state = match probe.await.unwrap_or(Probe::Down) {1469+ let state = match probe {
1462 Probe::Up { body, ms } => format!(1470 Probe::Up { body, ms } => format!(
1463 r#"<span class="health-dot health-on"></span>{} <span class="muted">· {ms} ms</span>"#,1471 r#"<span class="health-dot health-on"></span>{} <span class="muted">· {ms} ms</span>"#,
1464 escape(&body)1472 escape(&body)
crates/im-web/src/directory.rsmodified+16 -6
@@ -68,7 +68,8 @@ async fn directory(cx: &Cx) -> topcoat::Result<topcoat::router::response::Respon
68 .filter(|user| !user.disabled)68 .filter(|user| !user.disabled)
69 .map(|user| DirectoryMember::of(&user))69 .map(|user| DirectoryMember::of(&user))
70 .collect();70 .collect();
71- Json(serde_json::to_value(members).unwrap()).into_response(cx)71+ let members = serde_json::to_value(members)?;
72+ Json(members).into_response(cx)
72 }73 }
73 /// `GET /directory/live`: the roster's change feed, as server-sent events.74 /// `GET /directory/live`: the roster's change feed, as server-sent events.
74 /// The same Basic pair `/directory` takes is the only credential. The75 /// The same Basic pair `/directory` takes is the only credential. The
@@ -144,10 +145,15 @@ async fn directory_live(cx: &Cx) -> topcoat::Result<topcoat::router::response::R
144 }145 }
145 Ok(Some(Ok(server::LiveEvent::Profile(member)))) => member,146 Ok(Some(Ok(server::LiveEvent::Profile(member)))) => member,
146 };147 };
148+ // A member that will not serialize cannot happen — plain
149+ // fields all the way down — but a stream cannot panic on
150+ // the impossible: ending is the honest answer, and the
151+ // client heals the gap the way it heals any disconnect.
152+ let Ok(json) = serde_json::to_string(&member) else {
153+ return None;
154+ };
147 return Some((155 return Some((
148- Ok(Event::new()156+ Ok(Event::new().event("profile").data(json)),
149- .event("profile")
150- .data(serde_json::to_string(&member).expect("member JSON"))),
151 (rx, deadline, stopping, first),157 (rx, deadline, stopping, first),
152 ));158 ));
153 }159 }
@@ -177,7 +183,8 @@ async fn family(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response>
177 }183 }
178 let store = server::app(cx).store.clone();184 let store = server::app(cx).store.clone();
179 let services = im_core::services::list(&store).await?;185 let services = im_core::services::list(&store).await?;
180- Json(serde_json::to_value(services).unwrap()).into_response(cx)186+ let services = serde_json::to_value(services)?;
187+ Json(services).into_response(cx)
181 }188 }
182 189
183 /// The body a sibling posts to keep its own row: its wordmark key, the190 /// The body a sibling posts to keep its own row: its wordmark key, the
@@ -216,7 +223,10 @@ async fn family_register(
216 )223 )
217 .await224 .await
218 {225 {
219- Ok(service) => Json(serde_json::to_value(service).unwrap()).into_response(cx),226+ Ok(service) => {
227+ let service = serde_json::to_value(&service)?;
228+ Json(service).into_response(cx)
229+ }
220 Err(im_core::store::StoreError::Conflict(_)) => (230 Err(im_core::store::StoreError::Conflict(_)) => (
221 StatusCode::CONFLICT,231 StatusCode::CONFLICT,
222 Json(serde_json::json!({ "error": "owned" })),232 Json(serde_json::json!({ "error": "owned" })),
crates/im-web/src/health.rsmodified+68 -0
@@ -3,11 +3,19 @@
3 //! `GET {url}/healthz` where it stands — no credentials, two seconds to3 //! `GET {url}/healthz` where it stands — no credentials, two seconds to
4 //! answer — and the callers fan the probes out concurrently, so a family4 //! answer — and the callers fan the probes out concurrently, so a family
5 //! member that is down costs its two seconds, not two seconds each.5 //! member that is down costs its two seconds, not two seconds each.
6+//! [`probe_family`] sits over that with the two things a per-render probe
7+//! used to pay again and again: one shared client, and a short-lived
8+//! cache so a burst of renders reuses the last reading instead of
9+//! re-stalling on a down sibling.
10+
11+use std::sync::{LazyLock, Mutex};
12+use std::time::{Duration, Instant};
6 13
7 /// One `/healthz` reading. `Up` carries the body — the deploy contract's14 /// One `/healthz` reading. `Up` carries the body — the deploy contract's
8 /// `ok <build sha>` — and the answer's latency; everything else, refused15 /// `ok <build sha>` — and the answer's latency; everything else, refused
9 /// or wrong status or a body that does not begin ok or the two-second16 /// or wrong status or a body that does not begin ok or the two-second
10 /// ceiling, is `Down`.17 /// ceiling, is `Down`.
18+#[derive(Clone)]
11 pub(crate) enum Probe {19 pub(crate) enum Probe {
12 Up { body: String, ms: u128 },20 Up { body: String, ms: u128 },
13 Down,21 Down,
@@ -37,3 +45,63 @@ pub(crate) async fn probe_healthz(http: &reqwest::Client, url: &str) -> Probe {
37 Probe::Down45 Probe::Down
38 }46 }
39 }47 }
48+
49+/// How long one family reading stands in for fresh probes. Long enough
50+/// that paging the panel does not re-stall on a dark sibling, short
51+/// enough that a service coming back is noticed within half a minute.
52+const CACHE_TTL: Duration = Duration::from_secs(30);
53+
54+/// The probe client every reader shares: one connection pool built once
55+/// per process, not a fresh client — and fresh sockets — per render.
56+static HTTP: LazyLock<reqwest::Client> = LazyLock::new(reqwest::Client::new);
57+
58+/// The last family reading: when it was taken, and what each probed
59+/// `/healthz` answered, keyed by URL.
60+static CACHE: LazyLock<Mutex<(Instant, Vec<(String, Probe)>)>> =
61+ LazyLock::new(|| Mutex::new((Instant::now(), Vec::new())));
62+
63+/// One reading per URL, in order. A reading younger than [`CACHE_TTL`]
64+/// that already covers every URL asked is reused whole — the chrome and
65+/// the panel can share a render without doubling the probes, and a down
66+/// sibling's two-second ceiling is paid once per window, not once per
67+/// page view. Otherwise every URL is probed at once and the reading is
68+/// remembered. A family that gained or lost a row reads fresh; a lost
69+/// probe task reads `Down`, and the next window re-probes.
70+pub(crate) async fn probe_family(urls: &[String]) -> Vec<Probe> {
71+ if let Some(cached) = fresh(urls) {
72+ return cached;
73+ }
74+ let probes: Vec<_> = urls
75+ .iter()
76+ .map(|url| {
77+ let url = url.clone();
78+ tokio::spawn(async move { probe_healthz(&HTTP, &url).await })
79+ })
80+ .collect();
81+ let mut readings: Vec<(String, Probe)> = Vec::with_capacity(urls.len());
82+ for (url, probe) in urls.iter().zip(probes) {
83+ readings.push((url.clone(), probe.await.unwrap_or(Probe::Down)));
84+ }
85+ if let Ok(mut slot) = CACHE.lock() {
86+ *slot = (Instant::now(), readings.clone());
87+ }
88+ readings.into_iter().map(|(_, probe)| probe).collect()
89+}
90+
91+/// The cached reading, when it is young enough to stand and covers every
92+/// URL asked. A poisoned cache is a miss — the next round re-probes.
93+fn fresh(urls: &[String]) -> Option<Vec<Probe>> {
94+ let cache = CACHE.lock().ok()?;
95+ let (at, readings) = &*cache;
96+ if at.elapsed() >= CACHE_TTL {
97+ return None;
98+ }
99+ urls.iter()
100+ .map(|url| {
101+ readings
102+ .iter()
103+ .find(|(seen, _)| seen == url)
104+ .map(|(_, probe)| probe.clone())
105+ })
106+ .collect()
107+}
crates/im-web/src/i18n.rsmodified+13 -0
@@ -63,6 +63,7 @@ pub enum Key {
63 ErrPhotoTooBig,63 ErrPhotoTooBig,
64 ErrNotAnImage,64 ErrNotAnImage,
65 ErrNoFile,65 ErrNoFile,
66+ ErrUnavailable,
66 ErrResetInvalid,67 ErrResetInvalid,
67 ErrSessionUnknown,68 ErrSessionUnknown,
68 ErrBadTheme,69 ErrBadTheme,
@@ -144,6 +145,7 @@ pub enum Key {
144 ServicesTitle,145 ServicesTitle,
145 ServiceKeyLabel,146 ServiceKeyLabel,
146 ServiceAdd,147 ServiceAdd,
148+ ServiceUrlPlaceholder,
147 ServiceKept,149 ServiceKept,
148 ServiceMoveUp,150 ServiceMoveUp,
149 ServiceMoveDown,151 ServiceMoveDown,
@@ -251,6 +253,7 @@ pub enum Key {
251 RedirectUrisLabel,253 RedirectUrisLabel,
252 RegisteredCol,254 RegisteredCol,
253 ClientAdd,255 ClientAdd,
256+ RedirectUrisPlaceholder,
254 RotateWord,257 RotateWord,
255 RevokeWord,258 RevokeWord,
256 ConfirmRotate,259 ConfirmRotate,
@@ -377,6 +380,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
377 (ErrNotAnImage, Tr) => "Bu dosya bir görsel değil.",380 (ErrNotAnImage, Tr) => "Bu dosya bir görsel değil.",
378 (ErrNoFile, En) => "Choose an image first.",381 (ErrNoFile, En) => "Choose an image first.",
379 (ErrNoFile, Tr) => "Önce bir görsel seç.",382 (ErrNoFile, Tr) => "Önce bir görsel seç.",
383+ (ErrUnavailable, En) => "That could not be saved right now — try again.",
384+ (ErrUnavailable, Tr) => "Bu şu anda kaydedilemedi — yeniden dene.",
380 (ErrResetInvalid, En) => "This reset link is not valid — ask for a fresh one.",385 (ErrResetInvalid, En) => "This reset link is not valid — ask for a fresh one.",
381 (ErrResetInvalid, Tr) => "Bu sıfırlama bağlantısı geçerli değil — yenisini iste.",386 (ErrResetInvalid, Tr) => "Bu sıfırlama bağlantısı geçerli değil — yenisini iste.",
382 (ErrSessionUnknown, En) => "That session is already gone.",387 (ErrSessionUnknown, En) => "That session is already gone.",
@@ -524,6 +529,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
524 (ServiceKeyLabel, Tr) => "Anahtar",529 (ServiceKeyLabel, Tr) => "Anahtar",
525 (ServiceAdd, En) => "Add service",530 (ServiceAdd, En) => "Add service",
526 (ServiceAdd, Tr) => "Hizmet ekle",531 (ServiceAdd, Tr) => "Hizmet ekle",
532+ (ServiceUrlPlaceholder, En) => "https://in.dizey.sh",
533+ (ServiceUrlPlaceholder, Tr) => "https://in.dizey.sh",
527 (ServiceKept, En) => "kept by the app",534 (ServiceKept, En) => "kept by the app",
528 (ServiceKept, Tr) => "uygulaması koruyor",535 (ServiceKept, Tr) => "uygulaması koruyor",
529 (ServiceMoveUp, En) => "Move up",536 (ServiceMoveUp, En) => "Move up",
@@ -749,6 +756,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
749 (RegisteredCol, Tr) => "Kayıt",756 (RegisteredCol, Tr) => "Kayıt",
750 (ClientAdd, En) => "Register client",757 (ClientAdd, En) => "Register client",
751 (ClientAdd, Tr) => "İstemci kaydet",758 (ClientAdd, Tr) => "İstemci kaydet",
759+ (RedirectUrisPlaceholder, En) => {
760+ "http://127.0.0.1:9000/callback https://drive.dizey.sh/callback"
761+ }
762+ (RedirectUrisPlaceholder, Tr) => {
763+ "http://127.0.0.1:9000/callback https://drive.dizey.sh/callback"
764+ }
752 (RotateWord, En) => "Rotate",765 (RotateWord, En) => "Rotate",
753 (RotateWord, Tr) => "Yenile",766 (RotateWord, Tr) => "Yenile",
754 (RevokeWord, En) => "Revoke",767 (RevokeWord, En) => "Revoke",
crates/im-web/src/layout.rsmodified+17 -16
@@ -7,7 +7,7 @@ use topcoat::asset::{Asset, asset};
7 use topcoat::context::Cx;7 use topcoat::context::Cx;
8 use topcoat::view::{BoxView, Child, View, ViewExt, view};8 use topcoat::view::{BoxView, Child, View, ViewExt, view};
9 9
10-use crate::health::{Probe, probe_healthz};10+use crate::health::{Probe, probe_family};
11 use crate::i18n::{Key, Lang, lang_of, t};11 use crate::i18n::{Key, Lang, lang_of, t};
12 use crate::server;12 use crate::server;
13 13
@@ -44,20 +44,19 @@ pub async fn family_wordmark(cx: &Cx) -> Result<BoxView<'_>> {
44 if siblings.is_empty() {44 if siblings.is_empty() {
45 return wordmark(cx).await.map(ViewExt::boxed);45 return wordmark(cx).await.map(ViewExt::boxed);
46 }46 }
47- // Every probe at once: a family member that is down costs its two47+ // One shared reading: a render inside the cache window reuses the
48- // seconds, not two seconds each.48+ // last probe round, so a family member that is down costs its two
49- let http = reqwest::Client::new();49+ // seconds once per window, not once per page view.
50- let mut probes = Vec::new();50+ let urls = siblings
51- for service in &siblings {51+ .iter()
52- let http = http.clone();52+ .map(|service| format!("{}/healthz", service.url.trim_end_matches('/')))
53- let url = format!("{}/healthz", service.url.trim_end_matches('/'));53+ .collect::<Vec<_>>();
54- probes.push(tokio::spawn(async move { probe_healthz(&http, &url).await }));54+ let probes = probe_family(&urls).await;
55- }55+ let rows = siblings
56- let mut rows = Vec::new();56+ .iter()
57- for (service, probe) in siblings.iter().zip(probes) {57+ .zip(probes)
58- let probe = probe.await.unwrap_or(Probe::Down);58+ .map(|(service, probe)| (service.key.as_str(), service.url.as_str(), probe))
59- rows.push((service.key.as_str(), service.url.as_str(), probe));59+ .collect::<Vec<_>>();
60- }
61 let marks = trio_marks(rows);60 let marks = trio_marks(rows);
62 Ok(view! {61 Ok(view! {
63 cx =>62 cx =>
@@ -366,7 +365,9 @@ pub async fn soft_nav_script(cx: &Cx) -> Result<impl View + '_> {
366 var a = e.target.closest ? e.target.closest('a') : null;365 var a = e.target.closest ? e.target.closest('a') : null;
367 if (!a || a.target || a.hasAttribute('download') || a.hasAttribute('data-hard')) { return; }366 if (!a || a.target || a.hasAttribute('download') || a.hasAttribute('data-hard')) { return; }
368 var href = a.getAttribute('href') || '';367 var href = a.getAttribute('href') || '';
369- if (href.indexOf('/') !== 0) { return; }368+ // Same-app paths only: `//host` is protocol-relative — another origin —
369+ // and goes the browser's own way.
370+ if (href.indexOf('/') !== 0 || href.indexOf('//') === 0) { return; }
370 e.preventDefault();371 e.preventDefault();
371 go(href, true, true);372 go(href, true, true);
372 }, true);373 }, true);
crates/im-web/src/oidc.rsmodified+4 -2
@@ -150,9 +150,10 @@ async fn authorize(cx: &Cx) -> Result<Response> {
150 let Some(user) = user else {150 let Some(user) = user else {
151 let back = format!("/authorize?{query}");151 let back = format!("/authorize?{query}");
152 let location = format!("/login?back={}", urlencode(&back));152 let location = format!("/login?back={}", urlencode(&back));
153+ let location = HeaderValue::from_str(&location)?;
153 return (154 return (
154 StatusCode::SEE_OTHER,155 StatusCode::SEE_OTHER,
155- [(header::LOCATION, HeaderValue::from_str(&location).unwrap())],156+ [(header::LOCATION, location)],
156 )157 )
157 .into_response(cx);158 .into_response(cx);
158 };159 };
@@ -172,9 +173,10 @@ async fn authorize(cx: &Cx) -> Result<Response> {
172 if let Some(state) = state {173 if let Some(state) = state {
173 location.push_str(&format!("&state={state}"));174 location.push_str(&format!("&state={state}"));
174 }175 }
176+ let location = HeaderValue::from_str(&location)?;
175 (177 (
176 StatusCode::SEE_OTHER,178 StatusCode::SEE_OTHER,
177- [(header::LOCATION, HeaderValue::from_str(&location).unwrap())],179+ [(header::LOCATION, location)],
178 )180 )
179 .into_response(cx)181 .into_response(cx)
180 }182 }
crates/im-web/src/pages.rsmodified+4 -2
@@ -40,6 +40,7 @@ pub fn error_text(code: &str, lang: Lang) -> &'static str {
40 "photo_too_big" => t(lang, Key::ErrPhotoTooBig),40 "photo_too_big" => t(lang, Key::ErrPhotoTooBig),
41 "not_an_image" => t(lang, Key::ErrNotAnImage),41 "not_an_image" => t(lang, Key::ErrNotAnImage),
42 "no_file" => t(lang, Key::ErrNoFile),42 "no_file" => t(lang, Key::ErrNoFile),
43+ "unavailable" => t(lang, Key::ErrUnavailable),
43 "session_unknown" => t(lang, Key::ErrSessionUnknown),44 "session_unknown" => t(lang, Key::ErrSessionUnknown),
44 "bad_theme" => t(lang, Key::ErrBadTheme),45 "bad_theme" => t(lang, Key::ErrBadTheme),
45 "bad_ui" => t(lang, Key::ErrBadUi),46 "bad_ui" => t(lang, Key::ErrBadUi),
@@ -485,6 +486,7 @@ pub(crate) fn escape(raw: &str) -> String {
485 .replace('<', "&lt;")486 .replace('<', "&lt;")
486 .replace('>', "&gt;")487 .replace('>', "&gt;")
487 .replace('"', "&quot;")488 .replace('"', "&quot;")
489+ .replace('\'', "&#39;")
488 }490 }
489 491
490 /// What the agent string means to a person — "Chrome on Linux", not the raw492 /// What the agent string means to a person — "Chrome on Linux", not the raw
@@ -832,7 +834,7 @@ async fn signed_in<'a>(cx: &'a Cx, user: im_core::model::User) -> Result<BoxView
832 <div class="auth-title">(t(lang, Key::EmailCardTitle))</div>834 <div class="auth-title">(t(lang, Key::EmailCardTitle))</div>
833 if let Some(pending) = pending_email.as_deref() {835 if let Some(pending) = pending_email.as_deref() {
834 <div class="auth-sub">836 <div class="auth-sub">
835- (crate::i18n::email_pending_line(lang, &escape(pending)))837+ (crate::i18n::email_pending_line(lang, pending))
836 </div>838 </div>
837 }839 }
838 if let Some(links) = query_value(&query, "links") {840 if let Some(links) = query_value(&query, "links") {
@@ -1105,7 +1107,7 @@ async fn email_change_page(cx: &Cx) -> Result<Response> {
1105 <div class="auth-head">1107 <div class="auth-head">
1106 <div class="auth-title">(t(lang, Key::EmailConfirmTitle))</div>1108 <div class="auth-title">(t(lang, Key::EmailConfirmTitle))</div>
1107 <div class="auth-sub">1109 <div class="auth-sub">
1108- (crate::i18n::email_confirm_sub(lang, &escape(&new_email)))1110+ (crate::i18n::email_confirm_sub(lang, &new_email))
1109 </div>1111 </div>
1110 </div>1112 </div>
1111 <form method="post" action="/email" data-hard="">1113 <form method="post" action="/email" data-hard="">
crates/im-web/src/people.rsmodified+3 -4
@@ -38,8 +38,7 @@ async fn people_page(cx: &Cx) -> Result<impl View + '_> {
38 // The stage template moves every value it mentions, so the account's38 // The stage template moves every value it mentions, so the account's
39 // template data is staged here as owned values first; the markup below39 // template data is staged here as owned values first; the markup below
40 // never names `person` itself.40 // never names `person` itself.
41- let face_button = avatar(cx, &person).await?.first().await?;41+ let face = avatar(cx, &person).await?.first().await?;
42- let face_plain = avatar(cx, &person).await?.first().await?;
43 let display_name = person.name.clone();42 let display_name = person.name.clone();
44 let email_shown = person.email.clone();43 let email_shown = person.email.clone();
45 let has_photo = person.has_photo;44 let has_photo = person.has_photo;
@@ -57,10 +56,10 @@ async fn people_page(cx: &Cx) -> Result<impl View + '_> {
57 // The face opens the viewer here too — same as56 // The face opens the viewer here too — same as
58 // the landing, same as iz's person page.57 // the landing, same as iz's person page.
59 <button class="avatar-view" type="button" aria-label=(t(lang, Key::ViewPhotoAria))>58 <button class="avatar-view" type="button" aria-label=(t(lang, Key::ViewPhotoAria))>
60- (face_button)59+ (face)
61 </button>60 </button>
62 } else {61 } else {
63- (face_plain)62+ (face)
64 }63 }
65 <div class="profile-heading">64 <div class="profile-heading">
66 <div class="auth-title">(display_name)</div>65 <div class="auth-title">(display_name)</div>
crates/im-web/src/photo.rsmodified+7 -7
@@ -115,23 +115,23 @@ fn bytes_response(
115 content_type: &str,115 content_type: &str,
116 cache: &'static str,116 cache: &'static str,
117 version: u64,117 version: u64,
118-) -> (StatusCode, HeaderMap, Vec<u8>) {118+) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
119 let etag = format!("\"p{version}\"");119 let etag = format!("\"p{version}\"");
120 let mut headers = HeaderMap::new();120 let mut headers = HeaderMap::new();
121- headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap());121+ headers.insert(header::ETAG, HeaderValue::from_str(&etag)?);
122 headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache));122 headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache));
123 let if_none_match = request_headers(cx)123 let if_none_match = request_headers(cx)
124 .get(header::IF_NONE_MATCH)124 .get(header::IF_NONE_MATCH)
125 .and_then(|v| v.to_str().ok());125 .and_then(|v| v.to_str().ok());
126 if if_none_match == Some(etag.as_str()) {126 if if_none_match == Some(etag.as_str()) {
127- return (StatusCode::NOT_MODIFIED, headers, Vec::new());127+ return Ok((StatusCode::NOT_MODIFIED, headers, Vec::new()));
128 }128 }
129 headers.insert(129 headers.insert(
130 header::CONTENT_TYPE,130 header::CONTENT_TYPE,
131 HeaderValue::from_str(content_type)131 HeaderValue::from_str(content_type)
132 .unwrap_or(HeaderValue::from_static("application/octet-stream")),132 .unwrap_or(HeaderValue::from_static("application/octet-stream")),
133 );133 );
134- (StatusCode::OK, headers, bytes)134+ Ok((StatusCode::OK, headers, bytes))
135 }135 }
136 136
137 /// The default face, as an image: the name's first letter on a quiet tile —137 /// The default face, as an image: the name's first letter on a quiet tile —
@@ -203,7 +203,7 @@ async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
203 } else {203 } else {
204 "private, no-cache"204 "private, no-cache"
205 };205 };
206- return Ok(bytes_response(cx, bytes, &mime, cache, version));206+ return bytes_response(cx, bytes, &mime, cache, version);
207 }207 }
208 let initial = user208 let initial = user
209 .as_ref()209 .as_ref()
@@ -211,13 +211,13 @@ async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
211 .unwrap_or('?')211 .unwrap_or('?')
212 .to_uppercase()212 .to_uppercase()
213 .to_string();213 .to_string();
214- Ok(bytes_response(214+ bytes_response(
215 cx,215 cx,
216 default_avatar(&initial),216 default_avatar(&initial),
217 "image/svg+xml",217 "image/svg+xml",
218 "private, no-cache",218 "private, no-cache",
219 version,219 version,
220- ))220+ )
221 }221 }
222 222
223 #[cfg(test)]223 #[cfg(test)]