Skip to main content

universal_exports/moneypenny/
pages.rs

1//! Pages Moneypenny publishes and how they are served.
2//!
3//! A page is what she makes for the person to open in a browser tab outside Outer Office: a
4//! dashboard reading live data, a report (a snapshot) or one file. The gateway keeps pages in
5//! a [`PageStore`] (a directory, so remembered pages outlive a restart), serves each at its own
6//! address (`{base}/p/{id}/`) to its person and whom they share it with, every request naming its
7//! viewer by the gateway's page authenticator or the page cookie, or to anyone through a public
8//! link (`{base}/s/{token}/`) the person makes, and never lets a page act as the app: every page
9//! response carries a CSP `sandbox` without `allow-same-origin`, so the page is an opaque
10//! origin, and `/v1` answers no cross-origin request. A page is shown in the gateway's own
11//! frame under a classification bar that says who made it and when it expires.
12//!
13//! Quotas and options are `[assistant.pages]` in the roster's `assistant` record, read at each
14//! use, so an administrator's change applies to the next publish.
15
16use 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
51// ---------------------------------------------------------------------------------------
52// What a page is
53// ---------------------------------------------------------------------------------------
54
55/// The scope every page audit record is made under.
56pub(crate) const RESOURCE: &str = "config:assistant";
57
58/// Where a page's top-level files read its feeds, `data/NAME`: no file of a page is under it.
59pub(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/// A live read a dashboard declares: the page asks for `data/{name}` and the gateway runs
66/// the read tool `tool` with the fixed `input` as the page's viewer.
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, FromValue, Schema)]
68#[map(deny_unknown_fields)]
69pub(crate) struct Feed {
70    /// What the page asks for as data/NAME.
71    pub(crate) name: String,
72    /// A read tool.
73    pub(crate) tool: String,
74    /// Its fixed input.
75    input: FeedArguments,
76}
77
78/// The arguments of the read tool named by a feed, decoded by that tool.
79#[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/// The read arguments that determine the scope a feed may serve.
113#[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/// One stored file of a page.
123#[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/// A page's record, `{id}/meta.json`.
131#[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    /// The first file shown.
139    pub(crate) entry: String,
140    pub(crate) files: Vec<FileMeta>,
141    pub(crate) bytes: u64,
142    pub(crate) created_at: f64,
143    /// When it goes; `None` once the person remembers it.
144    pub(crate) expires_at: Option<f64>,
145    pub(crate) feeds: Vec<Feed>,
146    /// Subjects the person shares it with.
147    #[serde(default)]
148    pub(crate) shares: Vec<String>,
149    /// The token of its public link (`{base}/s/{token}/`), while the person keeps one. It sits
150    /// beside the files it opens, so keeping it here exposes nothing they do not.
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub(crate) public: Option<String>,
153    /// The people other than its person who confirmed that this page reads their data through
154    /// its feeds. A replace starts the list again, since the feeds may be others.
155    #[serde(default, skip_serializing_if = "Vec::is_empty")]
156    pub(crate) feed_readers: Vec<String>,
157    /// What the conversation she made it in held when she made it: the Reports an exposed Run
158    /// wrote that she had read (`report:ID`). A page made after reading them is marked.
159    #[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    /// How the app and her `pages` tool list it to its person, with whom it is shared.
179    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    /// [`summary`](Self::summary) with the address of its public link, under `base`.
188    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    /// How it is listed to `viewer`: its person sees [`summary`](Self::summary); anyone it is
199    /// shared with sees whose it is, and not whom else it is shared with.
200    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/// A page as the app and her `pages` tool list it. A listing to the person it is shared with
228/// names whose it is and leaves out whom else it is shared with.
229#[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
249/// A share's kind and ID: `person:`, `group:` or `account:` (as the access policy names people),
250/// `compartment:{id}` (the people read into it) or `operation:{id}` (the people who hold
251/// `mission.read` there). The ID is 1 to 256 bytes without control characters.
252pub(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// ---------------------------------------------------------------------------------------
263// Formats
264// ---------------------------------------------------------------------------------------
265
266/// How a file is served, from its extension.
267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
268pub(crate) enum Serve {
269    Html,
270    Markdown,
271    /// UTF-8 text with this content type.
272    Text(&'static str),
273    /// A bundle asset with this content type.
274    Asset(&'static str),
275    /// Anything else: offered as a download, never rendered.
276    Attachment,
277}
278
279/// The one table of formats.
280pub(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
305/// A page path as stored: `/`-separated, no empty part or hidden name (so no `.` or `..`),
306/// no backslash or control character, at most 512 bytes and 255 to a part, and nothing a
307/// Windows path reads as more than a name inside its directory: no `:` (a drive, as in
308/// `D:x`, or a stream), no device name (`CON`, `NUL`, `COM1` and the rest, with or without an
309/// extension), no trailing dot or space.
310pub(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
325/// Whether Windows reads `part` as a device (`CON`, `PRN`, `AUX`, `NUL`, `COM0` to `COM9`,
326/// `LPT0` to `LPT9`, `CONIN$`, `CONOUT$`), whatever follows its first dot.
327fn 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
344/// `path`, the `/`-separated name of a page file, under `base`: `None` unless the result is
345/// still inside `base` by its components and holds only plain names, which a part such as
346/// `D:x` or `C:..` is not on Windows, where joining it replaces or climbs out of `base`.
347pub(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
357/// Markdown rendered as a page: tables, strikethrough and task lists; raw HTML is kept, the
358/// result being served as any HTML page is.
359pub(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
378/// `text` safe inside HTML text and quoted attributes.
379pub(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("&amp;"),
384            '<' => out.push_str("&lt;"),
385            '>' => out.push_str("&gt;"),
386            '"' => out.push_str("&quot;"),
387            '\'' => out.push_str("&#39;"),
388            c => out.push(c),
389        }
390    }
391    out
392}
393
394/// `seconds` (Unix time) as `2026-11-01 12:30 UTC`.
395pub(crate) fn utc_text(seconds: f64) -> String {
396    // Past the years `time` represents (+-9999) the text shows the last one.
397    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
414/// `bytes` as unpadded base64url.
415fn base64url(bytes: &[u8]) -> String {
416    URL_SAFE_NO_PAD.encode(bytes)
417}
418
419/// 32 random bytes.
420fn 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
427/// 32 random bytes as base64url: a capability token or a page ID suffix.
428fn random_token() -> String {
429    base64url(&random_bytes())
430}
431
432/// The HMAC-SHA256 under `key` of `parts`, each ended by a NUL so no two lists run together.
433fn 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
445/// The key at `path`, made of 32 random bytes and written there (owner-only on Unix) when there
446/// is none.
447fn 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        // Another gateway on the same directory made it first.
475        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
484// ---------------------------------------------------------------------------------------
485// The store
486// ---------------------------------------------------------------------------------------
487
488/// The key the page cookies and view tokens are made with, in the pages directory: hidden, so no
489/// page is ever read from it.
490const KEY_FILE: &str = ".key";
491
492/// Files a Station sent for a `publish_page` call, until the call takes them.
493struct 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 uploads by (conversation, call digest).
505    staged: HashMap<(String, String), Staged>,
506    /// Feed reads in the current minute, by [`viewing`] key.
507    reads: HashMap<String, (Instant, u32)>,
508    /// Hand-offs not yet used, by the digest of their token. In memory only, so a restart ends
509    /// them.
510    handoffs: HashMap<String, Handoff>,
511    /// A replacement of a shared or public page that waits for its person, by page ID: the page
512    /// keeps showing what it showed until they confirm. In memory only, so a restart drops it.
513    drafts: HashMap<String, Prepared>,
514    /// Why requests were refused, each logged once per page, viewer and reason.
515    noted: HashSet<(String, String)>,
516    /// What was logged, for the tests to read.
517    #[cfg(test)]
518    log: Vec<String>,
519}
520
521/// What a hand-off's single-use token stands for.
522#[derive(Debug, Clone)]
523pub(crate) struct Handoff {
524    pub(crate) page: String,
525    pub(crate) person: String,
526    /// The login the page cookie it sets will name, which must still stand when it is used.
527    pub(crate) sign_in: String,
528    /// The SHA-256 of the nonce the asking browser holds in its hand-off cookie, which spending
529    /// the token needs back: a browser another person sent the address to has none. `None`
530    /// where the asker held no browser (the desktop app) or pages have an origin of their own.
531    pub(crate) binder: Option<String>,
532    /// Unix seconds.
533    pub(crate) expires: f64,
534}
535
536/// The key of one viewer's viewing of one page, which notes and read counts are kept by.
537pub(crate) fn viewing(page: &str, viewer: &str) -> String {
538    format!("{page} {viewer}")
539}
540
541/// The pages on disk, and the uploads and counters in memory.
542pub(crate) struct PageStore {
543    dir: PathBuf,
544    /// The key view tokens and page cookies are made with, kept in the pages directory.
545    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/// A page checked against the quotas and written aside, not yet in the store: the audit
560/// record comes between [`PageStore::prepare`] and [`PageStore::commit`].
561#[derive(Debug)]
562pub(crate) struct Prepared {
563    pub(crate) page: Page,
564    temp: PathBuf,
565}
566
567impl Prepared {
568    /// What the person is shown and confirms of it: a digest of the title, entry, files and
569    /// feeds, which a confirmation must name.
570    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    /// Takes over whom `current`, the page this one replaces, is shared with now and its public
581    /// link, which the person may have changed while this waited.
582    fn rebase(&mut self, current: &Page) -> io::Result<()> {
583        self.page.shares.clone_from(&current.shares);
584        self.page.public.clone_from(&current.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    /// Opens `dir`, created private (`0700` on Unix), reading each page's record and the key,
594    /// which it makes the first time.
595    ///
596    /// # Errors
597    ///
598    /// The directory cannot be made or read, or the key cannot be read or made.
599    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                // A publish that never finished.
611                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    /// The keyed digest of `parts` under the store's key, as base64url.
637    pub(crate) fn keyed_text(&self, parts: &[&str]) -> String {
638        base64url(&keyed(&self.key, parts))
639    }
640
641    /// The view token the frame of `page` names for `viewer`, with `network`, until `expires`
642    /// (Unix seconds): `{expires}.{network}.{mark}`, its end in Unix milliseconds. It names the page's files and feeds and
643    /// opens nothing by itself; it ties those requests to the frame its viewer was shown, which
644    /// another site cannot know.
645    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    /// The network of the view token `token` when it is `viewer`'s for `page` and has not
658    /// expired; why not, otherwise.
659    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    /// Makes a single-use token for `handoff`, keeping only its digest. A person past `most`
687    /// unused ones loses their oldest.
688    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    /// Spends the hand-off `token`, whatever comes of it: what it stands for, unless it was spent
719    /// already or has ended.
720    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    /// Puts back a hand-off [`PageStore::take_handoff`] spent, for a browser that has to say it
729    /// means to swap the person its pages are signed in as before it is used.
730    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    /// Logs why a request for a page was refused, once for each [`viewing`] key and reason.
737    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    /// What [`note`](Self::note) logged.
751    #[cfg(test)]
752    pub(crate) fn logged(&self) -> Vec<String> {
753        self.state().log.clone()
754    }
755
756    /// Whether this call is the one that starts the sweeper.
757    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    /// A fresh page ID.
768    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    /// Pages of other people than `person` that are shared with someone, newest first: the
777    /// ones that might be shared with `person`.
778    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    /// Sets whom a page is shared with.
791    ///
792    /// # Errors
793    ///
794    /// The record could not be written; nothing changed.
795    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    /// Records that `viewer` let page `id` read their data through its feeds.
808    ///
809    /// # Errors
810    ///
811    /// The record could not be written; nothing changed.
812    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    /// Records that `viewer` no longer lets page `id` read their data through its feeds.
827    ///
828    /// # Errors
829    ///
830    /// The record could not be written; nothing changed.
831    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    /// `person`'s pages, newest first.
844    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    /// Checks `page` and its `files` against `limits` and writes them aside. `replace` is the
857    /// ID of the page these files take the place of, whose size does not count.
858    ///
859    /// # Errors
860    ///
861    /// The quota or path that refuses it, in words for her.
862    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    /// Puts a prepared page in the store, in place of the one with its ID.
950    ///
951    /// # Errors
952    ///
953    /// The directory could not be moved into place.
954    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    /// Throws a prepared page away.
970    pub(crate) fn discard(&self, prepared: Prepared) {
971        let _ = std::fs::remove_dir_all(prepared.temp);
972    }
973
974    /// Keeps a replacement of a shared or public page aside until its person confirms it; an
975    /// earlier one waiting for the same page is thrown away.
976    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    /// Throws away every waiting replacement `keep` does not name by its page ID and digest.
987    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    /// The replacement of page `id` waiting for its person, for the preview only they open.
1003    pub(crate) fn draft(&self, id: &str) -> Option<Page> {
1004        self.state().drafts.get(id).map(|draft| draft.page.clone())
1005    }
1006
1007    /// One listed file of the replacement of page `id` waiting for its person.
1008    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    /// The replacement of page `id` (or the new page of that id) waiting for its person when it
1020    /// is the one `digest` names, made over what the page is shared with now.
1021    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(&current).is_err()
1031        {
1032            self.discard(draft);
1033            return None;
1034        }
1035        Some(draft)
1036    }
1037
1038    /// Rewrites a page's record.
1039    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    /// Removes a page, with what was counted and noted of its viewing.
1047    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    /// Drops the read counts and notes of pages that are gone.
1059    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    /// Sets or clears a page's expiry: remembered pages have none.
1072    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    /// The bytes of one listed file of a page.
1086    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    /// Deletes expired pages and stale uploads; answers the pages deleted.
1095    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    /// Counts a feed read of the [`viewing`] key `key`; false past `most` in the minute.
1121    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    // ---- public links
1135
1136    /// Gives page `id` a public link, keeping the one it has; `None` turns it off. Answers the
1137    /// page as it now stands.
1138    ///
1139    /// # Errors
1140    ///
1141    /// The record could not be written; nothing changed.
1142    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    /// The page whose public link is `token`, while it stands.
1159    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    // ---- uploads from Stations
1172
1173    /// Takes one file of a page a Station uploads for the call `digest` of `conversation`.
1174    ///
1175    /// # Errors
1176    ///
1177    /// The reason it was refused.
1178    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    /// Ends an upload with the Station's manifest, or its refusal.
1229    ///
1230    /// # Errors
1231    ///
1232    /// No such upload for that Station.
1233    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    /// Takes the upload for the call, waiting up to `wait` for the Station to finish it; its
1266    /// files are checked against the manifest. A refusal, a mismatch or silence is the error.
1267    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            // Registered before the look, so a `done` between the look and the wait is seen.
1279            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
1307/// The files a Station sent, held to the manifest it ended with: each listed file arrived with
1308/// its size and SHA-256, and nothing else did.
1309fn 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
1331// ---------------------------------------------------------------------------------------
1332// Headers
1333// ---------------------------------------------------------------------------------------
1334
1335/// The origin of the pages' base: `frame-ancestors` is compared with a parent's origin, whose path
1336/// is `/`, so a source with any other path never matches and the browser blocks the frame.
1337fn 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
1344/// The `sandbox` tokens of a page for `network` and `scripts`, never `allow-same-origin` or
1345/// `allow-top-navigation*`, so a page is an opaque origin and cannot reach its host. Only `open`
1346/// lets a page open windows: a window the sandbox does not hold is a way out for what the page
1347/// read.
1348fn 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
1360/// The CSP of every page response for `network` and `scripts`; `base` is the pages' base, whose
1361/// origin alone may frame a page. `own` and `none` load only the page's own files, post no form
1362/// outside, and open no window; `own` may also fetch its own files and feeds, `none` fetches
1363/// nothing. What a CSP cannot block is in the docs: WebRTC, and a page navigating its own frame.
1364pub(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
1386/// The CSP of the gateway's frame document: no script, only what is under the pages' base
1387/// framed (`frame-src` takes a path as a prefix only with a trailing slash).
1388pub(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
1395/// `GET /p/{id}/draft/`: the replacement of a shared or public page that waits for its person's
1396/// Confirm, framed for that person alone and with no network, so they see what they confirm.
1397/// Nobody else, the page's viewers and public link included, can open it.
1398async 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    // Its files sit under a view token of their own, as a published page's do, so a request that
1421    // only carries the cookie reads nothing of it.
1422    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
1438/// What a preview's view token is made for: a page's own tokens never open its draft.
1439fn draft_key(id: &str) -> String {
1440    format!("{id}#draft")
1441}
1442
1443/// `GET /p/{id}/draft/{token}/f/{path}`: a file of the preview, for the page's person alone, with
1444/// no network, under the view token its frame named.
1445async 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
1475/// The headers every page response carries, the CSP in `csp`.
1476fn 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    // The opaque page loads its own files from another origin as it sees it: who asks, and the
1488    // view token its frame named, guard them.
1489    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
1502/// The profile a link is served under: the administrator's, or tighter when the viewer asked.
1503pub(crate) fn profile(limits: &AssistantPageLimits, asked: Option<PageNetwork>) -> PageNetwork {
1504    limits.network.tighter(asked.unwrap_or(PageNetwork::Open))
1505}
1506
1507// ---------------------------------------------------------------------------------------
1508// Serving
1509// ---------------------------------------------------------------------------------------
1510
1511/// Where pages are served from: a directory, and optionally their own origin and listener.
1512#[derive(Debug, Clone, PartialEq, Eq)]
1513pub struct PagesConfig {
1514    /// Where pages are kept.
1515    pub dir: PathBuf,
1516    /// `[pages] origin`: the pages' own origin, such as `https://pages.example.net`. Without
1517    /// one, pages are served under `/pages/` on the API's origin, by design.
1518    pub origin: Option<String>,
1519    /// `[pages] listen`: the loopback address of the pages' own listener (with `origin`).
1520    pub listen: Option<std::net::SocketAddr>,
1521}
1522
1523impl PagesConfig {
1524    /// Pages kept in `dir`, served on the API's own origin.
1525    #[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    /// Serves pages on their own `origin` and `listen` address.
1535    #[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
1543/// The base URL pages are served under, no trailing slash.
1544pub(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
1555/// The routes of pages. `/p/{id}/` is a private page's frame; `/p/{id}/{token}/f/{path}` and
1556/// `/p/{id}/{token}/data/{name}` are its files and feeds under the view token the frame names,
1557/// each feed also at `/p/{id}/{token}/f/data/{name}`, where `data/NAME` from a file at the top of
1558/// the page leads. Every one of them names its viewer ([`page_access::viewer`]) and checks
1559/// [`may_view`]. `/s/{token}/` and `/s/{token}/f/{path}` are a public link's frame and files, with
1560/// no feed. Nothing of `/v1`.
1561pub(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
1579/// What the compartments grant now, read for one decision; `None` without a configuration
1580/// provider or when it cannot be read, which grants nothing.
1581async 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
1590/// Whether `person` holds `mission.read` on Operation `operation`, compartments and the tree of
1591/// Operations included.
1592pub(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
1603/// Whether `person` is read into compartment `id` now.
1604pub(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
1610/// Whether `viewer` may read `page`: its person, or someone one of its shares names while
1611/// `limits` lets pages be shared. An administrator is no exception.
1612pub(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
1640/// The live `[assistant.pages]`; `None` when the roster cannot be read.
1641async 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
1651/// What a viewer whose sign-in has ended reads.
1652pub(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
1655/// `403` with [`SIGNED_OUT`], as plain text nothing runs in.
1656fn 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
1665/// A request for private page `id`, once it names a person who may read the page now: the page,
1666/// the person and the live `[assistant.pages]`; otherwise the answer to give, its reason logged.
1667/// A request that names nobody, or someone the page is hidden from, is answered as a page that
1668/// does not exist.
1669async 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
1714/// What a browser is told of a live report: it is drawn by the app from the gateway's own
1715/// routes, so nothing of it is served here, no script and no file.
1716fn 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
1730/// A `303 See Other` to `to`.
1731fn 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
1739/// Whether a request is a top-level navigation: the frame's own load is an `iframe` and a
1740/// page's loads are other destinations.
1741fn 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
1748/// What a request for a frame is.
1749enum Loads {
1750    /// A browser loading the page: a navigation, or a frame of the pages' own address.
1751    Page,
1752    /// A request that says nothing of what it loads (a script's `fetch` is `empty`, but a client
1753    /// that sends no `Sec-Fetch-Dest` could be anything): it opens nothing and records nothing.
1754    Unknown,
1755    /// Another site's `<img>`, `<script>`, `fetch` or `<iframe>`.
1756    Elsewhere,
1757}
1758
1759/// Classifies a request for a frame by `Sec-Fetch-Dest`: `document` is a browser navigating, and
1760/// `iframe` only counts when the site that framed it is this origin, since another site's frame
1761/// would otherwise write an "opened" audit record and mint a view token for whoever it reaches.
1762fn 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        // A browser too old to send fetch metadata sends neither header; one that sends the
1771        // site and no destination is not one.
1772        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
1780/// Whether a post to the pages' own address came from it: by the fetch metadata when the browser
1781/// sends it, else by `Origin`, which every browser sends with a post and which another site's
1782/// form carries as its own.
1783fn 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
1798/// What a request that names no destination is given: a page with a link, which a browser opens
1799/// as a navigation. It looks nothing up, so it says nothing of whether the page exists.
1800fn open_link(gateway: &Gateway, id: &str, network: Option<&str>) -> Response {
1801    let base = pages_base(gateway);
1802    // A form post of the pages' own address: a browser that sends no fetch metadata cannot be
1803    // told a link click from another site's, but it does send `Origin` with a post.
1804    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    /// `none`, `own` or `open`: a tighter network than the deployment's, for this opening.
1827    network: Option<String>,
1828    /// A hand-off's single-use token, which [`handed_off`] spends.
1829    handoff: Option<String>,
1830}
1831
1832/// `GET /p/{id}/?handoff=`: a browser the app sent here with a hand-off and perhaps no cookie.
1833/// Spends the token, then sets the page cookie and sends the browser to the page's clean address,
1834/// so the token leaves the address bar. Anything but a good token for this page answers as a page
1835/// that does not exist. Only a navigation spends one: another site's `<img>`, a prefetch or a
1836/// `HEAD` would otherwise use it up, or set the cookie, without the person opening anything.
1837async 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        // The button of the prompt below: a form post of the pages' own frame document.
1848        *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    // A browser that already holds a page cookie of another signed-in person is not signed in
1888    // as someone else by a link: whoever made the link may be that someone else. It asks first.
1889    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    // The audit record comes before the browser holds the cookie.
1930    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
1956/// The page a browser is shown when a hand-off is for someone other than the person its pages are
1957/// signed in as: who is signed in, who the link is for, and a button that is a form post of this
1958/// page's own address, with no script, that signs it in as the other.
1959fn 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
2000/// `POST /p/{id}/`: the button of [`swap_prompt`], from the pages' own address.
2001async 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    // The button of [`open_link`]: no hand-off, only the person's own click on the pages' own
2011    // address, which opens the page as a navigation would.
2012    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
2037/// The person a hand-off stands for, when the page may still be shown to them.
2038async 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
2059/// `GET /p/{id}/`: a private page's frame, for its person and whom it is shared with, opened from
2060/// the app, a bookmark, a new tab or another device alike. The page in it is named under a view
2061/// token for this viewer and opening ([`PageStore::view_token`]); each opening is audited.
2062async 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    // Another site's `<img>`, `<script>` or `<iframe>` for this address would otherwise write an
2076    // "opened" audit record and mint a view token for the person whose cookie it carries.
2077    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
2092/// The frame of private page `id` for the person the request names: audited, with its view token.
2093async 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    // Feeds read as whoever opens the page: another person than its own is asked once.
2126    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
2146/// Everything the frame document and the framed page need to be served.
2147fn 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
2157/// Audits an opening of `page` by `viewer`.
2158async 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
2170/// Whom a frame is shown to.
2171enum Viewing<'a> {
2172    /// A signed-in viewer, by their ID.
2173    Person(&'a str),
2174    /// Anyone holding the page's public link.
2175    Public,
2176}
2177
2178/// The frame: the classification bar above an iframe of the page's entry under `src`. A
2179/// viewer's frame drops the bar with `[assistant.pages] frame = false`; a public one never does.
2180fn 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            // The owner's name (their ID when never seen), or "you" to the owner.
2212            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    // The question comes whatever `frame` says, and cannot be hidden: until it is answered the
2235    // page's feeds stay off.
2236    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\">&#10005;</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
2290/// `part` percent-encoded for a URL path segment.
2291pub(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
2308/// A request for a file or feed of private page `id` under view token `token`: the request names
2309/// its viewer, who may read the page, and the token is the one the frame named for them. Answers
2310/// the page, the viewer, the live `[assistant.pages]` and the token's network.
2311async 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
2337/// `GET /p/{id}/{token}/f/{path}`: a file of the page. A top-level request is sent to the
2338/// frame, which carries the bar.
2339async 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
2371/// Lets the page's own script read the answer to a request it made with its credentials: the
2372/// page is an opaque origin, which sends `Origin: null`, and `*` admits no credentialed request.
2373/// The address names its view token, which another site cannot read from the frame, so only the
2374/// page's own script reaches it with a request the gateway answers this way.
2375fn 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
2392/// One listed file of `page`, by its format, under `csp`; `None` when there is no such file.
2393fn 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
2404/// `bytes`, the file `path` of `page`, by its format, under `csp`.
2405fn 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
2450/// `GET /p/{id}/{token}/data/{name}`: a feed of the page, run as its viewer. A page's script
2451/// reads it with `fetch(url, {credentials: "include"})`, which sends the page cookie from the
2452/// page's opaque origin (`Origin: null`); the answer lets that script read it.
2453async 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
2482/// What reading a feed of a page comes to.
2483pub(crate) enum FeedAnswer {
2484    /// The page declares no such feed.
2485    Unknown,
2486    /// The status and body to answer with.
2487    Reply(StatusCode, FeedReply),
2488}
2489
2490/// Reads feed `name` of `page` as `viewer`: the one path a feed is read by, for a script in a
2491/// browser and for a live report in the app alike. The viewer's own permissions answer: the
2492/// read tool runs with their token, after the page's author is checked to still hold what the
2493/// feed reads, the viewer has allowed the page's feeds if the page is not theirs, and the
2494/// viewer's reads this minute are counted.
2495pub(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    // The page reads as its viewer, on what its author was allowed to have it read: an author
2526    // who has lost that since publishing leaves every viewer without the feed.
2527    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/// What a page's feed route answers: the data, or why not.
2567#[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    /// A refusal that the viewer can lift by allowing the page's feeds.
2590    fn confirm(error: &'static str) -> Self {
2591        Self::Refused {
2592            error,
2593            confirm: Some(true),
2594        }
2595    }
2596}
2597
2598/// Whether `viewer` still has to allow `page`'s feeds: they read as the viewer, so anyone but the
2599/// page's person is asked once per page, and again after a replace.
2600pub(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
2611/// Whether `page`'s feeds read as `viewer`, who is not its person and has allowed them.
2612fn 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
2619/// `POST /p/{id}/{token}/withdraw`: the viewer stops the page's feeds reading their data, until
2620/// they allow them again. Audited, under the view token the frame named for this viewer.
2621async 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
2665/// `POST /p/{id}/{token}/confirm`: the viewer lets the page's feeds read their data. Audited
2666/// before it is recorded, and only under the view token the frame named for this viewer, which
2667/// another site cannot know. It answers with the frame again.
2668async 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
2700/// Lets `page`'s feeds read `viewer`'s data, when they still have to allow them: audited
2701/// before it is recorded.
2702///
2703/// # Errors
2704///
2705/// The allowance could not be audited or recorded, and nothing is allowed.
2706pub(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
2740/// The feeds of `page` as the audit of an allowance records them: each tool and its input.
2741pub(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
2749/// The page a public link opens, while public links are allowed, with the live
2750/// `[assistant.pages]`.
2751async 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
2760/// `GET /s/{token}/`: a public link's frame, for anyone holding it; its bar says it is public.
2761async 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
2772/// `GET /s/{token}/f/{path}`: a file of a public page, under the deployment's network profile.
2773/// A public link has no feed: nobody signed in to read with.
2774async 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
2797/// The Operation `feed` names in its input and the action that reads the tool's answer there. A
2798/// read tool that lists what its caller may see answers `200` with an empty list to a person who
2799/// holds nothing, so a feed must name where it reads.
2800fn 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        // With `subject`, `action` and `resource` the tool checks someone else's access to
2816        // another resource, which `operation_id` does not name.
2817        "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
2849/// Whether `author` holds the read action of `feed` on the Operation it names.
2850///
2851/// # Errors
2852///
2853/// The feed and why, in words for her.
2854async 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
2875/// Refuses a feed that `person`, whose page it is, may not read: each names a scope, the person
2876/// holds the tool's read action there, and the read as the person answers. A page reads as each
2877/// viewer, so one who could not read it themselves must not be able to have a page do it for
2878/// another.
2879///
2880/// # Errors
2881///
2882/// The feed and why, in words for her.
2883pub(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
2914/// Checks the declared feeds of a dashboard: each a read tool with input its schema accepts, at
2915/// most `limits.max_feeds`, distinct names.
2916pub(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;