1use std::collections::{BTreeMap, HashMap, HashSet};
17use std::fmt::Write as _;
18use std::io;
19use std::net::SocketAddr;
20use std::path::PathBuf;
21use std::sync::{Mutex, MutexGuard, PoisonError};
22use std::time::{Duration, Instant};
23
24use ai6::{AssistantPageFile, AssistantPageLimits, PageNetwork, Person};
25use axum::Extension;
26use axum::extract::{ConnectInfo, Path as UrlPath, Query, State};
27use axum::http::header::{
28 CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_SECURITY_POLICY, CONTENT_TYPE, LOCATION, ORIGIN,
29 REFERRER_POLICY, X_CONTENT_TYPE_OPTIONS,
30};
31use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
32use axum::response::{IntoResponse, Response};
33use axum::routing::{get, post};
34use axum::{Json, Router};
35use base64::Engine as _;
36use base64::engine::general_purpose::URL_SAFE_NO_PAD;
37use coqui_acp_api::{jsonrpc::Carried, mcp::ToolCall};
38use coqui_peer::PeerId;
39use guatiao::{FromValue, Schema};
40use serde::{Deserialize, Serialize};
41#[cfg(test)]
42use serde_json::{Value, json};
43use sha2::Sha256;
44use tokio::sync::Notify;
45
46use super::tools;
47use crate::Gateway;
48use crate::page_access::{self, Connection, NoViewer};
49use crate::tls::ClientCertificates;
50
51pub(crate) const RESOURCE: &str = "config:assistant";
57
58pub(crate) const FEEDS_DIR: &str = "data/";
60
61use ai6::wire::OpaqueJson;
62use ai6::wire::assistant_events::PageEntry;
63pub(crate) use ai6::wire::assistant_events::PageKind as Kind;
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, FromValue, Schema)]
68#[map(deny_unknown_fields)]
69pub(crate) struct Feed {
70 pub(crate) name: String,
72 pub(crate) tool: String,
74 input: FeedArguments,
76}
77
78#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80#[serde(transparent)]
81struct FeedArguments(Carried);
82
83impl FromValue for FeedArguments {
84 const KINDS: guatiao::Kinds = guatiao::Kinds::MAP;
85
86 fn from_value(input: &guatiao::Value) -> Result<Self, guatiao::MapError> {
87 <&guatiao::Map>::try_from(input)?;
88 Ok(Self(Carried::new(input.clone())))
89 }
90}
91
92impl Schema for FeedArguments {
93 fn kind(alloc: guatiao::Alloc) -> guatiao::schema::KindBuilder {
94 use guatiao::schema::{Extras as _, KindBuilder, vocab};
95 KindBuilder::any_in(alloc).extra(
96 vocab::TYPE,
97 guatiao::Text::new_in(alloc, vocab::TYPE_OBJECT).map(guatiao::Value::from),
98 )
99 }
100}
101
102impl Feed {
103 fn call(&self) -> ToolCall {
104 ToolCall::raw(&self.tool, self.input.0.clone())
105 }
106
107 fn input_json(&self) -> String {
108 serde_json::to_string(&self.input).expect("a dashboard feed's input is JSON")
109 }
110}
111
112#[derive(FromValue)]
114struct FeedScopeArgs {
115 operation_id: Option<String>,
116 scope: Option<String>,
117 subject: Option<String>,
118 action: Option<String>,
119 resource: Option<String>,
120}
121
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
124pub(crate) struct FileMeta {
125 pub(crate) path: String,
126 pub(crate) bytes: u64,
127 pub(crate) sha256: String,
128}
129
130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132pub(crate) struct Page {
133 pub(crate) id: String,
134 pub(crate) person_id: String,
135 pub(crate) conversation_id: String,
136 pub(crate) kind: Kind,
137 pub(crate) title: String,
138 pub(crate) entry: String,
140 pub(crate) files: Vec<FileMeta>,
141 pub(crate) bytes: u64,
142 pub(crate) created_at: f64,
143 pub(crate) expires_at: Option<f64>,
145 pub(crate) feeds: Vec<Feed>,
146 #[serde(default)]
148 pub(crate) shares: Vec<String>,
149 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub(crate) public: Option<String>,
153 #[serde(default, skip_serializing_if = "Vec::is_empty")]
156 pub(crate) feed_readers: Vec<String>,
157 #[serde(default, skip_serializing_if = "Vec::is_empty")]
160 pub(crate) marks: Vec<String>,
161}
162
163impl Page {
164 pub(crate) fn entry(&self) -> PageEntry {
165 PageEntry {
166 id: self.id.clone(),
167 kind: self.kind,
168 title: self.title.clone(),
169 bytes: self.bytes,
170 expires_at: self.expires_at,
171 feeds: self.feeds.iter().map(|feed| feed.name.clone()).collect(),
172 marks: self.marks.clone(),
173 shares: self.shares.clone(),
174 public: self.public.is_some(),
175 }
176 }
177
178 pub(crate) fn summary(&self) -> PageSummary {
180 PageSummary {
181 shares: Some(self.shares.clone()),
182 public: Some(self.public.is_some()),
183 ..self.common()
184 }
185 }
186
187 pub(crate) fn summary_with_link(&self, base: &str) -> PageSummary {
189 PageSummary {
190 public_url: self
191 .public
192 .as_ref()
193 .map(|token| format!("{base}/s/{token}/")),
194 ..self.summary()
195 }
196 }
197
198 pub(crate) fn summary_for(&self, viewer: &str) -> PageSummary {
201 if viewer == self.person_id {
202 return self.summary();
203 }
204 PageSummary {
205 shared_by: Some(self.person_id.clone()),
206 ..self.common()
207 }
208 }
209
210 fn common(&self) -> PageSummary {
211 PageSummary {
212 id: self.id.clone(),
213 kind: self.kind.as_str(),
214 title: self.title.clone(),
215 bytes: self.bytes,
216 expires_at: self.expires_at,
217 feeds: self.feeds.iter().map(|feed| feed.name.clone()).collect(),
218 marks: self.marks.clone(),
219 shares: None,
220 public: None,
221 public_url: None,
222 shared_by: None,
223 }
224 }
225}
226
227#[derive(Debug, Serialize)]
230pub(crate) struct PageSummary {
231 id: String,
232 kind: &'static str,
233 title: String,
234 bytes: u64,
235 expires_at: Option<f64>,
236 feeds: Vec<String>,
237 #[serde(skip_serializing_if = "Vec::is_empty")]
238 marks: Vec<String>,
239 #[serde(skip_serializing_if = "Option::is_none")]
240 shares: Option<Vec<String>>,
241 #[serde(skip_serializing_if = "Option::is_none")]
242 public: Option<bool>,
243 #[serde(skip_serializing_if = "Option::is_none")]
244 public_url: Option<String>,
245 #[serde(skip_serializing_if = "Option::is_none")]
246 shared_by: Option<String>,
247}
248
249pub(crate) fn share_subject(text: &str) -> Option<(&str, &str)> {
253 let (kind, id) = text.split_once(':')?;
254 let known = matches!(
255 kind,
256 "person" | "group" | "account" | "compartment" | "operation"
257 );
258 (known && !id.is_empty() && id.len() <= 256 && !id.chars().any(char::is_control))
259 .then_some((kind, id))
260}
261
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
268pub(crate) enum Serve {
269 Html,
270 Markdown,
271 Text(&'static str),
273 Asset(&'static str),
275 Attachment,
277}
278
279pub(crate) fn classify(path: &str) -> Serve {
281 let extension = path
282 .rsplit_once('.')
283 .map(|(_, extension)| extension.to_ascii_lowercase())
284 .unwrap_or_default();
285 match extension.as_str() {
286 "html" | "htm" => Serve::Html,
287 "md" | "markdown" => Serve::Markdown,
288 "txt" | "log" => Serve::Text("text/plain; charset=utf-8"),
289 "csv" => Serve::Text("text/csv; charset=utf-8"),
290 "json" => Serve::Text("application/json; charset=utf-8"),
291 "svg" => Serve::Asset("image/svg+xml"),
292 "js" | "mjs" => Serve::Asset("text/javascript; charset=utf-8"),
293 "css" => Serve::Asset("text/css; charset=utf-8"),
294 "png" => Serve::Asset("image/png"),
295 "jpg" | "jpeg" => Serve::Asset("image/jpeg"),
296 "gif" => Serve::Asset("image/gif"),
297 "webp" => Serve::Asset("image/webp"),
298 "ico" => Serve::Asset("image/x-icon"),
299 "woff2" => Serve::Asset("font/woff2"),
300 "wasm" => Serve::Asset("application/wasm"),
301 _ => Serve::Attachment,
302 }
303}
304
305pub(crate) fn valid_path(path: &str) -> bool {
311 !path.is_empty()
312 && path.len() <= 512
313 && !path.contains('\\')
314 && !path.chars().any(char::is_control)
315 && path.split('/').all(|part| {
316 !part.is_empty()
317 && !part.starts_with('.')
318 && part.len() <= 255
319 && !part.contains(':')
320 && !part.ends_with(['.', ' '])
321 && !is_device_name(part)
322 })
323}
324
325fn is_device_name(part: &str) -> bool {
328 let stem = part.split('.').next().unwrap_or_default().trim_end();
329 let upper = stem.to_ascii_uppercase();
330 matches!(
331 upper.as_str(),
332 "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
333 ) || ["COM", "LPT"].iter().any(|prefix| {
334 upper.strip_prefix(prefix).is_some_and(|digit| {
335 let mut chars = digit.chars();
336 matches!(
337 (chars.next(), chars.next()),
338 (Some('0'..='9' | '\u{b9}' | '\u{b2}' | '\u{b3}'), None)
339 )
340 })
341 })
342}
343
344pub(crate) fn inside(base: &std::path::Path, path: &str) -> Option<PathBuf> {
348 let at = path
349 .split('/')
350 .fold(base.to_path_buf(), |at, part| at.join(part));
351 let rest = at.strip_prefix(base).ok()?;
352 rest.components()
353 .all(|part| matches!(part, std::path::Component::Normal(_)))
354 .then_some(at)
355}
356
357pub(crate) fn markdown_page(title: &str, source: &str) -> String {
360 use pulldown_cmark::{Options, Parser, html};
361 let options =
362 Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS;
363 let mut body = String::new();
364 html::push_html(&mut body, Parser::new_ext(source, options));
365 format!(
366 "<!doctype html><html><head><meta charset=\"utf-8\"><title>{}</title>\
367 <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><style>{MARKDOWN_STYLE}</style>\
368 </head><body><main>{body}</main></body></html>",
369 escape(title)
370 )
371}
372
373const MARKDOWN_STYLE: &str = "body{font:16px/1.55 system-ui,sans-serif;margin:0;color:#1d1d1f;\
374background:#fff}main{max-width:50rem;margin:0 auto;padding:1.5rem}table{border-collapse:collapse}\
375td,th{border:1px solid #ccc;padding:.3rem .6rem}pre,code{background:#f4f4f6}pre{padding:.8rem;\
376overflow:auto}img{max-width:100%}blockquote{margin-left:0;padding-left:1rem;border-left:4px solid #ccc}";
377
378pub(crate) fn escape(text: &str) -> String {
380 let mut out = String::with_capacity(text.len());
381 for c in text.chars() {
382 match c {
383 '&' => out.push_str("&"),
384 '<' => out.push_str("<"),
385 '>' => out.push_str(">"),
386 '"' => out.push_str("""),
387 '\'' => out.push_str("'"),
388 c => out.push(c),
389 }
390 }
391 out
392}
393
394pub(crate) fn utc_text(seconds: f64) -> String {
396 let at = time::OffsetDateTime::from_unix_timestamp(seconds.max(0.0) as i64).unwrap_or(
398 time::OffsetDateTime::new_utc(time::Date::MAX, time::Time::MIDNIGHT),
399 );
400 format!(
401 "{:04}-{:02}-{:02} {:02}:{:02} UTC",
402 at.year(),
403 u8::from(at.month()),
404 at.day(),
405 at.hour(),
406 at.minute()
407 )
408}
409
410pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
411 PeerId::of(bytes).hex()
412}
413
414fn base64url(bytes: &[u8]) -> String {
416 URL_SAFE_NO_PAD.encode(bytes)
417}
418
419fn random_bytes() -> [u8; 32] {
421 let mut bytes = [0u8; 32];
422 bytes[..16].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
423 bytes[16..].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
424 bytes
425}
426
427fn random_token() -> String {
429 base64url(&random_bytes())
430}
431
432fn keyed(key: &[u8], parts: &[&str]) -> Vec<u8> {
434 use hmac::{KeyInit, Mac};
435 let Ok(mut mac) = hmac::Hmac::<Sha256>::new_from_slice(key) else {
436 unreachable!("HMAC takes a key of any length")
437 };
438 for part in parts {
439 mac.update(part.as_bytes());
440 mac.update(&[0]);
441 }
442 mac.finalize().into_bytes().to_vec()
443}
444
445fn read_or_make_key(path: &std::path::Path) -> io::Result<Vec<u8>> {
448 match std::fs::read(path) {
449 Ok(key) if key.len() == 32 => return Ok(key),
450 Ok(_) => {
451 return Err(io::Error::new(
452 io::ErrorKind::InvalidData,
453 format!("{} is not a key of 32 bytes", path.display()),
454 ));
455 }
456 Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error),
457 Err(_) => {}
458 }
459 let key = random_bytes();
460 let mut options = std::fs::OpenOptions::new();
461 options.write(true).create_new(true);
462 #[cfg(unix)]
463 {
464 use std::os::unix::fs::OpenOptionsExt;
465 options.mode(0o600);
466 }
467 match options.open(path) {
468 Ok(mut file) => {
469 use std::io::Write as _;
470 file.write_all(&key)?;
471 file.sync_all()?;
472 Ok(key.to_vec())
473 }
474 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => std::fs::read(path),
476 Err(error) => Err(error),
477 }
478}
479
480fn now() -> f64 {
481 crate::unix_timestamp().unwrap_or(0.0)
482}
483
484const KEY_FILE: &str = ".key";
491
492struct Staged {
494 station: String,
495 files: BTreeMap<String, Vec<u8>>,
496 bytes: u64,
497 at: Instant,
498 done: Option<Result<Vec<AssistantPageFile>, String>>,
499}
500
501#[derive(Default)]
502struct Inner {
503 pages: BTreeMap<String, Page>,
504 staged: HashMap<(String, String), Staged>,
506 reads: HashMap<String, (Instant, u32)>,
508 handoffs: HashMap<String, Handoff>,
511 drafts: HashMap<String, Prepared>,
514 noted: HashSet<(String, String)>,
516 #[cfg(test)]
518 log: Vec<String>,
519}
520
521#[derive(Debug, Clone)]
523pub(crate) struct Handoff {
524 pub(crate) page: String,
525 pub(crate) person: String,
526 pub(crate) sign_in: String,
528 pub(crate) binder: Option<String>,
532 pub(crate) expires: f64,
534}
535
536pub(crate) fn viewing(page: &str, viewer: &str) -> String {
538 format!("{page} {viewer}")
539}
540
541pub(crate) struct PageStore {
543 dir: PathBuf,
544 key: Vec<u8>,
546 state: Mutex<Inner>,
547 staged: Notify,
548 sweeping: std::sync::atomic::AtomicBool,
549}
550
551impl std::fmt::Debug for PageStore {
552 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
553 f.debug_struct("PageStore")
554 .field("dir", &self.dir)
555 .finish_non_exhaustive()
556 }
557}
558
559#[derive(Debug)]
562pub(crate) struct Prepared {
563 pub(crate) page: Page,
564 temp: PathBuf,
565}
566
567impl Prepared {
568 pub(crate) fn digest(&self) -> String {
571 let what = (
572 &self.page.title,
573 &self.page.entry,
574 &self.page.files,
575 &self.page.feeds,
576 );
577 sha256_hex(serde_json::to_string(&what).unwrap_or_default().as_bytes())
578 }
579
580 fn rebase(&mut self, current: &Page) -> io::Result<()> {
583 self.page.shares.clone_from(¤t.shares);
584 self.page.public.clone_from(¤t.public);
585 std::fs::write(
586 self.temp.join("meta.json"),
587 serde_json::to_vec_pretty(&self.page).map_err(io::Error::other)?,
588 )
589 }
590}
591
592impl PageStore {
593 pub(crate) fn open(dir: PathBuf) -> io::Result<Self> {
600 std::fs::create_dir_all(&dir)?;
601 #[cfg(unix)]
602 {
603 use std::os::unix::fs::PermissionsExt;
604 std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700))?;
605 }
606 let mut pages = BTreeMap::new();
607 for entry in std::fs::read_dir(&dir)?.flatten() {
608 let name = entry.file_name().to_string_lossy().into_owned();
609 if name.contains(".tmp-") {
610 let _ = std::fs::remove_dir_all(entry.path());
612 continue;
613 }
614 let Ok(text) = std::fs::read(entry.path().join("meta.json")) else {
615 continue;
616 };
617 if let Ok(page) = serde_json::from_slice::<Page>(&text)
618 && page.id == name
619 {
620 pages.insert(page.id.clone(), page);
621 }
622 }
623 let key = read_or_make_key(&dir.join(KEY_FILE))?;
624 Ok(Self {
625 dir,
626 key,
627 state: Mutex::new(Inner {
628 pages,
629 ..Inner::default()
630 }),
631 staged: Notify::new(),
632 sweeping: std::sync::atomic::AtomicBool::new(false),
633 })
634 }
635
636 pub(crate) fn keyed_text(&self, parts: &[&str]) -> String {
638 base64url(&keyed(&self.key, parts))
639 }
640
641 pub(crate) fn view_token(
646 &self,
647 page: &str,
648 viewer: &str,
649 network: PageNetwork,
650 expires: f64,
651 ) -> String {
652 let expires = format!("{:.0}", (expires * 1000.0).floor());
653 let mark = self.keyed_text(&["view", page, viewer, network.as_str(), &expires]);
654 format!("{expires}.{}.{mark}", network.as_str())
655 }
656
657 pub(crate) fn viewed(
660 &self,
661 token: &str,
662 page: &str,
663 viewer: &str,
664 ) -> Result<PageNetwork, &'static str> {
665 let mut parts = token.splitn(3, '.');
666 let (Some(expires), Some(network), Some(mark)) = (parts.next(), parts.next(), parts.next())
667 else {
668 return Err("a view token that is none");
669 };
670 let network = match network {
671 "open" => PageNetwork::Open,
672 "own" => PageNetwork::Own,
673 "none" => PageNetwork::None,
674 _ => return Err("a view token that is none"),
675 };
676 let expected = self.keyed_text(&["view", page, viewer, network.as_str(), expires]);
677 if !crate::constant_time_eq(expected.as_bytes(), mark.as_bytes()) {
678 return Err("a view token that is not this viewer's for this page");
679 }
680 match expires.parse::<f64>() {
681 Ok(end) if end / 1000.0 > now() => Ok(network),
682 _ => Err("a view token that has expired; reload the page"),
683 }
684 }
685
686 pub(crate) fn hand_off(&self, handoff: Handoff, most: usize) -> String {
689 let token = format!(
690 "{}{}",
691 uuid::Uuid::new_v4().simple(),
692 uuid::Uuid::new_v4().simple()
693 );
694 let mut inner = self.state();
695 let at = now();
696 inner.handoffs.retain(|_, held| held.expires > at);
697 let person = handoff.person.clone();
698 inner.handoffs.insert(sha256_hex(token.as_bytes()), handoff);
699 loop {
700 let mine = inner
701 .handoffs
702 .iter()
703 .filter(|(_, held)| held.person == person);
704 if mine.clone().count() <= most {
705 break;
706 }
707 let Some(oldest) = mine
708 .min_by(|(_, one), (_, other)| one.expires.total_cmp(&other.expires))
709 .map(|(digest, _)| digest.clone())
710 else {
711 break;
712 };
713 inner.handoffs.remove(&oldest);
714 }
715 token
716 }
717
718 pub(crate) fn take_handoff(&self, token: &str) -> Option<Handoff> {
721 let handoff = self
722 .state()
723 .handoffs
724 .remove(&sha256_hex(token.as_bytes()))?;
725 (handoff.expires > now()).then_some(handoff)
726 }
727
728 pub(crate) fn restore_handoff(&self, token: &str, handoff: Handoff) {
731 self.state()
732 .handoffs
733 .insert(sha256_hex(token.as_bytes()), handoff);
734 }
735
736 pub(crate) fn note(&self, key: &str, reason: &str) {
738 let mut state = self.state();
739 if state.noted.insert((key.to_owned(), reason.to_owned())) {
740 let line = match key.split_once(' ') {
741 Some((page, viewer)) => format!("page {page}, viewer {viewer}: {reason}"),
742 None => format!("page {key}: {reason}"),
743 };
744 eprintln!("universal-exports: {line}");
745 #[cfg(test)]
746 state.log.push(line);
747 }
748 }
749
750 #[cfg(test)]
752 pub(crate) fn logged(&self) -> Vec<String> {
753 self.state().log.clone()
754 }
755
756 pub(crate) fn start_sweeper(&self) -> bool {
758 !self
759 .sweeping
760 .swap(true, std::sync::atomic::Ordering::AcqRel)
761 }
762
763 fn state(&self) -> MutexGuard<'_, Inner> {
764 self.state.lock().unwrap_or_else(PoisonError::into_inner)
765 }
766
767 pub(crate) fn new_id() -> String {
769 format!("page-{}", uuid::Uuid::new_v4().simple())
770 }
771
772 pub(crate) fn get(&self, id: &str) -> Option<Page> {
773 self.state().pages.get(id).cloned()
774 }
775
776 pub(crate) fn shared_by_others(&self, person: &str) -> Vec<Page> {
779 let mut pages: Vec<Page> = self
780 .state()
781 .pages
782 .values()
783 .filter(|page| page.person_id != person && !page.shares.is_empty())
784 .cloned()
785 .collect();
786 pages.sort_by(|a, b| b.created_at.total_cmp(&a.created_at));
787 pages
788 }
789
790 pub(crate) fn share(&self, id: &str, shares: Vec<String>) -> io::Result<Option<Page>> {
796 let mut state = self.state();
797 let Some(page) = state.pages.get(id) else {
798 return Ok(None);
799 };
800 let mut changed = page.clone();
801 changed.shares = shares;
802 self.save(&changed)?;
803 state.pages.insert(changed.id.clone(), changed.clone());
804 Ok(Some(changed))
805 }
806
807 pub(crate) fn confirm_feeds(&self, id: &str, viewer: &str) -> io::Result<Option<Page>> {
813 let mut state = self.state();
814 let Some(page) = state.pages.get(id) else {
815 return Ok(None);
816 };
817 let mut changed = page.clone();
818 if !changed.feed_readers.iter().any(|reader| reader == viewer) {
819 changed.feed_readers.push(viewer.to_owned());
820 }
821 self.save(&changed)?;
822 state.pages.insert(changed.id.clone(), changed.clone());
823 Ok(Some(changed))
824 }
825
826 pub(crate) fn withdraw_feeds(&self, id: &str, viewer: &str) -> io::Result<Option<Page>> {
832 let mut state = self.state();
833 let Some(page) = state.pages.get(id) else {
834 return Ok(None);
835 };
836 let mut changed = page.clone();
837 changed.feed_readers.retain(|reader| reader != viewer);
838 self.save(&changed)?;
839 state.pages.insert(changed.id.clone(), changed.clone());
840 Ok(Some(changed))
841 }
842
843 pub(crate) fn of(&self, person: &str) -> Vec<Page> {
845 let mut pages: Vec<Page> = self
846 .state()
847 .pages
848 .values()
849 .filter(|page| page.person_id == person)
850 .cloned()
851 .collect();
852 pages.sort_by(|a, b| b.created_at.total_cmp(&a.created_at));
853 pages
854 }
855
856 pub(crate) fn prepare(
863 &self,
864 page: Page,
865 files: &BTreeMap<String, Vec<u8>>,
866 limits: &AssistantPageLimits,
867 ) -> Result<Prepared, String> {
868 let total: u64 = files.values().map(|bytes| bytes.len() as u64).sum();
869 if files.is_empty() {
870 return Err("the page has no file".to_owned());
871 }
872 if !limits.max_page_files.allows(files.len()) {
873 return Err(format!("a page may hold {} files", limits.max_page_files));
874 }
875 for (path, bytes) in files {
876 if !valid_path(path) {
877 return Err(format!("{path:?} is not a path inside a page"));
878 }
879 if !limits.max_file_bytes.allows(bytes.len()) {
880 return Err(format!(
881 "{path} is longer than {} bytes, the most one file of a page may hold",
882 limits.max_file_bytes
883 ));
884 }
885 }
886 if let Some(path) = files.keys().find(|path| path.starts_with(FEEDS_DIR)) {
887 return Err(format!(
888 "{path} is under a top-level {FEEDS_DIR} directory, where a dashboard reads its \
889 feeds as {FEEDS_DIR}NAME; put it in another directory"
890 ));
891 }
892 if !limits.max_page_bytes.allows(total as usize) {
893 return Err(format!(
894 "the page is longer than {} bytes",
895 limits.max_page_bytes
896 ));
897 }
898 {
899 let state = self.state();
900 let others = state.pages.values().filter(|other| other.id != page.id);
901 let (mut count, mut person, mut all) = (0usize, 0u64, 0u64);
902 for other in others {
903 all += other.bytes;
904 if other.person_id == page.person_id {
905 count += 1;
906 person += other.bytes;
907 }
908 }
909 if !limits.max_pages.allows(count + 1) {
910 return Err(format!(
911 "you already have {} pages, the most kept; delete one first",
912 limits.max_pages
913 ));
914 }
915 if !limits.max_person_bytes.allows((person + total) as usize) {
916 return Err(format!(
917 "your pages would be longer than {} bytes in all",
918 limits.max_person_bytes
919 ));
920 }
921 if !limits.max_total_bytes.allows((all + total) as usize) {
922 return Err("this gateway holds all the page bytes it is set to".to_owned());
923 }
924 }
925 let temp = self
926 .dir
927 .join(format!("{}.tmp-{}", page.id, uuid::Uuid::new_v4().simple()));
928 let write = || -> io::Result<()> {
929 for (path, bytes) in files {
930 let at = inside(&temp.join("files"), path)
931 .ok_or_else(|| io::Error::other(format!("{path} is not inside the page")))?;
932 if let Some(parent) = at.parent() {
933 std::fs::create_dir_all(parent)?;
934 }
935 std::fs::write(at, bytes)?;
936 }
937 std::fs::write(
938 temp.join("meta.json"),
939 serde_json::to_vec_pretty(&page).map_err(io::Error::other)?,
940 )
941 };
942 if let Err(error) = write() {
943 let _ = std::fs::remove_dir_all(&temp);
944 return Err(format!("the page could not be stored: {error}"));
945 }
946 Ok(Prepared { page, temp })
947 }
948
949 pub(crate) fn commit(&self, prepared: Prepared) -> io::Result<Page> {
955 let Prepared { page, temp } = prepared;
956 let at = self.dir.join(&page.id);
957 let mut state = self.state();
958 if at.exists() {
959 std::fs::remove_dir_all(&at)?;
960 }
961 std::fs::rename(&temp, &at)?;
962 if let Some(draft) = state.drafts.remove(&page.id) {
963 let _ = std::fs::remove_dir_all(draft.temp);
964 }
965 state.pages.insert(page.id.clone(), page.clone());
966 Ok(page)
967 }
968
969 pub(crate) fn discard(&self, prepared: Prepared) {
971 let _ = std::fs::remove_dir_all(prepared.temp);
972 }
973
974 pub(crate) fn hold_draft(&self, prepared: Prepared) {
977 let earlier = self
978 .state()
979 .drafts
980 .insert(prepared.page.id.clone(), prepared);
981 if let Some(earlier) = earlier {
982 self.discard(earlier);
983 }
984 }
985
986 pub(crate) fn retain_drafts(&self, keep: impl Fn(&str, &str) -> bool) {
988 let mut state = self.state();
989 let gone: Vec<String> = state
990 .drafts
991 .iter()
992 .filter(|(id, draft)| !keep(id, &draft.digest()))
993 .map(|(id, _)| id.clone())
994 .collect();
995 for id in gone {
996 if let Some(draft) = state.drafts.remove(&id) {
997 let _ = std::fs::remove_dir_all(draft.temp);
998 }
999 }
1000 }
1001
1002 pub(crate) fn draft(&self, id: &str) -> Option<Page> {
1004 self.state().drafts.get(id).map(|draft| draft.page.clone())
1005 }
1006
1007 pub(crate) fn read_draft_file(&self, id: &str, path: &str) -> Option<Vec<u8>> {
1009 let state = self.state();
1010 let draft = state.drafts.get(id)?;
1011 if !draft.page.files.iter().any(|file| file.path == path) {
1012 return None;
1013 }
1014 let at = inside(&draft.temp.join("files"), path)?;
1015 drop(state);
1016 std::fs::read(at).ok()
1017 }
1018
1019 pub(crate) fn take_draft(&self, id: &str, digest: &str) -> Option<Prepared> {
1022 let mut state = self.state();
1023 let current = state.pages.get(id).cloned();
1024 if state.drafts.get(id)?.digest() != digest {
1025 return None;
1026 }
1027 let mut draft = state.drafts.remove(id)?;
1028 drop(state);
1029 if let Some(current) = current
1030 && draft.rebase(¤t).is_err()
1031 {
1032 self.discard(draft);
1033 return None;
1034 }
1035 Some(draft)
1036 }
1037
1038 fn save(&self, page: &Page) -> io::Result<()> {
1040 std::fs::write(
1041 self.dir.join(&page.id).join("meta.json"),
1042 serde_json::to_vec_pretty(page).map_err(io::Error::other)?,
1043 )
1044 }
1045
1046 pub(crate) fn delete(&self, id: &str) -> Option<Page> {
1048 let mut state = self.state();
1049 let page = state.pages.remove(id)?;
1050 if let Some(draft) = state.drafts.remove(id) {
1051 let _ = std::fs::remove_dir_all(draft.temp);
1052 }
1053 Self::forget_viewing(&mut state);
1054 let _ = std::fs::remove_dir_all(self.dir.join(id));
1055 Some(page)
1056 }
1057
1058 fn forget_viewing(state: &mut Inner) {
1060 let Inner {
1061 pages,
1062 reads,
1063 noted,
1064 ..
1065 } = state;
1066 let standing = |key: &str| pages.contains_key(key.split(' ').next().unwrap_or(key));
1067 reads.retain(|key, _| standing(key));
1068 noted.retain(|(key, _)| standing(key));
1069 }
1070
1071 pub(crate) fn remember(&self, id: &str, remember: bool, ttl: Duration) -> Option<Page> {
1073 let mut state = self.state();
1074 let page = state.pages.get_mut(id)?;
1075 page.expires_at = if remember {
1076 None
1077 } else {
1078 Some(now() + ttl.as_secs_f64())
1079 };
1080 let page = page.clone();
1081 let _ = self.save(&page);
1082 Some(page)
1083 }
1084
1085 pub(crate) fn read_file(&self, page: &Page, path: &str) -> Option<Vec<u8>> {
1087 if !page.files.iter().any(|file| file.path == path) {
1088 return None;
1089 }
1090 let at = inside(&self.dir.join(&page.id).join("files"), path)?;
1091 std::fs::read(at).ok()
1092 }
1093
1094 pub(crate) fn sweep(&self, at: f64, stage_ttl: Duration) -> Vec<Page> {
1096 let mut state = self.state();
1097 let expired: Vec<String> = state
1098 .pages
1099 .values()
1100 .filter(|page| page.expires_at.is_some_and(|end| end <= at))
1101 .map(|page| page.id.clone())
1102 .collect();
1103 let mut gone = Vec::new();
1104 for id in expired {
1105 if let Some(page) = state.pages.remove(&id) {
1106 if let Some(draft) = state.drafts.remove(&id) {
1107 let _ = std::fs::remove_dir_all(draft.temp);
1108 }
1109 let _ = std::fs::remove_dir_all(self.dir.join(&id));
1110 gone.push(page);
1111 }
1112 }
1113 Self::forget_viewing(&mut state);
1114 state
1115 .staged
1116 .retain(|_, staged| staged.at.elapsed() < stage_ttl);
1117 gone
1118 }
1119
1120 pub(crate) fn note_read(&self, key: &str, most: usize) -> bool {
1122 let mut state = self.state();
1123 let entry = state
1124 .reads
1125 .entry(key.to_owned())
1126 .or_insert((Instant::now(), 0));
1127 if entry.0.elapsed() >= Duration::from_secs(60) {
1128 *entry = (Instant::now(), 0);
1129 }
1130 entry.1 += 1;
1131 usize::try_from(entry.1).is_ok_and(|count| ai6::Limit::at(most as u64).allows(count))
1132 }
1133
1134 pub(crate) fn set_public(&self, id: &str, on: bool) -> io::Result<Option<Page>> {
1143 let mut state = self.state();
1144 let Some(page) = state.pages.get(id) else {
1145 return Ok(None);
1146 };
1147 let mut changed = page.clone();
1148 changed.public = match (on, changed.public.take()) {
1149 (true, Some(kept)) => Some(kept),
1150 (true, None) => Some(random_token()),
1151 (false, _) => None,
1152 };
1153 self.save(&changed)?;
1154 state.pages.insert(changed.id.clone(), changed.clone());
1155 Ok(Some(changed))
1156 }
1157
1158 pub(crate) fn public(&self, token: &str) -> Option<Page> {
1160 let at = now();
1161 self.state()
1162 .pages
1163 .values()
1164 .find(|page| {
1165 page.public.as_deref() == Some(token)
1166 && !page.expires_at.is_some_and(|end| end <= at)
1167 })
1168 .cloned()
1169 }
1170
1171 pub(crate) fn stage_file(
1179 &self,
1180 station: &str,
1181 conversation: &str,
1182 digest: &str,
1183 path: &str,
1184 bytes: Vec<u8>,
1185 limits: &AssistantPageLimits,
1186 ) -> Result<(), String> {
1187 if !valid_path(path) {
1188 return Err(format!("{path:?} is not a path inside a page"));
1189 }
1190 if !limits.max_file_bytes.allows(bytes.len()) {
1191 return Err(format!(
1192 "{path} is longer than {} bytes",
1193 limits.max_file_bytes
1194 ));
1195 }
1196 let key = (conversation.to_owned(), digest.to_owned());
1197 let mut state = self.state();
1198 if !state.staged.contains_key(&key) && !limits.staged_uploads.allows(state.staged.len() + 1)
1199 {
1200 return Err("too many uploads wait to be published".to_owned());
1201 }
1202 let staged = state.staged.entry(key).or_insert_with(|| Staged {
1203 station: station.to_owned(),
1204 files: BTreeMap::new(),
1205 bytes: 0,
1206 at: Instant::now(),
1207 done: None,
1208 });
1209 if staged.station != station || staged.done.is_some() {
1210 return Err("this upload is not open to that Station".to_owned());
1211 }
1212 let before = staged.files.get(path).map_or(0, Vec::len) as u64;
1213 let bytes_total = staged.bytes - before + bytes.len() as u64;
1214 if !limits
1215 .max_page_files
1216 .allows(staged.files.len() + usize::from(before == 0))
1217 {
1218 return Err(format!("a page may hold {} files", limits.max_page_files));
1219 }
1220 if !limits.max_page_bytes.allows(bytes_total as usize) {
1221 return Err(format!("a page may hold {} bytes", limits.max_page_bytes));
1222 }
1223 staged.bytes = bytes_total;
1224 staged.files.insert(path.to_owned(), bytes);
1225 Ok(())
1226 }
1227
1228 pub(crate) fn stage_done(
1234 &self,
1235 station: &str,
1236 conversation: &str,
1237 digest: &str,
1238 outcome: Result<Vec<AssistantPageFile>, String>,
1239 limits: &AssistantPageLimits,
1240 ) -> Result<(), String> {
1241 let key = (conversation.to_owned(), digest.to_owned());
1242 {
1243 let mut state = self.state();
1244 if !state.staged.contains_key(&key)
1245 && !limits.staged_uploads.allows(state.staged.len() + 1)
1246 {
1247 return Err("too many uploads wait to be published".to_owned());
1248 }
1249 let staged = state.staged.entry(key).or_insert_with(|| Staged {
1250 station: station.to_owned(),
1251 files: BTreeMap::new(),
1252 bytes: 0,
1253 at: Instant::now(),
1254 done: None,
1255 });
1256 if staged.station != station {
1257 return Err("this upload is not open to that Station".to_owned());
1258 }
1259 staged.done = Some(outcome);
1260 }
1261 self.staged.notify_waiters();
1262 Ok(())
1263 }
1264
1265 pub(crate) async fn claim(
1268 &self,
1269 conversation: &str,
1270 digest: &str,
1271 wait: Duration,
1272 ) -> Result<BTreeMap<String, Vec<u8>>, String> {
1273 let key = (conversation.to_owned(), digest.to_owned());
1274 let deadline = tokio::time::Instant::now() + wait;
1275 loop {
1276 let notified = self.staged.notified();
1277 tokio::pin!(notified);
1278 notified.as_mut().enable();
1280 {
1281 let mut state = self.state();
1282 if state
1283 .staged
1284 .get(&key)
1285 .is_some_and(|staged| staged.done.is_some())
1286 && let Some(staged) = state.staged.remove(&key)
1287 {
1288 return match staged.done {
1289 Some(Ok(manifest)) => verify(staged.files, manifest),
1290 Some(Err(reason)) => Err(format!("the Station refused it: {reason}")),
1291 None => Err("the upload did not finish".to_owned()),
1292 };
1293 }
1294 }
1295 if tokio::time::timeout_at(deadline, notified).await.is_err() {
1296 self.state().staged.remove(&key);
1297 return Err(format!(
1298 "the Station sent no files within {} seconds; is the path under \
1299 personal/ or scratch/?",
1300 wait.as_secs()
1301 ));
1302 }
1303 }
1304 }
1305}
1306
1307fn verify(
1310 files: BTreeMap<String, Vec<u8>>,
1311 manifest: Vec<AssistantPageFile>,
1312) -> Result<BTreeMap<String, Vec<u8>>, String> {
1313 if manifest.len() != files.len() {
1314 return Err("the Station's manifest does not match what it sent".to_owned());
1315 }
1316 for file in &manifest {
1317 match files.get(&file.path) {
1318 Some(bytes) if bytes.len() as u64 == file.bytes && sha256_hex(bytes) == file.sha256 => {
1319 }
1320 _ => {
1321 return Err(format!(
1322 "{} does not match the Station's manifest",
1323 file.path
1324 ));
1325 }
1326 }
1327 }
1328 Ok(files)
1329}
1330
1331fn origin_of(base: &str) -> &str {
1338 let after_scheme = base.find("://").map_or(0, |at| at + 3);
1339 base[after_scheme..]
1340 .find('/')
1341 .map_or(base, |at| &base[..after_scheme + at])
1342}
1343
1344fn sandbox_tokens(network: PageNetwork, scripts: bool) -> String {
1349 let mut tokens = String::from("allow-forms");
1350 if network == PageNetwork::Open {
1351 tokens.push_str(" allow-popups allow-popups-to-escape-sandbox");
1352 }
1353 tokens.push_str(" allow-downloads allow-modals");
1354 if scripts {
1355 tokens.push_str(" allow-scripts");
1356 }
1357 tokens
1358}
1359
1360pub(crate) fn page_csp(base: &str, network: PageNetwork, scripts: bool) -> String {
1365 let mut csp = format!("sandbox {}", sandbox_tokens(network, scripts));
1366 let _ = write!(csp, "; frame-ancestors {}", origin_of(base));
1367 let default_src = "default-src 'self' data: blob: 'unsafe-inline' 'unsafe-eval'";
1368 match network {
1369 PageNetwork::Own => {
1370 let _ = write!(
1371 csp,
1372 "; {default_src}; connect-src 'self' data: blob:; form-action 'self'"
1373 );
1374 }
1375 PageNetwork::None => {
1376 let _ = write!(
1377 csp,
1378 "; {default_src}; connect-src 'none'; form-action 'self'"
1379 );
1380 }
1381 _ => {}
1382 }
1383 csp
1384}
1385
1386pub(crate) fn frame_csp(base: &str) -> String {
1389 format!(
1390 "default-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-src {base}/; \
1391 form-action 'self'; base-uri 'none'; frame-ancestors 'none'"
1392 )
1393}
1394
1395async fn draft_frame(
1399 State(gateway): State<Gateway>,
1400 UrlPath(id): UrlPath<String>,
1401 connection: Option<Extension<ConnectInfo<SocketAddr>>>,
1402 certificates: Option<Extension<ClientCertificates>>,
1403 headers: HeaderMap,
1404) -> Response {
1405 if !matches!(loads(&headers), Loads::Page) {
1406 return gone();
1407 }
1408 let (store, page, viewer, limits) =
1409 match asked(&gateway, &id, &headers, (connection, certificates)).await {
1410 Ok(asked) => asked,
1411 Err(refused) => return *refused,
1412 };
1413 let Some(mut draft) = store
1414 .draft(&page.id)
1415 .filter(|_| viewer.id == page.person_id)
1416 else {
1417 return gone();
1418 };
1419 draft.title = format!("Preview: {}", draft.title);
1420 let expires = now() + limits.open_ttl.0.as_secs_f64();
1423 let token = store.view_token(&draft_key(&page.id), &viewer.id, PageNetwork::None, expires);
1424 let src = format!("{token}/f/");
1425 let mut response = frame_html(
1426 &draft,
1427 &Viewing::Person(&viewer.id),
1428 "",
1429 &src,
1430 (&limits, PageNetwork::None),
1431 None,
1432 )
1433 .into_response();
1434 *response.headers_mut() = frame_headers(&pages_base(&gateway));
1435 response
1436}
1437
1438fn draft_key(id: &str) -> String {
1440 format!("{id}#draft")
1441}
1442
1443async fn draft_file(
1446 State(gateway): State<Gateway>,
1447 UrlPath((id, token, path)): UrlPath<(String, String, String)>,
1448 Query(query): Query<FileQuery>,
1449 connection: Option<Extension<ConnectInfo<SocketAddr>>>,
1450 certificates: Option<Extension<ClientCertificates>>,
1451 headers: HeaderMap,
1452) -> Response {
1453 let (store, page, viewer, limits) =
1454 match asked(&gateway, &id, &headers, (connection, certificates)).await {
1455 Ok(asked) => asked,
1456 Err(refused) => return *refused,
1457 };
1458 if viewer.id != page.person_id
1459 || store
1460 .viewed(&token, &draft_key(&page.id), &viewer.id)
1461 .is_err()
1462 {
1463 return gone();
1464 }
1465 let Some(draft) = store.draft(&page.id) else {
1466 return gone();
1467 };
1468 let csp = page_csp(&pages_base(&gateway), PageNetwork::None, limits.scripts);
1469 store
1470 .read_draft_file(&page.id, &path)
1471 .and_then(|bytes| serve_bytes(&draft, &path, bytes, query.source.is_some(), &csp))
1472 .unwrap_or_else(gone)
1473}
1474
1475fn page_headers(csp: &str) -> HeaderMap {
1477 let mut headers = HeaderMap::new();
1478 let set = |headers: &mut HeaderMap, name: HeaderName, value: &str| {
1479 if let Ok(value) = HeaderValue::from_str(value) {
1480 headers.insert(name, value);
1481 }
1482 };
1483 set(&mut headers, CONTENT_SECURITY_POLICY, csp);
1484 set(&mut headers, X_CONTENT_TYPE_OPTIONS, "nosniff");
1485 set(&mut headers, REFERRER_POLICY, "no-referrer");
1486 set(&mut headers, CACHE_CONTROL, "no-store, private");
1487 set(
1490 &mut headers,
1491 HeaderName::from_static("cross-origin-resource-policy"),
1492 "cross-origin",
1493 );
1494 set(
1495 &mut headers,
1496 HeaderName::from_static("access-control-allow-origin"),
1497 "*",
1498 );
1499 headers
1500}
1501
1502pub(crate) fn profile(limits: &AssistantPageLimits, asked: Option<PageNetwork>) -> PageNetwork {
1504 limits.network.tighter(asked.unwrap_or(PageNetwork::Open))
1505}
1506
1507#[derive(Debug, Clone, PartialEq, Eq)]
1513pub struct PagesConfig {
1514 pub dir: PathBuf,
1516 pub origin: Option<String>,
1519 pub listen: Option<std::net::SocketAddr>,
1521}
1522
1523impl PagesConfig {
1524 #[must_use]
1526 pub fn new(dir: impl Into<PathBuf>) -> Self {
1527 Self {
1528 dir: dir.into(),
1529 origin: None,
1530 listen: None,
1531 }
1532 }
1533
1534 #[must_use]
1536 pub fn with_origin(mut self, origin: impl Into<String>, listen: std::net::SocketAddr) -> Self {
1537 self.origin = Some(origin.into());
1538 self.listen = Some(listen);
1539 self
1540 }
1541}
1542
1543pub(crate) fn pages_base(gateway: &Gateway) -> String {
1545 match gateway
1546 .pages_config
1547 .as_ref()
1548 .and_then(|config| config.origin.clone())
1549 {
1550 Some(origin) => origin.trim_end_matches('/').to_owned(),
1551 None => format!("{}/pages", gateway.public_origin().trim_end_matches('/')),
1552 }
1553}
1554
1555pub(crate) fn pages_router() -> Router<Gateway> {
1562 Router::new()
1563 .route("/p/{id}/", get(frame).post(continue_as))
1564 .route("/p/{id}/draft/", get(draft_frame))
1565 .route("/p/{id}/draft/{token}/f/{*path}", get(draft_file))
1566 .route("/p/{id}/{token}/f/{*path}", get(file))
1567 .route("/p/{id}/{token}/data/{name}", get(feed))
1568 .route("/p/{id}/{token}/confirm", post(confirm))
1569 .route("/p/{id}/{token}/withdraw", post(withdraw))
1570 .route("/p/{id}/{token}/f/data/{name}", get(feed))
1571 .route("/s/{token}/", get(public_frame))
1572 .route("/s/{token}/f/{*path}", get(public_file))
1573}
1574
1575fn gone() -> Response {
1576 StatusCode::NOT_FOUND.into_response()
1577}
1578
1579async fn compartments_now(gateway: &Gateway) -> Option<ai6::CompiledCompartments> {
1582 let roster = gateway.roster.clone()?;
1583 tokio::task::spawn_blocking(move || {
1584 ai6::directorates::m::compartments::current(roster.as_ref()).ok()
1585 })
1586 .await
1587 .ok()?
1588}
1589
1590pub(crate) async fn reads_operation(gateway: &Gateway, person: &Person, operation: &str) -> bool {
1593 crate::resource_action_allowed(
1594 gateway,
1595 person.clone(),
1596 crate::tree::operation_resource(operation),
1597 "mission.read",
1598 )
1599 .await
1600 .unwrap_or(false)
1601}
1602
1603pub(crate) async fn read_into(gateway: &Gateway, person: &Person, id: &str) -> bool {
1605 compartments_now(gateway)
1606 .await
1607 .is_some_and(|compiled| compiled.person_holds(id, person))
1608}
1609
1610pub(crate) async fn may_view(
1613 gateway: &Gateway,
1614 page: &Page,
1615 viewer: &Person,
1616 limits: &AssistantPageLimits,
1617) -> bool {
1618 if page.person_id == viewer.id {
1619 return true;
1620 }
1621 if !limits.sharing {
1622 return false;
1623 }
1624 for share in &page.shares {
1625 let named = match share_subject(share) {
1626 Some(("compartment", id)) => read_into(gateway, viewer, id).await,
1627 Some(("operation", id)) => reads_operation(gateway, viewer, id).await,
1628 Some(_) => share
1629 .parse::<ai6::Subject>()
1630 .is_ok_and(|subject| subject.matches(viewer)),
1631 None => false,
1632 };
1633 if named {
1634 return true;
1635 }
1636 }
1637 false
1638}
1639
1640async fn page_limits(gateway: &Gateway) -> Option<AssistantPageLimits> {
1642 Some(
1643 super::assistant_settings(gateway)
1644 .await
1645 .ok()?
1646 .pages()
1647 .clone(),
1648 )
1649}
1650
1651pub(crate) const SIGNED_OUT: &str = "You are signed out: your sign-in has ended. Sign in to \
1653 Outer Office and open the page again.";
1654
1655fn signed_out() -> Response {
1657 let mut headers = page_headers("sandbox; default-src 'none'");
1658 headers.insert(
1659 CONTENT_TYPE,
1660 HeaderValue::from_static("text/plain; charset=utf-8"),
1661 );
1662 (StatusCode::FORBIDDEN, headers, SIGNED_OUT).into_response()
1663}
1664
1665async fn asked(
1670 gateway: &Gateway,
1671 id: &str,
1672 headers: &HeaderMap,
1673 connection: Connection,
1674) -> Result<(std::sync::Arc<PageStore>, Page, Person, AssistantPageLimits), Box<Response>> {
1675 let refused = || Box::new(gone());
1676 let store = gateway.pages.clone().ok_or_else(refused)?;
1677 let at = now();
1678 let page = store
1679 .get(id)
1680 .filter(|page| !page.expires_at.is_some_and(|end| end <= at))
1681 .ok_or_else(refused)?;
1682 let viewer = match page_access::viewer(gateway, headers, connection).await {
1683 Ok(viewer) => viewer,
1684 Err(NoViewer::SignedOut) => {
1685 store.note(
1686 &page.id,
1687 "asked for with the cookie of a sign-in that has ended",
1688 );
1689 return Err(Box::new(signed_out()));
1690 }
1691 Err(NoViewer::Nobody) => return Err(refused()),
1692 Err(NoViewer::Unavailable) => {
1693 store.note(&page.id, "the viewer could not be told");
1694 return Err(Box::new(StatusCode::SERVICE_UNAVAILABLE.into_response()));
1695 }
1696 };
1697 let Some(limits) = page_limits(gateway).await else {
1698 store.note(&page.id, "the roster could not be read");
1699 return Err(Box::new(StatusCode::SERVICE_UNAVAILABLE.into_response()));
1700 };
1701 if !may_view(gateway, &page, &viewer, &limits).await {
1702 store.note(
1703 &viewing(&page.id, &viewer.id),
1704 "the viewer may not read the page",
1705 );
1706 return Err(refused());
1707 }
1708 if page.kind == Kind::Live {
1709 return Err(Box::new(in_the_app()));
1710 }
1711 Ok((store, page, viewer, limits))
1712}
1713
1714fn in_the_app() -> Response {
1717 let mut headers = page_headers("sandbox; default-src 'none'");
1718 headers.insert(
1719 CONTENT_TYPE,
1720 HeaderValue::from_static("text/plain; charset=utf-8"),
1721 );
1722 (
1723 StatusCode::NOT_FOUND,
1724 headers,
1725 "This is a live report: open it in Outer Office.",
1726 )
1727 .into_response()
1728}
1729
1730fn see_other(to: &str) -> Response {
1732 let mut response = StatusCode::SEE_OTHER.into_response();
1733 if let Ok(to) = HeaderValue::from_str(to) {
1734 response.headers_mut().insert(LOCATION, to);
1735 }
1736 response
1737}
1738
1739fn top_level(headers: &HeaderMap) -> bool {
1742 headers
1743 .get("sec-fetch-dest")
1744 .and_then(|value| value.to_str().ok())
1745 == Some("document")
1746}
1747
1748enum Loads {
1750 Page,
1752 Unknown,
1755 Elsewhere,
1757}
1758
1759fn loads(headers: &HeaderMap) -> Loads {
1763 let site = headers
1764 .get("sec-fetch-site")
1765 .and_then(|value| value.to_str().ok());
1766 match headers
1767 .get("sec-fetch-dest")
1768 .and_then(|value| value.to_str().ok())
1769 {
1770 None if site.is_none() => Loads::Unknown,
1773 None => Loads::Elsewhere,
1774 Some("document") => Loads::Page,
1775 Some("iframe") if site == Some("same-origin") => Loads::Page,
1776 Some(_) => Loads::Elsewhere,
1777 }
1778}
1779
1780fn same_origin_post(gateway: &Gateway, headers: &HeaderMap) -> bool {
1784 match headers
1785 .get("sec-fetch-site")
1786 .and_then(|value| value.to_str().ok())
1787 {
1788 Some(site) => site == "same-origin",
1789 None => {
1790 !headers.contains_key("sec-fetch-dest")
1791 && headers.get(ORIGIN).is_some_and(|origin| {
1792 origin.as_bytes() == origin_of(&pages_base(gateway)).as_bytes()
1793 })
1794 }
1795 }
1796}
1797
1798fn open_link(gateway: &Gateway, id: &str, network: Option<&str>) -> Response {
1801 let base = pages_base(gateway);
1802 let network = network
1805 .map(|network| {
1806 format!(
1807 "<input type=\"hidden\" name=\"network\" value=\"{}\">",
1808 escape(network)
1809 )
1810 })
1811 .unwrap_or_default();
1812 let html = format!(
1813 "<!doctype html><html><head><meta charset=\"utf-8\"><title>Open this page</title>\
1814</head><body><form method=\"post\" action=\"{base}/p/{id}/\">{network}\
1815<button type=\"submit\">Open this page</button></form></body></html>",
1816 id = percent(id),
1817 );
1818 let mut response = (StatusCode::OK, html).into_response();
1819 *response.headers_mut() = frame_headers(&base);
1820 response
1821}
1822
1823#[derive(Deserialize, Default)]
1824#[serde(default)]
1825struct FrameQuery {
1826 network: Option<String>,
1828 handoff: Option<String>,
1830}
1831
1832async fn handed_off(
1838 gateway: &Gateway,
1839 id: &str,
1840 token: &str,
1841 network: Option<&str>,
1842 method: &Method,
1843 headers: &HeaderMap,
1844 swap: bool,
1845) -> Response {
1846 let navigation = if swap {
1847 *method == Method::POST && same_origin_post(gateway, headers)
1849 } else {
1850 *method == Method::GET
1851 && !headers.contains_key("sec-purpose")
1852 && headers
1853 .get("sec-fetch-dest")
1854 .is_none_or(|dest| dest == "document")
1855 };
1856 if !navigation || !matches!(network, None | Some("none" | "own" | "open")) {
1857 return gone();
1858 }
1859 let Some(store) = gateway.pages.clone() else {
1860 return gone();
1861 };
1862 let handoff = store.take_handoff(token);
1863 let at = now();
1864 let Some(page) = store
1865 .get(id)
1866 .filter(|page| !page.expires_at.is_some_and(|end| end <= at))
1867 else {
1868 return gone();
1869 };
1870 let Some(handoff) = handoff.filter(|handoff| handoff.page == page.id) else {
1871 store.note(&page.id, "a hand-off spent, ended or for another page");
1872 return gone();
1873 };
1874 if let Some(binder) = &handoff.binder {
1875 let held = page_access::hand_nonce(headers).map(|nonce| sha256_hex(nonce.as_bytes()));
1876 if held.as_deref() != Some(binder.as_str()) {
1877 store.note(
1878 &page.id,
1879 "a hand-off used by a browser that did not ask for it",
1880 );
1881 return gone();
1882 }
1883 }
1884 let Some(viewer) = handoff_viewer(gateway, &store, &page, &handoff).await else {
1885 return gone();
1886 };
1887 if !swap
1890 && let Ok(held) = page_access::viewer(gateway, headers, (None, None)).await
1891 && held.id != viewer.id
1892 {
1893 let held_label = crate::principals::label_of(gateway, &held.id).await;
1894 let for_label = crate::principals::label_of(gateway, &viewer.id).await;
1895 store.restore_handoff(token, handoff);
1896 let (held_label, for_label) = (
1897 format!("{held_label} (person:{})", held.id),
1898 format!("{for_label} (person:{})", viewer.id),
1899 );
1900 store.note(
1901 &viewing(&page.id, &viewer.id),
1902 "a hand-off for another person than the browser's pages are signed in as",
1903 );
1904 return swap_prompt(
1905 gateway,
1906 &page.id,
1907 (token, network),
1908 (&held_label, &for_label),
1909 );
1910 }
1911 let registry = gateway.registry.clone();
1912 let sign_in = handoff.sign_in.clone();
1913 let Some(Ok(Ok(Some(login)))) = (match registry {
1914 Some(registry) => {
1915 Some(tokio::task::spawn_blocking(move || registry.login_by_id(&sign_in)).await)
1916 }
1917 None => None,
1918 }) else {
1919 store.note(
1920 &viewing(&page.id, &viewer.id),
1921 "a hand-off whose sign-in has ended",
1922 );
1923 return gone();
1924 };
1925 let seconds = login.expires_at() - now();
1926 let Some(cookie) = page_access::handed_off_cookie(gateway, &handoff.sign_in, seconds) else {
1927 return gone();
1928 };
1929 if super::audit(
1931 gateway,
1932 &viewer,
1933 "moneypenny.page.handoff_used",
1934 String::new(),
1935 Some(RESOURCE.to_owned()),
1936 &page.id,
1937 )
1938 .await
1939 .is_err()
1940 {
1941 store.note(&page.id, "a hand-off that could not be audited");
1942 return StatusCode::SERVICE_UNAVAILABLE.into_response();
1943 }
1944 let mut clean = format!("{}/p/{}/", pages_base(gateway), percent(&page.id));
1945 if let Some(network) = network {
1946 clean.push_str(&format!("?network={network}"));
1947 }
1948 let mut response = see_other(&clean);
1949 let answer = response.headers_mut();
1950 answer.insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
1951 answer.insert(REFERRER_POLICY, HeaderValue::from_static("no-referrer"));
1952 page_access::append(answer, Some(cookie));
1953 response
1954}
1955
1956fn swap_prompt(
1960 gateway: &Gateway,
1961 id: &str,
1962 (token, network): (&str, Option<&str>),
1963 (held, linked): (&str, &str),
1964) -> Response {
1965 let base = pages_base(gateway);
1966 let fields = format!(
1967 "<input type=\"hidden\" name=\"handoff\" value=\"{}\">{}",
1968 escape(token),
1969 network
1970 .map(|network| format!(
1971 "<input type=\"hidden\" name=\"network\" value=\"{}\">",
1972 escape(network)
1973 ))
1974 .unwrap_or_default()
1975 );
1976 let html = format!(
1977 "<!doctype html><html><head><meta charset=\"utf-8\"><title>Open this page</title>\
1978<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><style>\
1979body{{font:16px system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}}\
1980</style></head><body><p>You are signed in to pages as <b>{held}</b>; this link is for \
1981<b>{linked}</b>. Continue as {linked}?</p>\
1982<form method=\"post\" action=\"{base}/p/{id}/\">{fields}<button type=\"submit\">Continue as \
1983{linked}</button></form></body></html>",
1984 held = escape(held),
1985 linked = escape(linked),
1986 id = percent(id),
1987 );
1988 let mut response = (StatusCode::OK, html).into_response();
1989 *response.headers_mut() = frame_headers(&base);
1990 response
1991}
1992
1993#[derive(Deserialize, Default)]
1994#[serde(default)]
1995struct ContinueForm {
1996 handoff: String,
1997 network: Option<String>,
1998}
1999
2000async fn continue_as(
2002 State(gateway): State<Gateway>,
2003 UrlPath(id): UrlPath<String>,
2004 connection: Option<Extension<ConnectInfo<SocketAddr>>>,
2005 certificates: Option<Extension<ClientCertificates>>,
2006 method: Method,
2007 headers: HeaderMap,
2008 axum::Form(form): axum::Form<ContinueForm>,
2009) -> Response {
2010 if form.handoff.is_empty() {
2013 if method != Method::POST || !same_origin_post(&gateway, &headers) {
2014 return gone();
2015 }
2016 return open_frame(
2017 &gateway,
2018 &id,
2019 form.network.as_deref(),
2020 &headers,
2021 (connection, certificates),
2022 )
2023 .await;
2024 }
2025 handed_off(
2026 &gateway,
2027 &id,
2028 &form.handoff,
2029 form.network.as_deref(),
2030 &method,
2031 &headers,
2032 true,
2033 )
2034 .await
2035}
2036
2037async fn handoff_viewer(
2039 gateway: &Gateway,
2040 store: &PageStore,
2041 page: &Page,
2042 handoff: &Handoff,
2043) -> Option<Person> {
2044 let Ok(viewer) = crate::person_by_id(gateway, handoff.person.clone()).await else {
2045 store.note(&page.id, "a hand-off whose person cannot be found");
2046 return None;
2047 };
2048 let limits = page_limits(gateway).await?;
2049 if !may_view(gateway, page, &viewer, &limits).await {
2050 store.note(
2051 &viewing(&page.id, &viewer.id),
2052 "a hand-off to someone who may not read the page",
2053 );
2054 return None;
2055 }
2056 Some(viewer)
2057}
2058
2059async fn frame(
2063 State(gateway): State<Gateway>,
2064 UrlPath(id): UrlPath<String>,
2065 Query(query): Query<FrameQuery>,
2066 connection: Option<Extension<ConnectInfo<SocketAddr>>>,
2067 certificates: Option<Extension<ClientCertificates>>,
2068 method: Method,
2069 headers: HeaderMap,
2070) -> Response {
2071 if let Some(token) = &query.handoff {
2072 let network = query.network.as_deref();
2073 return handed_off(&gateway, &id, token, network, &method, &headers, false).await;
2074 }
2075 match loads(&headers) {
2078 Loads::Page => {}
2079 Loads::Unknown => return open_link(&gateway, &id, query.network.as_deref()),
2080 Loads::Elsewhere => return gone(),
2081 }
2082 open_frame(
2083 &gateway,
2084 &id,
2085 query.network.as_deref(),
2086 &headers,
2087 (connection, certificates),
2088 )
2089 .await
2090}
2091
2092async fn open_frame(
2094 gateway: &Gateway,
2095 id: &str,
2096 network: Option<&str>,
2097 headers: &HeaderMap,
2098 connection: Connection,
2099) -> Response {
2100 let (store, page, viewer, limits) = match asked(gateway, id, headers, connection).await {
2101 Ok(asked) => asked,
2102 Err(refused) => return *refused,
2103 };
2104 let asked_network = match network {
2105 None => None,
2106 Some("none") => Some(PageNetwork::None),
2107 Some("own") => Some(PageNetwork::Own),
2108 Some("open") => Some(PageNetwork::Open),
2109 Some(_) => return StatusCode::BAD_REQUEST.into_response(),
2110 };
2111 let network = profile(&limits, asked_network);
2112 let mut expires = now() + limits.open_ttl.0.as_secs_f64();
2113 if let Some(end) = page.expires_at {
2114 expires = expires.min(end);
2115 }
2116 let token = store.view_token(&page.id, &viewer.id, network, expires);
2117 audit_opened(gateway, &viewer, &page, network).await;
2118 let base = pages_base(gateway);
2119 let src = format!("{token}/f/");
2120 let owner = if viewer.id == page.person_id {
2121 String::new()
2122 } else {
2123 crate::principals::label_of(gateway, &page.person_id).await
2124 };
2125 let confirm = if needs_confirmation(&page, &viewer, &limits) {
2127 Some((token.as_str(), true))
2128 } else if reads_as_viewer(&page, &viewer, &limits) {
2129 Some((token.as_str(), false))
2130 } else {
2131 None
2132 };
2133 let mut response = frame_html(
2134 &page,
2135 &Viewing::Person(&viewer.id),
2136 &owner,
2137 &src,
2138 (&limits, network),
2139 confirm,
2140 )
2141 .into_response();
2142 *response.headers_mut() = frame_headers(&base);
2143 response
2144}
2145
2146fn frame_headers(base: &str) -> HeaderMap {
2148 let mut headers = page_headers(&frame_csp(base));
2149 headers.insert(
2150 CONTENT_TYPE,
2151 HeaderValue::from_static("text/html; charset=utf-8"),
2152 );
2153 headers.remove(HeaderName::from_static("access-control-allow-origin"));
2154 headers
2155}
2156
2157async fn audit_opened(gateway: &Gateway, viewer: &Person, page: &Page, network: PageNetwork) {
2159 let _ = super::audit(
2160 gateway,
2161 viewer,
2162 "moneypenny.page.opened",
2163 String::new(),
2164 Some(RESOURCE.to_owned()),
2165 &format!("{} ({})", page.id, network.as_str()),
2166 )
2167 .await;
2168}
2169
2170enum Viewing<'a> {
2172 Person(&'a str),
2174 Public,
2176}
2177
2178fn frame_html(
2181 page: &Page,
2182 viewing: &Viewing,
2183 owner: &str,
2184 src: &str,
2185 (limits, network): (&AssistantPageLimits, PageNetwork),
2186 confirm: Option<(&str, bool)>,
2187) -> String {
2188 let expiry = match page.expires_at {
2189 Some(end) => format!("Expires {}.", escape(&utc_text(end))),
2190 None => "Remembered.".to_owned(),
2191 };
2192 let what = format!(
2193 "{} <b>{}</b>.",
2194 escape(page.kind.as_str()),
2195 escape(&page.title)
2196 );
2197 let marked = if page.marks.is_empty() {
2198 String::new()
2199 } else {
2200 format!(
2201 " She made it after reading what an exposed Run wrote ({}): its text is unverified.",
2202 page.marks
2203 .iter()
2204 .map(|mark| escape(mark))
2205 .collect::<Vec<_>>()
2206 .join(", ")
2207 )
2208 };
2209 let (note, bar) = match viewing {
2210 Viewing::Person(viewer) => {
2211 let mut note = if *viewer == page.person_id {
2213 format!("Made by Moneypenny for you, not part of Outer Office. {what} {expiry}")
2214 } else {
2215 format!(
2216 "Made by Moneypenny for {}, not part of Outer Office. {what} {expiry}",
2217 escape(owner),
2218 )
2219 };
2220 if *viewer != page.person_id {
2221 let _ = write!(note, " Shared by {}.", escape(owner));
2222 }
2223 note.push_str(&marked);
2224 (note, limits.frame)
2225 }
2226 Viewing::Public => (
2227 format!(
2228 "Made by Moneypenny, not part of Outer Office. {what} Public: anyone with this \
2229 link sees this page, without live data. {expiry}{marked}"
2230 ),
2231 true,
2232 ),
2233 };
2234 let ask = confirm.map(|(token, asking)| {
2237 let reads = page
2238 .feeds
2239 .iter()
2240 .map(|feed| format!("{} {}", escape(&feed.tool), escape(&feed.input_json())))
2241 .collect::<Vec<_>>()
2242 .join("; ");
2243 if asking {
2244 format!(
2245 "<form class=\"ask\" method=\"post\" action=\"{token}/confirm\"><span>This page \
2246reads your data: {reads}. Its feeds stay off until you allow them.</span>\
2247<button type=\"submit\">Allow</button></form>"
2248 )
2249 } else {
2250 format!(
2251 "<form class=\"ask\" method=\"post\" action=\"{token}/withdraw\"><span>This page \
2252reads your data: {reads}.</span>\
2253<button type=\"submit\">Stop reading my data</button></form>"
2254 )
2255 }
2256 });
2257 let bar = if bar {
2258 format!(
2259 "<input type=\"checkbox\" id=\"c\" aria-label=\"Hide the notice\">\
2260<div class=\"bar\" role=\"note\"><span>{note}</span><label for=\"c\" title=\"Hide for this view\">✕</label></div>"
2261 )
2262 } else {
2263 String::new()
2264 };
2265 let bar = format!("{bar}{}", ask.unwrap_or_default());
2266 let sandbox = sandbox_tokens(network, limits.scripts);
2267 let entry = page
2268 .entry
2269 .split('/')
2270 .map(percent)
2271 .collect::<Vec<_>>()
2272 .join("/");
2273 format!(
2274 "<!doctype html><html><head><meta charset=\"utf-8\"><title>{title}</title>\
2275<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><style>\
2276html,body{{height:100%;margin:0}}body{{display:flex;flex-direction:column;font:14px system-ui,sans-serif}}\
2277.bar{{background:#e8eef7;color:#10233f;padding:.45rem .8rem;display:flex;gap:.8rem;align-items:flex-start;\
2278border-bottom:1px solid #9fb3cf}}\
2279.ask{{background:#fdf0d5;color:#3d2b00;padding:.45rem .8rem;display:flex;gap:.8rem;align-items:center;\
2280border-bottom:1px solid #d9b45a}}.ask span{{flex:1}}\
2281.bar span{{flex:1}}.bar label{{cursor:pointer;font-weight:700;padding:0 .4rem}}\
2282#c{{position:absolute;opacity:0;pointer-events:none}}#c:checked~.bar{{display:none}}\
2283iframe{{flex:1;border:0;width:100%;background:#fff}}</style></head><body>{bar}\
2284<iframe src=\"{src}{entry}\" sandbox=\"{sandbox}\" allow=\"fullscreen\" referrerpolicy=\"no-referrer\" \
2285title=\"{title}\"></iframe></body></html>",
2286 title = escape(&page.title),
2287 )
2288}
2289
2290pub(crate) fn percent(part: &str) -> String {
2292 let mut out = String::new();
2293 for byte in part.bytes() {
2294 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
2295 out.push(char::from(byte));
2296 } else {
2297 let _ = write!(out, "%{byte:02X}");
2298 }
2299 }
2300 out
2301}
2302
2303#[derive(Deserialize)]
2304struct FileQuery {
2305 source: Option<String>,
2306}
2307
2308async fn viewed(
2312 gateway: &Gateway,
2313 id: &str,
2314 token: &str,
2315 headers: &HeaderMap,
2316 connection: Connection,
2317) -> Result<
2318 (
2319 std::sync::Arc<PageStore>,
2320 Page,
2321 Person,
2322 AssistantPageLimits,
2323 PageNetwork,
2324 ),
2325 Box<Response>,
2326> {
2327 let (store, page, viewer, limits) = asked(gateway, id, headers, connection).await?;
2328 match store.viewed(token, &page.id, &viewer.id) {
2329 Ok(network) => Ok((store, page, viewer, limits, network)),
2330 Err(reason) => {
2331 store.note(&viewing(&page.id, &viewer.id), reason);
2332 Err(Box::new(gone()))
2333 }
2334 }
2335}
2336
2337async fn file(
2340 State(gateway): State<Gateway>,
2341 UrlPath((id, token, path)): UrlPath<(String, String, String)>,
2342 Query(query): Query<FileQuery>,
2343 connection: Option<Extension<ConnectInfo<SocketAddr>>>,
2344 certificates: Option<Extension<ClientCertificates>>,
2345 headers: HeaderMap,
2346) -> Response {
2347 let base = pages_base(&gateway);
2348 if top_level(&headers) {
2349 return match asked(&gateway, &id, &headers, (connection, certificates)).await {
2350 Ok(_) => see_other(&format!("{base}/p/{}/", percent(&id))),
2351 Err(refused) => *refused,
2352 };
2353 }
2354 let (store, page, viewer, limits, network) =
2355 match viewed(&gateway, &id, &token, &headers, (connection, certificates)).await {
2356 Ok(viewed) => viewed,
2357 Err(refused) => return *refused,
2358 };
2359 let csp = page_csp(&base, network.tighter(limits.network), limits.scripts);
2360 let Some(mut served) = serve_file(&store, &page, &path, query.source.is_some(), &csp) else {
2361 store.note(
2362 &viewing(&page.id, &viewer.id),
2363 &format!("{path} is not a file of the page"),
2364 );
2365 return gone();
2366 };
2367 credentialed(&headers, served.headers_mut());
2368 served
2369}
2370
2371fn credentialed(asked: &HeaderMap, answer: &mut HeaderMap) {
2376 if asked.get(ORIGIN).is_some_and(|origin| origin == "null") {
2377 answer.insert(
2378 HeaderName::from_static("access-control-allow-origin"),
2379 HeaderValue::from_static("null"),
2380 );
2381 answer.insert(
2382 HeaderName::from_static("access-control-allow-credentials"),
2383 HeaderValue::from_static("true"),
2384 );
2385 answer.insert(
2386 HeaderName::from_static("vary"),
2387 HeaderValue::from_static("origin"),
2388 );
2389 }
2390}
2391
2392fn serve_file(
2394 store: &PageStore,
2395 page: &Page,
2396 path: &str,
2397 source: bool,
2398 csp: &str,
2399) -> Option<Response> {
2400 let bytes = store.read_file(page, path)?;
2401 serve_bytes(page, path, bytes, source, csp)
2402}
2403
2404fn serve_bytes(
2406 page: &Page,
2407 path: &str,
2408 bytes: Vec<u8>,
2409 source: bool,
2410 csp: &str,
2411) -> Option<Response> {
2412 let mut headers = page_headers(csp);
2413 let content_type = |value: &'static str| HeaderValue::from_static(value);
2414 let body: Vec<u8> = match classify(path) {
2415 Serve::Html => {
2416 headers.insert(CONTENT_TYPE, content_type("text/html; charset=utf-8"));
2417 bytes
2418 }
2419 Serve::Markdown if source => {
2420 headers.insert(CONTENT_TYPE, content_type("text/plain; charset=utf-8"));
2421 bytes
2422 }
2423 Serve::Markdown => {
2424 let text = String::from_utf8(bytes).ok()?;
2425 headers.insert(CONTENT_TYPE, content_type("text/html; charset=utf-8"));
2426 markdown_page(&page.title, &text).into_bytes()
2427 }
2428 Serve::Text(kind) | Serve::Asset(kind) => {
2429 headers.insert(CONTENT_TYPE, content_type(kind));
2430 bytes
2431 }
2432 Serve::Attachment => {
2433 headers.insert(CONTENT_TYPE, content_type("application/octet-stream"));
2434 let name: String = path
2435 .rsplit('/')
2436 .next()
2437 .unwrap_or("download")
2438 .chars()
2439 .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'))
2440 .collect();
2441 if let Ok(value) = HeaderValue::from_str(&format!("attachment; filename=\"{name}\"")) {
2442 headers.insert(CONTENT_DISPOSITION, value);
2443 }
2444 bytes
2445 }
2446 };
2447 Some((headers, body).into_response())
2448}
2449
2450async fn feed(
2454 State(gateway): State<Gateway>,
2455 UrlPath((id, token, name)): UrlPath<(String, String, String)>,
2456 connection: Option<Extension<ConnectInfo<SocketAddr>>>,
2457 certificates: Option<Extension<ClientCertificates>>,
2458 headers: HeaderMap,
2459) -> Response {
2460 let (store, page, viewer, limits, network) =
2461 match viewed(&gateway, &id, &token, &headers, (connection, certificates)).await {
2462 Ok(viewed) => viewed,
2463 Err(refused) => return *refused,
2464 };
2465 let base = pages_base(&gateway);
2466 let mut answer_headers = page_headers(&page_csp(&base, network, limits.scripts));
2467 credentialed(&headers, &mut answer_headers);
2468 if network.tighter(limits.network) == PageNetwork::None {
2469 return (
2470 StatusCode::FORBIDDEN,
2471 answer_headers,
2472 Json(FeedReply::refused("this page may not read live data")),
2473 )
2474 .into_response();
2475 }
2476 match run_feed(&gateway, &store, &page, &viewer, &limits, &name).await {
2477 FeedAnswer::Unknown => gone(),
2478 FeedAnswer::Reply(status, body) => (status, answer_headers, Json(body)).into_response(),
2479 }
2480}
2481
2482pub(crate) enum FeedAnswer {
2484 Unknown,
2486 Reply(StatusCode, FeedReply),
2488}
2489
2490pub(crate) async fn run_feed(
2496 gateway: &Gateway,
2497 store: &PageStore,
2498 page: &Page,
2499 viewer: &Person,
2500 limits: &AssistantPageLimits,
2501 name: &str,
2502) -> FeedAnswer {
2503 let key = viewing(&page.id, &viewer.id);
2504 let reply = |status: StatusCode, body: FeedReply| FeedAnswer::Reply(status, body);
2505 if !limits.feeds {
2506 return reply(
2507 StatusCode::FORBIDDEN,
2508 FeedReply::refused("this page may not read live data"),
2509 );
2510 }
2511 if needs_confirmation(page, viewer, limits) {
2512 store.note(
2513 &key,
2514 "a feed asked for before the viewer allowed the page's feeds",
2515 );
2516 return reply(
2517 StatusCode::FORBIDDEN,
2518 FeedReply::confirm("this page reads your data: allow its feeds on the page's bar"),
2519 );
2520 }
2521 let Some(feed) = page.feeds.iter().find(|feed| feed.name == name) else {
2522 store.note(&key, &format!("{name} is not a feed of the page"));
2523 return FeedAnswer::Unknown;
2524 };
2525 let author = crate::person_by_id(gateway, page.person_id.clone()).await;
2528 if match &author {
2529 Ok(author) => author_holds(gateway, author, feed).await.is_err(),
2530 Err(_) => true,
2531 } {
2532 store.note(&key, "a feed whose author may no longer read what it reads");
2533 return reply(
2534 StatusCode::FORBIDDEN,
2535 FeedReply::refused("this page's author may no longer read this"),
2536 );
2537 }
2538 if !store.note_read(&key, limits.feed_reads_per_minute.or_max()) {
2539 return reply(
2540 StatusCode::TOO_MANY_REQUESTS,
2541 FeedReply::refused("too many reads this minute"),
2542 );
2543 }
2544 let stand_in = gateway.stand_in(&viewer.id);
2545 match tools::read_call(gateway, stand_in.token(), &feed.call()).await {
2546 Ok(tools::Fetched::Value(data)) => {
2547 reply(StatusCode::OK, FeedReply::Data { data, at: now() })
2548 }
2549 Ok(tools::Fetched::Guide(_)) => reply(StatusCode::NOT_FOUND, FeedReply::refused("no data")),
2550 Err(failed) => match failed.status {
2551 Some(StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED) => reply(
2552 StatusCode::FORBIDDEN,
2553 FeedReply::refused("not allowed to read this"),
2554 ),
2555 Some(StatusCode::NOT_FOUND) => {
2556 reply(StatusCode::NOT_FOUND, FeedReply::refused("not found"))
2557 }
2558 _ => reply(
2559 StatusCode::BAD_GATEWAY,
2560 FeedReply::refused("the read failed"),
2561 ),
2562 },
2563 }
2564}
2565
2566#[derive(Serialize)]
2568#[serde(untagged)]
2569pub(crate) enum FeedReply {
2570 Data {
2571 data: OpaqueJson,
2572 at: f64,
2573 },
2574 Refused {
2575 error: &'static str,
2576 #[serde(skip_serializing_if = "Option::is_none")]
2577 confirm: Option<bool>,
2578 },
2579}
2580
2581impl FeedReply {
2582 fn refused(error: &'static str) -> Self {
2583 Self::Refused {
2584 error,
2585 confirm: None,
2586 }
2587 }
2588
2589 fn confirm(error: &'static str) -> Self {
2591 Self::Refused {
2592 error,
2593 confirm: Some(true),
2594 }
2595 }
2596}
2597
2598pub(crate) fn needs_confirmation(
2601 page: &Page,
2602 viewer: &Person,
2603 limits: &AssistantPageLimits,
2604) -> bool {
2605 limits.feeds
2606 && !page.feeds.is_empty()
2607 && viewer.id != page.person_id
2608 && !page.feed_readers.contains(&viewer.id)
2609}
2610
2611fn reads_as_viewer(page: &Page, viewer: &Person, limits: &AssistantPageLimits) -> bool {
2613 limits.feeds
2614 && !page.feeds.is_empty()
2615 && viewer.id != page.person_id
2616 && page.feed_readers.contains(&viewer.id)
2617}
2618
2619async fn withdraw(
2622 State(gateway): State<Gateway>,
2623 UrlPath((id, token)): UrlPath<(String, String)>,
2624 connection: Option<Extension<ConnectInfo<SocketAddr>>>,
2625 certificates: Option<Extension<ClientCertificates>>,
2626 headers: HeaderMap,
2627) -> Response {
2628 if headers
2629 .get("sec-fetch-site")
2630 .is_some_and(|site| site == "cross-site")
2631 {
2632 return gone();
2633 }
2634 let (store, page, viewer, _limits, network) =
2635 match viewed(&gateway, &id, &token, &headers, (connection, certificates)).await {
2636 Ok(viewed) => viewed,
2637 Err(refused) => return *refused,
2638 };
2639 if page.feed_readers.contains(&viewer.id) {
2640 if super::audit(
2641 &gateway,
2642 &viewer,
2643 "moneypenny.page.feeds_withdrawn",
2644 String::new(),
2645 Some(RESOURCE.to_owned()),
2646 &page.id,
2647 )
2648 .await
2649 .is_err()
2650 {
2651 return StatusCode::SERVICE_UNAVAILABLE.into_response();
2652 }
2653 if store.withdraw_feeds(&page.id, &viewer.id).is_err() {
2654 return StatusCode::SERVICE_UNAVAILABLE.into_response();
2655 }
2656 }
2657 see_other(&format!(
2658 "{}/p/{}/?network={}",
2659 pages_base(&gateway),
2660 percent(&page.id),
2661 network.as_str()
2662 ))
2663}
2664
2665async fn confirm(
2669 State(gateway): State<Gateway>,
2670 UrlPath((id, token)): UrlPath<(String, String)>,
2671 connection: Option<Extension<ConnectInfo<SocketAddr>>>,
2672 certificates: Option<Extension<ClientCertificates>>,
2673 headers: HeaderMap,
2674) -> Response {
2675 if headers
2676 .get("sec-fetch-site")
2677 .is_some_and(|site| site == "cross-site")
2678 {
2679 return gone();
2680 }
2681 let (store, page, viewer, limits, network) =
2682 match viewed(&gateway, &id, &token, &headers, (connection, certificates)).await {
2683 Ok(viewed) => viewed,
2684 Err(refused) => return *refused,
2685 };
2686 if allow_feeds(&gateway, &store, &page, &viewer, &limits)
2687 .await
2688 .is_err()
2689 {
2690 return StatusCode::SERVICE_UNAVAILABLE.into_response();
2691 }
2692 see_other(&format!(
2693 "{}/p/{}/?network={}",
2694 pages_base(&gateway),
2695 percent(&page.id),
2696 network.as_str()
2697 ))
2698}
2699
2700pub(crate) async fn allow_feeds(
2707 gateway: &Gateway,
2708 store: &PageStore,
2709 page: &Page,
2710 viewer: &Person,
2711 limits: &AssistantPageLimits,
2712) -> Result<(), ()> {
2713 if !needs_confirmation(page, viewer, limits) {
2714 return Ok(());
2715 }
2716 let names = feeds_text(page);
2717 if super::audit(
2718 gateway,
2719 viewer,
2720 "moneypenny.page.feeds_allowed",
2721 String::new(),
2722 Some(RESOURCE.to_owned()),
2723 &format!("{} {names}", page.id),
2724 )
2725 .await
2726 .is_err()
2727 {
2728 store.note(
2729 &viewing(&page.id, &viewer.id),
2730 "an allowance that could not be audited",
2731 );
2732 return Err(());
2733 }
2734 store
2735 .confirm_feeds(&page.id, &viewer.id)
2736 .map(|_| ())
2737 .map_err(|_| ())
2738}
2739
2740pub(crate) fn feeds_text(page: &Page) -> String {
2742 page.feeds
2743 .iter()
2744 .map(|feed| format!("{} {}", feed.tool, feed.input_json()))
2745 .collect::<Vec<_>>()
2746 .join("; ")
2747}
2748
2749async fn public_page(gateway: &Gateway, token: &str) -> Option<(Page, AssistantPageLimits)> {
2752 let store = gateway.pages.clone()?;
2753 let limits = page_limits(gateway).await?;
2754 if !limits.public {
2755 return None;
2756 }
2757 Some((store.public(token)?, limits))
2758}
2759
2760async fn public_frame(State(gateway): State<Gateway>, UrlPath(token): UrlPath<String>) -> Response {
2762 let Some((page, limits)) = public_page(&gateway, &token).await else {
2763 return gone();
2764 };
2765 let network = limits.network;
2766 let mut response =
2767 frame_html(&page, &Viewing::Public, "", "f/", (&limits, network), None).into_response();
2768 *response.headers_mut() = frame_headers(&pages_base(&gateway));
2769 response
2770}
2771
2772async fn public_file(
2775 State(gateway): State<Gateway>,
2776 UrlPath((token, path)): UrlPath<(String, String)>,
2777 Query(query): Query<FileQuery>,
2778 headers: HeaderMap,
2779) -> Response {
2780 let Some((page, limits)) = public_page(&gateway, &token).await else {
2781 return gone();
2782 };
2783 let Some(store) = gateway.pages.clone() else {
2784 return gone();
2785 };
2786 let base = pages_base(&gateway);
2787 if top_level(&headers) {
2788 return see_other(&format!("{base}/s/{token}/"));
2789 }
2790 let csp = page_csp(&base, limits.network, limits.scripts);
2791 let Some(served) = serve_file(&store, &page, &path, query.source.is_some(), &csp) else {
2792 return gone();
2793 };
2794 served
2795}
2796
2797fn feed_scope(feed: &Feed) -> Result<(&'static str, String), String> {
2801 let input = feed
2802 .input
2803 .0
2804 .read::<FeedScopeArgs>()
2805 .map_err(|why| format!("feed {}: could not read its scope: {why}", feed.name))?;
2806 let operation = |action: &'static str| {
2807 input
2808 .operation_id
2809 .as_ref()
2810 .filter(|id| !id.is_empty())
2811 .map(|id| (action, id.clone()))
2812 };
2813 let found = match feed.tool.as_str() {
2814 "audit" | "timeline" => operation("audit.read"),
2815 "access"
2818 if input.subject.is_some() || input.action.is_some() || input.resource.is_some() =>
2819 {
2820 None
2821 }
2822 "access" => operation("access.read"),
2823 "agent_roles"
2824 | "attention"
2825 | "class_authorizations"
2826 | "green_ink"
2827 | "held_briefs"
2828 | "issue_proposals"
2829 | "mission"
2830 | "mission_proposals"
2831 | "missions"
2832 | "reports" => operation("mission.read"),
2833 "charges" => input
2834 .scope
2835 .as_deref()
2836 .and_then(|scope| scope.strip_prefix("operation:"))
2837 .map(|id| ("mission.read", id.to_owned())),
2838 _ => None,
2839 };
2840 found.ok_or_else(|| {
2841 format!(
2842 "feed {}: {} must name the operation_id it reads, because a page reads as each viewer \
2843 and a list of what the person may see proves nothing about what the viewer may",
2844 feed.name, feed.tool
2845 )
2846 })
2847}
2848
2849async fn author_holds(gateway: &Gateway, author: &Person, feed: &Feed) -> Result<(), String> {
2855 let (action, id) = feed_scope(feed)?;
2856 let allowed = match ai6_diptel::OperationId::new(id.clone()) {
2857 Ok(operation) => {
2858 crate::authorize_operation_action(gateway, author.clone(), &operation, action)
2859 .await
2860 .is_ok()
2861 }
2862 Err(_) => false,
2863 };
2864 if allowed {
2865 Ok(())
2866 } else {
2867 Err(format!(
2868 "feed {}: the person does not hold {action} on {id}, so a page may not read {} there \
2869 for anyone",
2870 feed.name, feed.tool
2871 ))
2872 }
2873}
2874
2875pub(crate) async fn author_runs_feeds(
2884 gateway: &Gateway,
2885 person: &str,
2886 feeds: &[Feed],
2887) -> Result<(), String> {
2888 let Ok(author) = crate::person_by_id(gateway, person.to_owned()).await else {
2889 return Err("the person could not be found, so the feeds could not be checked".to_owned());
2890 };
2891 let stand_in = gateway.stand_in(person);
2892 for feed in feeds {
2893 author_holds(gateway, &author, feed).await?;
2894 if let Err(failed) = tools::read_call(gateway, stand_in.token(), &feed.call()).await {
2895 return Err(match failed.status {
2896 Some(StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED | StatusCode::NOT_FOUND) => {
2897 format!(
2898 "feed {}: the person may not read {} with that input, so a page may \
2899 not read it for anyone",
2900 feed.name, feed.tool
2901 )
2902 }
2903 _ => format!(
2904 "feed {}: {} could not be read as the person, so the feed could not be \
2905 checked",
2906 feed.name, feed.tool
2907 ),
2908 });
2909 }
2910 }
2911 Ok(())
2912}
2913
2914pub(crate) fn check_feeds(feeds: &[Feed], limits: &AssistantPageLimits) -> Result<(), String> {
2917 if !limits.feeds {
2918 return Err("this deployment turns live feeds off".to_owned());
2919 }
2920 if !limits.max_feeds.allows(feeds.len()) {
2921 return Err(format!(
2922 "a dashboard may declare {} feeds",
2923 limits.max_feeds
2924 ));
2925 }
2926 let mut seen = std::collections::BTreeSet::new();
2927 for feed in feeds {
2928 let name_ok = !feed.name.is_empty()
2929 && feed.name.len() <= 64
2930 && feed
2931 .name
2932 .chars()
2933 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'));
2934 if !name_ok || !seen.insert(feed.name.as_str()) {
2935 return Err(format!(
2936 "feed name {:?} is not a distinct name of letters, digits, - or _",
2937 feed.name
2938 ));
2939 }
2940 let Some(tool) = tools::read_tools()
2941 .iter()
2942 .find(|tool| tool.name == feed.tool && tool.name != "field_guide")
2943 else {
2944 return Err(format!(
2945 "{:?} is not a read tool a feed may use; feeds read, they never propose or send",
2946 feed.tool
2947 ));
2948 };
2949 tool.validate(&feed.call())
2950 .map_err(|problem| format!("feed {}: {problem}", feed.name))?;
2951 feed_scope(feed)?;
2952 }
2953 Ok(())
2954}
2955
2956#[cfg(test)]
2957mod tests;